Skip to content

fix(#4936,#4937): the WAL append is the commit's point of no return - #5053

Merged
lvca merged 9 commits into
mainfrom
fix/4936-4937-commit-point-of-no-return
Jul 7, 2026
Merged

lvca merged 9 commits into
mainfrom
fix/4936-4937-commit-point-of-no-return

Conversation

@lvca

@lvca lvca commented Jul 6, 2026

Copy link
Copy Markdown
Member

#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

  • I have run the build using mvn clean package command
  • My unit tests cover both failure and success scenarios

#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.
@lvca lvca self-assigned this Jul 6, 2026
@lvca lvca added this to the 26.7.2 milestone Jul 6, 2026
@mergify

mergify Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

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

  • Queue this pull request

@codacy-production

codacy-production Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 minor

Alerts:
⚠ 1 issue (≤ 0 issues of at least minor severity)

Results:
1 new issue

Category Results
CodeStyle 1 minor

View in Codacy

🟢 Metrics 37 complexity

Metric Results
Complexity 37

View in Codacy

🟢 Coverage 94.59% diff coverage · -7.20% coverage variation

Metric Results
Coverage variation ✅ -7.20% coverage variation
Diff coverage ✅ 94.59% diff coverage

View coverage diff in Codacy

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +750 to +753
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

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.

Suggested change
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);
}

Comment on lines +729 to +736
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

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.

Suggested change
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;

@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: fix(#4936,#4937) - WAL append as the commit point of no return

Reviewed the reordering of commit2ndPhase (validate/bump -> WAL -> publish), the PageManager.updatePages split, the late-joiner lock coverage in commit1stPhase, and the multi-file index lock fix. The core design is sound and I verified the key claims against the surrounding code.

What checks out

  • WAL format is unchanged by the reorder. WALFile.writeTransactionToBuffer serializes newPage.version + 1 (WALFile.java:363), built in phase 1 before any bump. validateAndBumpVersions then bumps the private MutablePage to the same version+1, so buffer and post-bump version stay consistent. The "no on-disk format change" claim holds.
  • Clean abort on validation failure. When validateAndBumpVersions throws ConcurrentModificationException, it fires before writeTransactionToWAL, committed stays false, and finally runs reset() which unlocks files and discards the transaction-private pages. No WAL record survives, and the new WalCommitOrderingTest pins it.
  • The validate/publish window is safe. The PageManager global lock is released between the two halves, but per-file commit locks are held until reset(), so no other committer can validate/bump/publish the same pages concurrently. Bumped versions live only on transaction-private MutablePage instances until publishPages.
  • Multi-file index locking. getFileIds() (plural) in TransactionIndexContext.addFilesToLock plus LSMVectorIndex.getFileIds() now including the companion graph file closes that leak; the other callers (LocalSchema, RebuildIndexStatement) benefit from the wider lock set too.

Issue worth addressing (medium): the explicit-lock branch in the late-joiner block is unreachable

In commit1stPhase (TransactionContext.java:749-758):

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, explicitLockedFiles is always null for an explicit-lock transaction: phase 1 already called checkExplicitLocks(modifiedFiles) at line 680, whose success path does lockedFiles = explicitLockedFiles; explicitLockedFiles = null; (lines 1120-1121). Nothing restores it. So the if (explicitLockedFiles != null) guard can never be true here, and an explicit-lock transaction that picks up a late-joining file (an index created in-tx, an EXTERNAL-property overflow bucket, etc.) falls into the else branch and gets its lock set silently expanded - precisely the "re-locking on their behalf would defeat the explicit-locking contract" behavior the comment says it wants to avoid.

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 Cannot commit transaction because not all the modified resources were locked error they would get for a direct modification of an unlocked file. To honor the intent, capture a boolean marking explicit-lock mode before checkExplicitLocks nulls the field, and branch on that instead of on explicitLockedFiles != null. A regression test covering "explicit lock + late-joining file" would lock this down whichever way you decide.

Minor / nits

  • Test style: WalCommitOrderingTest uses fully-qualified names inline ((com.arcadedb.database.TransactionContext) db.getTransaction() and java.lang.reflect.Method) even though TransactionContext is already imported. CLAUDE.md asks for imports over FQNs.
  • Test coupling: the test reaches into PageManager.INSTANCE and reflects putPageInReadCache; brittle against future refactors - a short comment on why reflection is required would help.
  • Micro: the late-joiner block iterates lockedFiles twice to build both lockedSet and union; could be one pass. Negligible, leader-only.

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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: fix(#4936,#4937) - WAL append as the commit's point of no return

I 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

  • Byte-compatible WAL confirmed. The concern with moving the version bump before the WAL append is whether the WAL buffer content stays consistent. It does: WALFile.writeTransactionToBuffer is called in phase 1 and already serializes newPage.version + 1 (line 363) and captures the phase-1 content delta. Since both the old and new code build the buffer at the same point (phase 1) and only the bump moves relative to the append, the on-disk WAL format is unchanged. The claim holds.
  • The bump is invisible on a WAL-append failure. validateAndBumpVersions mutates only the transaction-private MutablePage instances (not the read-cache ImmutablePage), so a writeTransactionToWAL failure (e.g. interrupt, per [tx] Interrupted thread silently skips the WAL write and commits anyway #4938) still aborts with nothing observable. Good.
  • Split PageManager lock is safe. updatePages used to hold the global PageManager lock across validate+bump+publish; now the lock is released between validateAndBumpVersions and publishPages (the WAL append happens in the gap). This is safe because the per-file locks (lockedFiles, held until reset()) serialize commits per file, so no concurrent committer can touch these pages, and a concurrent reader only ever sees the old-or-new committed state, never a torn intermediate. Worth a one-line comment at the publishPages call site noting that per-file-lock coverage is what makes the two separate lock sections safe.

#4937 late-joiner coverage - solid, with minor notes

  • The getFileId() -> getFileIds() change in TransactionIndexContext.addFilesToLock is a strict improvement: the old code could add -1 (composite/TypeIndex.getFileId()) to the lock set and omitted multi-file index components. Now it adds all valid component file ids.
  • The dead-branch fix in commit 2 is a genuine catch: checkExplicitLocks nulls explicitLockedFiles on success, so the original if (explicitLockedFiles != null) in the late-joiner block was always false and would have silently expanded an explicit-lock transaction's lock set. Capturing explicitLockMode up front is the right fix, and the new regression test (external-property paired bucket as a real late joiner) pins it well.

Issues and suggestions

  1. Style (CLAUDE.md): fully-qualified names in the new test. explicitLockTransactionWithLateJoiningFileIsRejectedNotSilentlyRelocked uses inline FQNs (com.arcadedb.schema.DocumentType, com.arcadedb.schema.Type, com.arcadedb.database.RID). CLAUDE.md asks to import the class and use the short name, and commit 2 already cleaned up FQNs in the sibling test - please import these too for consistency.

  2. checkExplicitLocksForUnion drops the migrated-file handling. checkExplicitLocks translates a missing-but-migrated file (index compaction) into a retriable ConcurrentModificationException. The new checkExplicitLocksForUnion throws a non-retriable TransactionException unconditionally. A late-joining migrated file in explicit-lock mode would therefore fail hard instead of signalling retry. Edge case, but consider mirroring the migration check or noting why it cannot occur here.

  3. Per-commit allocation on the hot path. The late-joiner block allocates a fresh IntHashSet on every leader commit, even in the overwhelmingly common no-late-joiner case. Given CLAUDE.md's emphasis on GC pressure and that commits are extremely frequent, it may be worth a fast-path guard when the transaction touched only files already in lockedFiles, or reusing a scratch set. Not blocking, but flagging since this is a very hot path.

  4. Late-joiner re-lock widens the CME window (perf/liveness, not correctness). When a late joiner is found in auto-lock mode, the code releases all locks (including the originally locked files) and re-acquires the union. During that gap a concurrent committer can bump a version on an already-locked file, producing an extra CME retry that the previous continuous-hold path would have avoided. Correctness is preserved by the version checks; just noting the added retry pressure on this (rare) path. The comment already acknowledges the ordering discipline, which is good.

  5. Test isolation of the global PageManager.INSTANCE. failedValidationLeavesNoWalRecord injects a conflicting CachedPage into the JVM-global PageManager.INSTANCE read cache and never removes it. @AfterEach drops the DB, so risk is low, but the injected entry is not explicitly evicted. If this suite ever runs under parallel forks sharing a JVM, a foreign cache entry keyed by PageId could bleed across tests. Consider evicting the injected page (or documenting the single-fork assumption).

Test coverage

Good: 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.

Summary

The 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 checkExplicitLocksForUnion (#2). Items 3-5 are optional polish. Given the stated blast radius (this reorders every engine commit), the extensive test sweep referenced in the description is the right call.

…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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: fix(#4936,#4937): the WAL append is the commit's point of no return

Reviewed the full diff plus the surrounding commit machinery (commit1stPhase/commit2ndPhase, PageManager.updatePages/validateAndBumpVersions/publishPages, WALFile.writeTransactionToBuffer/writeTransactionToFile, addFilesToLock, LSM*Index.getFileIds). This is a well-reasoned, well-documented fix and the core invariant it establishes is correct.

What checks out

  • The reorder is sound. validate+bump now runs (and can throw ConcurrentModificationException) strictly before writeTransactionToWAL, so the WAL append genuinely becomes the point of no return. publishPages stays after. Verified the WAL buffer is built in phase 1 and serializes newPage.version + 1 (WALFile.java:363), and the bump in validateAndBumpVersions moves the in-memory version to exactly that value - so the on-disk WAL format is unchanged, as the description claims.
  • writeTransactionToFile does not read live page versions (WALFile.java:382-407) - it only appends the pre-built buffer and does the ack bookkeeping (setWALFile, pagesToFlush++). Confirmed, so the reorder can't skew what lands in the WAL.
  • Late-joiner coverage ([tx] Files can join a transaction's page set after the commit lock set is computed #4937) is the right enabler. addFilesToLock switching from getFileId() to getFileIds() correctly pulls in multi-file index components (vector companion graph file, LSM sub-index during compaction), and the generic phase-1 safety net catches EXTERNAL buckets / in-tx-created indexes that join after lock computation. The explicitLockMode capture before checkExplicitLocks nulls explicitLockedFiles (TransactionContext.java:685) is a genuine, subtle correctness detail - nicely caught.
  • Failure semantics. A ConcurrentModificationException (or WAL-append interrupt) leaves only transaction-private MutablePage instances mutated, discarded by reset(); nothing observable escapes.
  • Tests are red-first and target the actual defect (WAL-bytes-before == after for a failed validation; explicit-lock late-joiner rejected rather than silently re-locked). Verified all referenced APIs exist and getPageManager() really returns the PageManager.INSTANCE the tests inject into.

Points worth addressing

  1. publishPages javadoc overstates the invariant for the HA follower path. The doc says the gap between the two lock() halves is "safe ONLY because the caller holds the per-file commit locks (until reset())". On a follower, commit1stPhase(false) sets lockedFiles = new ArrayList<>() (empty) and the late-joiner block is skipped, yet RaftReplicatedDatabase still drives commit2ndPhase (lines 430/469) through this same split. There the gap is protected by single-threaded Raft apply, not per-file locks. The code is still safe, but the comment describes an invariant that doesn't literally hold on that path - suggest expanding it to name the follower case so a future reader doesn't rely on a lock that isn't there.

  2. PageManager.updatePages is now dead code. After this change it has zero callers (only the delegating body remains). Either drop it or add a note that it's kept as public API - otherwise it reads as a live path and invites the assumption that validate+publish are still atomic under one lock.

  3. getFileIds() on the hot commit path takes an index read lock. LSMTreeIndex.getFileIds() wraps its work in lock.executeInReadLock(...), and addFilesToLock now calls it for every touched index during commit1stPhase (previously the lock-free getFileId()). Almost certainly negligible, but it's a new lock acquisition per index per commit on one of the hottest paths - worth a conscious ack given the perf mandate.

  4. Minor - error double-wrapping. checkExplicitLocksForUnion throws TransactionException, which the generic catch (Exception) in commit1stPhase re-wraps as TransactionException("Transaction error on commit", e). The test copes via hasRootCauseMessage, but users see a nested message. Not blocking; flagging for awareness.

  5. Nit - containsFileId "boxing-free" comment. lockedFiles.get(i) == fileId still unboxes the Integer from the List<Integer> on each iteration; the comment is right that no new boxing of the int arg happens, but "boxing-free" reads a touch stronger than reality.

Test coverage

Good and targeted. One thing to keep an eye on: totalWalBytes() relies on File.length() reflecting the append. With the default (possibly non-YES_FULL) WAL flush type this is usually fine because the channel write extends the file synchronously, but if it ever proves timing-sensitive across environments, asserting on a more direct signal (e.g. WAL position/offset) would be sturdier. A crash-recovery-level test (kill after a forced phase-2 failure, reopen, assert no partial replay) would also nail the end-to-end #4936 guarantee that the unit test approximates via the byte count - worth considering as a follow-up given the blast radius.

Overall: correct, carefully argued, and appropriately split out for focused review. The items above are documentation/cleanup refinements rather than blockers.

Static review only - I did not run the build in this pass.

lvca added 2 commits July 6, 2026 16:14
…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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: fix(#4936,#4937) - WAL append as the commit's point of no return

Thorough, well-documented change. I traced the reordering through commit1stPhase / commit2ndPhase, the PageManager split, the WAL buffer encoding, and both tests. Overall this looks correct and the reasoning in the comments matches the code. Notes below.

Correctness - verified points

  • WAL buffer is reorder-safe. WALFile.writeTransactionToBuffer encodes newPage.version + 1 (WALFile.java:363) and the buffer is built in phase 1 before any bump - which was already true in the old order (WAL-then-updatePages). So moving the incrementVersion() bump ahead of the WAL append keeps the published page version and the WAL-encoded version identical. No on-disk format change, as claimed.
  • The bump is transaction-private. validateAndBumpVersions -> updatePageVersion mutates only this tx's MutablePage instances (not the read cache), so a WAL-append failure aborts via reset() with nothing observable.
  • New catch (TransactionException e) in commit1stPhase is correctly ordered: ConcurrentModificationException (extends NeedRetryException) and DuplicatedKeyException are separate hierarchies caught earlier, so the new block only intercepts genuine TransactionExceptions (the explicit-lock contract violation) and avoids double-wrapping. This is what makes the second test's exact-message assertion pass.
  • getFileIds() for multi-file indexes (LSMVectorIndex companion graph file, LSMTreeIndex sub-index) is the right fix for the lock-coverage hole; addFilesToLock now unions all component files.
  • containsFileId relies on list.get(i) == fileId unboxing the stored Integer to int - correct (int==int, not reference identity), and the comment flags it.
  • checkExplicitLocksForUnion mirrors the existing checkExplicitLocks message construction and its Javadoc soundly justifies skipping the migrated-file translation (locks held continuously since lock(), so no compaction migration can occur).
  • Lock release between the two PageManager halves is safe on the leader (per-file commit locks held until reset(), coverage guaranteed by [tx] Files can join a transaction's page set after the commit lock set is computed #4937) and on the follower (single-threaded Raft apply). The publishPages Javadoc documents both regimes clearly.

Things worth considering

  1. New full scan on the hottest commit path (performance). The late-joiner detection loop iterates every entry in modifiedPages (and newPages) on every leader commit - O(pages x lockedFiles). lockedFiles is tiny so it is effectively O(pages), but for large batch transactions (tens/hundreds of thousands of pages) this is a brand-new per-commit scan that did not exist before. The allocation-free fast path is a good mitigation, but it may be worth a micro-benchmark on a large batch INSERT to confirm the added scan is in the noise. An alternative would be accumulating touched fileIds as pages are staged, but that is a larger refactor and probably not warranted now.

  2. "Reported-failed-but-actually-committed" window (document, not fix). If publishPages throws after the WAL append (e.g. an IOException writing the read cache), the caller sees a failed commit but the transaction will be replayed on recovery and become durable on restart. This is inherent to "WAL is the point of no return" and existed in the old WAL-then-updatePages order too, so it is not a regression - but since this PR makes the WAL append explicitly the commit boundary, it may be worth one sentence in the release note that a failure after the WAL append is resolved by replay, never by abort.

  3. Test cleanup on the failure path (minor). In failedValidationLeavesNoWalRecord, removePageFromCache(victim.getPageId()) is only reached on the happy path; if an assertion fails earlier the injected entry lingers in the JVM-global PageManager.INSTANCE cache. In practice db.close() in the finally calls removeAllReadPagesOfDatabase, so the foreign entry is cleaned regardless - but moving the explicit eviction into the finally would make the intent robust rather than incidental.

  4. Non-deterministic error message (pre-existing). checkExplicitLocksForUnion builds the resource list via Collectors.toSet(), so with more than one missing file the message ordering is unspecified. The existing checkExplicitLocks has the same property, so this only matters if a test ever asserts on a multi-file message (the current test asserts a single [Doc_0_ext], which is fine).

Test coverage

Both tests are on point: failedValidationLeavesNoWalRecord is a genuine red-first guard for #4936 (byte-identical WAL before/after a failed phase 2), and the explicit-lock test exercises the #4937 late-joiner path through an EXTERNAL-property bucket. I could not execute the suite in this environment (no Maven access), so I am relying on the PR's stated 372-class / 2851-test green run for runtime confirmation.

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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

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)

  • WAL buffer already serializes version+1: WALFile.writeTransactionToBuffer writes newPage.version + 1 (WALFile.java:363) at phase-1 buffer-build time, and validateAndBumpVersions bumps the live MutablePage to version+1 in phase-2. They match, so reordering validate/bump before the WAL append does not change on-disk WAL content.
  • writeTransactionToFile never reads live page versions: it appends the pre-built buffer and only attaches setWALFile/pagesToFlush bookkeeping (WALFile.java:382-407).
  • Clean-abort on pre-WAL failure: validateAndBumpVersions mutates only transaction-private MutablePage instances and does not touch readCache; a CME (or WAL-append failure) leaves committed=false then reset() discards them. Nothing observable leaks.
  • Late-joiner union re-lock is sound: anything that advanced during the unlocked window is caught by the subsequent version checks as a retriable CME, and ordering is preserved through the sorted lockFilesInOrder.

Design concern worth discussing (not necessarily blocking)
A failure AFTER the WAL append (e.g. IOException in publishPages, or in the updatePageCount/bucketRecordDelta loops) throws with committed=false, so finally runs reset() which unlocks the files and discards the in-memory pages, while the WAL record survives. Two follow-ups:

  1. Live/WAL divergence: after reset() unlocks, another leader transaction can read the old cached version, bump to v+1, and append its own WAL record for the same page at the same version. On recovery both records target v+1. Is that reconciled cleanly, or can it reproduce the exact torn/duplicated replay this PR closes? Rare (IOException mid-publish), but the window is real.
  2. Clean close vs. crash: crash recovery replays the orphaned WAL record. Does a subsequent clean close+reopen also replay it, or could checkpointing drop a WAL whose pages were never flushed, turning "durable on restart" into silent loss?

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)
addFilesToLock now iterates index.getFileIds() instead of getFileId(). Beyond the vector index, LSMTreeIndex.getFileIds() (LSMTreeIndex.java:211) also returns the mutable sub-index file, so every LSM index now adds an extra file to the commit lock set. This looks correct and even fixes a latent bug (TypeIndex.getFileId() returns -1, which the old code would add(-1); getFileIds() returns real bucket ids). Deadlock-safety holds via the sorted lock order. Just confirm the extra sub-index lock does not measurably reduce write concurrency on hot LSM indexes.

Minor / style

  • checkExplicitLocksForUnion uses fully-qualified java.util.TreeSet::new although java.util.* is imported. CLAUDE.md asks to import and use the simple name.
  • containsFileId (get(i) == fileId) correctly relies on Integer-to-int unboxing; allocation-free as documented. Fine.

Tests

  • failedValidationLeavesNoWalRecord is a genuine red-first test: WAL append grows the file via channel.write(buffer, channel.size()) with no preallocation, so the byte-length assertion truly detects a stray record. Good cleanup of the JVM-global PageManager.INSTANCE cache entry in finally.
  • Coverage gap: no test for the late-joiner path in auto-lock mode (the else branch that unlocks and re-locks the union, then re-validates and succeeds). A test that forces a real late joiner (index created inside the tx, or the vector companion graph file) and asserts the commit succeeds with the expanded lock set would lock in the fix for the common path. A follower-path (isLeader=false) assertion that the block is skipped would also help.

Not verified here
mvn is approval-gated in my environment, so I did not run the suite. Given the blast radius (this reorders every engine commit), please ensure CI is green on this PR alone.

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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: fix(#4936,#4937) - WAL append as the commit's point of no return

Overall 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 updatePages into validateAndBumpVersions/publishPages is clean, and the late-joiner lock-coverage fix closes a genuine hole. The Javadoc and release notes are unusually thorough. A few observations below, one of which I think is an actual bug.

Potential bug: walAppended is set even when nothing was written to the WAL

In commit2ndPhase (TransactionContext.java:875-878):

if (changes.result != null)
  // WRITE TO THE WAL: THE POINT OF NO RETURN
  database.getTransactionManager().writeTransactionToWAL(changes.modifiedPages, walFlush, txId, changes.result);
walAppended = true;   // <-- unconditional

changes.result is null whenever the transaction runs with WAL disabled (useWAL == false -> commit1stPhase never builds the buffer, TransactionContext.java:815-821). setUseWAL(false) / GlobalConfiguration.TX_WAL=false is a supported configuration (commonly used for bulk loading).

In that case no WAL record is appended, yet walAppended becomes true. If publishPages (or updatePageCount, onAfterCommit, etc.) then throws, e.g. an IOException during flush, which is exactly the post-validation failure class the fence was designed for, the finally block fences the whole database:

if (walAppended && database.getEmbedded() instanceof LocalDatabase localDatabase)
  localDatabase.fenceForRecovery("commit of tx " + txId + " failed after its WAL append");

The fence message promises "recovery will replay it", but with useWAL=false there is nothing in the WAL to replay. The result is a permanently unusable database (every op throws until close/reopen) for a transaction that opted out of WAL durability, where reopening recovers nothing. This is a regression versus the pre-PR behavior, where a useWAL=false publish failure simply aborted the transaction.

Suggested fix, only treat the WAL as crossed when it actually was:

if (changes.result != null) {
  // WRITE TO THE WAL: THE POINT OF NO RETURN
  database.getTransactionManager().writeTransactionToWAL(...);
  walAppended = true;
}

(or equivalently gate the fence on changes.result != null). A regression test with setUseWAL(false) + an injected post-validation failure would pin it.

Worth confirming: fence interaction with the HA/Raft phase-2 path

commit2ndPhase is also invoked from RaftReplicatedDatabase (lines 332/431/456) after Raft has already committed the entry, and there's existing machinery (Issue4740Phase2ReconcileIT, MajorityCommittedAllFailedException) that expects a local phase-2 failure to be reconciled by replay rather than by aborting. Since fenceForRecovery triggers on any LocalDatabase post-append failure, a phase-2 failure on the leader would now fence the DB in addition to whatever Raft reconciliation does. The PR notes claim the follower path leaves lockedFiles empty and relies on single-threaded Raft apply, but it would be good to confirm the fence doesn't interfere with the leader-side reconcile flow those ITs exercise (i.e. run the ha-raft phase-2 ITs against this branch).

Minor notes

  • containsFileId (TransactionContext.java:1015) uses lockedFiles.get(i) in a loop; this is O(n) per call and O(n*m) over the page set. The Javadoc justifies it as "lockedFiles is small (< 10)", which is reasonable, but it assumes the list is RandomAccess. Worth a one-line assumption note or an instanceof RandomAccess guard if lockFilesInOrder could ever return a LinkedList. Given the measured scan cost in the commit notes, this is cosmetic.
  • The fence path is only exercised by a manually-injected fenceForRecovery(...) call in the test, not by a real mid-publish failure (acknowledged in the commit message, no fault-injection hooks). Reasonable given the constraints, but a @Tag-gated fault-injection test would raise confidence that the finally trigger actually fires on the intended exception classes.

Test coverage

Good: failedValidationLeavesNoWalRecord directly asserts the core invariant (zero WAL bytes after a failed validation), explicitLockTransactionWithLateJoiningFileIsRejectedNotSilentlyRelocked covers the explicit-lock contract via a real EXTERNAL-property late joiner, and read-cache cleanup is handled in finally. The main gap is the useWAL=false case flagged above.

Nice work overall, the reasoning and documentation quality here are excellent. The walAppended gate is the one item I'd treat as blocking.

Reviewed with Claude Code.

…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.
@claude

claude Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review: fix(#4936,#4937) - WAL append as the commit's point of no return

I 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

  • The reorder is WAL-format neutral. WALFile.writeTransactionToBuffer serializes newPage.version + 1 (WALFile.java:363) and the buffer is built in phase 1 (createTransactionBuffer) before any bump. In both orderings the bytes appended to the WAL are identical, and writeTransactionToFile only appends the pre-built buffer plus ack bookkeeping (setWALFile, pagesToFlush++); it never reads live page versions. So moving validateAndBumpVersions ahead of the append changes nothing durable.
  • The fence happens-before argument holds. fenceForRecovery(...) is called in the finally before reset() releases the per-file commit locks (reset at TransactionContext.java:958-968). Any transaction blocked on a shared file lock therefore observes the fence (volatile) once it acquires those locks, so it cannot append a conflicting record for the same page versions. Non-sharing transactions are fenced globally anyway via the volatile read.
  • Late-joiner coverage. getFileIds() (plural) now covers LSMVectorIndex's companion graph file, addFilesToLock consumes it, and the generic post-mutation coverage check in commit1stPhase closes the remaining hole. The leader-only guard (isLeader && lockedFiles != null) is consistent with followers taking no file locks and relying on single-threaded Raft apply.
  • The split signatures line up and no other production caller of updatePages exists, so keeping it as an atomic convenience wrapper is safe.

Points worth discussing

  1. Behavior change for explicit-lock transactions that create files they could not pre-lock. With the new checkExplicitLocksForUnion, an explicit-lock transaction that writes a file which was not (and could not have been) in the user's lock set - e.g. an index created inside the same transaction, or its late-joining component file - now fails with TransactionException("...not all the modified resources were locked...") where it previously committed (unsafely). This is correct hardening, but it is a semantic change that could surface as a regression for anyone mixing DDL with explicit locking. Worth calling out explicitly in the release note (the note covers the EXTERNAL-bucket case but not the "file you literally could not have locked" case).

  2. The fence is a global hammer, including for post-publish failures that leave consistent state. Any failure after the WAL append fences the whole database until close/reopen. The injected test failure (bogus id in newPageCounters) fires after publishPages fully succeeded; at that point the pages are already in the read cache and scheduled to flush, so the only divergence is cached record counters / onAfterCommit, which are recomputed on demand. Fencing there is defensible (conservative, integrity-first), but a benign post-publish hiccup then bricks the DB until a restart. If unnecessary restarts ever matter, consider narrowing the fence to failures at or before publishPages rather than every failure through the end of the try. Not blocking, but the blast radius deserves a conscious decision.

  3. HA follower implications of fencing. database.getEmbedded() resolves to the wrapped LocalDatabase on a follower, so a post-append publish failure fences the follower too, halting replication apply until the node is restarted for recovery. Probably the intended fail-safe, but there is no HA/follower test for the in-process fence path (the RaftLeaderCrash*IT tests exercise crash-recovery, not the live fence). Consider adding coverage or at least noting the follower semantics.

  4. Minor: fence pre-check placement. In commit2ndPhase the isFencedForRecovery() check runs after validateAndBumpVersions, so a fenced DB still does the full validate+bump (on transaction-private pages, later discarded) before throwing. Harmless, but it could sit at the top of the method since the file locks it depends on were acquired back in phase 1. Micro-optimization only.

Nits

  • containsFileId depends on lockedFiles being RandomAccess; the Javadoc says so, but a defensive instanceof RandomAccess check or iterator fallback would make it robust if a future caller passes a LinkedList. On a hot path the current array-style loop is the right default.
  • The two new tests reach into JVM-global PageManager.INSTANCE and reflect into the private newPageCounters field. Pragmatic, and cleanup (removePageFromCache in finally) is handled, but it couples the tests to internal layout; a fault-injection seam would be less brittle long term.

Test coverage

Strong. Red-first failedValidationLeavesNoWalRecord, the explicit-lock rejection, the fence-refuses-new-ops case, and importantly publishFailureWithWalDisabledAbortsWithoutFencing guarding the useWAL=false bulk-load path from being fenced for a replay that cannot happen. The walAppended gate that makes that distinction is the right call.

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.
lvca added a commit that referenced this pull request Jul 6, 2026
…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

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.78378% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.49%. Comparing base (b4ddc6c) to head (fbc9f1f).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...java/com/arcadedb/database/TransactionContext.java 85.45% 2 Missing and 6 partials ⚠️
...src/main/java/com/arcadedb/engine/PageManager.java 60.00% 2 Missing ⚠️
...main/java/com/arcadedb/database/LocalDatabase.java 87.50% 0 Missing and 1 partial ⚠️
...java/com/arcadedb/index/vector/LSMVectorIndex.java 50.00% 0 Missing and 1 partial ⚠️
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.
📢 Have feedback on the report? Share it here.

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

@lvca
lvca merged commit 2f9f9f4 into main Jul 7, 2026
26 of 31 checks passed
@lvca
lvca deleted the fix/4936-4937-commit-point-of-no-return branch July 7, 2026 00:28
lvca added a commit that referenced this pull request Jul 7, 2026
…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.
oc007us pushed a commit to oc007us/arcadedb-grpc that referenced this pull request Jul 8, 2026
…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).
lvca added a commit that referenced this pull request Aug 2, 2026
…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.
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…-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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
robfrank pushed a commit that referenced this pull request Aug 14, 2026
…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)
lvca added a commit that referenced this pull request Aug 20, 2026
…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).
lvca added a commit that referenced this pull request Aug 20, 2026
…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.
lvca added a commit that referenced this pull request Aug 21, 2026
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.
lvca added a commit that referenced this pull request Sep 12, 2026
… 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.
oc007us pushed a commit to oc007us/arcadedb-grpc that referenced this pull request Sep 13, 2026
…'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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant