Skip to content

fix(mongodb-sync): recover from duplicate journal sequences - #991

Open
bercianor wants to merge 5 commits into
masterfrom
fix/journal-sequence-resynchronization
Open

bercianor wants to merge 5 commits into
masterfrom
fix/journal-sequence-resynchronization

Conversation

@bercianor

Copy link
Copy Markdown
Member

Summary

  • Normalize confirmed MongoDB sync journal position collisions to DuplicateStreamSequenceException; event-ID duplicates still propagate unchanged.
  • Resynchronize the current sequencer from the primary's majority-committed journal tail and retry the persistence attempt at most once. Transactional replay requires confirmed rollback; standalone replay never repeats the audit-state save. User changes are never replayed.
  • Independent of the runner-scoped factory in fix(core): share stage audit persistence within a runner #990. Other audit stores and simulated failover orchestration are out of scope. Core behavior and its first working backend are kept together with their tests.

Testing

  • ./gradlew :core:flamingock-core:test :core:flamingock-core:spotlessCheck :core:flamingock-core-commons:test :core:flamingock-core-commons:spotlessCheck :community:flamingock-mongodb-sync-auditstore:test :community:flamingock-mongodb-sync-auditstore:spotlessCheck — 356 core, 91 commons and 97 MongoDB sync tests passed, none skipped. MongoDB integration tests ran through Testcontainers on local Docker.
  • Durable collision recovery covered journal-only and combined audit writes, with and without transactions. The majority-read regression models a rollbackable tail without triggering a real primary election.

return getLastEventByStream(collection, streamId);
}

Optional<JournalEvent<AuditEntry>> getMajorityCommittedTail(String streamId) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: High

getMajorityCommittedTail() hardcodes ReadConcern.MAJORITY, which MongoDB does not support on a standalone (non-replica-set) mongod — exactly the deployment MongoDBSyncTargetSystem.withTransactionsSupported(false) is documented to target ("Set this to false for standalone MongoDB").

On a duplicate stream-sequence collision, the non-transactional retry path (MongoDBSyncAuditPersistence.appendStandaloneAndConfirm → JournalEventSequencer.retryOnceOnCollision → journalEventStore::getMajorityCommittedTail) issues this majority-read, which a standalone server rejects. The failure is caught by retryOnceOnCollision's catch (RuntimeException readFailure) block, added as a suppressed exception, and the original DuplicateStreamSequenceException is rethrown unchanged — so the whole recovery feature this PR adds is silently inert for standalone deployments, the exact case it was built for.

The existing test suite can't catch this: Testcontainers' MongoDBContainer always auto-initializes a single-node replica set regardless of the transactional flag passed to freshPersistence, so the "non-transactional" test scenario never actually runs against a true standalone server.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for spotting the coverage gap. I added an E2E test against MongoDB 4.4.6 in standalone mode. It forces a journal sequence collision and verifies that the retry writes the second event at position 2 and preserves both audit entries. The test passed with ReadConcern.MAJORITY unchanged. Commit 14fa68bd.

return result;
}

private Result retryJournalTransaction(Supplier<Result> transaction) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: Low

retryJournalTransaction re-derives retry-eligibility by sniffing DatabaseTransactionException internals (rollbackStatus == SUCCESS, getSuppressed().length == 0, cause instanceof DuplicateStreamSequenceException) rather than having the transaction-wrapper boundary (MongoDBSyncTxWrapper) preserve/expose the typed cause directly.

This is a bandaid one layer removed from the real failure: any future change to how MongoDBSyncTxWrapper builds DatabaseTransactionException (e.g. adding another suppressed exception during cleanup, or changing rollback bookkeeping) silently breaks retry eligibility with no compile-time signal, because the safety check here depends on incidental details of a generic wrapper exception rather than an explicit contract between the wrapper and the retry logic.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. The transaction wrapper now explicitly authorizes retry for the specific journal write that failed, and only if rollback and session cleanup return without errors. The persistence layer no longer infers retry eligibility from DatabaseTransactionException. Tests cover failures in setup, commit, rollback, and cleanup. Commit 7e7412d1.

&& failure.getSuppressed().length == 0
&& failure.getCause() instanceof DuplicateStreamSequenceException) {
DuplicateStreamSequenceException collision = (DuplicateStreamSequenceException) failure.getCause();
throw new DuplicateStreamSequenceException(collision.getStreamId(), collision.getStreamSequence(), failure);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: Low

A brand-new DuplicateStreamSequenceException is constructed with cause=failure (the DatabaseTransactionException) instead of reusing the original collision exception, adding an extra indirection layer to the cause chain.

The final exception chain becomes new-DSE → DatabaseTransactionException → original-DSE → MongoWriteException instead of just propagating the original DSE (which already carries streamId/streamSequence and the real MongoWriteException as its direct cause). Anyone calling getCause() on the exception that ultimately escapes a persistent collision gets a DatabaseTransactionException instead of the backend-level detail, losing a layer of fidelity for no documented benefit over rethrowing the original collision object directly.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. When the wrapper authorizes a retry, the sequencer receives the original DuplicateStreamSequenceException, with the original MongoWriteException as its direct cause. We no longer create a second collision exception, and the tests check that the original instance and cause are preserved. Commit 7e7412d1.

* @param <T> result type
* @return the successful attempt's result
*/
public <T> T retryOnceOnCollision(Function<String, Optional<JournalEvent<AuditEntry>>> readDurableTail,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: Low

retryOnceOnCollision's "exactly one retry" invariant is expressed as fallthrough from a catch block into a second, un-guarded write.get() call after the try/catch, rather than an explicit bounded loop or flag.

Readability/maintenance cost: a maintainer must notice that the catch block has no return/throw on its success path and that control falls through to the trailing return write.get(); to understand that the retry happens exactly once. A small bounded loop (e.g. for (int attempt = 0; attempt < 2; attempt++)) or an explicit retried boolean would make the single-retry guarantee visually obvious and less likely to be broken by a future edit that adds code after the catch block without noticing the fallthrough semantics.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point about making the recovery path easier to follow. I moved the second write.get() into the catch, immediately after resynchronizing the sequence. A second collision still propagates, so the one-retry behavior is unchanged. Commit 59771a34.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants