Repository navigation
fix(#6096): skip record-table holes when computing the RESTORE insertion offset - #6119
Conversation
…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.
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Coverage variation | Report missing for cd58bed1 |
| Diff coverage | ✅ 60.00% diff coverage |
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.
|
Tick the box to add this pull request to the merge queue (same as
|
ReviewSolid, well-scoped fix. I read through the diff, the full surrounding Correctness
On the new
|
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
…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.
Fixes #6096.
What was wrong
RESTORE DOCUMENT/VERTEX/EDGEexecuted in the same transaction as theDELETEwrote the restored record on top of the page's own slot table. The record was then unreachable by every scan and lookup, whilecount(*)still reported it as present - theDELETE's-1and theRESTORE'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:A delete leaves a
0entry in that table.0was 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 is0: the varint read at offset 0 lands on therecordCountInPageheader 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 atcontentHeaderSize- 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 those0entries 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-skippinggetLastRecordPositionInPage(). 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 reopenRestoreRecordAtPositionTest.restoresIntoAPageWhoseEverySlotIsAHole- single-bucket type, all three records deleted in one transaction, middle one restoredRestoreSqlStatementTest.restoreDocumentInTheSameTransactionAsTheDelete- the reporter's exact SQL shape,count(*)vs full scan vslookupByRID, before and after reopenFull
enginesuite: 11709 tests, 1 failure -Issue5279ConcurrentUpdateTest.growingUpdatesUnderContentionKeepTheDatabaseConsistent, which fails identically on cleanmain(verified by stashing this change) and is a known pre-existing contention flake. Full project compiles.Not in this PR
RESTOREdoes not add index entries for the restored record (the statements callbucket.restoreRecordAtPosition()directly, bypassing theLocalDatabase.createRecordpath 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.