Skip to content

feat(fsck): reclaim chunks behind stale links to dechunked nar_files - #1396

Merged
kalbasit merged 2 commits into
mainfrom
fix/cleanup-stale-cdc-chunk-links
Jun 11, 2026
Merged

kalbasit merged 2 commits into
mainfrom
fix/cleanup-stale-cdc-chunk-links

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

Stacked on #1394 / the data-repair PR. 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 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; idempotent.

Test plan

  • New TestReclaimStaleChunkLinks: stale link + its chunk reclaimed; shared chunk and chunked NAR retained; idempotent.
  • task fmt/lint green; targeted fsck tests pass.

Refs #1392

@kalbasit

kalbasit commented Jun 11, 2026 •

Copy link
Copy Markdown
Owner Author

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 11, 2026
@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kalbasit, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 04455b88-061c-4256-a04f-3c789c28bdeb

📥 Commits

Reviewing files that changed from the base of the PR and between ada5fe0 and 95eab3b.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/.openspec.yaml
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/proposal.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/specs/cdc-chunk-residue-cleanup/spec.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/tasks.md
  • openspec/specs/cdc-chunk-residue-cleanup/spec.md
  • pkg/ncps/fsck.go
  • pkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go
📝 Walkthrough

Walkthrough

This PR implements a CDC fsck repair feature that reclaims chunks stranded behind stale nar_file_chunks links. When a NAR is dechunked (total_chunks <= 0), its chunk links become stale; this change adds logic to delete those links and reclaim now-orphaned chunks from both the database and chunk storage, while preserving chunks linked from active chunked NARs.

Changes

CDC Stale Chunk Link Reclamation

Layer / File(s) Summary
Specification & Design Documentation
openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/.openspec.yaml, openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md, openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/proposal.md, openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/specs/cdc-chunk-residue-cleanup/spec.md, openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/tasks.md, openspec/specs/cdc-chunk-residue-cleanup/spec.md
Openspec change set defines the requirement to delete nar_file_chunks links from dechunked NARs and reclaim resulting orphaned chunks. Design document outlines the strategy, proposal specifies implementation expectations, and spec repository entry documents the behavioral contract with scenarios for idempotency, shared chunks, and preservation of chunked NAR content.
Reclaim Implementation in fsck.go
pkg/ncps/fsck.go
New reclaimStaleChunkLinks helper queries nar_file_chunks rows whose parent nar_file has total_chunks <= 0 and no active chunking, deletes those stale links, then reclaims orphaned chunks by removing both their database rows and storage blobs (ignoring missing blobs). Integrated into repairFsckIssues with logging under the existing CDC mode guard.
Comprehensive Test for Stale Chunk Reclamation
pkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go
Test creates dechunked and chunked NAR scenarios with stale-only, shared, and healthy chunks, verifies deletion of stale links and orphaned chunks, asserts preservation of chunked NAR content and shared chunk references, and confirms idempotency by running reclaim twice with zero additional deletions on the second run.

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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1364: Both PRs modify pkg/ncps/fsck.go’s CDC-mode/repair flow: #1364 changes CDC detection for chunk residue; this PR adds the reclaim step that runs under that CDC-mode guard.

Suggested labels

merge-stack

"I nibble at stale links in the night,
unearth stray blobs by lantern-light,
fsck hums, I hop—operation neat,
orphaned chunks meet tidy feet. 🐇"

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main feature addition: reclaiming chunks behind stale links in dechunked nar_files during fsck repair.
Description check ✅ Passed The description is detailed and directly related to the changeset, explaining the problem, solution, implementation approach, testing, and references.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@dosubot dosubot Bot added enhancement New feature or request go Pull requests that update go code labels Jun 11, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/ncps/fsck.go Resolved
@kalbasit

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
pkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go (1)

33-47: ⚡ Quick win

Add a mid-chunking exclusion scenario to lock in the safety contract.

Current test does not cover a nar_file with total_chunks = 0 and chunking_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

📥 Commits

Reviewing files that changed from the base of the PR and between 5bc522d and 59fc205.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/.openspec.yaml
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/proposal.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/specs/cdc-chunk-residue-cleanup/spec.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/tasks.md
  • openspec/specs/cdc-chunk-residue-cleanup/spec.md
  • pkg/ncps/fsck.go
  • pkg/ncps/fsck_reclaim_stale_chunk_links_internal_test.go

Comment thread pkg/ncps/fsck.go Resolved
Comment thread pkg/ncps/fsck.go Resolved
@kalbasit

Copy link
Copy Markdown
Owner Author

Addressed all three (N+1, OOM, TOCTOU) together: stale links are now removed with a single bulk Delete().Where(HasNarFileWith(TotalChunksLTE(0), ChunkingStartedAtIsNil())) — the predicate is evaluated atomically at delete time, so it both eliminates the per-row deletes/in-memory load and closes the TOCTOU window (a parent that starts chunking no longer matches). Orphaned-chunk reclamation is now paged at fsckEagerLoadBatchSize with a bounded IDIn bulk delete per page. Added the defensive dbClient nil guard and a mid-chunking exclusion test case.

@kalbasit
kalbasit force-pushed the fix/repair-narinfo-compression-desync branch from 5bc522d to 0b7e679 Compare June 11, 2026 00:58
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
@kalbasit
kalbasit force-pushed the fix/cleanup-stale-cdc-chunk-links branch from 59fc205 to 33beb11 Compare June 11, 2026 00:58
@kalbasit
kalbasit force-pushed the fix/repair-narinfo-compression-desync branch from 0b7e679 to 8ffb231 Compare June 11, 2026 05:14
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
@kalbasit
kalbasit force-pushed the fix/cleanup-stale-cdc-chunk-links branch from 33beb11 to ca6ed75 Compare June 11, 2026 05:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md (1)

5-13: ⚡ Quick win

Clarify the total_chunks criterion for consistency.

Line 8 states total_chunks = 0, but the Decisions section (line 17) and the implementation use total_chunks <= 0. For documentation clarity, ensure the criterion is consistently stated throughout the document—either use <= 0 everywhere or explain why the shorthand = 0 appears 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

📥 Commits

Reviewing files that changed from the base of the PR and between 59fc205 and ca6ed75.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/.openspec.yaml
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/design.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/proposal.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/specs/cdc-chunk-residue-cleanup/spec.md
  • openspec/changes/archive/2026-06-10-cleanup-stale-cdc-chunk-links/tasks.md
  • openspec/specs/cdc-chunk-residue-cleanup/spec.md
  • pkg/ncps/fsck.go
  • pkg/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

@kalbasit
kalbasit force-pushed the fix/repair-narinfo-compression-desync branch from 8ffb231 to f4fa370 Compare June 11, 2026 06:26
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
@kalbasit
kalbasit force-pushed the fix/cleanup-stale-cdc-chunk-links branch from ca6ed75 to ada5fe0 Compare June 11, 2026 06:26
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
@kalbasit
kalbasit force-pushed the fix/cleanup-stale-cdc-chunk-links branch from ada5fe0 to d8df4c1 Compare June 11, 2026 06:38
Base automatically changed from fix/repair-narinfo-compression-desync to main June 11, 2026 06:44
kalbasit and others added 2 commits June 11, 2026 06:45
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]>
@kalbasit
kalbasit force-pushed the fix/cleanup-stale-cdc-chunk-links branch from d8df4c1 to 95eab3b Compare June 11, 2026 06:45
@kalbasit
kalbasit enabled auto-merge (squash) June 11, 2026 06:45
@kalbasit
kalbasit merged commit f5dbd68 into main Jun 11, 2026
38 checks passed
@kalbasit
kalbasit deleted the fix/cleanup-stale-cdc-chunk-links branch June 11, 2026 06:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code merge-stack size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant