Skip to content

fix(fsck): detect chunk residue post-drain - #1364

Merged
kalbasit merged 1 commit into
mainfrom
fix-fsck-reclaim-orphaned-chunk-residue
Jun 7, 2026
Merged

kalbasit merged 1 commit into
mainfrom
fix-fsck-reclaim-orphaned-chunk-residue

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Summary

After a CDC→whole migration fully drains, fsck detected CDC mode only when cdc_enabled=true or a nar_file had total_chunks>0. Once the serve restart cleared cdc_enabled and every NAR was de-chunked, both signals went false while orphaned chunk rows/files could remain — so fsck never initialized the chunk store and silently skipped reclamation, stranding the residue forever (observed in prod: ~5.5M orphaned chunk rows, reclaimable only because the one fsck run started ~46s before drain cleared the config).

  • Extracted the inline CDC-mode detection into detectFsckCDCMode() returning a cdcModeReason.
  • Added a third, lowest-priority signal: a non-empty chunks table (Chunk.Query().Exist). It fires only when signals 1 and 2 are both false, emitting a distinct info log so a post-drain fsck's chunk work is self-explanatory.
  • Precedence and the existing signal-1/2 log messages are unchanged → active-CDC and chunked-NAR runs behave identically.

Spec: adds requirement "Fsck MUST enable CDC mode when chunk residue exists, even after CDC and drain are fully disabled" to openspec/specs/fsck.

Test plan

  • task fmt / task lint / task test pass
  • 4 internal unit tests covering all detection branches (residue-only, never-CDC, config precedence, chunked-nar-files fallback)
  • e2e: fsck --dry-run reports + fsck --repair reclaims residue with no cdc_enabled config and no chunked nar_files

@kalbasit

kalbasit commented Jun 7, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

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

coderabbitai Bot commented Jun 7, 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 10 minutes and 47 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more 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: ce5bdf5b-254d-488e-ba16-8d2542672c03

📥 Commits

Reviewing files that changed from the base of the PR and between 1d7b37c and 2584e3a.

📒 Files selected for processing (9)
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/.openspec.yaml
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/design.md
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/proposal.md
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/specs/fsck/spec.md
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/tasks.md
  • openspec/specs/fsck/spec.md
  • pkg/ncps/fsck.go
  • pkg/ncps/fsck_cdc_mode_detection_internal_test.go
  • pkg/ncps/fsck_test.go
📝 Walkthrough

Walkthrough

This PR enhances ncps fsck to detect and reclaim orphaned chunk residue left behind after CDC-to-whole drain migrations. It introduces a third CDC mode detection signal based on checking whether the chunks table has unreferenced rows, prioritized after config and chunked NAR checks, with comprehensive testing and specification updates.

Changes

Fsck orphaned chunk residue reclamation

Layer / File(s) Summary
Specification and design documentation
openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/*, openspec/specs/fsck/spec.md
Archive metadata, design document, proposal, task checklist, and spec requirements define CDC mode detection with ordered signal precedence: config key, chunked NAR files, then orphaned chunk residue. Specifies distinct logging when residue-only triggers CDC mode, preservation of existing repair/dry-run behavior, and test scenarios.
CDC mode detection implementation and unit tests
pkg/ncps/fsck.go, pkg/ncps/fsck_cdc_mode_detection_internal_test.go
New cdcModeReason type and detectFsckCDCMode() function centralize CDC mode decision logic with three ordered signal checks (config, chunked NAR files, chunk table existence). Error-on-query falls back to next signal. fsckCommand integration point uses detectFsckCDCMode(...).enabled(). Four unit tests validate residue-only detection, never-CDC state, config precedence, and chunked NAR file fallback using SQLite fixtures.
Integration test
pkg/ncps/fsck_test.go
Regression test TestFsckReclaimsOrphanedChunkResiduePostDrain validates end-to-end behavior: dry-run reports issues without deleting orphaned chunks; repair mode reclaims (deletes) orphaned residue, leaving chunk table empty.

Sequence Diagram(s)

sequenceDiagram
  participant fsckCommand
  participant detectFsckCDCMode
  participant ConfigDB as Config DB
  participant NarDB as NAR File DB
  participant ChunkDB as Chunk DB
  fsckCommand->>detectFsckCDCMode: Call with context
  detectFsckCDCMode->>ConfigDB: Query cdc_enabled key
  alt Config enables CDC
    detectFsckCDCMode-->>fsckCommand: cdcModeFromConfig (enabled)
  else Config absent
    detectFsckCDCMode->>NarDB: Query nar_file.total_chunks > 0
    alt Chunked NARs exist
      detectFsckCDCMode-->>fsckCommand: cdcModeFromChunkedNarFiles (enabled)
    else No chunked NARs
      detectFsckCDCMode->>ChunkDB: Query chunks.exist()
      alt Orphaned chunks found
        detectFsckCDCMode-->>fsckCommand: cdcModeFromChunkResidue (enabled, with Info log)
      else Empty chunks table
        detectFsckCDCMode-->>fsckCommand: cdcModeOff (disabled)
      end
    end
  end
  fsckCommand->>fsckCommand: Set cdcMode from reason.enabled()
  fsckCommand->>fsckCommand: Run fsck with chunk repair if enabled
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 After drains leave chunks behind,
fsck detects residue's sign,
Three signals checked with care and grace,
Config, files, then table space!
Repair reclaims what once was lost, 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly summarizes the main change: fsck now detects and can reclaim orphaned chunk residue post-drain, which is the core fix in this PR.
Description check ✅ Passed The description clearly explains the problem, implementation approach, spec changes, and testing, all directly related to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 bug Something isn't working go Pull requests that update go code labels Jun 7, 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 third signal for detecting CDC mode in fsck by checking if the chunks table is non-empty. This ensures that orphaned chunk residue can be detected and reclaimed even after CDC and drain mode are fully disabled and no nar_file references chunks. The implementation includes a new helper function detectFsckCDCMode in pkg/ncps/fsck.go along with comprehensive unit and integration tests. Feedback on the changes suggests adding a defensive nil check for dbClient in detectFsckCDCMode to prevent potential nil-pointer dereferences.

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
@dosubot

dosubot Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Documentation Updates

1 document(s) were updated by changes in this PR:

Cache and Storage Configuration Flags
View Changes
@@ -352,12 +352,15 @@
 - `--cache-cdc-avg` (average chunk size)
 - `--cache-cdc-max` (maximum chunk size)
 
-**Note on configuration key format:** The CDC configuration keys are stored in the database with underscores (`cdc_enabled`, `cdc_min`, `cdc_avg`, `cdc_max`), not dots. This is important for fsck operations: the fsck command uses a two-tier detection mechanism to determine whether to perform CDC-specific integrity checks:
-
-1. **Primary detection:** fsck reads the `cdc_enabled` database config key
-2. **Fallback detection:** If the `cdc_enabled` key cannot be read or is missing, fsck automatically detects CDC mode by checking if any chunked nar_files exist in the database (nar_files with `total_chunks > 0`)
-
-The fallback mechanism prevents false positives where chunked nar_files would be incorrectly reported as "missing from storage" when the CDC config is not properly set. These checks verify that chunked NAR files are stored correctly and all chunks are present in storage. A bug fix in PR #986 corrected fsck's CDC mode detection to properly read `cdc_enabled` (with underscore) instead of incorrectly looking for `cdc.enabled` (with dot). All tools now correctly reference these underscore-based keys.
+**Note on configuration key format:** The CDC configuration keys are stored in the database with underscores (`cdc_enabled`, `cdc_min`, `cdc_avg`, `cdc_max`), not dots. This is important for fsck operations: the fsck command uses a three-signal detection mechanism to determine whether to perform CDC-specific integrity checks:
+
+1. **Signal 1:** The DB config key `cdc_enabled` equals `"true"` (active or draining CDC)
+2. **Signal 2:** At least one `nar_file` has `total_chunks > 0` (chunked data present)
+3. **Signal 3:** The `chunks` table is non-empty (orphaned chunk residue after CDC disabled and all NARs de-chunked)
+
+Signal 3 is specifically for detecting orphaned chunk residue that remains after a CDC→whole migration fully drains and the serve restart clears `cdc_enabled`. Without this signal, orphaned chunks would be undetectable since they're not referenced by any `nar_file`. When CDC mode is enabled solely by signal 3, fsck emits a distinct informational log: "chunk residue detected (orphaned chunks remain after CDC was disabled); enabling CDC mode to reclaim them — run with --repair to delete"
+
+These checks verify that chunked NAR files are stored correctly and all chunks are present in storage. A bug fix in PR #986 corrected fsck's CDC mode detection to properly read `cdc_enabled` (with underscore) instead of incorrectly looking for `cdc.enabled` (with dot). All tools now correctly reference these underscore-based keys.
 
 **Fsck CDC Detection Warnings:**
 
@@ -369,15 +372,17 @@
 
 **Fallback Detection Logic:**
 
-Fsck uses a two-tier CDC detection mechanism:
-
-1. **Primary detection:** Reads the `cdc_enabled` database config key
-2. **Fallback detection:** If the `cdc_enabled` key cannot be read or is not set, fsck automatically checks if any chunked nar_files exist in the database (nar_files with `total_chunks > 0`)
-
-The fallback mechanism prevents false positives where chunked nar_files would be incorrectly reported as "missing from storage" when the CDC config is unavailable. This can occur when:
+Fsck uses a three-signal CDC detection mechanism evaluated in priority order:
+
+1. **Signal 1:** The DB config key `cdc_enabled` equals `"true"` (active or draining CDC)
+2. **Signal 2:** At least one `nar_file` has `total_chunks > 0` (chunked data present)
+3. **Signal 3:** The `chunks` table is non-empty (orphaned chunk residue after CDC disabled and all NARs de-chunked)
+
+Signals 2 and 3 prevent false positives where chunked data would be incorrectly reported as "missing from storage" when the CDC config is unavailable. Signal 3 specifically detects orphaned chunk residue that remains after CDC is disabled and all NARs are de-chunked — a state where signals 1 and 2 are both false but chunks still exist. Without signal 3, such residue would be undetectable and stranded forever. This can occur when:
 - The database URL is incorrect or points to the wrong database
 - The `cdc_enabled` config key was never set but chunked data exists
 - Database connection or read errors prevent config access
+- A CDC→whole migration has fully drained, clearing `cdc_enabled` and de-chunking all NARs, but orphaned chunks remain
 
 **Action Required:**
 

How did I do? Any feedback?  Join Discord

@kalbasit

kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 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.

🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/specs/fsck/spec.md (1)

5-11: ⚡ Quick win

Consider specifying error-handling behavior for CDC mode detection queries.

The spec mandates the residue check query (line 11) but doesn't specify what should happen if Chunk.Query().Exist(ctx) returns an error. The implementation handles this gracefully by logging a warning and treating the error as "signal absent," allowing detection to degrade rather than abort the fsck run. This error-handling contract should be explicit in the requirements to ensure future implementations maintain the same resilient behavior.

📋 Suggested addition to the requirement

Add after line 11:

Query errors during signal detection (config lookup, chunked nar_file check, or chunk residue check) SHALL be logged and treated as "signal absent," allowing detection to degrade gracefully to the next signal rather than aborting the fsck run.
🤖 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-07-fsck-reclaim-orphaned-chunk-residue/specs/fsck/spec.md`
around lines 5 - 11, The spec omits error-handling for CDC detection queries;
update the ncps fsck requirement to state that any query errors (config lookup
for cdc_enabled, the nar_file total_chunks check, or the
Chunk.Query().Exist(ctx) residue check) MUST be logged and treated as the signal
being absent so detection degrades to the next check rather than aborting the
run; reference the cdcMode determination logic, the DB config key `cdc_enabled`,
the `nar_file` total_chunks check, and `Chunk.Query().Exist(ctx)` in the wording
and require logging of the error before treating the signal as absent.
🤖 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-07-fsck-reclaim-orphaned-chunk-residue/specs/fsck/spec.md`:
- Around line 5-11: The spec omits error-handling for CDC detection queries;
update the ncps fsck requirement to state that any query errors (config lookup
for cdc_enabled, the nar_file total_chunks check, or the
Chunk.Query().Exist(ctx) residue check) MUST be logged and treated as the signal
being absent so detection degrades to the next check rather than aborting the
run; reference the cdcMode determination logic, the DB config key `cdc_enabled`,
the `nar_file` total_chunks check, and `Chunk.Query().Exist(ctx)` in the wording
and require logging of the error before treating the signal as absent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d8e64b5d-f6b1-4b4c-94d9-e507e3cd173b

📥 Commits

Reviewing files that changed from the base of the PR and between 78caff8 and 1d7b37c.

📒 Files selected for processing (9)
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/.openspec.yaml
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/design.md
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/proposal.md
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/specs/fsck/spec.md
  • openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/tasks.md
  • openspec/specs/fsck/spec.md
  • pkg/ncps/fsck.go
  • pkg/ncps/fsck_cdc_mode_detection_internal_test.go
  • pkg/ncps/fsck_test.go

After a CDC->whole migration fully drains, fsck detected CDC mode only
when cdc_enabled=true OR a nar_file had total_chunks>0. Once the serve
restart cleared cdc_enabled and every NAR was de-chunked, both signals
went false while orphaned chunk rows/files could remain -- so fsck
never initialized the chunk store and silently skipped reclamation,
stranding the residue forever (observed: ~5.5M orphaned chunk rows).

Extract the inline detection into detectFsckCDCMode() returning a
cdcModeReason, and add a third, lowest-priority signal: a non-empty
chunks table (Chunk.Query().Exist). It only fires when signals 1 and 2
are both false, emitting a distinct info log so a post-drain fsck's
chunk work is self-explanatory. Precedence and the existing signal-1/2
log messages are unchanged, so active-CDC and chunked-NAR runs behave
identically.

Covered by internal unit tests (all four detection branches) and an
end-to-end test asserting fsck --dry-run reports and --repair reclaims
residue with no cdc_enabled config and no chunked nar_files.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the fix-fsck-reclaim-orphaned-chunk-residue branch from 1d7b37c to 2584e3a Compare June 7, 2026 21:35
@kalbasit
kalbasit enabled auto-merge (squash) June 7, 2026 21:37
@kalbasit
kalbasit merged commit 7b567fd into main Jun 7, 2026
98 of 116 checks passed
@kalbasit
kalbasit deleted the fix-fsck-reclaim-orphaned-chunk-residue branch June 7, 2026 22:37
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
bryandph pushed a commit to bryandph/ncps that referenced this pull request Jun 11, 2026
## Summary

After a CDC→whole migration fully drains, `fsck` detected CDC mode only
when `cdc_enabled=true` **or** a `nar_file` had `total_chunks>0`. Once
the serve restart cleared `cdc_enabled` and every NAR was de-chunked,
both signals went false while orphaned chunk rows/files could remain —
so `fsck` never initialized the chunk store and silently skipped
reclamation, stranding the residue forever (observed in prod: ~5.5M
orphaned chunk rows, reclaimable only because the one `fsck` run started
~46s before drain cleared the config).

- Extracted the inline CDC-mode detection into `detectFsckCDCMode()`
returning a `cdcModeReason`.
- Added a third, lowest-priority signal: a non-empty `chunks` table
(`Chunk.Query().Exist`). It fires only when signals 1 and 2 are both
false, emitting a distinct info log so a post-drain `fsck`'s chunk work
is self-explanatory.
- Precedence and the existing signal-1/2 log messages are unchanged →
active-CDC and chunked-NAR runs behave identically.

Spec: adds requirement "Fsck MUST enable CDC mode when chunk residue
exists, even after CDC and drain are fully disabled" to
`openspec/specs/fsck`.

## Test plan

- [x] `task fmt` / `task lint` / `task test` pass
- [x] 4 internal unit tests covering all detection branches
(residue-only, never-CDC, config precedence, chunked-nar-files fallback)
- [x] e2e: `fsck --dry-run` reports + `fsck --repair` reclaims residue
with no `cdc_enabled` config and no chunked nar_files

Co-authored-by: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
…1396)

## 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

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

Refs #1392

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code 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