Repository navigation
fix(fsck): detect chunk residue post-drain - #1364
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
|
Warning Review limit reached
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 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 (9)
📝 WalkthroughWalkthroughThis PR enhances ChangesFsck orphaned chunk residue reclamation
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 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 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.
|
Documentation Updates 1 document(s) were updated by changes in this PR: Cache and Storage Configuration FlagsView 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:**
|
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/specs/fsck/spec.md (1)
5-11: ⚡ Quick winConsider 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
📒 Files selected for processing (9)
openspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/.openspec.yamlopenspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/design.mdopenspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/proposal.mdopenspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/specs/fsck/spec.mdopenspec/changes/archive/2026-06-07-fsck-reclaim-orphaned-chunk-residue/tasks.mdopenspec/specs/fsck/spec.mdpkg/ncps/fsck.gopkg/ncps/fsck_cdc_mode_detection_internal_test.gopkg/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]>
1d7b37c to
2584e3a
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]>
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]>
## 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]>
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]>
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]>
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]>
…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]>
Summary
After a CDC→whole migration fully drains,
fsckdetected CDC mode only whencdc_enabled=trueor anar_filehadtotal_chunks>0. Once the serve restart clearedcdc_enabledand every NAR was de-chunked, both signals went false while orphaned chunk rows/files could remain — sofscknever initialized the chunk store and silently skipped reclamation, stranding the residue forever (observed in prod: ~5.5M orphaned chunk rows, reclaimable only because the onefsckrun started ~46s before drain cleared the config).detectFsckCDCMode()returning acdcModeReason.chunkstable (Chunk.Query().Exist). It fires only when signals 1 and 2 are both false, emitting a distinct info log so a post-drainfsck's chunk work is self-explanatory.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 testpassfsck --dry-runreports +fsck --repairreclaims residue with nocdc_enabledconfig and no chunked nar_files