Repository navigation
feat(fsck): reclaim chunks behind stale links to dechunked nar_files - #1396
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
|
Warning Review limit reached
More reviews will be available in 51 minutes and 25 seconds. Learn how PR review limits work. Your organization has reached its usage spending cap. Adjust your spending cap in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (8)
📝 WalkthroughWalkthroughThis PR implements a CDC fsck repair feature that reclaims chunks stranded behind stale ChangesCDC Stale Chunk Link Reclamation
Sequence Diagram(s)sequenceDiagram
participant repairFsckIssues
participant reclaimStaleChunkLinks
participant DB
participant chunkStore
repairFsckIssues->>reclaimStaleChunkLinks: invoke under CDC + --repair
reclaimStaleChunkLinks->>DB: DELETE nar_file_chunks WHERE total_chunks<=0 AND chunking_started_at IS NULL
reclaimStaleChunkLinks->>DB: SELECT chunks WHERE NOT HasNarFileLinks() (paginate)
reclaimStaleChunkLinks->>chunkStore: Delete chunk blob (ignore ErrNotFound)
reclaimStaleChunkLinks->>DB: DELETE chunk rows
reclaimStaleChunkLinks->>repairFsckIssues: return (linksDeleted, chunksReclaimed)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces a cleanup mechanism to reclaim CDC chunks stranded behind stale nar_file_chunks links to dechunked nar_files during fsck --repair in CDC mode. It adds the reclaimStaleChunkLinks function to delete these stale links and subsequently delete the now-orphaned chunks from both the database and the chunk store. Feedback on the implementation highlights a critical performance bottleneck and OOM risk when processing large datasets. Specifically, the reviewer recommends replacing the N+1 individual deletes with bulk deletions and paginating the orphaned chunks query to prevent memory exhaustion, alongside adding a defensive nil check for the database client.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
pkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go (1)
33-47: ⚡ Quick winAdd a mid-chunking exclusion scenario to lock in the safety contract.
Current test does not cover a
nar_filewithtotal_chunks = 0andchunking_started_at != nil. Adding that case would protect the “not actively chunking” guard from regressions.Also applies to: 73-77, 105-109
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go` around lines 33 - 47, Add a test case that creates a nar_file where TotalChunks is 0 but ChunkingStartedAt is non-nil to exercise the "mid-chunking" exclusion: create a new record similar to dechunkedNF (use SetHash with a unique value, SetTotalChunks(0)) and call SetChunkingStartedAt(...) with a non-nil timestamp, then Save and require.NoError; assert afterwards that this mid‑chunking nar_file's links/chunks are preserved (i.e., not reclaimed) just like chunkedNF, to lock in the "not actively chunking" guard and prevent regressions. Reference the variables/declarations dechunkedNF, chunkedNF, TotalChunks and ChunkingStartedAt when locating where to add the case and assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/ncps/fsck.go`:
- Around line 1767-1773: The current queries that call All(ctx) on
dbClient.Ent().NarFileChunk.Query() (used to populate staleLinks and the
orphaned-chunk scan) must be converted to keyset/batched loops: use
Limit(fsckEagerLoadBatchSize) on the Query() and run it in a for loop (e.g., for
{ rows, err := Query().Limit(fsckEagerLoadBatchSize).All(ctx); if err != nil {
return err }; if len(rows)==0 { break }; process/delete rows; } ), preserving
existing Where(entnarfilechunk.HasNarFileWith(...)) predicates; apply the same
batched loop pattern to both the staleLinks logic (staleLinks variable) and the
orphaned-chunk reclamation query, ensuring ctx/err handling and breaking when a
batch returns zero rows.
- Around line 1779-1781: The current loop unconditionally deletes each stale
link by ID (calling dbClient.Ent().NarFileChunk.DeleteOneID(link.ID).Exec(ctx)),
which risks TOCTOU if the parent nar_file became active; change the deletion to
perform a guarded conditional delete that matches the chunk ID and the parent
nar_file predicate (use IDEQ for the chunk and HasNarFileWith(TotalChunksLTE(0),
ChunkingStartedAtIsNil()) for the parent) so the delete only succeeds if the
parent is still non-chunked, execute the delete as a Count/Exec to get affected
rows, increment linksDeleted only when affected rows==1, and return an error on
unexpected failures while preserving the same error wrapping behavior.
---
Nitpick comments:
In `@pkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go`:
- Around line 33-47: Add a test case that creates a nar_file where TotalChunks
is 0 but ChunkingStartedAt is non-nil to exercise the "mid-chunking" exclusion:
create a new record similar to dechunkedNF (use SetHash with a unique value,
SetTotalChunks(0)) and call SetChunkingStartedAt(...) with a non-nil timestamp,
then Save and require.NoError; assert afterwards that this mid‑chunking
nar_file's links/chunks are preserved (i.e., not reclaimed) just like chunkedNF,
to lock in the "not actively chunking" guard and prevent regressions. Reference
the variables/declarations dechunkedNF, chunkedNF, TotalChunks and
ChunkingStartedAt when locating where to add the case and assertions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8015df3b-8dfe-4397-a671-6090f504b634
📒 Files selected for processing (8)
openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/.openspec.yamlopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.mdopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/proposal.mdopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/specs/cdc-chunk-residue-cleanup/spec.mdopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/tasks.mdopenspec/specs/cdc-chunk-residue-cleanup/spec.mdpkg/ncps/fsck.gopkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go
|
Addressed all three (N+1, OOM, TOCTOU) together: stale links are now removed with a single bulk |
5bc522d to
0b7e679
Compare
Rework reclaimStaleChunkLinks to scale to multi-million-row residue and close a TOCTOU window: - Delete stale links in a single bulk statement whose predicate is evaluated at delete time, so a parent that starts chunking between scan and delete no longer matches and is not affected (fixes TOCTOU). This also removes the full in-memory link load and the N per-row deletes. - Reclaim orphaned chunks in fsckEagerLoadBatchSize pages, deleting each page's rows with a bounded IDIn bulk delete, to bound memory/DB load on large caches (OOM fix). - Add a defensive dbClient nil guard (no-panic posture). Adds a mid-chunking (total_chunks=0, chunking_started_at set) exclusion case to the test. Addresses PR #1396 review threads PRRT_kwDONV6tZs6Ip9QX, PRRT_kwDONV6tZs6IqTpo, PRRT_kwDONV6tZs6IqTps. Co-Authored-By: Claude Opus 4.8 <[email protected]>
59fc205 to
33beb11
Compare
0b7e679 to
8ffb231
Compare
Rework reclaimStaleChunkLinks to scale to multi-million-row residue and close a TOCTOU window: - Delete stale links in a single bulk statement whose predicate is evaluated at delete time, so a parent that starts chunking between scan and delete no longer matches and is not affected (fixes TOCTOU). This also removes the full in-memory link load and the N per-row deletes. - Reclaim orphaned chunks in fsckEagerLoadBatchSize pages, deleting each page's rows with a bounded IDIn bulk delete, to bound memory/DB load on large caches (OOM fix). - Add a defensive dbClient nil guard (no-panic posture). Adds a mid-chunking (total_chunks=0, chunking_started_at set) exclusion case to the test. Addresses PR #1396 review threads PRRT_kwDONV6tZs6Ip9QX, PRRT_kwDONV6tZs6IqTpo, PRRT_kwDONV6tZs6IqTps. Co-Authored-By: Claude Opus 4.8 <[email protected]>
33beb11 to
ca6ed75
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md (1)
5-13: ⚡ Quick winClarify the
total_chunkscriterion for consistency.Line 8 states
total_chunks = 0, but the Decisions section (line 17) and the implementation usetotal_chunks <= 0. For documentation clarity, ensure the criterion is consistently stated throughout the document—either use<= 0everywhere or explain why the shorthand= 0appears in some sections.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md` around lines 5 - 13, The document inconsistently refers to the dechunked criterion as `total_chunks = 0` in Goals but uses `total_chunks <= 0` elsewhere (Decisions/implementation); pick one and make it consistent: either change the Goals line to `total_chunks <= 0` to match Decisions/implementation, or add a brief clarifying sentence explaining that `total_chunks = 0` is shorthand for `total_chunks <= 0` and why negative values may occur; update all occurrences of the phrase (e.g., the Goals section text and any Decision/implementation mentions of `total_chunks`) so they use the chosen form or include the explanatory note.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md`:
- Around line 5-13: The document inconsistently refers to the dechunked
criterion as `total_chunks = 0` in Goals but uses `total_chunks <= 0` elsewhere
(Decisions/implementation); pick one and make it consistent: either change the
Goals line to `total_chunks <= 0` to match Decisions/implementation, or add a
brief clarifying sentence explaining that `total_chunks = 0` is shorthand for
`total_chunks <= 0` and why negative values may occur; update all occurrences of
the phrase (e.g., the Goals section text and any Decision/implementation
mentions of `total_chunks`) so they use the chosen form or include the
explanatory note.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 6e9535a1-1dfb-448f-926e-afceff3d7e46
📒 Files selected for processing (8)
openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/.openspec.yamlopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.mdopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/proposal.mdopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/specs/cdc-chunk-residue-cleanup/spec.mdopenspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/tasks.mdopenspec/specs/cdc-chunk-residue-cleanup/spec.mdpkg/ncps/fsck.gopkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go
✅ Files skipped from review due to trivial changes (2)
- openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/tasks.md
- openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/proposal.md
🚧 Files skipped from review as they are similar to previous changes (4)
- openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/specs/cdc-chunk-residue-cleanup/spec.md
- openspec/specs/cdc-chunk-residue-cleanup/spec.md
- openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/.openspec.yaml
- pkg/ncps/fsck.go
8ffb231 to
f4fa370
Compare
Rework reclaimStaleChunkLinks to scale to multi-million-row residue and close a TOCTOU window: - Delete stale links in a single bulk statement whose predicate is evaluated at delete time, so a parent that starts chunking between scan and delete no longer matches and is not affected (fixes TOCTOU). This also removes the full in-memory link load and the N per-row deletes. - Reclaim orphaned chunks in fsckEagerLoadBatchSize pages, deleting each page's rows with a bounded IDIn bulk delete, to bound memory/DB load on large caches (OOM fix). - Add a defensive dbClient nil guard (no-panic posture). Adds a mid-chunking (total_chunks=0, chunking_started_at set) exclusion case to the test. Addresses PR #1396 review threads PRRT_kwDONV6tZs6Ip9QX, PRRT_kwDONV6tZs6IqTpo, PRRT_kwDONV6tZs6IqTps. Co-Authored-By: Claude Opus 4.8 <[email protected]>
ca6ed75 to
ada5fe0
Compare
Rework reclaimStaleChunkLinks to scale to multi-million-row residue and close a TOCTOU window: - Delete stale links in a single bulk statement whose predicate is evaluated at delete time, so a parent that starts chunking between scan and delete no longer matches and is not affected (fixes TOCTOU). This also removes the full in-memory link load and the N per-row deletes. - Reclaim orphaned chunks in fsckEagerLoadBatchSize pages, deleting each page's rows with a bounded IDIn bulk delete, to bound memory/DB load on large caches (OOM fix). - Add a defensive dbClient nil guard (no-panic posture). Adds a mid-chunking (total_chunks=0, chunking_started_at set) exclusion case to the test. Addresses PR #1396 review threads PRRT_kwDONV6tZs6Ip9QX, PRRT_kwDONV6tZs6IqTpo, PRRT_kwDONV6tZs6IqTps. Co-Authored-By: Claude Opus 4.8 <[email protected]>
ada5fe0 to
d8df4c1
Compare
A live cache accumulated ~5.5M orphaned chunk rows and ~8164 nar_file_chunks links while zero nar_files have total_chunks > 0. fsck's orphaned-chunk reclamation only deletes chunks with NO nar_file_chunks link, so chunks held by a stale link to a dechunked (total_chunks = 0) nar_file are never orphaned and never reclaimed; collectNarFilesWithChunkIssues only inspects total_chunks > 0 rows, so the stale links escape there too. The residue grows unbounded. Add reclaimStaleChunkLinks, invoked from repairFsckIssues under --repair + CDC mode (which #1364's chunk-residue signal already enables post-drain): delete nar_file_chunks whose parent nar_file is dechunked and not actively chunking, then reclaim the chunks left with no remaining links (DB rows + chunk-store blobs). Chunks shared with a still-chunked nar_file keep a live link and are retained; chunked NARs are untouched; the cleanup is idempotent. Refs #1392 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Rework reclaimStaleChunkLinks to scale to multi-million-row residue and close a TOCTOU window: - Delete stale links in a single bulk statement whose predicate is evaluated at delete time, so a parent that starts chunking between scan and delete no longer matches and is not affected (fixes TOCTOU). This also removes the full in-memory link load and the N per-row deletes. - Reclaim orphaned chunks in fsckEagerLoadBatchSize pages, deleting each page's rows with a bounded IDIn bulk delete, to bound memory/DB load on large caches (OOM fix). - Add a defensive dbClient nil guard (no-panic posture). Adds a mid-chunking (total_chunks=0, chunking_started_at set) exclusion case to the test. Addresses PR #1396 review threads PRRT_kwDONV6tZs6Ip9QX, PRRT_kwDONV6tZs6IqTpo, PRRT_kwDONV6tZs6IqTps. Co-Authored-By: Claude Opus 4.8 <[email protected]>
d8df4c1 to
95eab3b
Compare
Summary
Stacked on #1394 / the data-repair PR. A live cache accumulated ~5.5M orphaned chunk rows and ~8164
nar_file_chunkslinks while zero nar_files havetotal_chunks > 0. fsck's orphaned-chunk reclamation only deletes chunks with NO link, so chunks held by a stale link to a dechunked (total_chunks = 0) nar_file are never orphaned and never reclaimed;collectNarFilesWithChunkIssuesonly inspectstotal_chunks > 0rows, so the stale links escape there too. The residue grows unbounded.Add
reclaimStaleChunkLinks, invoked fromrepairFsckIssuesunder--repair+ CDC mode (which #1364's chunk-residue signal already enables post-drain): deletenar_file_chunkswhose parent nar_file is dechunked and not actively chunking, then reclaim the chunks left with no remaining links (DB rows + chunk-store blobs). Chunks shared with a still-chunked nar_file keep a live link and are retained; chunked NARs are untouched; idempotent.Test plan
TestReclaimStaleChunkLinks: stale link + its chunk reclaimed; shared chunk and chunked NAR retained; idempotent.task fmt/lintgreen; targeted fsck tests pass.Refs #1392