Skip to content

fix(#6096): skip record-table holes when computing the RESTORE insertion offset - #6119

Merged
lvca merged 1 commit into
mainfrom
fix/6096-restore-same-tx
Aug 13, 2026
Merged

lvca merged 1 commit into
mainfrom
fix/6096-restore-same-tx

Conversation

@lvca

@lvca lvca commented Aug 13, 2026

Copy link
Copy Markdown
Member

Fixes #6096.

What was wrong

RESTORE DOCUMENT/VERTEX/EDGE executed in the same transaction as the DELETE wrote the restored record on top of the page's own slot table. The record was then unreachable by every scan and lookup, while count(*) still reported it as present - the DELETE's -1 and the RESTORE's +1 (added by #6082 for #6069) cancel out, so the counter is right about a record that is not there.

Root cause

LocalBucket.findContentInsertionOffset() took the max over the page's record table to find where the last record's bytes end:

if (recordPositionInPage > lastRecordPositionInPage)   // 0 == hole, not a record
  lastRecordPositionInPage = recordPositionInPage;

A delete leaves a 0 entry in that table. 0 was treated as a record starting at content offset 0 instead of as a hole, so on a page whose every slot is a hole the max is 0: the varint read at offset 0 lands on the recordCountInPage header short, decodes as size 0 ("deleted, v<24.1.1"), and the computed insertion offset comes out as 1 - inside the 8194-byte page header. The restore wrote the record there, over the slot-table entry it had just written for itself.

Only the same-transaction shape can reach it. On commit, compressPage() resets an all-holes page's record count to 0, so a restore in a later transaction sees 0 slots and correctly starts at contentHeaderSize - which is exactly why the reporter's separate-transaction run worked and the one-transaction run did not.

The fix

The allocator's getFreeSpaceInPage() has always skipped those 0 entries correctly (if (recordPositionInPage == 0) { ... } else if (... > last)). findContentInsertionOffset() was a second copy of the same "offset past the last record" computation, and the two had drifted.

Rather than patching the copy, the shared part is now one method - contentEndOffset() - used by both callers, over the existing hole-skipping getLastRecordPositionInPage(). Net effect: 34 duplicated lines removed, and the two paths can no longer diverge again.

It also rejects a live slot pointing inside the page header outright. That state is a corrupted record table, and failing loudly beats deriving an insertion offset from header bytes - the same guard getPageOccupiedInBytes() already applies on the update path.

Verification

Three regression tests, all confirmed red on the pre-fix code and green with it:

  • RestoreRecordAtPositionTest.restoresARecordDeletedInTheSameTransaction - engine primitive, delete + restore in one transaction, asserts scan, bucket.count() and lookup agree before and after a reopen
  • RestoreRecordAtPositionTest.restoresIntoAPageWhoseEverySlotIsAHole - single-bucket type, all three records deleted in one transaction, middle one restored
  • RestoreSqlStatementTest.restoreDocumentInTheSameTransactionAsTheDelete - the reporter's exact SQL shape, count(*) vs full scan vs lookupByRID, before and after reopen

Full engine suite: 11709 tests, 1 failure - Issue5279ConcurrentUpdateTest.growingUpdatesUnderContentionKeepTheDatabaseConsistent, which fails identically on clean main (verified by stashing this change) and is a known pre-existing contention flake. Full project compiles.

Not in this PR

RESTORE does not add index entries for the restored record (the statements call bucket.restoreRecordAtPosition() directly, bypassing the LocalDatabase.createRecord path that indexes). That is a separate pre-existing gap in the same family - an indexed query and a full scan disagree after a restore - and I will file it separately rather than widen this fix.

…ion offset

RESTORE DOCUMENT/VERTEX/EDGE run in the SAME transaction as the DELETE
wrote the restored record on top of the page's own slot table, so the
record was unreachable by every scan and lookup while count(*) - whose
-1/+1 folds cancelled out - still reported it as present.

LocalBucket.findContentInsertionOffset() took the max over the page's
record table to find where the last record's bytes end. A delete leaves
a 0 entry in that table, and 0 was treated as "a record starting at
content offset 0" instead of as a hole. On a page whose every slot is a
hole the max is therefore 0, the varint read at offset 0 lands on the
record-count header, and the computed insertion offset is 1 - inside the
8194-byte page header. The restore then wrote the record there, over the
slot-table entry it had just written for itself.

Only the same-transaction shape could reach it: on commit compressPage()
resets an all-holes page's record count to 0, so a restore in a later
transaction sees 0 slots and correctly starts at contentHeaderSize.

The allocator's getFreeSpaceInPage() has always skipped those 0 entries
correctly. findContentInsertionOffset() was a second copy of the same
computation that had drifted, so rather than patching the copy the
shared part is now one method, contentEndOffset(), used by both, over
the existing hole-skipping getLastRecordPositionInPage(). It also
rejects a slot pointing inside the page header outright: that is a
corrupted record table, and failing loudly beats deriving an insertion
offset from header bytes (the same guard getPageOccupiedInBytes already
applies on the update path).

Regression coverage at both levels, all three confirmed red on the
pre-fix code: LocalBucket.restoreRecordAtPosition() with the delete in
the same transaction and with every slot of the page a hole, and the SQL
RESTORE DOCUMENT statement in one transaction with the DELETE, asserting
scan, count(*) and lookup agree before and after a reopen.
@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

🟢 Coverage 60.00% diff coverage

Metric Results
Coverage variation Report missing for cd58bed1
Diff coverage ✅ 60.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (cd58bed) Report Missing Report Missing Report Missing
Head commit (0b86f4c) 188491 135533 71.90%

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 (#6119) 5 3 60.00%

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

1 Codacy didn't receive coverage data for the commit, or there was an error processing the received data. Check your integration for errors and validate that your coverage setup is correct.

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.

@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

@claude

claude Bot commented Aug 13, 2026

Copy link
Copy Markdown

Review

Solid, well-scoped fix. I read through the diff, the full surrounding LocalBucket.java context (all callers of getLastRecordPositionInPage/getFreeSpaceInPage/getPageOccupiedInBytes), and the new tests.

Correctness

  • Root cause and fix match: findContentInsertionOffset()'s old loop took a plain max() over slot-table entries without skipping 0 (hole) entries, so an all-holes page produced lastRecordPositionInPage == 0, which was then misread as a real record header, yielding an insertion offset of 1 inside the page header. Routing it through the already-correct getLastRecordPositionInPage() (which explicitly skips recordPositionInPage == 0) fixes this.
  • Confirmed getFreeSpaceInPage()'s own loop (engine/src/main/java/com/arcadedb/engine/LocalBucket.java:2992-3006) already skipped holes correctly before this change, so factoring the shared tail into contentEndOffset() is a faithful, behavior-preserving extraction for that path - not a fix for it.
  • The MutablePage → BasePage widening on getLastRecordPositionInPage is safe (MutablePage extends BasePage), and it's needed since findContentInsertionOffset is only ever handed an immutable/read page reference in some call shapes.

On the new lastRecordPositionInPage < contentHeaderSize guard in contentEndOffset()

Worth double-checking (not blocking): tracing both call sites, the value passed in is always either -1 or something produced by getRecordPositionInPage(), which already throws IOException for any non-zero value < contentHeaderSize (LocalBucket.java:2515-2521). So this new branch looks unreachable under the current call graph - it mirrors the identical pre-existing guard in getPageOccupiedInBytes() (LocalBucket.java:2859), which has the same "should never occur" characteristic. That's a reasonable defensive-programming choice consistent with the file's existing style, just flagging it's belt-and-suspenders rather than reachable dead-record-table handling, in case that wasn't the intent.

Tests

  • Good coverage at both the engine primitive level (RestoreRecordAtPositionTest) and the SQL statement level (RestoreSqlStatementTest), each with the same-transaction (bug-triggering) shape and a same-page-many-holes variant, and each asserting count()/full-scan/lookupByRID agreement rather than count(*) - correctly avoiding the cached-counter trap called out in this module's own count(*) vs count() documentation, since the whole bug was that the cached counter's -1/+1 fold looked fine while the record itself was unreachable.
  • Both engine-level tests reopen the database and re-assert, which also exercises compressPage()'s post-commit renumbering path against the restored record - good regression coverage for the "why did the separate-transaction case never hit this" root-cause explanation in the PR description.

Style/perf

  • No new dependencies, no System.out, final used consistently, single-line if bodies without braces match the surrounding code.
  • No perf concern: the refactor is a straight line-for-line extraction: same O(records-in-page) walk as before, no new allocations or extra page reads on the hot insert path.

Nothing blocking. Nice writeup in the PR description tying the bug to the #6082/#6069 counter-fold interaction.

@lvca lvca self-assigned this Aug 13, 2026
@lvca lvca added this to the 26.9.1 milestone Aug 13, 2026
@lvca
lvca merged commit 59e590a into main Aug 13, 2026
25 of 28 checks passed
@lvca
lvca deleted the fix/6096-restore-same-tx branch August 13, 2026 00:55
@codecov

codecov Bot commented Aug 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 40.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.72%. Comparing base (5157337) to head (0b86f4c).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...src/main/java/com/arcadedb/engine/LocalBucket.java 40.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6119      +/-   ##
==========================================
+ Coverage   69.68%   69.72%   +0.04%     
==========================================
  Files        1821     1821              
  Lines      156116   156148      +32     
  Branches    32950    32959       +9     
==========================================
+ Hits       108782   108871      +89     
+ Misses      33677    33613      -64     
- Partials    13657    13664       +7     

☔ 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 added a commit that referenced this pull request Aug 13, 2026
…6123)

* docs(#6096): record why the contentEndOffset() header guard is kept though 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.

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

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.

* fix(#6120): give restoreRecord auto-transaction and persistent-record 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.

* fix(#6120): register the restored record before indexing it

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.

* test(#6120): fold the no-arg countByScan into the parametrized one

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

* fix(#6120): hold one read lock across the restore and its implicit commit

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.
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 in the same transaction as the DELETE: count(*) reports 1, a full scan returns 0

1 participant