Skip to content

fix(#8401): measure the free tail directly on a rebased delete and on the delete wipe - #8416

Merged
lvca merged 1 commit into
mainfrom
fix/8401-rebase-delete-free-space
Sep 25, 2026
Merged

lvca merged 1 commit into
mainfrom
fix/8401-rebase-delete-free-space

Conversation

@lvca

@lvca lvca commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Fixes #8401

Root cause

rebaseRecordDeleteOnPage (the disjoint-slot merge of a record delete) and wipeOutFreeSpace (the free-tail wipe after a delete's compaction) both used the allocator's getFreeSpaceInPage as a measurement of the page's free tail. That method answers a different question, "can a new record go on this page?", and on a page whose slot table is full (recordCount >= maxRecordsInPage) it returns before measuring anything (#2258), leaving spaceAvailableInCurrentPage at its -1 default.

Small records reach that shape routinely: 2048 edges of ~14 bytes fill the slot table of a 64 KB page with about half of its bytes still free. So:

  • rebased delete: -1 was reported to updatePageStatistics as the page's free space. Under -ea this trips the tripwire and fails the commit (page N of bucket 'RELATES_TO_0' is reported with -1 free bytes and a delta of 0). In production the value was absorbed and the commit-time compaction re-measured the page, so the effect there was a transient wrong hint.
  • delete wipe (correlated, same short-circuit): with bucketWipeOutOnDelete (default on) the compaction after a delete skipped zeroing the free tail on these pages, leaving a stale copy of the records the defragmentation had just moved down. That is the leftover content the setting exists to remove.

Fix

Both now measure the tail with findContentInsertionOffset (offset past the last record), which is the same slot scan without the allocator's short-circuit. It is also cheaper than before: no hole search, and no RID allocation plus isDeletedInTransaction lookup per hole.

The allocator keeps its short-circuit on purpose: skipping pages whose slot table is full is the #2258 bulk-insert optimisation, and changing what the allocator considers usable is a separate decision.

Tests

  • Issue8401RebasedDeleteOnFullSlotTableTest
    • aRebasedDeleteOnAPageWithAFullSlotTableReportsTheRealFreeTail: page 0 with a full slot table, a delete committed after a concurrent update of another record on the same page (so it goes through rebaseRecordDeleteOnPage). Red before the fix (the assertion above), green after. It also checks that the delete and the concurrent update both survive, and that the hint is the real tail.
    • theCompactionAfterADeleteWipesTheFreeTailOfAPageWithAFullSlotTable: red before the fix (free tail byte at offset 54165 of 65528 must be wiped), green after.
  • Related classes (slot merge, free-space claims, delete, bucket layout; 276 tests): green.
  • Full engine unit lane (-DexcludedGroups=slow,benchmark,vector, 16508 tests): green except SleepStatementExecutionTest, which measured SLEEP 1000 with the wall clock and got 957 ms. It now measures with System.nanoTime() (test-only change), and passes.
  • The concurrent stress workload that hit the assertion within seconds (16 threads, 60k vertices, deletes) passes 3 runs out of 3.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability when deleting records from pages whose record-slot tables are full but still have unused space. Concurrent updates and deletes are better preserved, and page compaction handles remaining free space more accurately.
    • Corrected free-space reporting for these pages, helping prevent available space from being misrepresented.
  • Tests

    • Added regression coverage for concurrent record changes, page compaction, and database integrity.

… the delete wipe

rebaseRecordDeleteOnPage and wipeOutFreeSpace borrowed the allocator's
getFreeSpaceInPage as a measurement of the page's free tail. On a page whose
slot table is full that method gives up before measuring anything (it only has
to tell the allocator to look elsewhere, #2258) and leaves -1 in place of the
free space:

- the disjoint-slot merge of a delete reported -1 free bytes to the free-space
  statistics, tripping the updatePageStatistics tripwire under -ea and failing
  the commit (reached in seconds by concurrent vertex deletes on edge buckets,
  whose ~14 byte records fill the 2048 slots of a page with half its bytes free)
- the compaction after a delete skipped the wipe of the free tail on those
  pages, leaving a stale copy of the records the defragmentation moved down,
  which bucketWipeOutOnDelete exists to prevent

Both now measure with findContentInsertionOffset, the same slot scan without
the allocator's short-circuit, hole search and per-hole RID allocation.

Also SleepStatementExecutionTest measured a Thread.sleep with the wall clock,
which reported 957 ms for SLEEP 1000 on a full engine run: it now uses
System.nanoTime.
@lvca lvca added this to the 26.10.1 milestone Sep 25, 2026
@lvca lvca self-assigned this Sep 25, 2026
@mergify

mergify Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codacy-production

codacy-production Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Coverage 100.00% diff coverage · -6.13% coverage variation

Metric Results
Coverage variation ✅ -6.13% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (a50f817) 191295 159945 83.61%
Head commit (ea27712) 223917 (+32622) 173505 (+13560) 77.49% (-6.13%)

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 (#8416) 4 4 100.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%

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.

@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 64456b7c-13e9-4a9d-9842-5f8bd8271bac

📥 Commits

Reviewing files that changed from the base of the PR and between 850de58 and ea27712.

📒 Files selected for processing (3)
  • engine/src/main/java/com/arcadedb/engine/LocalBucket.java
  • engine/src/test/java/com/arcadedb/engine/Issue8401RebasedDeleteOnFullSlotTableTest.java
  • engine/src/test/java/com/arcadedb/query/sql/executor/SleepStatementExecutionTest.java

Included review availability: Your plan provides up to 4 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

LocalBucket now measures free page tails directly during delete rebasing and free-space wiping. New regression tests cover deletes on full-slot-table pages. The sleep test now measures elapsed time with a monotonic clock.

Changes

Delete free-tail measurement

Layer / File(s) Summary
Measure and record page free tails
engine/src/main/java/com/arcadedb/engine/LocalBucket.java
Delete-rebase statistics and free-space wiping now use the content insertion offset to measure the page tail. The method documentation describes this measurement.
Test full-slot-table delete behavior
engine/src/test/java/com/arcadedb/engine/Issue8401RebasedDeleteOnFullSlotTableTest.java
Regression tests check rebased deletes, concurrent updates, free-tail statistics, tail zeroing, and database integrity on full-slot-table pages.

Sleep test timing

Layer / File(s) Summary
Measure sleep duration monotonically
engine/src/test/java/com/arcadedb/query/sql/executor/SleepStatementExecutionTest.java
The basic sleep test uses System.nanoTime() and converts elapsed nanoseconds to milliseconds before checking the one-second duration.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: robfrank

Merge Risk: ⚪ Minimal · up to ea277

The regression test does not need to require a retained free-space hint. No actionable merge-blocking risk remains after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to ea277

The change improves cleanup of freed page space without adding a new data-access path. No introduced security issue was established. Cleanup remains best-effort if a page wipe fails.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The security-relevant effect is confined to residual bytes in affected bucket pages; the change does not establish erasure of earlier backups or other persisted copies.

Trust Boundaries and Controls

  • observed — Public delete operations retain their delete-permission checks. The changed rebasing and private wipe operations are downstream of the existing deletion and compression paths.

Resilience and Maintainability Implications

  • observed — A wipe exception is still caught and logged rather than propagated. This pre-existing best-effort behavior can leave residual bytes after a failure, despite the improved full-slot measurement.

Hardening Proposals

  • proposed — If page-tail wiping is intended to be a guaranteed data-removal control, define the required commit and recovery behavior on wipe failure and exercise it with fault injection.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning SleepStatementExecutionTest changes an unrelated sleep timing assertion from System.currentTimeMillis() to System.nanoTime(). This change does not implement or test the free-tail behavior in #84… Remove the SleepStatementExecutionTest change from this pull request, or submit it in a separate pull request.
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main fix: measuring the free tail directly during rebased deletes and delete wiping.
Description check ✅ Passed The description is detailed and on topic. It explains the root cause, fix, motivation, related issue, regression tests, broader test results, and stress testing. It does not use the template headings …
Linked Issues check ✅ Passed The PR addresses #8401. In rebaseRecordDeleteOnPage, it replaces getFreeSpaceInPage with page.getMaxContentSize() - findContentInsertionOffset(...), so a full slot table does not produce the all…
Full details: Out of Scope Changes check

Explanation

SleepStatementExecutionTest changes an unrelated sleep timing assertion from System.currentTimeMillis() to System.nanoTime(). This change does not implement or test the free-tail behavior in #8401.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude

claude Bot commented Sep 25, 2026

Copy link
Copy Markdown

Review

I traced through LocalBucket.java to verify the root-cause claim and the fix independently rather than just taking the PR description at face value.

Root cause checks out. getFreeSpaceInPage (the allocator's method) short-circuits on totalRecordsInPage >= maxRecordsInPage and returns before touching spaceAvailableInCurrentPage, which defaults to -1 on PageAnalysis. Both rebaseRecordDeleteOnPage and wipeOutFreeSpace were reusing that method purely as a measurement, so on a full-slot-table page they inherited the -1 sentinel as if it were a real answer. That lines up exactly with the updatePageStatistics assert (availableSpace >= 0) and with the silent no-op in the wipe path (spaceAvailableInCurrentPage > 0 was never true when it stayed -1).

The fix is well-targeted. Routing both call sites through findContentInsertionOffset (which already existed for restoreRecordAtPosition) instead of duplicating a new measurement is the right call - the class-level comment on contentEndOffset explicitly documents #6096, where two independently-drifted copies of this exact logic caused a corruption bug. Reusing the consolidated helper here is consistent with that lesson and with the project's "reuse existing components" guidance.

  • In rebaseRecordDeleteOnPage, recordCountInPage is read before the slot is zeroed, but since deleting only clears the record-table entry (doesn't shrink the count, per the existing comment on that method), using it as the scan bound for findContentInsertionOffset afterwards is correct.
  • In wipeOutFreeSpace, the recordCountInPage parameter semantics are unchanged from the pre-fix code (same value passed from compressPageInternal), so there's no new inconsistency introduced around the record-count-shrink path.
  • The page.getMaxContentSize() - findContentInsertionOffset(...) result is bounded by construction (never negative barring page corruption, which contentEndOffset already guards with a loud failure), so it satisfies the updatePageStatistics precondition it used to violate.

Performance: the claim that this is also cheaper holds up - findContentInsertionOffset/getLastRecordPositionInPage skip the hole search and the per-hole RID allocation + isDeletedInTransaction lookup that getFreeSpaceInPage does (that bookkeeping is only needed for the allocator's "find me an insertion slot" job, not for a pure tail measurement).

Tests: the two new regression tests are good - they build the specific "slots full, bytes free" page shape, and the second one directly inspects page bytes past the new content end to prove the wipe actually happened, rather than just asserting no exception was thrown. Reusing BucketPageLayoutTestSupport instead of duplicating fixture setup is consistent with how the other page-layout regression tests in this package are structured. The hint assertion (isIn(-1, freeTailAfter)) is a little loose, but that's appropriate given the statistics map can legitimately evict/drop an entry - asserting equality there would make the test depend on GATHER_STATS_MIN_SPACE_PERC/MAX_PAGES_GATHER_STATS internals it shouldn't need to know about.

The SleepStatementExecutionTest change (wall clock → System.nanoTime()) is unrelated to the main fix but is a small, clearly-justified hygiene fix for a real flake source (NTP/clock adjustment during a full-suite run), and it's called out honestly in the PR description rather than smuggled in.

No concerns on security - this is internal storage-engine bookkeeping with no external input surface, and no new dependencies were introduced.

One very minor nit, not blocking: the doc comment on findContentInsertionOffset now serves three purposes (insertion offset for restore, tail measurement for delete-rebase, tail measurement for wipe) but the method name still reads as insertion-specific. Not worth renaming given how much surrounding prose already documents the reuse, just flagging in case a future reader finds the name misleading next to its two new "measurement only" callers.

Overall: solid, narrowly-scoped fix with a well-reasoned root cause, tests that reproduce the exact failure before the fix and pass after, and no regressions to the allocator behavior the PR correctly leaves untouched.

@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.31%. Comparing base (a50f817) to head (ea27712).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8416      +/-   ##
============================================
+ Coverage     75.28%   75.31%   +0.03%     
  Complexity     2910     2910              
============================================
  Files          2023     2023              
  Lines        191295   191372      +77     
  Branches      40098    40106       +8     
============================================
+ Hits         144009   144125     +116     
+ Misses        31391    31352      -39     
  Partials      15895    15895              

☔ 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 7ae128c into main Sep 25, 2026
52 of 54 checks passed
@lvca
lvca deleted the fix/8401-rebase-delete-free-space branch September 25, 2026 21:07
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.

rebaseRecordDeleteOnPage reports -1 free bytes to updatePageStatistics under concurrent vertex deletes

1 participant