Repository navigation
fix(#4936,#4937): the WAL append is the commit's point of no return - #5053
Conversation
#4936 (HIGH): commit phase 2 appended the transaction to the WAL FIRST and validated the page versions after (inside updatePages). A phase-2 validation failure - reachable through the late-joining-files hole below - aborted the transaction while its record stayed in the WAL with no abort marker. Crash recovery then replayed the aborted transaction's OTHER pages (version == disk+1) while the conflicted page was skipped: a partial application of an aborted transaction - torn multi-page records, index entries pointing at data never committed. updatePages is split into validateAndBumpVersions (validates against the most recent committed version and bumps the transaction-private page versions) and publishPages (read cache + flush scheduling + page counters). commit2ndPhase now runs validate -> WAL append -> publish, so a WAL record can only ever exist for a transaction that can no longer fail validation. The bump mutates only the transaction's own MutablePage instances: a WAL append failure (e.g. interrupt) still aborts cleanly with nothing observable, and the phase-1 WAL buffer already serializes version+1, so the reorder changes no on-disk format. writeTransactionToFile never reads live page versions (verified) - it only appends the pre-built buffer and attaches the ack bookkeeping. #4937 (HIGH, the enabler): files can join the transaction's page set AFTER the commit lock set is computed - EXTERNAL-property buckets written during phase-1 serialization, indexes created inside the transaction (written directly at COMMIT_1ST_PHASE), and the vector index's companion graph file, which addFilesToLock omitted entirely. Their pages passed the version checks WITHOUT their file lock held. Two-layer fix: LSMVectorIndex getFileIds() now includes the graph file and addFilesToLock consumes getFileIds (plural), covering any multi-file index; and a generic phase-1 safety net verifies - after ALL page-set mutation - that every file in modifiedPages/newPages is locked, releasing and re-acquiring the UNION in order when a late joiner is found (the version checks that follow catch anything that changed while unlocked with the standard retriable CME). In explicit-lock mode an uncovered file surfaces as the contract violation it is instead of being silently re-locked. Red-first verified: on the old ordering, a transaction that failed phase-2 validation left its bytes in the WAL; now the WAL is byte-identical before and after the failed commit. Union sweep with the companion WAL-recovery branch: 372 classes, 2851 tests, 0 failures; the ordering test re-verified green on this branch alone. NOTE for reviewers: this is the highest-blast-radius change of the audit series - it reorders every commit in the engine. Split into its own PR precisely so it gets focused review.
|
Tick the box to add this pull request to the merge queue (same as
|
Not up to standards ⛔🔴 Issues
|
| Category | Results |
|---|---|
| CodeStyle | 1 minor |
🟢 Metrics 37 complexity
Metric Results Complexity 37
🟢 Coverage 94.59% diff coverage · -7.20% coverage variation
Metric Results Coverage variation ✅ -7.20% coverage variation Diff coverage ✅ 94.59% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (b4ddc6c) 134938 100463 74.45% Head commit (fbc9f1f) 166841 (+31903) 112204 (+11741) 67.25% (-7.20%) 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 (#5053) 74 70 94.59% 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.
There was a problem hiding this comment.
Code Review
This pull request refactors the transaction commit process to make the WAL append the point of no return, preventing crash recovery from replaying aborted transactions. It validates and bumps page versions before the WAL append, and verifies lock coverage for late-joining files. The review feedback identifies a critical bug where the explicit lock safety check is bypassed because explicitLockedFiles is always null at that point, and suggests an optimization to combine two redundant loops over lockedFiles into a single loop.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| if (explicitLockedFiles != null) | ||
| // The user's explicit lock list does not cover files this transaction actually modified: | ||
| // re-locking on their behalf would defeat the explicit-locking contract - surface it instead. | ||
| checkExplicitLocks(union); |
There was a problem hiding this comment.
Bug: Explicit Lock Safety Check Bypassed
Issue: explicitLockedFiles is guaranteed to be null at line 750 because checkExplicitLocks(modifiedFiles) (called on line 680) sets explicitLockedFiles = null on line 1121 [1]. As a result, the check if (explicitLockedFiles != null) will always evaluate to false, and the safety check for explicit locks will be silently bypassed, violating the explicit-locking contract.
Fix: Capture whether explicit locks were used in a boolean flag (e.g., final boolean isExplicitLock = explicitLockedFiles != null;) at the start of commit1stPhase before checkExplicitLocks is called. Then, check that flag here and temporarily restore explicitLockedFiles = lockedFiles; before calling checkExplicitLocks(union); so that the union is validated against the original explicit locks.
| if (explicitLockedFiles != null) | |
| // The user's explicit lock list does not cover files this transaction actually modified: | |
| // re-locking on their behalf would defeat the explicit-locking contract - surface it instead. | |
| checkExplicitLocks(union); | |
| if (isExplicitLock) { | |
| explicitLockedFiles = lockedFiles; | |
| checkExplicitLocks(union); | |
| } |
| final IntHashSet lockedSet = new IntHashSet(); | ||
| for (final int fileId : lockedFiles) | ||
| lockedSet.add(fileId); | ||
|
|
||
| final IntHashSet union = new IntHashSet(); | ||
| boolean lateJoiners = false; | ||
| for (final int fileId : lockedFiles) | ||
| union.add(fileId); |
There was a problem hiding this comment.
Optimization: Single Loop for Set Population
This code iterates over lockedFiles twice to populate lockedSet and union with the exact same elements. We can optimize this into a single loop to avoid redundant iterations and improve efficiency.
| final IntHashSet lockedSet = new IntHashSet(); | |
| for (final int fileId : lockedFiles) | |
| lockedSet.add(fileId); | |
| final IntHashSet union = new IntHashSet(); | |
| boolean lateJoiners = false; | |
| for (final int fileId : lockedFiles) | |
| union.add(fileId); | |
| final IntHashSet lockedSet = new IntHashSet(); | |
| final IntHashSet union = new IntHashSet(); | |
| for (final int fileId : lockedFiles) { | |
| lockedSet.add(fileId); | |
| union.add(fileId); | |
| } | |
| boolean lateJoiners = false; |
|
Review: fix(#4936,#4937) - WAL append as the commit point of no return Reviewed the reordering of What checks out
Issue worth addressing (medium): the explicit-lock branch in the late-joiner block is unreachable In if (lateJoiners) {
if (explicitLockedFiles != null)
checkExplicitLocks(union); // intended: surface the contract violation
else {
database.getTransactionManager().unlockFilesInOrder(lockedFiles, getRequester());
lockedFiles = lockFilesInOrder(union); // silently re-lock the union
}
}By the time this block runs, Net effect: not a crash (the union re-lock is safe), but it contradicts the documented intent and means explicit-lock users will not get the Minor / nits
Overall a well-reasoned, high-value durability fix with good inline documentation. The one behavioral gap above is the dead explicit-lock branch; everything else in the reorder holds up. Automated review - please verify findings independently. |
…heck The reviewer correctly found that the explicit-lock branch of the late-joiner block was unreachable: checkExplicitLocks nulls explicitLockedFiles on its success path (moving the set into lockedFiles), so by the time the late-joiner block ran, explicitLockedFiles was always null. An explicit-lock transaction that picked up a genuine late joiner (an EXTERNAL property's paired bucket, an index written mid-tx) therefore fell into the else branch and had its lock set SILENTLY EXPANDED - exactly the explicit-locking-contract violation the comment said it wanted to avoid, and the opposite of the direct-modification behavior (ExplicitLockingTransactionTest already pins that direct case). Fix: capture the explicit-lock mode into a boolean BEFORE checkExplicitLocks nulls the field, and branch the late-joiner block on that. A new checkExplicitLocksForUnion surfaces an uncovered late joiner as the same 'not all the modified resources were locked' contract violation instead of re-locking on the user's behalf. New regression test (WalCommitOrderingTest): an explicit type-lock transaction that updates an EXTERNAL property - whose paired bucket is a real late joiner, since collectTypeFileIds omits external buckets and the write happens in phase-1 serialization after the initial explicit-lock check - is now rejected with the contract violation. Red-first verified: on the pre-review code the commit silently succeeded. Also from the review: - Dropped the now-unnecessary reflection in WalCommitOrderingTest (putPageInReadCache is package-private since #5011) and replaced the inline FQNs with the imported names. - Single-pass late-joiner detection: IntHashSet.add returns true for a new file id, so the union build and the late-joiner test are now one pass. Clean regression (no concurrent build): 119 classes, 606 tests, 0 failures across the commit path, explicit-locking, external-property and async suites.
Review: fix(#4936,#4937) - WAL append as the commit's point of no returnI reviewed the full diff against the engine commit path. This is a high-quality, well-reasoned change and the core reordering is sound. Below is my detailed feedback. Correctness (the core reorder) - looks correct
#4937 late-joiner coverage - solid, with minor notes
Issues and suggestions
Test coverageGood: both the WAL-record invariant (red-first verified per the description) and the explicit-lock contract violation are covered, and the second is a true regression test that was red on the pre-review code. Nice. SummaryThe reordering is well-justified and, as far as I can trace, correct and format-compatible. The only changes I'd ask for before merge are the FQN style cleanup (#1) and a decision on the migrated-file gap in |
…ion-gap note; test polish Point-by-point from the second review round: 1. FQN style: imported DocumentType, Type and RID in the explicit-lock regression test instead of inline fully-qualified names. 2. checkExplicitLocksForUnion and the migrated-file translation: documented why mirroring it is unnecessary rather than adding dead defensive logic. The migration race checkExplicitLocks handles lives in the window between snapshotting file ids and acquiring the locks; by the time the late-joiner check runs, the explicit locks have been held continuously since the user's lock() call (explicitLock -> lockFilesInOrder at line ~996), and compaction's splitIndex must tryLockFile the file it migrates (LSMTreeIndex:622) - so no file in lockedFiles can have been migrated while this transaction runs. A missing file here is genuinely unlocked, never a stale id of a locked one. Verified both call sites in source. 3. Hot-path allocation: the late-joiner block no longer allocates on the common path. A boxing-free linear scan over lockedFiles (small, typically under 10 entries) detects late joiners first; the union IntHashSet is built only when one is actually found (the rare path that re-locks). 4. Wider CME window on late-joiner re-lock: acknowledged as noted - correctness is preserved by the version checks that follow, the path is rare, and lock-ordering discipline forbids acquiring extra locks in place. No change. 5. Test isolation: the injected conflicting CachedPage is now explicitly evicted from the JVM-global PageManager.INSTANCE read cache after the assertion, so it cannot bleed into other tests sharing the JVM. Also took the reviewer's suggestion to state at publishPages itself that the split-lock window is safe only because callers hold the per-file commit locks until reset(). Regression: 119 classes, 606 tests, 0 failures across the commit path, explicit-locking, external-property, database and engine suites.
Review:
|
…unwrapped contract errors 1. publishPages javadoc no longer overstates the invariant: it now names both serialization regimes. On a leader the per-file commit locks (held until reset()) protect the gap between the two lock() halves; on an HA follower commit1stPhase(false) leaves lockedFiles EMPTY and the single-threaded Raft apply in RaftReplicatedDatabase provides the serialization instead - verified against RaftReplicatedDatabase:331/430. A future reader must not rely on file locks being held on that path. 2. updatePages has zero callers repo-wide after the split (verified across engine, server, ha-raft, gremlin, integration). Kept as public API for embedded users and backward compatibility, with an explicit note that the engine commit path no longer uses it and that validate+publish are NOT atomic under one lock there - so it no longer reads as a live path. 3. getFileIds() read lock on the commit path: conscious ack, no change. It is one uncontended ReentrantReadWriteLock CAS per touched index per commit, contended only while a concurrent splitIndex swaps the mutable/compacted pair - and in exactly that race the lock is what makes the returned id pair consistent, which the lock-set needs. The lock-free alternative would reintroduce the stale-id window the migration-retry machinery exists to paper over. 4. Error double-wrapping: commit1stPhase now rethrows TransactionException as-is (rollback still runs) instead of nesting it inside a generic 'Transaction error on commit'. Users of the explicit-lock contract violation now see the real message directly; no test or caller depended on the wrapped form (verified: callers catch the type, not the message). The regression test asserts hasMessage instead of hasRootCauseMessage. 5. Reworded the containsFileId comment: 'allocation-free' with the honest caveat that get(i) == fileId unboxes the stored Integer - nothing new is allocated, but 'boxing-free' overstated it. Regression: commit path, explicit-locking, external-property and database suites green.
Review: fix(#4936,#4937) - WAL append as the commit's point of no returnThorough, well-documented change. I traced the reordering through Correctness - verified points
Things worth considering
Test coverageBoth tests are on point: Nice work isolating this into its own PR given the blast radius. None of the notes above are blockers. |
…s documented; test polish 1. Late-joiner scan cost, measured as requested: iterating a 200,000-entry page map with 5 locked files costs ~1.0ms (best of 30, JIT-warmed, live accumulator to defeat dead-code elimination). A transaction that big writes hundreds of MB through the WAL and page pipeline, so the scan is orders of magnitude inside the noise; typical commits (tens to hundreds of pages) see sub-microsecond cost. The accumulate-fileIds-as-staged alternative is noted and agreed as not warranted. 2. Release note now states the commit boundary explicitly: a failure AFTER the WAL append (e.g. while publishing pages) is resolved by recovery replay, never by abort - the caller may see an error for a transaction that becomes durable on restart. Inherent to WAL-as-point-of-no-return and unchanged from the old order, but worth the sentence. 3. The injected conflicting page is now evicted in the finally block (null-guarded), so the JVM-global read cache is clean even when an assertion fails - robust rather than incidental via db.close(). 4. checkExplicitLocksForUnion builds the violation message with a TreeSet: deterministic resource ordering for multi-file messages. (Pre-existing nondeterminism in checkExplicitLocks left untouched.) Commit-path and explicit-locking suites green.
|
Review: fix(#4936,#4937): the WAL append is the commit point of no return Thorough, well-reasoned change. I traced the correctness-critical claims against the source and they hold. Correctness verification (claims that check out)
Design concern worth discussing (not necessarily blocking)
Consider fencing the DB (force read-only / "recovery required") on a post-WAL-append failure rather than silently reset()+unlock. getFileIds() scope broadening (please confirm intended) Minor / style
Tests
Not verified here Overall: the ordering fix is correct and the lock-coverage net closes the enabling hole. Main ask is a clear answer on the post-WAL-append failure semantics (points 1-2) before merge. |
…tFileIds scope confirmed
The design concern was worth more than a comment - implemented the
suggested fence.
1a. Live/WAL divergence: the reviewer's window is real but PRE-EXISTING
(the old WAL-then-updatePages order had the identical exposure for any
non-validation failure) and this PR already NARROWED it by moving
validation - the reachable failure class - ahead of the append. The
residue (IOException while publishing) is now closed with the suggested
fence: LocalDatabase.fenceForRecovery(reason) is set in commit2ndPhase's
finally when a failure occurs AFTER the WAL append, BEFORE reset()
releases the file locks - the volatile write is therefore visible to
any transaction blocked on those locks, so no conflicting WAL record
for the same page versions can follow. The fence surfaces at the
checkDatabaseIsOpen choke point (every new operation) and at an
explicit guard before the WAL append (covers in-flight commits whose
reads bypass the choke point). Close still works: it is the recovery
entry point.
1b. Clean close vs crash: already answered by the #5012 ack gate, no new
code needed. The orphaned record's pages were never queued for flush,
so their WAL acks (bumped at append time) are never released -
getPendingPagesToFlush() > 0 makes the clean close preserve the WAL and
the lock file, and the next open replays the record. 'Durable on
restart' holds for both crash and clean close.
2. getFileIds() broadening confirmed intended, including the compacted
sub-index file: it adds no new serialization between transactions -
any transaction locking the compacted id also locks the mutable id, so
the contender set per index is unchanged - and compaction itself does
not take commit file locks for its appends (only splitIndex's
tryLockFile on the mutable id, which contended before this change
too). The reviewer's observation that this also fixes the latent
add(-1) for composite TypeIndex ids is correct.
3. TransactionException is now rethrown unwrapped by commit2ndPhase too
(same as phase 1, round 3), so first-class errors like the fence are
not buried under 'Transaction error on commit'.
4. java.util.TreeSet::new -> TreeSet::new (java.util.* was imported).
New test: fenced database refuses the WAL point of no return (WAL
byte-identical after the refused commit), fences new operations, and still
closes cleanly. The post-append fence trigger itself is wired in the
finally; forcing a real mid-publish IOException deterministically is not
feasible without fault-injection hooks, so the trigger is covered by code
path inspection and the fence mechanics by the test.
Regression: 118 classes, 577 tests, 0 failures.
Review: fix(#4936,#4937) - WAL append as the commit's point of no returnOverall this is a careful, well-reasoned change and the commit history shows it has already absorbed several rounds of review. The core reorder (validate+bump -> WAL append -> publish) is the right shape, the split of Potential bug:
|
…Ts verified green
1. The reviewer found a genuine bug in the round-5 fence: walAppended was
set unconditionally, outside the 'if (changes.result != null)' guard.
With useWAL=false (the supported bulk-load mode) no WAL record exists,
yet a post-validation publish failure fenced the whole database while
promising a WAL replay that cannot happen - a permanently unusable
database for a transaction that opted OUT of durability, regressing the
pre-PR abort behavior. walAppended is now set inside the guard, exactly
as suggested.
Two regression tests pin it, both driving a REAL post-publish failure
through the live catch/finally (a bogus file id planted in
newPageCounters makes the counter loop after publishPages throw - no
fault-injection hooks needed, which also addresses the reviewer's minor
note that the fence trigger was only exercised by a manual call):
- useWAL=false + publish failure -> aborts, NOT fenced, database keeps
working. RED on the round-5 code (it fenced, with the false promise in
the SEVERE log).
- useWAL=true + same failure -> fenced through the real finally trigger.
2. HA/Raft interaction verified as requested: Issue4740Phase2ReconcileIT
(multi-node), Issue5018Phase2ConflictMessageTest and
DatabaseReconcilerTest all green against this branch (17 tests). The
reconcile flow's fault-injection point fires BEFORE commit2ndPhase, so
those failures abort pre-append and never engage the fence. A genuine
post-append leader failure WOULD fence the local instance - intended,
since it is the same live/WAL divergence hazard; the Raft log still
holds the entry and replay reconciles after reopen.
3. containsFileId now documents its RandomAccess assumption (both
producers return ArrayLists).
Battery: commit path, explicit locking, ACID, tx and async suites green.
Review: fix(#4936,#4937) - WAL append as the commit's point of no returnI reviewed the commit-ordering reorder, the late-joiner lock-coverage fix, and the recovery fence. Overall this is a careful, well-documented change to one of the hottest and most safety-critical paths in the engine, and the reasoning holds up under scrutiny. I verified the central claim that the reorder is on-disk-format neutral, and I have a few points worth discussing before merge. What I verified as correct
Points worth discussing
Nits
Test coverageStrong. Red-first Nice work; the in-comment documentation density is exactly right for a change of this blast radius. |
…hoisted; semantics callouts Point-by-point from the seventh review round (which independently re-verified the WAL-format neutrality, the fence happens-before argument, the late-joiner coverage and the updatePages wrapper safety): 1. Explicit-lock behavioral change: the release note now calls out the full scope - a transaction using explicit locks that writes ANY file absent from its lock list, including files it could not have locked up front (an index created inside the same transaction, an EXTERNAL property's paired bucket), now fails with the contract violation where it previously committed without the lock. Workaround documented: lock the type after creating its indexes, or create indexes outside explicit-lock transactions. 2. Fence width: conscious decision made and documented in the code - the fence deliberately stays WIDE (append through end of try) rather than narrowing to at-or-before publishPages. The decisive argument: a mid-publish failure can leave SOME pages visible and others not, a partial publication no boolean flag can distinguish from a complete one; under-fencing there risks exactly the divergence the fence exists to prevent. Post-publish failures also leave component metadata that recovery replay repairs. The cost - a restart after an exceptional post-append failure - is the acceptable side of that trade. 3. HA follower semantics documented at fenceForRecovery: a replica fences its wrapped LocalDatabase too, halting apply until restart - intended, the fence surfaces exactly like a crash and the standard restart reconciliation (recovery replay or DatabaseReconciler snapshot re-install) repairs the node. 4. Fence pre-check hoisted to the top of commit2ndPhase, before validateAndBumpVersions: the happens-before edge comes from the phase-1 file locks, so nothing required the later placement - a fenced commit now does no wasted validate/bump work. Nits: RandomAccess defensive check declined (hot path; both producers are ArrayLists and the assumption is documented); the reflection coupling in the tests acknowledged - a fault-injection seam is noted as the better long-term shape. Commit path, explicit locking, ACID and tx suites green.
…rollback Two corrections to the #4940 fix, found while cross-verifying it against current main and the pending PR #5053 (point-of-no-return reordering): 1. walAppended was set to true even when changes.result == null, i.e. for useWAL=false transactions that never touch the WAL. A publish failure in such a transaction was treated as "durable, recovery replays it" and only reset() ran - but there is NO WAL record to ever replay, so this kept the exact #4940 defect (dangling RIDs on user-held documents, stale modified records) alive on the useWAL=false path. The flag is now set only after a real append, matching the point-of-no-return boundary #4936/#5053 formalizes; when that PR lands, this placement also prevents its fencing from bricking a useWAL=false database over a failure that recovery could never repair. Red-first: Issue4940Phase2FailureRollbackTest.phase2PublishFailureWithoutWalStillRollsBack fails on the previous placement with "expected: null" (the created record kept its dangling RID after a publish-stage ConcurrentModificationException with useWAL=false) and passes with the corrected one. The test drives phase 1 with useWAL disabled, then bumps the committed version of the transaction's page behind its back so the phase-2 publish fails past the (skipped) WAL stage. 2. The changes == null no-op call was left inside the try, so it fell into the new rollback() branch of the finally instead of the pre-#4940 reset(). Restored as an early return with reset(): a no-op 2nd phase must release resources without touching user-held record state. Tests run (all green): com.arcadedb.database.** (142 incl. the new regression), ACIDTransactionTest, ExplicitLockingTransactionTest, TransactionIsolationTest, TransactionIsolationContractTest, TransactionBucketTest, TransactionTypeTest.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #5053 +/- ##
============================================
+ Coverage 65.47% 65.49% +0.01%
+ Complexity 840 839 -1
============================================
Files 1687 1687
Lines 134938 135038 +100
Branches 28858 28882 +24
============================================
+ Hits 88351 88439 +88
- Misses 34512 34514 +2
- Partials 12075 12085 +10 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…ntics The documented composition, now realized: commit2ndPhase distinguishes three failure regimes in the finally - - committed: resetAndFireCallbacks() as always. - walAppended (the tx IS durable): fence the database (#5053) and reset() WITHOUT touching user-held record state - the RIDs assigned in this tx remain valid because recovery replays the record. - pre-durability failure: rollback() restores user-held records exactly like a phase-1 failure (#4940/#4562) - reload modified records, reset created-record identities to provisional. Plus one interaction discovered by the merged test suites: a fence-REFUSED commit (the fence pre-check throws before this tx appends anything) must NOT roll back - rollback()'s record reload hits the fence choke point itself and replaces the fence error with a confusing secondary failure. That case releases resources only (reset()); the database is unusable until close/reopen anyway. Caught by WalCommitOrderingTest's fence test going red on the naive composition. Union battery green: WalCommitOrderingTest 5/5, Issue4940Phase2Failure- RollbackTest 3/3, Issue4959TransactionCleanupsTest 3/3, TransactionIsola- tionContractTest 2/2, ExplicitLockingTransactionTest 5/5, ACIDTransaction- Test 11/11.
…failure When the Raft quorum durably committed a transaction but the leader's LOCAL phase-2 apply failed, the application received a generic commit failure - told the commit failed while the data was committed cluster-wide. Worse, an application-level retry of the same records INSERTED DUPLICATES: the ArcadeData#4940 rollback reset their identities to provisional, so the retry re-inserted records the cluster already held. Option A from the design discussion, as approved: - New TransactionCommittedRemotelyException (engine exception package, so applications can catch it without an ha-raft dependency): 'committed cluster-wide, do NOT retry, reload the records', with the local reconciliation outcome in the message (reconcileLeaderPagesAfterPhase2Failure now reports success/failure instead of swallowing silently). - TransactionContext gains a remotelyCommitted durability regime, set by the HA layer after quorum commit and before the local phase 2: a local failure past that point releases resources WITHOUT rolling back user-held record identities (the cluster committed them) and WITHOUT fencing (no orphaned local WAL record exists; the Raft layer reconciles the pages from the replicated payload). The regime slots between walAppended and the fence-refused/rollback regimes in commit2ndPhase's finally, composing with ArcadeData#4940/ArcadeData#5053 semantics unchanged for non-replicated databases. The ALL-quorum recovery path gets the same boundary shift. Red-first: Issue5064CommittedRemotelyContractIT (3-node cluster, single-shot post-quorum fault) fails on the pre-fix behavior (raw ConcurrentModificationException escapes, identity reset); green with the fix - distinct type, actionable message, identity preserved, and all three nodes converge on the committed data after the step-down. A baseline write pre-registers the dictionary name so the internal dictionary transaction does not consume the single-shot fault. HA phase-2 battery green (Issue4740Phase2ReconcileIT, Issue5018Phase2ConflictMessageTest, DatabaseReconcilerTest); engine commit-path battery green (WalCommitOrdering, Issue4940, Issue4959, ExplicitLocking, IsolationContract).
…ase, and a guarded request answers for the index asked for (#5775) * fix(engine) #5765: creating a manual index no longer fences the database, and a guarded request answers for the index asked for ManualIndexBuilder.create() registered the new index's file under `index instanceof PaginatedComponent`, a test that never matched: LSMTreeIndex and HashIndex WRAP their paginated component rather than being one. The file stayed unknown to the schema, and the commit that creates it then failed resolving that file id AFTER its WAL append - which fences the database for recovery (#5053). Every manual index creation ended there, and the builder's own error callback threw on the fenced database, replacing the real cause with a bare fence error. Registration goes through index.getComponent() now, the same accessor the type-index path uses, and the cleanup callback no longer throws. Three defects the first one hid, each found by fixing the previous: - Schema.createManualIndex(indexType, ...) dropped its indexType argument, so every call through that deprecated overload failed with a NullPointerException inside the index factory. - A UNIQUE manual index could not commit an entry: TransactionIndexContext's lock collection and its uniqueness check both resolved the index's type name to reach the polymorphic index over the same properties, and a manual index has neither. It is now recognised as its own whole search space, which it is. - withNullStrategy(null) installed the null instead of leaving the default, and the index constructor refused it with "Index null strategy is null". null now means "not specified", the convention withPageSize already follows. An index kind that cannot be built without a type (FULL_TEXT, GEOSPATIAL, LSM_VECTOR, LSM_SPARSE_VECTOR) is refused by name instead of failing inside the factory with a NullPointerException or a ClassCastException. The guarded branch still carried the two defects #5675 removed from TypeIndexBuilder: a request differing only in uniqueness DROPPED the existing index behind a dead `x != null && x == null` null-strategy test, and the index kind was not compared at all. It follows the same rule as the type path now. There is no withReplaceIfIncompatible here: the setter raises on a manual builder, because the replacement it authorises elsewhere is a rebuild from the type's records and here it would be an unrecoverable delete of the only copy of the entries. fix(engine) #5765: CREATE INDEX IF NOT EXISTS compares the settings the METADATA clause named The guard compared the structural definition only - kind and uniqueness - so a guarded statement asking for 768 dimensions over a 384-dimension vector index was a silent no-op, and every vector written afterwards went unindexed. Same for full-text analyzers and geospatial precision. Only the settings the clause actually NAMED are compared, so a statement with no METADATA compares none and stays the no-op it has always been. The clause is read through the index type's own reader before comparing, so "384" and 384, "cosine" and COSINE are the one value each denotes. Both entry points ask the same question through one helper: the IF NOT EXISTS shortcut of CreateIndexStatement, which answers before a builder exists, and TypeIndexBuilder.create(). The read side of each per-type key set is covered by a test that fails if a key is added to one list and not the other. test(engine) #5765: poll for the vector rebuild instead of sleeping a fixed interval Two Thread.sleep(6_000) + hard assertion pairs in LSMVectorIndexRecoveryTest, and the ceilings in LSMVectorIndexRebuildTest computed as a multiple of the inactivity timeout - which makes the wait shortest exactly where the work is slowest. Four of them failed in a whole-package run here and passed in isolation. They share one absolute ceiling now; the class also runs faster, since a poll returns as soon as the rebuild lands. chore(engine) #5765: CREATE INDEX and REBUILD INDEX log their progress instead of printing dots to stdout * docs(engine) #5765: mark the guarded-create settings comparison BREAKING, and say why the builder path does not re-wrap the clause Review follow-ups on #5775, both documentation-level. - The release note now frames the settings comparison as what it is for anyone with a re-runnable schema script: a guarded CREATE INDEX naming a setting MAY NOW RAISE where it used to be a no-op, including for the runtime-tunable keys a rebuild would not be needed to change (efSearch, mutationsBeforeRebuild, inactivityRebuildTimeoutMs, the cache sizes). Both ways back to an idempotent statement are spelled out: drop the keys the script does not actually require, or align the value with the existing index. - TypeIndexBuilder.create() calls findUnsatisfiedSettings without the try/catch the CreateIndexStatement shortcut wraps its own call in, and the invariant that makes that safe is now written down rather than implied: the SQL branches call withMetadata and withUserMetadata inside one try, so the clause has already been read - and any unreadable value already reported - before create() runs. A caller that sets the user clause without the parsed one has skipped that validation and gets the reader's own message; there is no such caller, and adding a second error path would only re-type an exception the reader already words correctly. Verified against the review's third ask: no CREATE INDEX IF NOT EXISTS with a METADATA clause exists outside engine/, and RemoteSchema.getOrCreateTypeIndex builds its guarded statement without one, so nothing outside the engine reaches the new comparison. Server module re-run against a freshly installed engine: 687 tests, 0 failures. * fix(engine) #5765: copy the user METADATA clause into the builder, and assert the file registration directly Round-two review follow-ups on #5775. - withUserMetadata deep-copies the clause. The callers hand the SAME JSONObject to withMetadata(JSONObject) and to withUserMetadata, and the two are read at different times: the first now, the second at create(). No withMetadata overload mutates it today - all four read it through fromUserMetadata - but the copy costs nothing at DDL time and means a future one could not silently change what a guarded request ends up comparing against. - A test asserts the registration itself rather than inferring it from the other tests happening to run. The index's file must resolve through the schema by its id, which is the call TransactionContext.commit2ndPhase makes for every file whose page count changed - past the WAL append, which is why an unregistered file fenced the database instead of failing the creation. The test pins the cause (getFileById resolves to the index's own component) and the consequence (the database still commits an unrelated write afterwards, which a fenced one cannot). Mutation-checked: restoring the `instanceof PaginatedComponent` test reproduces "commit of tx 4 failed after its WAL append". Three other review points taken as no-action, with reasons: refusing runtime-tunable settings on a guarded create is the intended semantics and is already documented as BREAKING; the TypeIndexBuilder invariant comment is the right mitigation for a caller shape that does not exist; and the mismatch message wording is already covered by tests. * refactor(engine) #5765: declare the METADATA statement directives once instead of stripping them per site Round-three review follow-up on #5775, the one observation with something to act on. "buildGraphNow" was removed at two sites - the IF NOT EXISTS reader and the LSM_VECTOR creation branch - because it directs the statement rather than configuring the index, so no index stores it and everything that reads the clause as configuration rejects it: fromUserMetadata refuses an unknown key, and the guarded comparison would report a mismatch for something an existing index cannot have. Both turn a well-formed statement into a 400. The key space is now one named DIRECTIVE_METADATA_KEYS set behind a stripDirectives() helper, so a future "do X now" key on another index type has an obvious place to be declared rather than being stripped at whichever site happens to notice it. No behaviour change: the same one key is removed in the same two places. Two other observations in that review need no change and are recorded here as judged: a future setter that cross-validates one METADATA key against another could validate against the default rather than the existing index's value when only one of the pair is named (no such coupling exists - every setter validates its own value), and the per-100k progress logging interval is already where it should be.
…heck The reviewer correctly found that the explicit-lock branch of the late-joiner block was unreachable: checkExplicitLocks nulls explicitLockedFiles on its success path (moving the set into lockedFiles), so by the time the late-joiner block ran, explicitLockedFiles was always null. An explicit-lock transaction that picked up a genuine late joiner (an EXTERNAL property's paired bucket, an index written mid-tx) therefore fell into the else branch and had its lock set SILENTLY EXPANDED - exactly the explicit-locking-contract violation the comment said it wanted to avoid, and the opposite of the direct-modification behavior (ExplicitLockingTransactionTest already pins that direct case). Fix: capture the explicit-lock mode into a boolean BEFORE checkExplicitLocks nulls the field, and branch the late-joiner block on that. A new checkExplicitLocksForUnion surfaces an uncovered late joiner as the same 'not all the modified resources were locked' contract violation instead of re-locking on the user's behalf. New regression test (WalCommitOrderingTest): an explicit type-lock transaction that updates an EXTERNAL property - whose paired bucket is a real late joiner, since collectTypeFileIds omits external buckets and the write happens in phase-1 serialization after the initial explicit-lock check - is now rejected with the contract violation. Red-first verified: on the pre-review code the commit silently succeeded. Also from the review: - Dropped the now-unnecessary reflection in WalCommitOrderingTest (putPageInReadCache is package-private since #5011) and replaced the inline FQNs with the imported names. - Single-pass late-joiner detection: IntHashSet.add returns true for a new file id, so the union build and the late-joiner test are now one pass. Clean regression (no concurrent build): 119 classes, 606 tests, 0 failures across the commit path, explicit-locking, external-property and async suites. (cherry picked from commit 6f1498f)
…ion-gap note; test polish Point-by-point from the second review round: 1. FQN style: imported DocumentType, Type and RID in the explicit-lock regression test instead of inline fully-qualified names. 2. checkExplicitLocksForUnion and the migrated-file translation: documented why mirroring it is unnecessary rather than adding dead defensive logic. The migration race checkExplicitLocks handles lives in the window between snapshotting file ids and acquiring the locks; by the time the late-joiner check runs, the explicit locks have been held continuously since the user's lock() call (explicitLock -> lockFilesInOrder at line ~996), and compaction's splitIndex must tryLockFile the file it migrates (LSMTreeIndex:622) - so no file in lockedFiles can have been migrated while this transaction runs. A missing file here is genuinely unlocked, never a stale id of a locked one. Verified both call sites in source. 3. Hot-path allocation: the late-joiner block no longer allocates on the common path. A boxing-free linear scan over lockedFiles (small, typically under 10 entries) detects late joiners first; the union IntHashSet is built only when one is actually found (the rare path that re-locks). 4. Wider CME window on late-joiner re-lock: acknowledged as noted - correctness is preserved by the version checks that follow, the path is rare, and lock-ordering discipline forbids acquiring extra locks in place. No change. 5. Test isolation: the injected conflicting CachedPage is now explicitly evicted from the JVM-global PageManager.INSTANCE read cache after the assertion, so it cannot bleed into other tests sharing the JVM. Also took the reviewer's suggestion to state at publishPages itself that the split-lock window is safe only because callers hold the per-file commit locks until reset(). Regression: 119 classes, 606 tests, 0 failures across the commit path, explicit-locking, external-property, database and engine suites. (cherry picked from commit 3080c70)
…unwrapped contract errors 1. publishPages javadoc no longer overstates the invariant: it now names both serialization regimes. On a leader the per-file commit locks (held until reset()) protect the gap between the two lock() halves; on an HA follower commit1stPhase(false) leaves lockedFiles EMPTY and the single-threaded Raft apply in RaftReplicatedDatabase provides the serialization instead - verified against RaftReplicatedDatabase:331/430. A future reader must not rely on file locks being held on that path. 2. updatePages has zero callers repo-wide after the split (verified across engine, server, ha-raft, gremlin, integration). Kept as public API for embedded users and backward compatibility, with an explicit note that the engine commit path no longer uses it and that validate+publish are NOT atomic under one lock there - so it no longer reads as a live path. 3. getFileIds() read lock on the commit path: conscious ack, no change. It is one uncontended ReentrantReadWriteLock CAS per touched index per commit, contended only while a concurrent splitIndex swaps the mutable/compacted pair - and in exactly that race the lock is what makes the returned id pair consistent, which the lock-set needs. The lock-free alternative would reintroduce the stale-id window the migration-retry machinery exists to paper over. 4. Error double-wrapping: commit1stPhase now rethrows TransactionException as-is (rollback still runs) instead of nesting it inside a generic 'Transaction error on commit'. Users of the explicit-lock contract violation now see the real message directly; no test or caller depended on the wrapped form (verified: callers catch the type, not the message). The regression test asserts hasMessage instead of hasRootCauseMessage. 5. Reworded the containsFileId comment: 'allocation-free' with the honest caveat that get(i) == fileId unboxes the stored Integer - nothing new is allocated, but 'boxing-free' overstated it. Regression: commit path, explicit-locking, external-property and database suites green. (cherry picked from commit e2d6950)
…s documented; test polish 1. Late-joiner scan cost, measured as requested: iterating a 200,000-entry page map with 5 locked files costs ~1.0ms (best of 30, JIT-warmed, live accumulator to defeat dead-code elimination). A transaction that big writes hundreds of MB through the WAL and page pipeline, so the scan is orders of magnitude inside the noise; typical commits (tens to hundreds of pages) see sub-microsecond cost. The accumulate-fileIds-as-staged alternative is noted and agreed as not warranted. 2. Release note now states the commit boundary explicitly: a failure AFTER the WAL append (e.g. while publishing pages) is resolved by recovery replay, never by abort - the caller may see an error for a transaction that becomes durable on restart. Inherent to WAL-as-point-of-no-return and unchanged from the old order, but worth the sentence. 3. The injected conflicting page is now evicted in the finally block (null-guarded), so the JVM-global read cache is clean even when an assertion fails - robust rather than incidental via db.close(). 4. checkExplicitLocksForUnion builds the violation message with a TreeSet: deterministic resource ordering for multi-file messages. (Pre-existing nondeterminism in checkExplicitLocks left untouched.) Commit-path and explicit-locking suites green. (cherry picked from commit 225de80)
…tFileIds scope confirmed
The design concern was worth more than a comment - implemented the
suggested fence.
1a. Live/WAL divergence: the reviewer's window is real but PRE-EXISTING
(the old WAL-then-updatePages order had the identical exposure for any
non-validation failure) and this PR already NARROWED it by moving
validation - the reachable failure class - ahead of the append. The
residue (IOException while publishing) is now closed with the suggested
fence: LocalDatabase.fenceForRecovery(reason) is set in commit2ndPhase's
finally when a failure occurs AFTER the WAL append, BEFORE reset()
releases the file locks - the volatile write is therefore visible to
any transaction blocked on those locks, so no conflicting WAL record
for the same page versions can follow. The fence surfaces at the
checkDatabaseIsOpen choke point (every new operation) and at an
explicit guard before the WAL append (covers in-flight commits whose
reads bypass the choke point). Close still works: it is the recovery
entry point.
1b. Clean close vs crash: already answered by the #5012 ack gate, no new
code needed. The orphaned record's pages were never queued for flush,
so their WAL acks (bumped at append time) are never released -
getPendingPagesToFlush() > 0 makes the clean close preserve the WAL and
the lock file, and the next open replays the record. 'Durable on
restart' holds for both crash and clean close.
2. getFileIds() broadening confirmed intended, including the compacted
sub-index file: it adds no new serialization between transactions -
any transaction locking the compacted id also locks the mutable id, so
the contender set per index is unchanged - and compaction itself does
not take commit file locks for its appends (only splitIndex's
tryLockFile on the mutable id, which contended before this change
too). The reviewer's observation that this also fixes the latent
add(-1) for composite TypeIndex ids is correct.
3. TransactionException is now rethrown unwrapped by commit2ndPhase too
(same as phase 1, round 3), so first-class errors like the fence are
not buried under 'Transaction error on commit'.
4. java.util.TreeSet::new -> TreeSet::new (java.util.* was imported).
New test: fenced database refuses the WAL point of no return (WAL
byte-identical after the refused commit), fences new operations, and still
closes cleanly. The post-append fence trigger itself is wired in the
finally; forcing a real mid-publish IOException deterministically is not
feasible without fault-injection hooks, so the trigger is covered by code
path inspection and the fence mechanics by the test.
Regression: 118 classes, 577 tests, 0 failures.
(cherry picked from commit 73a413a)
…Ts verified green
1. The reviewer found a genuine bug in the round-5 fence: walAppended was
set unconditionally, outside the 'if (changes.result != null)' guard.
With useWAL=false (the supported bulk-load mode) no WAL record exists,
yet a post-validation publish failure fenced the whole database while
promising a WAL replay that cannot happen - a permanently unusable
database for a transaction that opted OUT of durability, regressing the
pre-PR abort behavior. walAppended is now set inside the guard, exactly
as suggested.
Two regression tests pin it, both driving a REAL post-publish failure
through the live catch/finally (a bogus file id planted in
newPageCounters makes the counter loop after publishPages throw - no
fault-injection hooks needed, which also addresses the reviewer's minor
note that the fence trigger was only exercised by a manual call):
- useWAL=false + publish failure -> aborts, NOT fenced, database keeps
working. RED on the round-5 code (it fenced, with the false promise in
the SEVERE log).
- useWAL=true + same failure -> fenced through the real finally trigger.
2. HA/Raft interaction verified as requested: Issue4740Phase2ReconcileIT
(multi-node), Issue5018Phase2ConflictMessageTest and
DatabaseReconcilerTest all green against this branch (17 tests). The
reconcile flow's fault-injection point fires BEFORE commit2ndPhase, so
those failures abort pre-append and never engage the fence. A genuine
post-append leader failure WOULD fence the local instance - intended,
since it is the same live/WAL divergence hazard; the Raft log still
holds the entry and replay reconciles after reopen.
3. containsFileId now documents its RandomAccess assumption (both
producers return ArrayLists).
Battery: commit path, explicit locking, ACID, tx and async suites green.
(cherry picked from commit 858d43d)
…-layer cleanups Issue #4940: on any commit2ndPhase failure the finally called reset(), which releases locks but skips the two record-restoration steps rollback() performs: reloading the records in modifiedRecordsCache to their committed content and resetting the identity of records created in the transaction (#4562). User-held MutableDocuments from the failed tx kept an optimistically-assigned RID pointing at a record that was never persisted; re-saving them in a retry was treated as an update of a missing record (which #4959's first fix now turns into a conflict, but before it was a silent lost insert). The finally now distinguishes durability: a failure BEFORE the transaction reaches the WAL calls rollback() (nothing durable exists - behave exactly like a phase-1 failure); a failure AFTER the WAL append keeps reset() (the tx is durable, recovery replays it, so the assigned RIDs remain valid and must not be reverted). This composes with PR #5053's point-of-no-return reordering, which adds fencing to the same post-append branch. Issue #4959 (low-severity transaction cleanups, all four items): - Silent dropped update: a deferred updatedRecords entry whose record was deleted by a concurrent transaction (page loaded after the delete committed, so the MVCC page-version check cannot see it) was logged at WARNING and skipped while the rest of the transaction committed - a silent partial commit. It now fails the whole transaction with a retryable ConcurrentModificationException. An in-tx delete removes the entry from updatedRecords (LocalBucket -> removeRecordFromCache) and never hits this path. - Futile duplicate-key retries: transaction() retried a deterministic DuplicatedKeyException through all TX_RETRIES attempts plus TX_RETRY_DELAY sleeps before surfacing it. Only a concurrency-induced duplicate can succeed on retry, and one retry disambiguates: the second identical failure is now rethrown immediately. - Requester identity: executeLockingFiles hardcoded Thread.currentThread() while file locks are keyed by requester (thread or session), so a thread acting for a session timed out (5s) on locks its own session already held. It now locks on behalf of the current transaction's requester (TransactionContext.getRequester(), widened to public); a same-requester re-acquisition is ALREADY_ACQUIRED and is not released on exit, only the locks actually acquired are. - Isolation contract: documented on Database.TRANSACTION_ISOLATION_LEVEL that page-level MVCC performs no read-set validation (write skew and phantoms possible under both levels, READ_COMMITTED may observe a concurrent multi-page commit partially, REPEATABLE_READ's per-tx page cache is unbounded), and pinned it with TransactionIsolationContractTest so any future contract change is a conscious one. Red-first evidence (all five fix-targeting tests fail on unfixed code): - Issue4940Phase2FailureRollbackTest.phase2FailureBeforeWalAppendResetsCreatedRecordIdentity: "identity must be reset after a pre-durability phase-2 failure - expected: null but was: #1:0" - Issue4940Phase2FailureRollbackTest.phase2FailureBeforeWalAppendReloadsModifiedRecords: "expected: 'committed' but was: 'uncommitted'" - Issue4959TransactionCleanupsTest.deferredUpdateOfConcurrentlyDeletedRecordFailsTheCommit: "Expecting code to raise a throwable" (the commit succeeded, silently dropping the update) - Issue4959TransactionCleanupsTest.deterministicDuplicatedKeyIsRetriedAtMostOnce: "expected: 2 but was: 10" - Issue4959TransactionCleanupsTest.executeLockingFilesUsesTheTransactionRequester: LockTimeoutException after the 5000ms timeout The two TransactionIsolationContractTest write-skew tests pass before and after (they pin existing, now-documented behavior). Tests: com.arcadedb.database.** (all 38 classes), ACIDTransactionTest, ExplicitLockingTransactionTest, LocalTransactionExplicitLockRetryTest, MVCCTest: 123 tests, 0 failures, 0 errors. (cherry picked from commit 5d5669e)
…hoisted; semantics callouts Point-by-point from the seventh review round (which independently re-verified the WAL-format neutrality, the fence happens-before argument, the late-joiner coverage and the updatePages wrapper safety): 1. Explicit-lock behavioral change: the release note now calls out the full scope - a transaction using explicit locks that writes ANY file absent from its lock list, including files it could not have locked up front (an index created inside the same transaction, an EXTERNAL property's paired bucket), now fails with the contract violation where it previously committed without the lock. Workaround documented: lock the type after creating its indexes, or create indexes outside explicit-lock transactions. 2. Fence width: conscious decision made and documented in the code - the fence deliberately stays WIDE (append through end of try) rather than narrowing to at-or-before publishPages. The decisive argument: a mid-publish failure can leave SOME pages visible and others not, a partial publication no boolean flag can distinguish from a complete one; under-fencing there risks exactly the divergence the fence exists to prevent. Post-publish failures also leave component metadata that recovery replay repairs. The cost - a restart after an exceptional post-append failure - is the acceptable side of that trade. 3. HA follower semantics documented at fenceForRecovery: a replica fences its wrapped LocalDatabase too, halting apply until restart - intended, the fence surfaces exactly like a crash and the standard restart reconciliation (recovery replay or DatabaseReconciler snapshot re-install) repairs the node. 4. Fence pre-check hoisted to the top of commit2ndPhase, before validateAndBumpVersions: the happens-before edge comes from the phase-1 file locks, so nothing required the later placement - a fenced commit now does no wasted validate/bump work. Nits: RandomAccess defensive check declined (hot path; both producers are ArrayLists and the assumption is documented); the reflection coupling in the tests acknowledged - a fault-injection seam is noted as the better long-term shape. Commit path, explicit locking, ACID and tx suites green. (cherry picked from commit fbc9f1f)
…rollback Two corrections to the #4940 fix, found while cross-verifying it against current main and the pending PR #5053 (point-of-no-return reordering): 1. walAppended was set to true even when changes.result == null, i.e. for useWAL=false transactions that never touch the WAL. A publish failure in such a transaction was treated as "durable, recovery replays it" and only reset() ran - but there is NO WAL record to ever replay, so this kept the exact #4940 defect (dangling RIDs on user-held documents, stale modified records) alive on the useWAL=false path. The flag is now set only after a real append, matching the point-of-no-return boundary #4936/#5053 formalizes; when that PR lands, this placement also prevents its fencing from bricking a useWAL=false database over a failure that recovery could never repair. Red-first: Issue4940Phase2FailureRollbackTest.phase2PublishFailureWithoutWalStillRollsBack fails on the previous placement with "expected: null" (the created record kept its dangling RID after a publish-stage ConcurrentModificationException with useWAL=false) and passes with the corrected one. The test drives phase 1 with useWAL disabled, then bumps the committed version of the transaction's page behind its back so the phase-2 publish fails past the (skipped) WAL stage. 2. The changes == null no-op call was left inside the try, so it fell into the new rollback() branch of the finally instead of the pre-#4940 reset(). Restored as an early return with reset(): a no-op 2nd phase must release resources without touching user-held record state. Tests run (all green): com.arcadedb.database.** (142 incl. the new regression), ACIDTransactionTest, ExplicitLockingTransactionTest, TransactionIsolationTest, TransactionIsolationContractTest, TransactionBucketTest, TransactionTypeTest. (cherry picked from commit b7ae242)
When the Raft quorum durably committed a transaction but the leader's LOCAL phase-2 apply failed, the application received a generic commit failure - told the commit failed while the data was committed cluster-wide. Worse, an application-level retry of the same records INSERTED DUPLICATES: the #4940 rollback reset their identities to provisional, so the retry re-inserted records the cluster already held. Option A from the design discussion, as approved: - New TransactionCommittedRemotelyException (engine exception package, so applications can catch it without an ha-raft dependency): 'committed cluster-wide, do NOT retry, reload the records', with the local reconciliation outcome in the message (reconcileLeaderPagesAfterPhase2Failure now reports success/failure instead of swallowing silently). - TransactionContext gains a remotelyCommitted durability regime, set by the HA layer after quorum commit and before the local phase 2: a local failure past that point releases resources WITHOUT rolling back user-held record identities (the cluster committed them) and WITHOUT fencing (no orphaned local WAL record exists; the Raft layer reconciles the pages from the replicated payload). The regime slots between walAppended and the fence-refused/rollback regimes in commit2ndPhase's finally, composing with #4940/#5053 semantics unchanged for non-replicated databases. The ALL-quorum recovery path gets the same boundary shift. Red-first: Issue5064CommittedRemotelyContractIT (3-node cluster, single-shot post-quorum fault) fails on the pre-fix behavior (raw ConcurrentModificationException escapes, identity reset); green with the fix - distinct type, actionable message, identity preserved, and all three nodes converge on the committed data after the step-down. A baseline write pre-registers the dictionary name so the internal dictionary transaction does not consume the single-shot fault. HA phase-2 battery green (Issue4740Phase2ReconcileIT, Issue5018Phase2ConflictMessageTest, DatabaseReconcilerTest); engine commit-path battery green (WalCommitOrdering, Issue4940, Issue4959, ExplicitLocking, IsolationContract). (cherry picked from commit 111e96b)
…e contract made explicit 1. The 3-node IT carries @tag(slow) at class level, consistent with its siblings (Issue4740Phase2ReconcileIT, RaftDivergedFollowerRecoveryIT). 2. The engine test's finally now evicts BOTH poisoned pages from the process-global PageManager (the second conflicting page leaked). 3. Wire propagation - the review's 'please confirm' investigated and answered with code, because the answer was 'partially': the new exception does NOT extend NeedRetryException, so it was never mapped to the retryable 503 - but with no explicit mapping it fell into the generic 5xx branch, and HTTP clients and load balancers routinely retry 5xx: the exact duplicate-insert hazard over the wire. The HTTP handler now maps TransactionCommittedRemotelyException to 409 with a do-not-retry detail and the exception class in the JSON payload - the same non-retryable rationale as the DuplicatedKeyException 409 (#4350). 4. Post-append remotely-committed path: declined as a separate test with reasoning - past the local append the walAppended branch runs IDENTICALLY regardless of the remote flag (fence + identity-preserving reset), and that branch is already covered by the #5053 fence tests; the only remotely-committed-specific behavior is pre-append, which both the IT and the engine test exercise. Nit acknowledged: the single (String, Throwable) constructor stays until another call site needs more. WalCommitOrderingTest 6/6, the tagged IT green, server module compiles. (cherry picked from commit 9478122)
…ase, and a guarded request answers for the index asked for (#5775) * fix(engine) #5765: creating a manual index no longer fences the database, and a guarded request answers for the index asked for ManualIndexBuilder.create() registered the new index's file under `index instanceof PaginatedComponent`, a test that never matched: LSMTreeIndex and HashIndex WRAP their paginated component rather than being one. The file stayed unknown to the schema, and the commit that creates it then failed resolving that file id AFTER its WAL append - which fences the database for recovery (#5053). Every manual index creation ended there, and the builder's own error callback threw on the fenced database, replacing the real cause with a bare fence error. Registration goes through index.getComponent() now, the same accessor the type-index path uses, and the cleanup callback no longer throws. Three defects the first one hid, each found by fixing the previous: - Schema.createManualIndex(indexType, ...) dropped its indexType argument, so every call through that deprecated overload failed with a NullPointerException inside the index factory. - A UNIQUE manual index could not commit an entry: TransactionIndexContext's lock collection and its uniqueness check both resolved the index's type name to reach the polymorphic index over the same properties, and a manual index has neither. It is now recognised as its own whole search space, which it is. - withNullStrategy(null) installed the null instead of leaving the default, and the index constructor refused it with "Index null strategy is null". null now means "not specified", the convention withPageSize already follows. An index kind that cannot be built without a type (FULL_TEXT, GEOSPATIAL, LSM_VECTOR, LSM_SPARSE_VECTOR) is refused by name instead of failing inside the factory with a NullPointerException or a ClassCastException. The guarded branch still carried the two defects #5675 removed from TypeIndexBuilder: a request differing only in uniqueness DROPPED the existing index behind a dead `x != null && x == null` null-strategy test, and the index kind was not compared at all. It follows the same rule as the type path now. There is no withReplaceIfIncompatible here: the setter raises on a manual builder, because the replacement it authorises elsewhere is a rebuild from the type's records and here it would be an unrecoverable delete of the only copy of the entries. fix(engine) #5765: CREATE INDEX IF NOT EXISTS compares the settings the METADATA clause named The guard compared the structural definition only - kind and uniqueness - so a guarded statement asking for 768 dimensions over a 384-dimension vector index was a silent no-op, and every vector written afterwards went unindexed. Same for full-text analyzers and geospatial precision. Only the settings the clause actually NAMED are compared, so a statement with no METADATA compares none and stays the no-op it has always been. The clause is read through the index type's own reader before comparing, so "384" and 384, "cosine" and COSINE are the one value each denotes. Both entry points ask the same question through one helper: the IF NOT EXISTS shortcut of CreateIndexStatement, which answers before a builder exists, and TypeIndexBuilder.create(). The read side of each per-type key set is covered by a test that fails if a key is added to one list and not the other. test(engine) #5765: poll for the vector rebuild instead of sleeping a fixed interval Two Thread.sleep(6_000) + hard assertion pairs in LSMVectorIndexRecoveryTest, and the ceilings in LSMVectorIndexRebuildTest computed as a multiple of the inactivity timeout - which makes the wait shortest exactly where the work is slowest. Four of them failed in a whole-package run here and passed in isolation. They share one absolute ceiling now; the class also runs faster, since a poll returns as soon as the rebuild lands. chore(engine) #5765: CREATE INDEX and REBUILD INDEX log their progress instead of printing dots to stdout * docs(engine) #5765: mark the guarded-create settings comparison BREAKING, and say why the builder path does not re-wrap the clause Review follow-ups on #5775, both documentation-level. - The release note now frames the settings comparison as what it is for anyone with a re-runnable schema script: a guarded CREATE INDEX naming a setting MAY NOW RAISE where it used to be a no-op, including for the runtime-tunable keys a rebuild would not be needed to change (efSearch, mutationsBeforeRebuild, inactivityRebuildTimeoutMs, the cache sizes). Both ways back to an idempotent statement are spelled out: drop the keys the script does not actually require, or align the value with the existing index. - TypeIndexBuilder.create() calls findUnsatisfiedSettings without the try/catch the CreateIndexStatement shortcut wraps its own call in, and the invariant that makes that safe is now written down rather than implied: the SQL branches call withMetadata and withUserMetadata inside one try, so the clause has already been read - and any unreadable value already reported - before create() runs. A caller that sets the user clause without the parsed one has skipped that validation and gets the reader's own message; there is no such caller, and adding a second error path would only re-type an exception the reader already words correctly. Verified against the review's third ask: no CREATE INDEX IF NOT EXISTS with a METADATA clause exists outside engine/, and RemoteSchema.getOrCreateTypeIndex builds its guarded statement without one, so nothing outside the engine reaches the new comparison. Server module re-run against a freshly installed engine: 687 tests, 0 failures. * fix(engine) #5765: copy the user METADATA clause into the builder, and assert the file registration directly Round-two review follow-ups on #5775. - withUserMetadata deep-copies the clause. The callers hand the SAME JSONObject to withMetadata(JSONObject) and to withUserMetadata, and the two are read at different times: the first now, the second at create(). No withMetadata overload mutates it today - all four read it through fromUserMetadata - but the copy costs nothing at DDL time and means a future one could not silently change what a guarded request ends up comparing against. - A test asserts the registration itself rather than inferring it from the other tests happening to run. The index's file must resolve through the schema by its id, which is the call TransactionContext.commit2ndPhase makes for every file whose page count changed - past the WAL append, which is why an unregistered file fenced the database instead of failing the creation. The test pins the cause (getFileById resolves to the index's own component) and the consequence (the database still commits an unrelated write afterwards, which a fenced one cannot). Mutation-checked: restoring the `instanceof PaginatedComponent` test reproduces "commit of tx 4 failed after its WAL append". Three other review points taken as no-action, with reasons: refusing runtime-tunable settings on a guarded create is the intended semantics and is already documented as BREAKING; the TypeIndexBuilder invariant comment is the right mitigation for a caller shape that does not exist; and the mismatch message wording is already covered by tests. * refactor(engine) #5765: declare the METADATA statement directives once instead of stripping them per site Round-three review follow-up on #5775, the one observation with something to act on. "buildGraphNow" was removed at two sites - the IF NOT EXISTS reader and the LSM_VECTOR creation branch - because it directs the statement rather than configuring the index, so no index stores it and everything that reads the clause as configuration rejects it: fromUserMetadata refuses an unknown key, and the guarded comparison would report a mismatch for something an existing index cannot have. Both turn a well-formed statement into a 400. The key space is now one named DIRECTIVE_METADATA_KEYS set behind a stripDirectives() helper, so a future "do X now" key on another index type has an obvious place to be declared rather than being stripped at whichever site happens to notice it. No behaviour change: the same one key is removed in the same two places. Two other observations in that review need no change and are recorded here as judged: a future setter that cross-validates one METADATA key against another could validate against the default rather than the existing index's value when only one of the pair is named (no such coupling exists - every setter validates its own value), and the per-100k progress logging interval is already where it should be. (cherry picked from commit 0b2ccfb)
…the WAL timer A database fenced for recovery (#5053) is still isOpen()==true, but two places only guarded against !isOpen(), not fencing: - TransactionManager's once-a-second WAL housekeeping timer kept running against a fenced database, logging a misleading SEVERE "Error on transaction manager task" every second on top of the real fencing failure already logged. - PageManager.flushPage() only guarded !isOpen(). Once fenced, any other page still in the async flush pipeline reached getFileManager()/getSchema(), which threw uncaught (not one of the exception types the pipeline's per-page catches expected), stranding that page's WAL ack forever - the same "stranded ack" bug class #6440/PR #6481 fixed for a plain close(), minus this one case. Confirmed against a real production log: every page that reached the pipeline after a fence landed got stuck the same way, spamming the exact same "fenced" exception 30,000+ times until the process was restarted. New BasicDatabase.isFencedForRecovery() default method, delegated through ServerDatabase/RaftReplicatedDatabase. Regression tests: TransactionManagerFencedTimerTaskTest, PageManagerFencedFlushAckTest (both fail without the fix, pass with it).
…he database Traced the "heimdall" fencing incident to its actual trigger via a production log: DELETE FROM ... BATCH's commit reached LSMTreeIndexMutable.onAfterCommit(), which called DatabaseAsyncExecutorImpl.compact() -> getBestSlot(). That threw "Async executor has been shut down" - the same exception #4955 intended for a genuine close()/kill(), but ALSO thrown during the momentary window setTransactionUseWAL()/setTransactionSync() leaves while createThreads() tears down and respawns the whole pool for an unrelated caller (#5665: GraphBatch toggling durability on every open/close). onAfterCommit() runs after the WAL append - past the point of no return (#5053) - so this transient scheduling hiccup fenced the entire database, even though the committing transaction's own data was never at risk. compact() now contains that race the same way it already contains a full queue: the reservation is handed back, nothing is lost, the next commit past the threshold schedules the compaction again. Also: the exception that fences a database was only ever logged at FINE (invisible under any default config) via TransactionContext's generic catch. fenceForRecovery() now takes the causing Throwable and logs it at SEVERE alongside the existing fence message, so the next incident is diagnosable without needing this kind of log archaeology. Regression test: DatabaseAsyncExecutorCompactionShutdownRaceTest (fails without the fix, passes with it). Full engine/database/index/async/graph package suites: 2775 tests, 0 failures.
Round 7 of the code review found no functional issue and two comments elsewhere in DatabaseAsyncExecutorImpl that now describe behaviour this PR removed. Both sit next to what item 1 rewrote, and in a file that carries its invariants in prose, a comment naming a cause that no longer exists is the kind that gets a future reader to revert a fix on purpose. 1. compact()'s catch named setParallelLevel() as a source of the transient "shut down" exception, on the grounds that it still went through createThreads(). It does not any more, so the ambiguity that comment existed to explain is gone: the only thing that reaches the catch now is a genuine terminal close()/kill(), where the pool is NOT coming back within milliseconds. The catch keeps all of its value - an escaping exception past writeTransactionToWAL() fences the database (#5053) - and now says which case it is protecting. 2. quiesceWorkers()'s early return named "a concurrent setParallelLevel on a shut-down executor" as the only way workers could appear after its check. resizeThreads() no longer resurrects a closed pool, and LocalDatabase assigns its async field once per instance, so that path is closed. The defence stays - it costs nothing and rests on a property owned by another class - and the residual it should name instead is the one that is still open: a GROW racing the scan. No code change; 97 engine tests still green.
… don't just leave it unused CodeRabbit review (this PR's fourth pass): WALFile.acquireLock() returning null on failure was never actually checked by any of its three construction sites - the file was still added to activeWALFilePool and used normally by checkIntegrity()'s recovery replay and by append(). A second embedded instance racing a WAL file-name collision would therefore share the file with whoever holds it instead of the collision being noticed anywhere. Now checked at all three sites, matching each one's own idiom instead of inventing one: - createWALFilePool() (initial open): throws LockException, refusing the open outright - the same response lockDatabase() already gives when the whole-database lock file is contested. - checkWALFiles()'s runtime rotation: fences the database via the existing #5053 mechanism, after closing the losing probe first so it isn't leaked. - checkIntegrity()'s crash-recovery replay: aborts and preserves every WAL file for manual inspection, the same response the existing corrupt-transaction and version-gap cases already give a few lines below - replaying WAL another live instance may be concurrently mutating is exactly the corruption this issue is about. New test TransactionManagerWalRotationCollidesWithForeignWalFencesTest exercises the rotation site (the one of the three a same-name collision can most realistically still reach, since createWALFilePool()'s own directory rescan already avoids it in the common case); verified red without the fix, green with it. Also from the same review round: documented on WALFile.acquireLock() that the guarantee is scoped to a separate OS process, not a second same-process WALFile on the same path (POSIX advisory locks are per-process, not per-descriptor - closing any handle on the file releases every lock the process holds on it); and hardened TransactionManagerWalFileDeleteFailureReportedTest against silently passing under a root-run test process, where chmod-based permission enforcement is normally bypassed.
…'s clean close from deleting another live instance's WAL files Discussion ArcadeData#7479: running GraphImporter as a separate embedded process against a database directory an ArcadeDB server already had open (Docker Desktop bind mount, whose virtualized filesystem does not enforce FileChannel.tryLock() across the container boundary) corrupted the server. TransactionManager.close()'s final WAL cleanup deleted every *.wal file it found by name in the directory, not only the ones its own pool created - so the importer's own clean close wiped the still-running server's active WAL files out from under it, which then spammed "No such file or directory" once a second forever from checkWALFiles() while continuing to silently accept writes. Two independent fixes: - close() now tries an exclusive lock on each WAL-named file before deleting it: a genuine orphan from an earlier unclean shutdown of the same database is still removed, but a file another live instance still has open is left alone. - checkWALFiles() now fences the database (the existing ArcadeData#5053 mechanism) the moment a WAL file it still has open becomes inaccessible, instead of logging the same SEVERE stack trace every second indefinitely. One clear diagnostic, and the housekeeping timer cancels itself on its next tick. GraphImporter's class Javadoc now calls out the hazard explicitly: never point it at a database directory a running server already has open.
#4936 (HIGH): commit phase 2 appended the transaction to the WAL FIRST and validated the page versions after (inside updatePages). A phase-2 validation failure - reachable through the late-joining-files hole below - aborted the transaction while its record stayed in the WAL with no abort marker. Crash recovery then replayed the aborted transaction's OTHER pages (version == disk+1) while the conflicted page was skipped: a partial application of an aborted transaction - torn multi-page records, index entries pointing at data never committed.
updatePages is split into validateAndBumpVersions (validates against the most recent committed version and bumps the transaction-private page versions) and publishPages (read cache + flush scheduling + page counters). commit2ndPhase now runs validate -> WAL append -> publish, so a WAL record can only ever exist for a transaction that can no longer fail validation. The bump mutates only the transaction's own MutablePage instances: a WAL append failure (e.g. interrupt) still aborts cleanly with nothing observable, and the phase-1 WAL buffer already serializes version+1, so the reorder changes no on-disk format. writeTransactionToFile never reads live page versions (verified) - it only appends the pre-built buffer and attaches the ack bookkeeping.
#4937 (HIGH, the enabler): files can join the transaction's page set AFTER the commit lock set is computed - EXTERNAL-property buckets written during phase-1 serialization, indexes created inside the transaction (written directly at COMMIT_1ST_PHASE), and the vector index's companion graph file, which addFilesToLock omitted entirely. Their pages passed the version checks WITHOUT their file lock held. Two-layer fix: LSMVectorIndex getFileIds() now includes the graph file and addFilesToLock consumes getFileIds (plural), covering any multi-file index; and a generic phase-1 safety net verifies - after ALL page-set mutation - that every file in modifiedPages/newPages is locked, releasing and re-acquiring the UNION in order when a late joiner is found (the version checks that follow catch anything that changed while unlocked with the standard retriable CME). In explicit-lock mode an uncovered file surfaces as the contract violation it is instead of being silently re-locked.
Red-first verified: on the old ordering, a transaction that failed phase-2 validation left its bytes in the WAL; now the WAL is byte-identical before and after the failed commit. Union sweep with the companion WAL-recovery branch: 372 classes, 2851 tests, 0 failures; the ordering test re-verified green on this branch alone.
NOTE for reviewers: this is the highest-blast-radius change of the audit series - it reorders every commit in the engine. Split into its own PR precisely so it gets focused review.
What does this PR do?
A brief description of the change being made with this pull request.
Motivation
What inspired you to submit this pull request?
Related issues
A list of issues either fixed, containing architectural discussions, otherwise relevant
for this Pull Request.
Additional Notes
Anything else we should know when reviewing?
Checklist
mvn clean packagecommand