Skip to content

fix(#6120): fold the index entries on RESTORE DOCUMENT/VERTEX/EDGE - #6123

Merged
lvca merged 6 commits into
mainfrom
fix/6120-restore-index-entries
Aug 13, 2026
Merged

lvca merged 6 commits into
mainfrom
fix/6120-restore-index-entries

Conversation

@lvca

@lvca lvca commented Aug 13, 2026

Copy link
Copy Markdown
Member

Fixes #6120. Follow-up to #6119 (#6096), which merged before this was ready.

What was wrong

RESTORE put the record back in its bucket but never re-added its index entries. After a restore, an index-resolved query missed the record while a full scan returned it:

viaIndex=0  viaScan=1

And a UNIQUE index never learned the key had come back, leaving it free to hand that same key to a second record unchallenged. Same "wrong answer indistinguishable from a right one" family as #6069 and #6096, but on every indexed query rather than on a counter.

The fix, and why it is not a one-liner

LocalBucket.restoreRecordAtPosition() performs only the physical page write, exactly like bucket-level create/delete. Everything a create folds on top of it is the caller's job - and having each RESTORE call site do that by hand is precisely how the record-count delta was missed in #6069 and the index entries here. Four call sites, four chances to forget, and #6082's shared helper could not even be reused by GraphEngine.restoreVertexAt without inverting the package dependency direction (that PR's review raised it and correctly declined).

So the primitive moves down to where the equivalent create bookkeeping already lives: DatabaseInternal.restoreRecord(record, bucket, position), implemented in LocalDatabase beside createRecordNoLock. It folds:

RESTORE DOCUMENT/VERTEX/EDGE and GraphEngine.restoreVertexAt all route through it; RestoreStatementSupport's hand-rolled copy is gone. One place to forget instead of four.

Two deliberate departures from createRecordNoLock

Both because RESTORE is admin repair, not user DML:

  • No validate() / setDefaultValues() - a mandatory-property check would block a structure-only shell restore exactly when the emergency repair is needed.
  • No create events - firing user triggers (including JS ones) during a repair is a behaviour change well beyond this gap.

Worth a maintainer opinion: both are now explicit decisions rather than accidents, and the second one means a restored record silently skips onAfterCreate. I lean toward documenting the contract in the SQL reference rather than changing it.

Verification

Six regression tests, each confirmed red with the fold removed:

  • RestoreSqlStatementTest.restoreDocumentReindexesTheRestoredRecord
  • RestoreSqlStatementTest.restoreVertexReindexesTheRestoredRecord
  • RestoreSqlStatementTest.restoreEdgeReindexesTheRestoredRecord
  • RestoreSqlStatementTest.restoreDocumentEnforcesTheUniqueIndexOnTheRestoredKey - the duplicate rejection a restored key now gets
  • RestoreRecordAtPositionTest.restoreRecordReindexesTheRestoredRecord - the Java API, via restoreRecord with a populated record
  • RestoreRecordAtPositionTest.rollingBackARestoreLeavesNoDanglingIdentityOnTheShell

No index test on GraphEngine.restoreVertexAt: it restores a property-less shell, and I verified a null-valued indexed property produces no index entry on any path, insert included - so such a test would be vacuous. It is covered for the count fold (#6069) as before, and shares this fold through restoreRecord.

Full engine suite: 11715 tests, 1 failure - Issue5279ConcurrentUpdateTest.growingUpdatesUnderContentionKeepTheDatabaseConsistent, which fails identically on clean main (verified by stashing this change). Whole project compiles; ServerDatabase and RaftReplicatedDatabase gain the delegating override the new interface method requires.

Also carries 072430913, the doc commit answering PR #6119's review point about the contentEndOffset() header guard being unreachable - it was pushed too late to reach that merge.

lvca added 2 commits August 12, 2026 21:04
…hough unreachable

PR #6119 code review traced the call graph and found the guard cannot
fire today: both callers derive the offset from getLastRecordPositionInPage(),
whose getRecordPositionInPage() already rejects a non-zero entry below
contentHeaderSize. Kept, but the reachability argument is now stated in
place so the next reader does not have to re-derive it.
RESTORE put the record back in its bucket but never re-added its index
entries, so after a restore an index-resolved query missed the record
while a full scan returned it, and a UNIQUE index never learned the key
had come back - leaving it free to hand the same key to a second record
unchallenged. Same "wrong answer indistinguishable from a right one"
family as #6069 and #6096, but on every indexed query rather than on a
counter.

LocalBucket.restoreRecordAtPosition() performs only the physical page
write, exactly like bucket-level create/delete. Everything a create
folds on top of it is the caller's job, and having each RESTORE call
site do that by hand is precisely how the record-count delta was missed
in #6069 and the index entries here: four call sites, four chances to
forget, and the #6082 fix could not even be shared with GraphEngine
without inverting the package dependency direction.

So the primitive moves down to where the equivalent create bookkeeping
already lives: DatabaseInternal.restoreRecord(record, bucket, position),
implemented in LocalDatabase beside createRecordNoLock. It folds the
bucket record-count delta (#6069), the transaction record cache, the
index entries (#6120) and the new-record registration a rollback needs
(#4562/#4940). RESTORE DOCUMENT/VERTEX/EDGE and GraphEngine.restoreVertexAt
all route through it, and RestoreStatementSupport's hand-rolled copy is
gone.

Two deliberate departures from createRecordNoLock, both because RESTORE
is admin repair rather than user DML: no validate()/setDefaultValues()
(a mandatory-property check would block a structure-only shell restore
exactly when the emergency repair is needed) and no create events (firing
user triggers on a repair is a behaviour change well beyond this gap).

Six regression tests, each confirmed red with the fold removed: the
document/vertex/edge SQL arms, the UNIQUE-index duplicate rejection a
restored key now gets, the Java API via restoreRecord with a populated
record, and the rollback identity reset. No index test on
GraphEngine.restoreVertexAt: it restores a property-less shell, and a
null-valued indexed property produces no index entry on any path,
insert included, so such a test would be vacuous.

ServerDatabase and RaftReplicatedDatabase gain the delegating override
the new interface method requires.
@mergify

mergify Bot commented Aug 13, 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 Aug 13, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 22 complexity

Metric Results
Complexity 22

View in Codacy

🟢 Coverage 81.08% diff coverage · -6.59% coverage variation

Metric Results
Coverage variation ✅ -6.59% coverage variation
Diff coverage ✅ 81.08% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (59e590a) 156148 122572 78.50%
Head commit (908c8a5) 188618 (+32470) 135629 (+13057) 71.91% (-6.59%)

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 (#6123) 37 30 81.08%

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

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

@claude

claude Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Review

Solid fix, and the write-up makes the reasoning easy to verify against the diff. The core idea of moving the "everything a create folds on top of the physical page write" bookkeeping down into DatabaseInternal.restoreRecord, next to createRecordNoLock, is the right shape: it collapses four call sites (three SQL statements plus GraphEngine.restoreVertexAt) that had already independently missed the count delta once (issue 6069) into one place, which is exactly the kind of duplication that caused the bug being fixed here.

Correctness

  • Traced LocalDatabase.restoreRecord (LocalDatabase.java:1091-1131) against createRecordNoLock line by line. The physical write, cache update, count delta, index, registerNewRecord, unsetDirty sequence looks right, and bucket.restoreRecordAtPosition sets the record identity before the index call, so indexer.createDocument sees a persistent RID. MutableVertex/MutableEdge both extend MutableDocument, so the record instanceof MutableDocument branch correctly covers all three RESTORE arms.
  • The ordering of indexer.createDocument(...) before transaction.registerNewRecord(record) (opposite of createRecordNoLock, which registers first) does not matter here; registerNewRecord just appends to a list consulted at rollback/commit time, no dependency either way.
  • Rollback path looks correct: TransactionContext.rollback() resets identity for everything in newRecords, and index mutations live in transaction-scoped pages that get discarded with the rest of the transaction, so the "no dangling identity, no orphaned index entry" test (rollingBackARestoreLeavesNoDanglingIdentityOnTheShell) is exercising real behavior rather than a coincidence.
  • Confirmed poisonEdgeAppendPage (fired in createRecordNoLock for MutableEdgeSegment/StripeDirectory) is correctly not needed here: RESTORE only ever hands restoreRecord a MutableDocument/MutableVertex/MutableEdge shell, never an edge-segment chunk, so this is not a gap, just something worth checking since it is easy to assume restoreRecord should mirror createRecordNoLock line for line.

One behavioral gap vs createRecordNoLock
createRecordNoLock guards the no-active-transaction case with checkTransactionIsActive(autoTransaction), which auto-begins and later auto-commits/rolls-back a transaction when the database has setAutoTransaction(true) set. restoreRecord instead calls getTransaction() directly (LocalDatabase.java:1093), which just throws TransactionException if nothing is active; it never auto-wraps.

In the default configuration (autoTransaction = false) this is a non-issue, since both paths throw the same TransactionException when called outside a transaction, matching the old restoreRecordAndUpdateCount helper this replaces. But for a database opened with setAutoTransaction(true), a plain INSERT would silently auto-wrap while RESTORE DOCUMENT/VERTEX/EDGE (or a direct restoreRecord call) now throws. Not a regression from prior behavior, but worth a short javadoc note on restoreRecord if the intent is to stay aligned with createRecordNoLock for auto-transaction users; RESTORE being an admin/repair operation that requires an explicit transaction also seems like a defensible choice either way.

Minor / nit

  • restoreRecord does not reject a record that already has a non-null identity before calling bucket.restoreRecordAtPosition, whereas createRecordNoLock explicitly rejects a persistent record up front. Low risk since the method is internal (DatabaseInternal, not user-facing) and every current caller constructs a fresh shell, but a defensive IllegalArgumentException would match the createRecordNoLock contract and catch a future misuse early instead of silently overwriting a live record identity.
  • RaftReplicatedDatabase.java new import com.arcadedb.engine.LocalBucket; (line 48) is inserted out of alphabetical order, between PageId and PageManager, while the equivalent import in ServerDatabase.java is placed correctly. Purely cosmetic.

Design departures (validate/setDefaultValues and create events skipped)
Both are called out explicitly in the PR description as deliberate, and the reasoning holds up: gating an emergency repair behind a mandatory-property check would defeat the point of the operation, and firing user-authored onAfterCreate triggers (including JS ones) during a repair is a much bigger behavioral surface than this fix should take on. Agreed that documenting the "restore skips create events" contract in the SQL reference is the right follow-up rather than changing the behavior now.

Tests
The six new regression tests are well targeted, each described as confirmed red with the fold removed, and restoreDocumentEnforcesTheUniqueIndexOnTheRestoredKey is a particularly good one since it exercises the exact "silently hands a duplicate key to a second record" failure mode from the bug report, not just presence/absence of an index entry. The reopenDatabase() calls in a couple of tests are a nice touch since they catch index entries that only look right in the in-memory, not-yet-flushed state.

One gap acknowledged in the PR description itself: no index-specific test on GraphEngine.restoreVertexAt, since it only restores a property-less shell and a null-valued indexed property produces no index entry on any path. Reasonable, not something to block on.

Summary
No blocking issues found. The auto-transaction gap and the two nits above are minor enough to leave to maintainer judgment rather than requiring changes before merge.

… parity with create

PR #6123 code review raised three points, all valid.

The substantive one: restoreRecord called getTransaction() directly, so
on a database opened with setAutoTransaction(true) a plain INSERT would
wrap itself in an implicit transaction while RESTORE DOCUMENT/VERTEX/EDGE
threw TransactionException. Not a regression - the helper it replaced did
the same - but RESTORE should not be the one statement that behaves
differently from an INSERT for those callers. It now uses the same
checkTransactionIsActive(autoTransaction) + implicit commit/rollback
frame as createRecordNoLock. The review offered a javadoc note as the
cheaper option; parity is the better one, and it costs a try/finally.

Second: restoreRecord did not reject an already-persistent record, so a
future misuse would silently overwrite the identity of a live record
rather than failing. It now raises the same IllegalArgumentException
createRecordNoLock does. Verified this does not catch RESTORE EDGE, whose
shell comes from the MutableEdge(database, type, out, in) constructor and
is non-persistent like the others.

Third: an out-of-order import in RaftReplicatedDatabase.

The interface javadoc now also states the transaction contract and both
deliberate departures from create (no validate()/default values, no
create events), so the next reader does not have to trace the call graph
to establish what the review just established.

Two tests, both confirmed red against the fix removed - the
auto-transaction one failing with exactly the "Transaction not begun" the
review predicted.

Full engine suite: 11717 tests, 1 failure - Issue5279ConcurrentUpdateTest,
which fails identically on clean main.
@claude

claude Bot commented Aug 13, 2026

Copy link
Copy Markdown

Review

This is a well-scoped fix with strong regression coverage (6 tests, each verified red against the fold removed per the PR description) and clear documentation of the two deliberate departures from createRecordNoLock (no validate()/defaults, no create events). The consolidation of four hand-rolled call sites into one DatabaseInternal.restoreRecord primitive is the right move given the #6069/#6120 history described in the PR body.

One correctness issue found on close reading:

registerNewRecord runs after the indexer call, unlike createRecordNoLock

In LocalDatabase.restoreRecordInTransaction (engine/src/main/java/com/arcadedb/database/LocalDatabase.java):

if (record instanceof MutableDocument doc) {
  indexer.createDocument(doc, doc.getType(), bucket);   // can throw DuplicatedKeyException
  transaction.registerNewRecord(record);                // skipped if the line above throws
}

Compare with createRecordNoLock a few lines above it, which does the two calls in the opposite order:

if (record instanceof MutableDocument)
  transaction.registerNewRecord(record);

if (record instanceof MutableDocument doc)
  indexer.createDocument(doc, doc.getType(), bucket);

TransactionContext.rollback() only clears a record's identity (and pulls it out of the reload loop) for records present in newRecords (see the comment on registerNewRecord: "if the transaction is rolled back, its optimistically-assigned identity can be reset to provisional"). Because restoreRecordInTransaction registers after indexing, a DuplicatedKeyException thrown by indexer.createDocument - which is exactly the scenario the new restoreDocumentEnforcesTheUniqueIndexOnTheRestoredKey test exercises - leaves the record un-registered. On rollback, that record object keeps a non-null getIdentity() pointing at a RID that was never actually restored (the physical page write itself is correctly discarded via modifiedPages = null, but the in-memory Java object is not reset).

This is the exact "dangling RID on the caller's object" bug class the PR's own docstring on restoreRecordInTransaction describes as the reason registerNewRecord exists, and that rollingBackARestoreLeavesNoDanglingIdentityOnTheShell guards against - but that test only rolls back a successful restore; it doesn't cover the exception path where registration is skipped.

Concretely, for a direct Java API caller:

MutableDocument shell = database.newDocument(type).set("k", "duplicate");
try {
  db.restoreRecord(shell, bucket, position);
} catch (DuplicatedKeyException e) {
  // shell.getIdentity() is non-null here even though nothing was persisted
}
// ...if the transaction is later rolled back, shell.getIdentity() stays non-null,
// so a subsequent shell.save() would be routed as an UPDATE instead of a CREATE.

Suggested fix: move transaction.registerNewRecord(record) before indexer.createDocument(...), matching createRecordNoLock's order, so the record is always tracked for rollback identity-reset regardless of whether indexing throws. A regression test analogous to restoreDocumentEnforcesTheUniqueIndexOnTheRestoredKey but asserting shell.getIdentity() is null after the duplicate-key exception + rollback would catch this and lock in the fix.

Minor / non-blocking

  • LocalBucket.getPurpose() != PRIMARY guard on restoreRecord is a good addition for parity with createRecordNoLock's equivalent check. No direct test for it here, but it's a defensive check outside this bug's blast radius, so that's fine to leave as-is unless you want belt-and-suspenders coverage.
  • Everything else (auto-transaction parity, persistent-record rejection, javadoc contract) looks correct and matches createRecordNoLock's behavior faithfully.

Nice work tracing this through to the DatabaseInternal interface level instead of patching yet another call site - that consolidation is exactly what prevents the next version of this bug.

PR #6123 second review flagged that restoreRecordInTransaction called
indexer.createDocument() before transaction.registerNewRecord(), the
opposite of createRecordNoLock's order, so an exception from the indexer
would skip the rollback identity reset and leave a dangling RID on the
caller's object.

The conclusion is right and the reorder costs nothing, so it is applied.
The mechanism the review cited is not, and the comment now records both
so the question is not reopened later: the review named the
unique-constraint path exercised by
restoreDocumentEnforcesTheUniqueIndexOnTheRestoredKey, but a duplicate
key is detected at COMMIT, not inline - measured directly, restoreRecord
returns normally with an identity, the DuplicatedKeyException comes out
of commit(), and the rollback already resets the identity to null. A
regression test written to that scenario would pass with and without the
reorder, so none was added.

What does make the order matter is that Index.put() can throw inline:
checkIsValid() on a dropped or invalidated index, and convertKeys() on a
key it cannot coerce. Reaching either needs an index dropped or corrupted
mid-transaction, which is contrived enough that a test would pin the
scaffolding rather than the behaviour, so this stands as defensive parity
with createRecordNoLock rather than a covered fix.
@lvca

lvca commented Aug 13, 2026

Copy link
Copy Markdown
Member Author

Addressed in e1c1ee8 — with one correction to the finding, since it changes what the code should say.

The reorder is applied. transaction.registerNewRecord(record) now runs before indexer.createDocument(...), matching createRecordNoLock.

The cited mechanism does not reproduce, though. The review names the unique-constraint path exercised by restoreDocumentEnforcesTheUniqueIndexOnTheRestoredKey, but a duplicate key is detected at commit, not inline. Measured directly against the pre-fix code:

restoreRecord returned, identity=#1:0
thrownAt=COMMIT: DuplicatedKeyException
identityAfterRollback=null

restoreRecord returns normally with an identity, DuplicatedKeyException comes out of commit(), and by then both calls have run — so the rollback already resets the identity to null. The suggested regression test would therefore pass with and without the reorder, so I did not add it rather than ship a green test that pins nothing.

(This also corrects the first review on this PR, which said the ordering "does not matter here". It does — just not via the duplicate-key path.)

What does make the order matter: Index.put() can throw inline — checkIsValid() on a dropped or invalidated index, and convertKeys() on a key it cannot coerce. On those paths, registering after indexing really would skip the rollback identity reset. So the change is worth making; it is defensive parity rather than a fix for a reachable-in-practice bug. Reaching either path requires an index dropped or corrupted mid-transaction, contrived enough that a test would pin the scaffolding rather than the behaviour, so none was added.

The code comment now records both halves — the reachable inline throws, and the fact that the unique path is not one of them — so this doesn't get re-litigated on the next read.

Verification: restore tests plus a Restore*,*Transaction*,*Index*,*Rollback*,*Graph* subset green. The prior commit had a full engine run at 11717 tests with one failure, Issue5279ConcurrentUpdateTest, which fails identically on clean main.

@claude

claude Bot commented Aug 13, 2026

Copy link
Copy Markdown

Review

Solid fix, and the PR description/commit history shows the tricky bits (auto-transaction parity, persistent-record rejection, register-before-index ordering) were already caught and addressed across the four commits. I read through the full diff plus the surrounding createRecordNoLock/TransactionContext/LocalBucket code it mirrors; here's what I found.

Correctness

  • LocalDatabase.restoreRecord/restoreRecordInTransaction (engine/src/main/java/com/arcadedb/database/LocalDatabase.java:1117-1176) tracks createRecordNoLock closely: identity-null check, read-only check, PRIMARY-purpose check, auto-transaction wrapping with commit/rollback in finally, cache update, bucket-count delta fold, registerNewRecord before indexer.createDocument (so an inline exception from Index.put still resets the shell's identity on rollback), then unsetDirty(). No divergence from the create path that isn't intentional and documented (no validate()/setDefaultValues(), no create events).
  • Verified MutableEdge(database, edgeType, out, in) (used by RestoreEdgeStatement) goes through the super(graph, type, null) constructor, so the identity-null check in restoreRecord doesn't misfire on the edge shell.
  • GraphEngine.restoreVertexAt, RestoreDocumentStatement, RestoreVertexStatement, RestoreEdgeStatement all route through the same DatabaseInternal.restoreRecord, and RestoreStatementSupport's hand-rolled duplicate is gone - directly addresses the 'four call sites, four chances to forget' problem described in the PR.
  • ServerDatabase and RaftReplicatedDatabase both get straightforward delegating overrides; confirmed via grep these are the only two DatabaseInternal implementors besides LocalDatabase, plus the test stub in SQLMethodTransformTest, so nothing else needed updating for the new interface method to compile.

Test coverage
Good breadth: SQL-level tests for DOCUMENT/VERTEX/EDGE reindexing, the UNIQUE-index duplicate-rejection case, the Java API (restoreRecord directly with a populated record, since restoreVertexAt's property-less shell can't exercise indexing), auto-transaction parity, persistent-record rejection, and rollback identity reset. The PR description states each was confirmed red with the fold removed, which is the right way to validate a regression test.

Minor / non-blocking

  • RestoreSqlStatementTest.countByScan(String type) (engine/src/test/java/com/arcadedb/query/sql/executor/RestoreSqlStatementTest.java:419) duplicates the pre-existing no-arg countByScan() (same file, ~line 436) almost line for line, just against a fixed DOC_TYPE vs. a parameter. Could fold the old one into a call to the new parametrized version (countByScan(DOC_TYPE)) to remove the near-duplicate - purely a nit.
  • The interface javadoc on DatabaseInternal.restoreRecord (engine/src/main/java/com/arcadedb/database/DatabaseInternal.java:17-40) is thorough and will save the next reader a call-graph trace.

Not re-litigating
The PR body already surfaces two deliberate, debatable departures from createRecordNoLock (no validate(), no create events) and asks for a maintainer opinion on whether to codify that in the SQL reference docs - deferring to Luca on that product decision; the code matches what's documented either way.

No correctness, security, or performance issues found. I could not run mvn compile/mvn verify in this sandbox, so this relied on manual tracing (interface implementors, constructor call chains, transaction/index ordering) rather than a live build - worth confirming CI is green before merge if it hasn't finished yet.

PR #6123 third review nit: the DOC_TYPE-specific countByScan() added
earlier duplicated the parametrized countByScan(String) almost line for
line. It now delegates.
@claude

claude Bot commented Aug 13, 2026

Copy link
Copy Markdown

Review

This is a solid fix for a real correctness bug (index entries silently missing after RESTORE), and the write-up/commit history shows the design was already tightened through several review rounds (auto-transaction parity, persistent-record guard, register-before-index ordering, import cleanup). Consolidating the four call sites into DatabaseInternal.restoreRecord is the right structural fix - it removes exactly the "one more call site to forget" failure mode that caused #6069 and #6120 in the first place. Test coverage is good: each new regression test is described as confirmed-red against the revert, and the choice to skip an index test on GraphEngine.restoreVertexAt (null-valued property -> no index entry on any path) is a reasonable, explained call rather than a coverage gap.

Two things worth a look before merge:

1. restoreRecord's implicit-transaction commit/rollback runs outside the read lock (LocalDatabase.java:1134-1148)

Every sibling method that opens an implicit auto-transaction - createRecordNoLock (via createRecord's wrapper), updateRecord, scanType - calls checkTransactionIsActive(autoTransaction), does the work, and calls the implicit commit()/rollback() all inside one executeInReadLock closure. restoreRecord instead calls checkTransactionIsActive before acquiring the lock, wraps only restoreRecordInTransaction in executeInReadLock, and calls wrappedDatabaseInstance.commit()/rollback() after releasing it (each of which reacquires its own read lock instance).

Functionally this still commits/rolls back the right transaction (same thread, same ThreadLocal context), so it's not broken in the common case. But it opens a window - absent everywhere else in this file - where a concurrent executeInWriteLock caller (drop(), close()) could interleave between the physical restore write and the commit that persists it, something the continuous-lock-hold pattern elsewhere in this file exists specifically to prevent. Given the PR's stated goal is exact parity with createRecordNoLock's transaction contract, it'd be worth wrapping the whole restoreRecord body in a single executeInReadLock, the same way createRecord/updateRecord/scanType do, rather than only the inner write.

2. restoreRecordInTransaction doesn't fold poisonEdgeAppendPage for MutableEdgeSegment/StripeDirectory (LocalDatabase.java:1150-1176 vs. 1086-1087)

createRecordNoLock poisons the page for a brand-new edge chunk or stripe directory so a same-transaction slot-merge replay at commit doesn't rebase an insert the committed page doesn't have yet (see the edge-append-merge note in engine/CLAUDE.md). restoreRecordInTransaction has no equivalent branch. Today this is harmless - every current caller (RESTORE DOCUMENT/VERTEX/EDGE, GraphEngine.restoreVertexAt) only ever restores a MutableDocument/MutableVertex/MutableEdge shell, never a raw MutableEdgeSegment or StripeDirectory - but restoreRecord is a general Record-typed method on a shared interface, and the javadoc's "two deliberate departures from createRecordNoLock" list (no validate(), no create events) doesn't mention this third one. Worth either a one-line javadoc note (this primitive isn't meant for edge-chunk/stripe-directory records) or, if that's the intent, an explicit guard so a future caller gets a clear error instead of a silent gap.

Neither point blocks the core fix - both are edge cases around the new primitive's contract rather than bugs in the index-fold logic itself, which is correct and well-tested.

@lvca lvca self-assigned this Aug 13, 2026
@lvca lvca added this to the 26.9.1 milestone Aug 13, 2026
…mmit

PR #6123 fourth review raised two contract gaps around the new primitive.
Both are real and both are now closed.

1. The implicit auto-transaction was opened before executeInReadLock and
   committed after it, so only the physical write was inside the lock.
   createRecord wraps ALL of createRecordNoLock - checkTransactionIsActive,
   the work and the implicit commit/rollback - in a single read lock, and
   the gap left a window unique in this class for an executeInWriteLock
   caller (drop(), close()) to interleave between the page write and the
   commit that persists it. The whole body is now one read lock, matching
   the sibling. Verified no deadlock: the auto-transaction regression test
   drives an implicit commit from inside the lock and passes, which is
   possible only because commit() does not need the write lock (the same
   reason createRecord's shape works).

2. restoreRecordInTransaction did not fold poisonEdgeAppendPage for
   MutableEdgeSegment/StripeDirectory the way createRecordNoLock does. A
   restored edge chunk is absent from the committed version of its page,
   so replaying this transaction's appends against that page at commit
   would target the wrong bytes. No current caller restores one - every
   RESTORE arm passes a document/vertex/edge shell - but this is a general
   Record-typed method on a shared interface, so the review's options were
   a javadoc note or a guard. Folding the same poison is better than
   either: a future caller gets correct behaviour instead of a documented
   trap. Note restoreRecordAtPosition already poisons the SLOT merge; this
   is the separate commutative edge-append merge.

Restore tests plus a Restore*/Transaction*/Concurren*/Drop*/Close*/Lock*/
Database* subset: 489 tests, 1 failure - Issue5279ConcurrentUpdateTest,
which fails identically on clean main.
@lvca

lvca commented Aug 13, 2026

Copy link
Copy Markdown
Member Author

Both points were valid — fixed in 908c8a5.

1. Implicit commit outside the read lock. Confirmed against the sibling: createRecord wraps all of createRecordNoLock — checkTransactionIsActive, the work, and the implicit commit/rollback — in a single executeInReadLock, so the commit really does happen under the lock there. restoreRecord now has the same shape.

Worth recording why this is safe, since it is the one thing that could have gone wrong: committing while holding a read lock would deadlock if commit() needed the write lock (a ReentrantReadWriteLock cannot upgrade). It does not — which is exactly why createRecord's shape works — and the auto-transaction regression test drives an implicit commit from inside the lock and passes rather than hanging.

2. Missing poisonEdgeAppendPage fold. You offered a javadoc note or a guard; I took a third option and folded the same poison createRecordNoLock applies. A restored edge chunk is absent from the committed version of its page for the same reason a brand-new one is, so the poison is equally correct here, and a future caller gets working behaviour instead of a documented trap. The comment notes that restoreRecordAtPosition already poisons the slot merge and that this is the separate commutative edge-append merge, so the two don't get confused.

The javadoc's "two deliberate departures" list stays accurate — folding this means it was never a third departure.

Verification: Restore*,*Transaction*,*Concurren*,*Drop*,*Close*,*Lock*,*Database* subset — 489 tests, 1 failure (Issue5279ConcurrentUpdateTest, which fails identically on clean main). That selection deliberately includes the drop()/close() and locking tests, since the lock restructure is the change most likely to break something far from the restore path. A full engine run is in progress.

On the sandbox note: understood that this review was manual tracing only. Local runs have been backing each commit — the prior one had a full engine suite at 11717 tests with the same single pre-existing failure.

@claude

claude Bot commented Aug 13, 2026

Copy link
Copy Markdown

Review

I read through the full diff plus the surrounding code (LocalDatabase.createRecordNoLock, LocalBucket.restoreRecordAtPosition, TransactionContext, and all four DatabaseInternal implementers) to check the parity claims in the PR description. I wasn't able to run mvn verify in this review environment (build commands weren't permitted here), so this is a static/manual review rather than an executed one - the PR body's own note that the full engine suite passes locally (modulo the pre-existing unrelated Issue5279ConcurrentUpdateTest flake) is good practice per this repo's CLAUDE.md and I have no reason to doubt it from reading the code.

Overall

This is a solid, well-scoped fix. The root cause diagnosis (index bookkeeping folded into createRecordNoLock but never extracted for RESTORE's four call sites) is correct, and centralizing it as DatabaseInternal.restoreRecord next to createRecordNoLock is the right structural fix rather than patching each call site again. I checked the parity claims line-by-line against createRecordNoLock (LocalDatabase.java:1038-1114 vs 1117-1195):

  • updateRecordInCache / updateBucketRecordDelta(+1) - present, same order.
  • registerNewRecord called before indexer.createDocument - matches create's order (this was the 4th review round's fix, correctly applied).
  • poisonEdgeAppendPage for MutableEdgeSegment/StripeDirectory - present, correctly folded in as the 5th round added.
  • The whole body (implicit-transaction begin, work, implicit commit/rollback) is inside a single executeInReadLock, matching createRecord's wrapping of createRecordNoLock - the lock-window fix from the last round is real and correctly shaped.
  • All four DatabaseInternal implementers got the new method: LocalDatabase (real impl), ServerDatabase and RaftReplicatedDatabase (delegating overrides), and the anonymous test double in SQLMethodTransformTest (stub). Nothing left half-wired.
  • MutableVertex/MutableEdge both extend MutableDocument, so the single instanceof MutableDocument doc branch correctly covers document/vertex/edge indexing without needing type-specific branches.

The two deliberate departures from createRecordNoLock (no validate()/default values, no create events) are reasonable for an admin-repair primitive and are called out clearly in both the interface javadoc and the PR description - agreed this is worth a maintainer opinion on the "restored record skips onAfterCreate" point, but that's a product decision, not a code issue.

Minor findings (not blocking)

  1. No dedicated test for the new bucket-purpose guard. LocalDatabase.restoreRecord (LocalDatabase.java:1127-1129) rejects restoring into a non-PRIMARY bucket (e.g. an EXTERNAL_PROPERTY bucket), mirroring createRecordNoLock's existing guard - but this specific check is new for the restore path and I didn't find a test exercising it (searched both RestoreRecordAtPositionTest and RestoreSqlStatementTest for getPurpose/EXTERNAL_PROPERTY/"is internal"). Given CLAUDE.md's "all new server-side code must be tested" guidance, a small test restoring into an external-property bucket and asserting the IllegalArgumentException would close the gap. Low severity since it's a defensive check, not new behavior on the happy path.

  2. GraphEngine.restoreVertexAt discards restoreRecord's return value (GraphEngine.java:446), relying on targetRid instead - unlike the three SQL statement call sites, which all use the returned restoredRid. The javadoc guarantees the return equals bucket's file id at position, so this isn't a bug, just a minor inconsistency in style across the four call sites. Not worth a change on its own.

Nits

  • contentEndOffset()'s new comment (LocalBucket.java:1144-1149) documenting the guard as currently-unreachable-but-kept is a nice addition for future readers - no issue there.
  • Import ordering in RaftReplicatedDatabase is correct (checked - LocalBucket sits alphabetically between FileManager and PageId).

Nothing here rises to a correctness or security concern. The iterative review history on this PR (auto-transaction parity, persistent-record guard, registration-before-indexing ordering, single-lock-window fix, edge-append poisoning) already caught the substantive issues; what's left is test-coverage polish.

@lvca
lvca merged commit d1c7494 into main Aug 13, 2026
15 checks passed
@lvca
lvca deleted the fix/6120-restore-index-entries branch August 13, 2026 02:46
@codecov

codecov Bot commented Aug 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 67.56757% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.72%. Comparing base (59e590a) to head (908c8a5).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...main/java/com/arcadedb/database/LocalDatabase.java 70.58% 5 Missing and 5 partials ⚠️
...rcadedb/server/ha/raft/RaftReplicatedDatabase.java 0.00% 1 Missing ⚠️
.../main/java/com/arcadedb/server/ServerDatabase.java 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main    #6123    +/-   ##
========================================
  Coverage   69.72%   69.72%            
========================================
  Files        1821     1821            
  Lines      156148   156275   +127     
  Branches    32959    32979    +20     
========================================
+ Hits       108873   108967    +94     
- Misses      33615    33644    +29     
- Partials    13660    13664     +4     

☔ 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.

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.

RESTORE DOCUMENT/VERTEX/EDGE does not re-add the record's index entries: an indexed query returns 0 rows while a full scan returns 1

1 participant