Skip to content

fix(#5503): lock the modified files on replicas and hold them until the local apply - #5507

Merged
robfrank merged 3 commits into
mainfrom
fix/5503-follower-concurrent-tx-corruption
Jul 28, 2026
Merged

robfrank merged 3 commits into
mainfrom
fix/5503-follower-concurrent-tx-corruption

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Closes #5503

Summary

Concurrent transactions issued through a shared follower Database handle corrupted records and silently lost committed writes. TransactionContext.commit1stPhase(false) skipped the per-file commit locks, on the assumption recorded in PageManager.publishPages that "the single-threaded Raft apply provides the serialization". The apply only orders the write side; nothing ordered the capture side. Concurrent transactions therefore all validated against the same base page version and each shipped a WAL delta stamped with the same next version. applyChanges applied the first and then met the others at equal version, which is deliberately re-applied to repair torn writes (#4926) - splicing partial page images computed against a page that no longer existed. That single event produces both symptoms: the invalid record sizes and the lost writes.

The fix has two halves, both load-bearing:

  1. Replicas take the same commit locks as the leader (plus the [tx] Files can join a transaction's page set after the commit lock set is computed #4937 late-joiner union check that keeps the lock set complete), so the loser of a race gets a retryable ConcurrentModificationException instead of shipping a colliding delta. indexChanges.commit() stays leader-only.
  2. Those locks are held until the replica has applied its own entry. Locking alone only moved the failure, because reset() released the locks as soon as the quorum acked while this node's pages were still at the old version. waitForLocalApply() could not be reused - a follower's commit index still trails the leader and does not cover the entry just written - so the committed index is carried back from Ratis through RaftGroupCommitter and RaftTransactionBroker, and the replica waits on waitForAppliedIndex. On timeout the wait returns silently, degrading to the previous behaviour rather than failing a transaction the cluster has already committed.

No deadlock: applyChanges takes no file locks, so the apply thread never waits on a committer.

Both halves were measured separately:

Records on a node Conflicts raised Corruption log lines
Before 155 / 450 0 200+
Locking only 302 / 450 4 many
Locking + apply wait 450 / 450 some, all retried 0

Test plan

  • Issue5503ConcurrentFollowerWritesIT - 3 nodes, 3 threads x 150 single-record transactions through a follower handle, retrying NeedRetryException as an application must. Asserts a scan count (count(@rid), not the cached count(*) counter, which would hide a record deleted as malformed) and the full distinct-value set on every node. Fails on main, passes here, stable over 3 consecutive runs.
  • ha-raft unit tests: 770 tests, 0 failures.
  • ha-raft ITs, 69 tests across four targeted batches, 0 failures: write-against-replica and commit-path (RaftEmbeddedWriteAgainstReplicaIT, RaftReplicationWriteAgainstReplicaIT, Raft3PhaseCommitIT, Issue4740Phase2ReconcileIT, Issue4790PhantomCommitOriginSkipIT, Issue5064CommittedRemotelyContractIT, Issue5410AbandonedTicketReleaseIT, OriginNodeSkipIT); replication/concurrency/index (RaftReplicationIT, RaftHTTPGraphConcurrentIT, SuperNodeAppendHAConsistencyIT, Issue5381SlotMergeRaftIT, Issue5443FollowerIndexGapIT, RaftIndexOperations3ServersIT); the read-consistency suites that share waitForAppliedIndex; and the crash/failover suites. The full 105-class IT suite was not run locally - it takes hours.
  • engine unit tests: 10074 tests. The 50 failures are all NoClassDefFoundError: org.graalvm.polyglot.Engine$ImplHolder / "Query engine 'js' was not found", reproduced identically on a pristine worktree at origin/main (eb7739e) - the Graal JS language is not loadable on this JDK. No transaction, bucket, locking or index test failed.

Reviewer notes

  • Follower write throughput drops. Replicas now hold per-file commit locks across the Raft round trip and the local apply, so concurrent writers to the same bucket serialize and retry. This is symmetric with the leader, which already held its locks across its own round trip, but it is a real cost for write-heavy follower workloads. Writes routed to the leader are unaffected.
  • db.transaction(...) on a follower now implies read-your-writes on that node, which it did not before.
  • RaftDictionaryManyNewKeysIT.httpInsertContentWithProgressivelyMoreKeysOnFollower failed once inside a batch with DatabaseIsClosedException, then passed on three subsequent runs including a re-run of the identical batch. Reported as an observed flake rather than proven pre-existing, since this change does slow follower writes and could plausibly aggravate a timing-sensitive follower-write test.
  • Not fixed here: indexChanges.commit() is still skipped on a replica, on the same "demanded to the leader" assumption that proved wrong for locking. Whether index entries for follower-originated writes are actually produced deserves its own investigation; it is orthogonal to this corruption and out of scope.

…he local apply

Concurrent transactions on a shared follower Database handle corrupted records and
lost committed writes: 155 of 450 single-record transactions survived, with 200+
"Invalid record size ... deleting record" lines and no conflict ever reported.

commit1stPhase(false) skipped the per-file commit locks, on the assumption recorded
in PageManager.publishPages that the single-threaded Raft apply serialized replicas.
It only orders the write side. Nothing ordered the capture side, so concurrent
transactions all validated against the same base page version and each shipped a
delta stamped with the same next version. applyChanges applied the first and then
met the others at EQUAL version, which is deliberately re-applied to repair torn
writes (#4926) - splicing partial page images computed against a page that no longer
existed, which is both the corruption and the lost writes.

Replicas now take the same locks as the leader (and the #4937 late-joiner union check
that keeps the lock set complete), so the loser of a race gets a retryable
ConcurrentModificationException instead of shipping a colliding delta.

Locking alone only moved the failure to 302/450: reset() released the locks as soon as
the quorum acked, while this node's pages were still at the old version. The replica
now waits for its own entry to be applied locally before releasing. waitForLocalApply()
could not be reused because a follower's commit index still trails the leader and does
not cover the entry just written, so the committed index is carried back from Ratis
through RaftGroupCommitter and RaftTransactionBroker. On timeout the wait returns
silently, degrading to the previous behaviour rather than failing a transaction the
cluster has already committed.

indexChanges.commit() stays leader-only. applyChanges takes no file locks, so the apply
thread never waits on a committer.
@mergify

mergify Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 76.00% diff coverage · -7.92% coverage variation

Metric Results
Coverage variation ✅ -7.92% coverage variation
Diff coverage ✅ 76.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (eb7739e) 139253 104974 75.38%
Head commit (95107f2) 178208 (+38955) 120231 (+15257) 67.47% (-7.92%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#5507) 25 19 76.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review: fix(#5503) - lock modified files on replicas and hold them until local apply

I reviewed the diff plus the surrounding commit path (TransactionContext.commit1stPhase/commit2ndPhase, RaftReplicatedDatabase.replicateAndCommitLocally, RaftGroupCommitter, TransactionManager.applyChanges, waitForAppliedIndex). This is a genuinely strong PR - the root-cause writeup in docs/5503-*.md is excellent, both halves of the fix are shown to be load-bearing, and the code comments carry the reasoning at every non-obvious spot. Below are verifications and a few points worth considering.

Correctness - things I checked and they hold up

  • Memory visibility of logIndex is correct. CancellablePendingEntry.logIndex is volatile and set at RaftGroupCommitter:523 before future.complete(null) at :524. The submitter only reads pending.logIndex after pending.future.get(...) returns, so the CompletableFuture completion supplies the happens-before edge. On every failure path the future is completed with an exception (so submitAndWait throws) and logIndex stays -1 - never read stale.
  • No deadlock, as claimed. applyChanges (TransactionManager:474) takes no per-file commit locks, and waitForAppliedIndex blocks on the applyNotifier monitor, not on any lock the apply thread needs. The committing thread at the wait point holds only the phase-1 file locks (not the PageManager global lock or a schema/read lock - phase-1's read lock was already released at RaftReplicatedDatabase:383), so the single-threaded apply can always make progress. Confirmed.
  • Lock release on the error paths. Since replicas now hold real file locks (previously lockedFiles was an empty list), I checked every exit of replicateAndCommitLocally: the DispatchedTimeout/ArcadeDBException/generic branches call rollback(), and the MajorityCommittedAllFailed branch reaches commit2ndPhase(...) -> reset(). Both rollback() and reset() unlock lockedFiles (TransactionContext:1058 / :1635). No new lock leak.
  • Retryability contract. Both ConcurrentModificationException and LockTimeoutException extend NeedRetryException, so the test's retry loop (and the "either commit or fail retryably" contract) is sound.

Points worth considering

  1. Timeout degradation silently reopens the corruption window. On waitForAppliedIndex timeout the wait returns, then reset() releases the locks while local pages are still at the pre-commit version - exactly the pre-HA: concurrent transactions on a shared follower Database handle corrupt records and lose committed writes #5503 state that produced the torn pages. The path does log a WARNING (waitForAppliedIndex(idx) -> throwOnTimeout=false -> the READ_YOUR_WRITES warning at RaftHAServer:2138), so it is observable, but that line reads as a read-consistency degradation, not "we may now corrupt pages." Consider a dedicated WARNING at the commit site so an operator seeing sustained apply-lag understands the actual risk being taken.

  2. New failure mode for follower writers: LockTimeoutException. Holding per-file commit locks across the Raft round trip and the apply wait means concurrent writers to the same bucket can now hit COMMIT_LOCK_TIMEOUT where before they would not. It is retryable (extends NeedRetryException) and the test retries it, but this is a behavior change for applications that previously only handled ConcurrentModificationException on follower writes. Worth an explicit line in the reviewer notes / release notes.

  3. raftHAServer field read vs requireRaftServer(). At :475 the code reads the field directly with a raft != null guard, whereas replication above uses requireRaftServer(). Given committedLogIndex > 0 already implies replication succeeded (field non-null), the guard is just shutdown-race defensiveness - fine, but a one-line comment on why this deliberately avoids requireRaftServer() (don't throw after the cluster already committed) would head off a future "why the inconsistency?" question.

  4. Replicas now lock index files they never commit. lockFilesFromChanges() calls indexChanges.addFilesToLock(...), so replicas take locks on index files even though indexChanges.commit() stays leader-only. Benign for correctness (and it keeps the late-joiner union check consistent), but it is extra contention on index files for follower writes. Combined with the open question you already flagged (are follower-originated index entries actually produced by the leader?), this reinforces that the indexChanges-on-replica story deserves its own follow-up.

Tests

  • Issue5503ConcurrentFollowerWritesIT is well-constructed: asserting on count(@rid) (a real scan) rather than the cached count(*) counter is exactly right for catching a record deleted as malformed, and checking the full distinct-value set on every node catches both loss and divergence. The before/locking-only/locking+wait table is convincing evidence both halves are needed.
  • Minor: the retry loop spins with no backoff (MAX_RETRIES = 100) - fine for a test, just hot-spins under heavy contention. Not worth changing.
  • The logIndex plumbing and the timeout-degradation branch are only covered indirectly through the IT. A small unit test on RaftGroupCommitter.submitAndWait returning the committed index (and -1 on failure paths) would lock in the contract cheaply - optional.

Style / conventions

Consistent with the codebase: final on locals/params, imported names (no FQNs), issue-referenced comments matching the existing #49xx/#5xxx convention, Apache headers present, no stray System.out, no new dependencies. Nothing to flag.

Overall: a solid, well-reasoned, well-tested fix for a nasty silent-corruption bug. The points above are mostly documentation/observability nits, not blockers.

…x contract

From the review on PR #5507:

- The apply wait degrades to best-effort on timeout, and releasing the commit locks
  with the local pages still behind is the pre-#5503 condition. waitForAppliedIndex
  already logs, but as a READ_YOUR_WRITES *consistency* warning, which reads like a
  stale-read risk rather than a page-corruption one. The replica branch now logs its
  own WARNING naming the risk and pointing at state machine apply lag.
- Documented why the replica branch reads the raftHAServer field directly instead of
  going through requireRaftServer(): the cluster has already committed the entry, so a
  shutdown race must not surface as "retry me".
- Two unit tests pin the submitAndWait contract: the committed log index is returned on
  success, and every failure path throws rather than handing back an index to wait on.
  Verified the first fails (expected 4242, got -1) with the publication removed.
- Tracking doc records the new LockTimeoutException failure mode for follower writers,
  and that replicas now lock index files they never commit.
@claude

claude Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review: fix(#5503) - lock modified files on replicas and hold them until local apply

Thorough, well-reasoned fix. The root-cause writeup (check-then-act version validation made non-atomic because replicas skipped the commit lock, then the equal-version repair path from #4926 splices two partial deltas) is convincing, and the two halves are each demonstrated load-bearing by the before/locking-only/locking+apply-wait table. I traced the concurrency argument and it holds up. A few things worth surfacing before merge.

What I verified and agree with

  • No deadlock. TransactionManager.applyChanges takes no per-file commit locks (it operates page-by-page via PageManager), so the apply thread never blocks on a committer holding those locks while the committer waits on the apply. Confirmed.
  • logIndex is per-entry correct. In flushBatch each entry has its own futures[i]/reply, so batch.get(i).logIndex = reply.getLogIndex() is the right index for that entry, not a shared batch value.
  • Publication safety. logIndex is volatile and written before future.complete(null); submitAndWait reads it only after future.get() returns, so the happens-before is sound.
  • Lock release paths. reset() (line 495) and the failure paths (rollback() / commit2ndPhase via the catch blocks) all release the file locks acquired in phase 1, so the newly-held replica locks do not leak on the normal or error exits.
  • Graceful degradation. waitForAppliedIndex(idx) passes throwOnTimeout=false, so a timeout returns silently and reset() still runs, degrading to pre-HA: concurrent transactions on a shared follower Database handle corrupt records and lose committed writes #5503 behavior rather than failing an already-committed write. Reading raftHAServer directly (instead of requireRaftServer()) to avoid turning a shutdown race into a spurious NeedRetryException is a nice touch.

Main concern: lock hold time vastly exceeds COMMIT_LOCK_TIMEOUT

Replicas now hold the per-file commit locks across the whole Raft round trip and the apply wait. With defaults:

  • submitAndWait waits up to 2 * quorumTimeout (= 20 s) for the future, plus a grace window;
  • waitForAppliedIndex then waits up to quorumTimeout (= 10 s);
  • while COMMIT_LOCK_TIMEOUT for other writers is 5 s.

So a single in-flight follower write can hold a bucket's lock for ~20-30 s, during which every other concurrent writer to that bucket fails lockFilesInOrder at 5 s with LockTimeoutException and retries. Under a healthy cluster this is invisible (apply is sub-millisecond), but under leader churn or apply lag the same-bucket writers effectively serialize and burn retries, and Issue5503ConcurrentFollowerWritesIT caps at MAX_RETRIES=100, so a slow CI cluster could make the very test that guards this flaky. This is plausibly the mechanism behind the RaftDictionaryManyNewKeysIT flake you already noted. The correctness tradeoff is right, but it is worth considering a dedicated, shorter bound for the apply-wait (it is a purely local catch-up, not a quorum operation, so 10 s is generous), and a release note is warranted since LockTimeoutException is a genuinely new failure mode for follower writers that previously took no locks.

Minor

Tests

Good coverage. The IT asserting count(@rid) (scan) rather than count(*) (cached counter) is exactly right for catching records deleted as malformed, and asserting the full distinct-value set on every node catches both loss and corruption. The two RaftGroupCommitterTest cases pin the contract that matters (real index returned on success, throw-not-fabricate on failure). One suggestion: consider tagging the IT @Tag("slow") per CLAUDE.md, since 3 nodes x 450 retryable transactions with a 5-minute join budget is a multi-second functional regression test.

Overall this is a solid fix to a serious silent-corruption bug, with unusually good documentation and honest impact analysis. The lock-hold-time amplification is the one thing I would want addressed or explicitly accepted (with a release note) before merge.

Second review cycle on PR #5507:

- getLastAppliedIndex() reports -1 while an in-place restart re-initializes the Ratis
  division (#5271), so the new #5503 warning fired on every commit in that window even
  though nothing was racing. Guarded with applied >= 0.
- Tagged Issue5503ConcurrentFollowerWritesIT @tag("slow") per CLAUDE.md: it is a
  multi-second functional regression test. Verified this does not hide it from CI - the
  ha-raft integration job (mvn-test.yml, -pl ha-raft -Pintegration) passes no
  excludedGroups, and sibling ITs such as Issue5064CommittedRemotelyContractIT are
  already tagged the same way.
- Documented the lock-hold-time amplification the review raised: a replica can hold a
  bucket lock for the round trip (2 * quorumTimeout) plus the apply wait (quorumTimeout)
  while other writers give up at COMMIT_LOCK_TIMEOUT. Note the round-trip half is not new
  and not replica-specific - the leader has always held its locks across submitAndWait.

Shortening the apply wait, as suggested, was considered and deliberately NOT done: the
timeout branch is exactly the one that releases the locks with stale pages and reopens the
corruption window, so a shorter bound makes the dangerous path more reachable to buy back
a few seconds of contention. The contention is accepted and documented instead.
@claude

claude Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review: fix(#5503) - lock modified files on replicas and hold until local apply

I traced the full commit path (RaftReplicatedDatabase.commit -> commit1stPhase(false) -> replicateAndCommitLocally -> reset()), the state-machine apply path, and the lock lifecycle. This is a careful, well-reasoned fix with an excellent write-up. The root-cause narrative (capture side unordered, equal-version re-apply from #4926 splicing partial page images) is convincing, and the before/locking-only/locking+wait table demonstrates both halves are genuinely load-bearing.

Correctness - the design holds up

  • Lock release on every exit is covered. The now-real replica locks are released via payload.tx().reset() on the happy path and via rollback() -> reset() on every replication failure branch (MajorityCommittedAllFailedException, ReplicationDispatchedTimeoutException, ArcadeDBException, generic). Previously lockedFiles was an empty list so release was a no-op; the release paths were already correct, so no leak is introduced.
  • No deadlock. Confirmed ArcadeStateMachine.applyTxEntry -> TransactionManager.applyChanges takes no per-file commit locks, so the apply thread never blocks on a committer holding file locks while that committer waits in waitForAppliedIndex. The claim in the PR body is accurate.
  • The apply-wait premise is sound. A follower-originated write is not "locally originated" from the follower's state-machine perspective (Ratis startTransaction / setStateMachineContext runs leader-side; the context is not shipped in the log), so applyTxEntry does not origin-skip it on the originating follower - it runs applyChanges and writes the pages, and lastAppliedIndex advances only after that. Waiting on committedLogIndex therefore genuinely gates on the page write. This is the subtle invariant the whole fix rests on, and it checks out.
  • submitAndWait contract. logIndex is volatile, defaults to -1, is set from reply.getLogIndex() only on the success branch before completing the future, and every failure path throws. The two new unit tests pin exactly this. The return-type change void -> long is source-compatible for the other callers I checked.

Points worth confirming

  1. Explicit-lock transactions on a follower now take a different path. Before this PR, a replica's commit1stPhase(false) skipped all lock logic, including checkExplicitLocks / checkExplicitLocksForUnion. Now those run on replicas too, and the late-joiner block changed from if (isLeader && lockedFiles != null) to if (lockedFiles != null). For an explicit-lock transaction committed through a follower handle, checkExplicitLocksForUnion can now throw where it previously never did. Arguably more correct (the contract is now enforced symmetrically), but it is a behavior change for follower explicit-lock writes that the write-up doesn't call out. Worth a targeted test or at least a note, since the IT only exercises auto-locked single-record inserts.

  2. Double WARNING on apply-wait timeout. waitForAppliedIndex(target) (lenient) already logs a READ_YOUR_WRITES consistency timeout WARNING on timeout, and the new replica branch then logs its own #5503 WARNING. Intentional per the comment (naming the corruption risk vs. a stale-read risk), but operators will see two WARNINGs per lagging commit. Consider whether the lenient overload's log is redundant here, or make the pairing explicit so it doesn't read like duplicate noise.

  3. Benign race in the warning gate. raft.getLastAppliedIndex() is re-read after waitForAppliedIndex returns; apply can advance in between, so the applied < committedLogIndex check is slightly racy. Only affects whether the WARNING fires (not correctness) - noting it for completeness.

Performance / operational

The author has already documented the throughput cost, the LockTimeoutException new failure mode, and the lock-hold-time-vs-COMMIT_LOCK_TIMEOUT amplification thoroughly in docs/5503-...md, and the decision not to shorten the apply wait (a shorter bound makes the corruption-reopening branch more reachable) is the right call for a silent-corruption fix. The indexChanges locking-without-committing on replicas is correctly flagged as a follow-up.

Test coverage

  • Issue5503ConcurrentFollowerWritesIT is a strong regression test: it asserts count(@rid) (a real scan, not the cached counter that would mask a deleted-as-malformed record) and the full distinct-value set on every node, honors the retry contract, is correctly @Tag("slow") per CLAUDE.md, and verified to fail on main.
  • The two RaftGroupCommitterTest additions pin the index-return contract, including the "throws rather than returning a fabricated index" failure case.
  • Minor: the new IT carries @author Luca Garulli while the PR author differs - cosmetic.

Verdict

Solid, well-tested fix for a serious silent-corruption/lost-write bug, with unusually thorough documentation of the residual trade-offs. My only substantive ask is confirming the follower explicit-lock path (point 1), since that's the one behavior that changed for replicas without direct test coverage. Nice work.

Reviewed by Claude (automated). Not a substitute for human review.

@robfrank
robfrank merged commit 0f414e8 into main Jul 28, 2026
22 of 26 checks passed
@codecov

codecov Bot commented Jul 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.00000% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.24%. Comparing base (eb7739e) to head (95107f2).
⚠️ Report is 12 commits behind head on main.

Files with missing lines Patch % Lines
...rcadedb/server/ha/raft/RaftReplicatedDatabase.java 40.00% 5 Missing and 1 partial ⚠️
...java/com/arcadedb/database/TransactionContext.java 90.90% 0 Missing and 1 partial ⚠️
...arcadedb/server/ha/raft/RaftTransactionBroker.java 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5507      +/-   ##
============================================
- Coverage     66.32%   65.24%   -1.08%     
- Complexity        0     1115    +1115     
============================================
  Files          1698     1745      +47     
  Lines        139253   146209    +6956     
  Branches      30160    31260    +1100     
============================================
+ Hits          92357    95393    +3036     
- Misses        34317    37895    +3578     
- Partials      12579    12921     +342     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

robfrank added a commit that referenced this pull request Aug 14, 2026
@robfrank
robfrank deleted the fix/5503-follower-concurrent-tx-corruption branch August 26, 2026 09:13
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.

HA: concurrent transactions on a shared follower Database handle corrupt records and lose committed writes

1 participant