Skip to content

fix(#10735, #10700): a BM25 pair known to be wrong is persisted with that proof, a growth packs the page's holes before it measures the room - #10837

Merged
lvca merged 1 commit into
mainfrom
fix/10735-10700-bm25-armed-rescan-and-page-holes
Oct 28, 2026
Merged

lvca merged 1 commit into
mainfrom
fix/10735-10700-bm25-armed-rescan-and-page-holes

Conversation

@lvca

@lvca lvca commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Fixes #10735
Fixes #10700

#10735 - a BM25 clamp armed the rescan in memory only

A clamp proves the persisted pair (totalDocs, sumDocLength) is wrong, but the armed rescan lived only in memory while the pair was saved with ft_countersValid: true. A restart before the next search kept the torn pair and dropped the proof.

The issue suggests writing ft_rescanRequired/ft_clamps, or ft_countersValid: false. This PR persists the armed flag inside the same unit as the pair, and also closes the ordering holes that a plain extra field would leave open:

  • ft_rescanRequired is written under the counters lock next to the pair, read back by fromJSON, and adopted with the pair by a follower taking a leader's recompute. Writing ft_countersValid: false was rejected: that throws the pair away (cold-scan semantics, not adoptable) where the flag keeps it and marks it as suspect.
  • Every arming bumps countersGeneration after the flag is set. Before, requireRescan() on its own (crash recovery, a replicated delta that could not be applied) left the counters clean, so a close before the first search wrote nothing: the same bug by another route. A save racing an arming now stays unsaved.
  • The drift check reads the flag instead of consuming it. Only an exact scan clears it, so a scan that fails or races a writer leaves the proof in place.
  • schema:index bm25 reports rescanRequired. clamps stays a per-session diagnostic.
  • The avgdl normaliser is one rule on every path (BM25Scorer.lengthNormalizer): the bucket-level path and EXPLAIN reported 0.0 for a torn pair, and the type-wide path floored any average below 1.0 to 1.0, real ones included.

The "cheap recomputable witness" for the sum, which the issue mentions, does not exist without analyzing the corpus. With every clamp site arming, and every arming now durable, the proof survives until a scan repairs the pair.

#10700 - a growth was refused while the page held tens of KB of holes

Every rung of the spill ladder measured room as the free tail. Holes left by shrinks or deletes of the same transaction are not counted there until the commit packs the page.

The issue proposes compressing the page just before the final throw. This PR does it earlier, before the growth attempt itself. A growth the free tail cannot host packs the page's holes first (packPageHoles), so:

  • the growth usually fits in place (the reporter's case: no pointer, no chunk, nothing moved);
  • otherwise the spill sees the packed tail and turns the slot into a chunk head instead of moving a live neighbour behind a pointer (relocateANeighbourOffPage becomes a real last resort).

Details:

  • It runs only on a page some write left unpacked (!hasOnlyPackedWrites()), so other growths skip the walk.
  • It is the commit's compression except that the slot table keeps its length. Trimming trailing freed slots mid-transaction would let the spill's own allocations reuse a slot this transaction deleted (a new test covers deleted neighbours).
  • The page is poisoned for the slot and edge-append merges, because every record past the first hole moved.

Not covered: #10669 (a page with no plain donor and no holes at all). It is assigned elsewhere and needs a separate design (shrinking a chunk head, or padding at create).

Tests

  • Issue10700GrowthReclaimsPageHolesTest (3 tests, all failed before the fix: two refused at commit, one moved a neighbour off-page)
  • Issue10735Bm25ArmedRescanSurvivesRestartTest (7 tests; disabling the fromJSON restore turns 4 of them red)
  • Related suites: full-text, BM25, bucket/page layout and merge tests (1424 tests), plus the database/graph/engine packages (2129 tests). All green except RecordNotMaterialisedTest.aSharedRecordNeverFailsWithANullPointerException, a thread race in ImmutableVertex lazy loading that passes on rerun and is not touched here.

Summary by CodeRabbit

  • Bug Fixes
    • Growing records can now reuse reclaimed space on a page, reducing unnecessary relocation of neighboring records.
    • Full-text search scoring handles zero, non-finite, and very small average document lengths more consistently.
    • Required full-text statistics rescans now persist across restarts and remain pending until a scan completes.

…that proof, a growth packs the page's holes before it measures the room

#10735: a clamp armed the BM25 rescan in memory only, while the pair it speaks
against was saved with ft_countersValid: true. A restart between the clamp and
the next search kept the torn pair (a sumDocLength of 0 with the document count
intact) and dropped the proof, so the drift check trusted it for good.
- the armed state is persisted with the pair (ft_rescanRequired), read back by
  fromJSON and adopted with the pair by a follower taking a leader's recompute
- every arming bumps the counters generation after setting the flag, so a
  rescan armed without moving a counter (crash recovery, a delta that could not
  be applied) reaches the save at close, and a save racing the arming stays
  unsaved
- the drift check reads the flag instead of consuming it: only an exact scan
  clears it
- schema:index bm25 reports rescanRequired
- the avgdl normaliser is one rule on every path (BM25Scorer.lengthNormalizer):
  the bucket-level path and EXPLAIN no longer report 0.0, and the type-wide
  path no longer floors real averages below 1.0

#10700: a growth on a page whose free tail is gone was refused for ever when the
bytes the page could give back were holes left by shrinks or deletes of the same
transaction. A growth the free tail cannot host now packs the page first, only
on a page some write left unpacked, keeping the slot table length so the
transaction never reuses a slot it deleted. The growth then often fits in place,
and otherwise spills into a chunk chain instead of moving a neighbour off-page.
@lvca lvca added this to the 26.11.1 milestone Oct 28, 2026
@lvca lvca self-assigned this Oct 28, 2026
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7d36d107-13aa-4d8a-a182-2e2467ef145d
Commits

Reviewing files that changed from the base of the PR and between 355b266 and 7d7e597.

Files selected for processing: 8
  • engine/CLAUDE.md
  • engine/src/main/java/com/arcadedb/engine/LocalBucket.java
  • engine/src/main/java/com/arcadedb/index/fulltext/BM25Scorer.java
  • engine/src/main/java/com/arcadedb/index/fulltext/FullTextSearch.java
  • engine/src/main/java/com/arcadedb/index/fulltext/LSMTreeFullTextIndex.java
  • engine/src/main/java/com/arcadedb/schema/FullTextIndexMetadata.java
  • engine/src/test/java/com/arcadedb/database/Issue10700GrowthReclaimsPageHolesTest.java
  • engine/src/test/java/com/arcadedb/index/fulltext/Issue10735Bm25ArmedRescanSurvivesRestartTest.java

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.

Walkthrough

The changes add page-hole packing before record growth and persist BM25 rescan state across restarts. They also use a shared document-length normalization rule in full-text scoring and add regression tests for both areas.

Changes: Sealed-page growth

Layer / File(s) Summary
Pack holes before record growth
engine/src/main/java/com/arcadedb/engine/LocalBucket.java, engine/src/test/java/com/arcadedb/database/Issue10700GrowthReclaimsPageHolesTest.java, engine/CLAUDE.md
When growth exceeds the free tail and the page has unpacked writes, LocalBucket packs holes without trimming the slot table, then recalculates offsets and continues growth. Tests cover reclaimed-space growth, spill growth, deleted records, integrity, and persistence after reopening. The engine summary describes this behavior.

BM25 counter recovery

Layer / File(s) Summary
Normalize document-length averages
engine/src/main/java/com/arcadedb/index/fulltext/BM25Scorer.java, engine/src/main/java/com/arcadedb/index/fulltext/FullTextSearch.java, engine/src/main/java/com/arcadedb/index/fulltext/LSMTreeFullTextIndex.java, engine/src/test/java/com/arcadedb/index/fulltext/Issue10735Bm25ArmedRescanSurvivesRestartTest.java
BM25Scorer.lengthNormalizer returns the input only when it is positive and finite; otherwise it returns 1.0. Term scoring and scoring-context creation use this rule. The minimum document-count clamp remains unchanged.
Persist and publish rescan state
engine/src/main/java/com/arcadedb/schema/FullTextIndexMetadata.java, engine/src/main/java/com/arcadedb/index/fulltext/LSMTreeFullTextIndex.java, engine/src/test/java/com/arcadedb/index/fulltext/Issue10735Bm25ArmedRescanSurvivesRestartTest.java
Metadata serialization, restoration, and counter adoption now include the armed rescan state. Generation tracking follows updates to that state. The index reads the state without consuming it and includes it in counter descriptions. Tests cover restart, rescanning, and counter publication.

Priority: Normal

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant FullTextSearch
  participant LSMTreeFullTextIndex
  participant FullTextIndexMetadata
  FullTextSearch->>LSMTreeFullTextIndex: Run search
  LSMTreeFullTextIndex->>FullTextIndexMetadata: Read rescan-required state
  LSMTreeFullTextIndex->>LSMTreeFullTextIndex: Scan corpus when rescan is required
  LSMTreeFullTextIndex->>FullTextIndexMetadata: Publish scanned counters and rescan state
Loading

Possibly related issues

Suggested labels: bug, engine

Suggested reviewers: robfrank

Merge Risk: Minimal · up to 7d7e5

No merge-blocking risk was identified in the page-growth or BM25 recovery changes.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title clearly identifies both fixed issues and summarizes the BM25 persistence and page-hole packing changes. It is longer than necessary but remains specific and relevant.
Description check Passed The description is detailed and covers the changes, motivation, related issues, implementation details, test coverage, and known test exception. It does not use the template headings or include the re…
Linked Issues check Passed The PR meets the coding requirements for both active linked issues. For #10735, FullTextIndexMetadata persists ft_rescanRequired with the counter pair, restores it in fromJSON, adopts it with re…
Out of Scope Changes check Passed The changed production code and tests have a direct connection to #10735 or #10700. BM25 normalizer changes correct the average-length behavior described by #10735. Page packing and merge poisoning su…
Docstring Coverage Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
Full details: Description check

Explanation

The description is detailed and covers the changes, motivation, related issues, implementation details, test coverage, and known test exception. It does not use the template headings or include the required checklist, but the content is mostly complete.

Full details: Linked Issues check

Explanation

The PR meets the coding requirements for both active linked issues. For #10735, FullTextIndexMetadata persists ft_rescanRequired with the counter pair, restores it in fromJSON, adopts it with replacement counters, and increments countersGeneration after arming. Drift checks read the flag, and only an exact scan clears it. The restart and repair tests cover save/reopen, rescan, generation ordering, adoption, and average-length normalization. For #10700, LocalBucket.updateRecordInternal packs page holes before growth when the free tail is insufficient and writes left the page unpacked. It preserves slot-table length, poisons affected merges, recalculates offsets, and leaves relocation as a fallback. The added regression tests cover growth into reclaimed space, neighbour movement, and deleted neighbours. The optional recomputable witness in #10735 is not a required objective.

Full details: Out of Scope Changes check

Explanation

The changed production code and tests have a direct connection to #10735 or #10700. BM25 normalizer changes correct the average-length behavior described by #10735. Page packing and merge poisoning support the #10700 growth fix. The test additions verify those behaviors. The PR explicitly excludes #10669, and the reviewed changes do not demonstrate unrelated implementation work.

Full details: Docstring Coverage

Explanation

Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 14 functions across 7 files. (1 skipped: 1 unsupported.)

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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 Oct 28, 2026

Copy link
Copy Markdown

Review of #10837 (fixes #10735 and #10700). Read from the diff only; I did not build the PR or run its tests.

BM25 rescan persistence (#10735)

  • Writing ft_rescanRequired under the counters lock next to the pair is sound. fromJSON and adoptPersistedCounters read it back.
  • Bumping countersGeneration after the flag is set, in both requireRescan() and publishScannedCounters, closes the save-races-arming window you describe.
  • isRescanRequired() replaces consume-on-read, so a failed or racing scan no longer loses the proof. This relies on publishScannedCounters being the only place that clears the flag.
  • The flag is written only when armed, so existing definitions stay unchanged. Old files without the key default to false.
  • BM25Scorer.lengthNormalizer now applies one rule on the bucket path, the type-wide path and EXPLAIN. The Double.isFinite guard is a good addition. The type-wide path no longer floors real averages below 1.0 to 1.0, so scores for sparse corpora will change. That is the intended fix, but it is worth a line in the release notes.

Packing page holes before a growth (#10700)

  • The cheap check (hasOnlyPackedWrites, then growthFitsFreeTail) keeps the new walk off the common growth path, which is what matters for performance.
  • Poisoning the slot-rebase and edge-append merges after the pack, and re-deriving recordPositionInPage and lastRecordPositionInPage, is the correct handling of moved offsets.
  • Keeping the slot table length in packPageHoles is a good call, with the reason documented.
  • One thing to check: poisonSlotRebasePage is guarded by slotMergeOn, while poisonEdgeAppendPage is guarded by slotTx != null. I assume that matches the existing guards elsewhere. If slotMergeOn can be true with slotTx == null, the first call would throw an NPE.

Tests

Security: no concerns. There are no new dependencies, no new input surfaces, and no unsafe deserialization.

No blocking issues from my side. Please make sure CI is green on the engine tests that touch bucket layout and full-text counters.

@codacy-production

codacy-production Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 91.67% diff coverage

Metric Results
Coverage variation Report missing for 355b2661
Diff coverage ✅ 91.67% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (355b266) Report Missing Report Missing Report Missing
Head commit (7d7e597) 285002 234655 82.33%

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 (#10837) 48 44 91.67%

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 Oct 28, 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.

@codecov

codecov Bot commented Oct 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.08333% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.07%. Comparing base (b090cbe) to head (7d7e597).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...src/main/java/com/arcadedb/engine/LocalBucket.java 71.42% 4 Missing and 6 partials ⚠️
...n/java/com/arcadedb/index/fulltext/BM25Scorer.java 50.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main   #10837      +/-   ##
============================================
+ Coverage     79.06%   79.07%   +0.01%     
- Complexity     4792     4793       +1     
============================================
  Files          2303     2304       +1     
  Lines        251882   252175     +293     
  Branches      54984    55094     +110     
============================================
+ Hits         199142   199414     +272     
+ Misses        32430    32402      -28     
- Partials      20310    20359      +49     

☔ 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 f08b477 into main Oct 28, 2026
35 of 38 checks passed
@lvca
lvca deleted the fix/10735-10700-bm25-armed-rescan-and-page-holes branch October 28, 2026 05:54
robfrank pushed a commit that referenced this pull request Nov 5, 2026
…that proof, a growth packs the page's holes before it measures the room (#10837)

#10735: a clamp armed the BM25 rescan in memory only, while the pair it speaks
against was saved with ft_countersValid: true. A restart between the clamp and
the next search kept the torn pair (a sumDocLength of 0 with the document count
intact) and dropped the proof, so the drift check trusted it for good.
- the armed state is persisted with the pair (ft_rescanRequired), read back by
  fromJSON and adopted with the pair by a follower taking a leader's recompute
- every arming bumps the counters generation after setting the flag, so a
  rescan armed without moving a counter (crash recovery, a delta that could not
  be applied) reaches the save at close, and a save racing the arming stays
  unsaved
- the drift check reads the flag instead of consuming it: only an exact scan
  clears it
- schema:index bm25 reports rescanRequired
- the avgdl normaliser is one rule on every path (BM25Scorer.lengthNormalizer):
  the bucket-level path and EXPLAIN no longer report 0.0, and the type-wide
  path no longer floors real averages below 1.0

#10700: a growth on a page whose free tail is gone was refused for ever when the
bytes the page could give back were holes left by shrinks or deletes of the same
transaction. A growth the free tail cannot host now packs the page first, only
on a page some write left unpacked, keeping the slot table length so the
transaction never reuses a slot it deleted. The growth then often fits in place,
and otherwise spills into a chunk chain instead of moving a neighbour off-page.

(cherry picked from commit f08b477)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment