Repository navigation
fix(#5503): lock the modified files on replicas and hold them until the local apply - #5507
Conversation
…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.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 0 |
🟢 Coverage 76.00% diff coverage · -7.92% coverage variation
Metric Results Coverage variation ✅ -7.92% coverage variation Diff coverage ✅ 76.00% diff coverage 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.
Review: fix(#5503) - lock modified files on replicas and hold them until local applyI reviewed the diff plus the surrounding commit path ( Correctness - things I checked and they hold up
Points worth considering
Tests
Style / conventionsConsistent with the codebase: 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.
Review: fix(#5503) - lock modified files on replicas and hold them until local applyThorough, well-reasoned fix. The root-cause writeup ( What I verified and agree with
Main concern: lock hold time vastly exceeds
|
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.
Review: fix(#5503) - lock modified files on replicas and hold until local applyI traced the full commit path ( Correctness - the design holds up
Points worth confirming
Performance / operationalThe author has already documented the throughput cost, the Test coverage
VerdictSolid, 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. |
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
Closes #5503
Summary
Concurrent transactions issued through a shared follower
Databasehandle corrupted records and silently lost committed writes.TransactionContext.commit1stPhase(false)skipped the per-file commit locks, on the assumption recorded inPageManager.publishPagesthat "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.applyChangesapplied 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:
ConcurrentModificationExceptioninstead of shipping a colliding delta.indexChanges.commit()stays leader-only.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 throughRaftGroupCommitterandRaftTransactionBroker, and the replica waits onwaitForAppliedIndex. On timeout the wait returns silently, degrading to the previous behaviour rather than failing a transaction the cluster has already committed.No deadlock:
applyChangestakes no file locks, so the apply thread never waits on a committer.Both halves were measured separately:
Test plan
Issue5503ConcurrentFollowerWritesIT- 3 nodes, 3 threads x 150 single-record transactions through a follower handle, retryingNeedRetryExceptionas an application must. Asserts a scan count (count(@rid), not the cachedcount(*)counter, which would hide a record deleted as malformed) and the full distinct-value set on every node. Fails onmain, passes here, stable over 3 consecutive runs.ha-raftunit tests: 770 tests, 0 failures.ha-raftITs, 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 sharewaitForAppliedIndex; and the crash/failover suites. The full 105-class IT suite was not run locally - it takes hours.engineunit tests: 10074 tests. The 50 failures are allNoClassDefFoundError: org.graalvm.polyglot.Engine$ImplHolder/ "Query engine 'js' was not found", reproduced identically on a pristine worktree atorigin/main(eb7739e) - the Graal JS language is not loadable on this JDK. No transaction, bucket, locking or index test failed.Reviewer notes
db.transaction(...)on a follower now implies read-your-writes on that node, which it did not before.RaftDictionaryManyNewKeysIT.httpInsertContentWithProgressivelyMoreKeysOnFollowerfailed once inside a batch withDatabaseIsClosedException, 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.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.