Skip to content

fix(cdc): heal orphaned mid-chunking NAR state via migration-lock liveness - #1317

Merged
kalbasit merged 6 commits into
kalbasit:mainfrom
mvanhorn:fix/1230-cdc-orphan-startup-recovery
Jun 7, 2026
Merged

kalbasit merged 6 commits into
kalbasit:mainfrom
mvanhorn:fix/1230-cdc-orphan-startup-recovery

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes the orphaned mid-chunking state described in #1230. When CDC is enabled, the
background chunker runs after the client is already served; a SIGKILL/OOM mid-chunking
leaves a nar_file row with total_chunks = 0, a fresh chunking_started_at, and a
partial set of nar_file_chunks. The read path treated the fresh lock as a live chunk,
streamed chunks 0..M, then stalled maxWaitPerChunk (30s) on a chunk no producer would
write — the client saw Truncated zstd input.

The fix uses the per-hash migration lock (migrationLockKey(hash), held by the
download-path chunker for the whole operation via withNarMigrationLock) as the single
cross-instance liveness signal, replacing the 1h cdcChunkingLockTTL age — a poor
liveness proxy — in the three places it was used:

  1. Read path (the actual symptom fix). isServable probes the lock (new
    cdcChunkerLive, fail-safe to "live") for the ambiguous total_chunks == 0 && fresh-lock case. A free lock means the producer is dead → the row is not servable →
    GetNar re-downloads cleanly before any bytes are streamed. A held lock keeps
    the row servable so legitimate progressive chunking still streams.
  2. Write path. findOrCreateNarFileForCDC always runs while holding the migration
    lock, so a fresh in-progress row it encounters belongs to a dead chunker. It now
    reclaims the partial chunks and re-chunks regardless of age, instead of refusing a fresh
    row with ErrAlreadyExists (which would strand the orphan and block the re-download).
    The redundant in-transaction age gate in clearStaleCDCChunkingLockWithEntTx is removed.
  3. Cron. runCDCLazyRecovery reaps in-progress orphans of any age, gated solely on
    a per-row TryLock(migrationLockKey(hash)) (skip if a peer holds it, reap if free); the
    1h staleCutoffTime predicate is gone. This handles rows that are never re-requested and
    reclaims their orphaned chunk blobs.

Why this is HA-safe

In a multi-replica shared-DB deployment, a total_chunks = 0 in-progress row may belong to
a peer's live chunker — total_chunks stays 0 for the whole healthy operation, so age
can't distinguish live from dead. The migration lock can: a live chunker (this instance or
a peer) holds it, so every reaping/serving/takeover decision keys off the lock, never off
age. The lazy-recovery cron is additionally serialized across instances by
withTryLock("cdc-lazy-recovery").

Also addressed (review threads on this PR)

  • Background CDC chunking that returns ErrMigrationInProgress (a peer holds the lock) is a
    benign debug no-op via reportBackgroundCDCError — no error-level log, no
    downloadState.setError — instead of HA log spam / spurious alerts.
  • The lazy-chunking-disabled skip uses a distinct lazy_chunking_disabled_skip_count
    counter instead of inflating stale_recovery_skip_count.

Testing

  • New internal tests (TDD): read-path liveness gate (read_path_liveness_internal_test.go),
    write-path orphan takeover (cdc_chunker_takeover_internal_test.go), benign
    ErrMigrationInProgress handling (background_cdc_error_internal_test.go), cron
    any-age reaping + lock-held skip + counter disambiguation
    (orphan_lazy_recovery_internal_test.go, recovery_skip_counter_internal_test.go).
  • The two progressive-streaming tests now hold the migration lock (via an export_test.go
    seam) to faithfully simulate a live chunker.
  • task fmt, task lint (0 issues), and task test all pass.

Known residual (accepted)

If a chunker dies after isServable passed (lock held) but mid-stream, the wait loop
still only fast-fails on >1h staleness — but bytes are already committed, so a clean
response isn't possible regardless. The dominant restart repro from #1230 is fully fixed.

A spec for this behavior is captured under OpenSpec (cdc-orphan-chunking-recovery,
modifying the cdc-chunking capability).

Fixes #1230

When CDC is enabled, storeNarWithCDCFromReader returns the NAR to the
client before the background chunker finishes. A crash/SIGKILL mid-chunk
leaves nar_files in an orphan state (total_chunks=0, chunking_started_at
SET and fresh, partial nar_file_chunks). On restart the read path treats
the fresh lock as live, streams the partial chunks, then times out after
30s waiting for a chunk no producer will write, and the client sees a
truncated stream.

The existing runCDCLazyRecovery cron only selects chunking_started_at IS
NULL rows, so this crash-orphan state was unhandled until the 1h lock TTL.

Add RecoverOrphanedChunkingOnStartup: a one-shot, idempotent startup scan
that selects total_chunks=0 AND chunking_started_at NOT NULL rows, and for
each (in a transaction, re-asserting the orphan predicate against the live
row) deletes partial nar_file_chunks, clears chunking_started_at, and
reclaims now-orphaned chunk blobs via the existing cleanupStaleLockChunks
helper. Wired into serve.go startup after the chunk store is set, gated on
CDC being enabled, log-and-continue on error.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 3, 2026
@dosubot dosubot Bot added the go Pull requests that update go code label Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Fixed streaming stall issue that occurred during CDC operations after unclean shutdowns.
    • Improved recovery of abandoned mid-chunking operations for reduced latency and reliability.
  • Improvements

    • Enhanced error handling for concurrent chunking scenarios with refined logging.
    • Improved observability of recovery skip conditions in distributed deployments.

Walkthrough

CDC orphan recovery is redesigned to use per-hash migration-lock liveness (instead of age heuristics) as the authoritative signal across read, write, cron, and background paths. Write-path CDC entry points now acquire migration locks and reclaim stale in-progress rows transactionally; read-path servability gates ambiguous in-progress rows on lock-probe liveness; recovery cron scans any-age orphans and reclaims them only when the lock is free; background chunking failures from peer-held locks are demoted to benign logging. Tests and OpenSpec documentation are updated throughout.

Changes

CDC Stale Chunking Lock Recovery

Layer / File(s) Summary
OpenSpec design and implementation requirements
openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/.*, openspec/specs/cdc-chunking/spec.md
Design document, proposal, tasks checklist, and comprehensive requirements specifications define lock-liveness recovery gating, skip-counter separation, read/write/cron path behavior, background error handling, and CDC ingestion validation constraints.
CLI messaging and recovery cron job registration
pkg/ncps/serve.go
CDC recovery schedule requirement now applies to any CDC mode (not just lazy chunking). Startup refactors recovery cron registration into a conditional helper that validates and parses schedules or skips gracefully when schedules are absent and lazy chunking is disabled.
CDC write-path migration locking and orphan reclamation
pkg/cache/cache.go
CDC storage entry points (storeNarWithCDC, storeNarWithCDCFromReaderWithMigrationLock) are refactored to acquire/hold per-NAR migration locks. Orphan detection and cleanup are centralized in clearStaleCDCChunkingLockWithEntTx (transaction helper); findOrCreateNarFileForCDC now reclaims orphans when the lock is held. Background CDC downloads route through lock-guarded wrappers.
Background CDC error reporting and tests
pkg/cache/background_cdc_error_internal_test.go, pkg/cache/cache.go, pkg/cache/cdc_chunker_takeover_internal_test.go
New reportBackgroundCDCError helper treats ErrMigrationInProgress as benign (debug logging, no download failure mark) while propagating real chunking errors. Tests verify benign vs fatal error handling and orphan takeover under lock.
Read-path liveness probing and servability gating
pkg/cache/cache.go, pkg/cache/read_path_liveness_internal_test.go
cdcChunkerLive non-blocking lock probe determines whether an in-progress row has an active producer. isServable rejects stalled orphans (free lock) to force re-download instead of stalling; remains servable when a peer holds the lock. Four test scenarios cover fresh/stale in-progress and fully-chunked states with/without held locks.
Migration lock lifecycle and test scaffolding
pkg/cache/cache.go, pkg/cache/export_test.go, pkg/cache/cache_prefetch_test.go
Per-NAR migration locks are kept alive during long migrations using TTL refreshers. New AcquireMigrationLockForTest export seam enables tests to simulate active chunkers; progressive streaming tests hold locks during background completion/abort and release to verify fail-fast behavior.
Cursor-backed lazy recovery scanning and stale-lock reclamation
pkg/cache/cache.go
runCDCLazyRecovery now uses a persisted keyset cursor for resumable scanning, selects any-age in-progress candidates, and processes each via recoverStaleCDCChunkingLock (non-blocking TryLock gating). Skip counters are separated (lazy-disabled vs stale-lock-held); stale chunk artifacts are cleaned immediately on successful reclamation.
Lazy recovery tests, fixtures, and skip-counter verification
pkg/cache/orphan_lazy_recovery_internal_test.go, pkg/cache/recovery_skip_counter_internal_test.go
Test fixtures initialize cache + CDC configuration and provide helpers for chunk-link seeding/counting. Four recovery scenarios verify: clearing stale orphans, reaping fresh orphans, preserving completed rows, and skipping lock-held rows. Separate test verifies lazy-disabled skip counter increments independently.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • kalbasit/ncps#1298: Implements persistent keyset cursor infrastructure for runCDCLazyRecovery resumability across restarts.
  • kalbasit/ncps#1301: Modifies per-hash migration-lock semantics and TTL refresh behavior in MigrateNarToChunks alongside CDC lock coordination.
  • kalbasit/ncps#1204: Ent-based refactoring of CDC recovery/state handling affecting nar_file chunking fields and recovery query construction.

Suggested labels

bug, size:L

Poem

🐰 A lock-liveness tale, with cheer—
Orphans reborn when peers disappear!
No more age-gate delay or stall,
Just a free lock reclaims them all.
Hops merrily ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and concisely summarizes the main change: fixing orphaned mid-chunking NAR state using migration-lock liveness as the liveness signal.
Description check ✅ Passed The PR description is detailed and directly related to the changeset, explaining the problem, the solution across read/write/cron paths, HA safety, and testing approach.
Linked Issues check ✅ Passed The PR implements all core objectives from issue #1230: read-path liveness probing, write-path orphan takeover, cron-based recovery of any-age orphans, and HA-safe cross-instance coordination via migration lock.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing #1230 orphaned mid-chunking recovery. Supporting changes include test-only exports, test additions, spec documentation, and benign error handling—all scoped to the core objective.

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


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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 startup recovery mechanism (RecoverOrphanedChunkingOnStartup) to heal CDC nar_file rows left in a mid-chunking state due to a previous process crash, along with corresponding unit tests and integration into the cache initialization. Feedback on the changes suggests that instead of returning an error and aborting the entire recovery loop when a single file recovery fails, the loop should log the error and continue processing other orphaned files to align with the best-effort nature of the recovery process.

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/cache/cache.go Resolved
@dosubot

dosubot Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Documentation Updates

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

NAR File Download and Streaming
View Changes
@@ -115,9 +115,9 @@
 
 - **Fully chunked**: Records with `total_chunks > 0` and `chunking_started_at` set. These records represent NAR files that have been successfully chunked and are ready for CDC streaming.
   - **Completeness check**: For completed chunked NARs (`total_chunks > 0`), the cache performs a synchronous completeness check before committing any HTTP response. This check verifies that the number of `nar_file_chunks` junction links equals `total_chunks`. If the NAR cannot be reassembled (fewer links than `total_chunks`), the cache returns `ErrNotFound` (HTTP 404) instead of starting an HTTP 200 response. This prevents the previous behavior where clients would receive "unexpected end of nar", "truncated input", or SSL errors on incomplete chunked NARs. The check only applies to completed NARs; the progressive path (`total_chunks = 0`) is unchanged and continues to stream chunks as they appear. `total_chunks` is the completion latch: it is set only after all junction links are durably committed, so `total_chunks > 0 && links < total_chunks` is always genuine post-completion loss (e.g., junction links stripped by the `nar_file_chunks.chunk_id -> chunks(id) ON DELETE CASCADE` foreign key without resetting `total_chunks`), never a mid-chunking race.
-- **Actively chunking**: Records with `chunking_started_at` set but `total_chunks = 0`. These records indicate that chunking is in progress. When lazy chunking is disabled, the `chunking_started_at` timestamp is set within milliseconds of download start (before decompression completes), allowing other HA instances to immediately detect active chunking operations and use progressive streaming. The system uses progressive streaming to serve these NARs while chunking completes.
+- **Actively chunking**: Records with `chunking_started_at` set but `total_chunks = 0`. These records indicate that chunking is in progress. When lazy chunking is disabled, the `chunking_started_at` timestamp is set within milliseconds of download start (before decompression completes), allowing other HA instances to immediately detect active chunking operations and use progressive streaming. The system checks if the background chunker is alive by probing the migration lock (`migrationLockKey(hash)`). If the migration lock is free (not held by any worker), the NAR is treated as orphaned and not servable, even if `chunking_started_at` is recent. The system uses progressive streaming to serve these NARs while chunking completes.
 - **Pending migration (lazy chunking)**: Records with `total_chunks = 0` and `chunking_started_at = NULL`. When lazy chunking is enabled, these records represent compressed NAR files stored without chunking that are awaiting background migration. Background workers asynchronously chunk these files using the `migrate-nar-to-chunks` infrastructure. If ncps is restarted before background chunking completes, these records can become "stuck" and will be recovered by the periodic recovery cron job (see "Recovery of Stuck NARs" in the lazy chunking section).
-- **Placeholder/Failed**: Records with `total_chunks = 0` and `chunking_started_at = NULL` can also represent placeholder records created during narinfo storage (via `storeInDatabase`) to link the narinfo to its eventual NAR file. If the subsequent background NAR download fails (e.g., temporary directory missing), or if a chunking operation fails partway through (e.g., "no space left on device"), these placeholder records persist in the database without actual chunked data. When chunking fails due to most errors, the system automatically clears the `chunking_started_at` lock via the `ClearNarFileChunkingStarted` database operation to prevent subsequent requests from waiting indefinitely for chunks that will never arrive. However, when chunking fails specifically due to truncation detection (where the total bytes consumed do not match the expected `NarSize`), the system intentionally leaves `chunking_started_at` set and relies on the stale lock recovery mechanism (1-hour TTL cleanup) to handle it, rather than clearing the lock immediately.
+- **Placeholder/Failed**: Records with `total_chunks = 0` and `chunking_started_at = NULL` can also represent placeholder records created during narinfo storage (via `storeInDatabase`) to link the narinfo to its eventual NAR file. If the subsequent background NAR download fails (e.g., temporary directory missing), or if a chunking operation fails partway through (e.g., "no space left on device"), these placeholder records persist in the database without actual chunked data. When chunking fails due to most errors, the system automatically clears the `chunking_started_at` lock via the `ClearNarFileChunkingStarted` database operation to prevent subsequent requests from waiting indefinitely for chunks that will never arrive. However, when chunking fails specifically due to truncation detection (where the total bytes consumed do not match the expected `NarSize`), the system intentionally leaves `chunking_started_at` set, marks the NAR as not servable via the migration-lock liveness probe, and relies on the next CDC lazy-recovery run to detect and fix the orphan.
 
 **CDC Residue Flag:**
 
@@ -204,13 +204,15 @@
 
 When CDC chunking fails (e.g., due to "no space left on device" in the temporary directory), the `storeNarWithCDCFromReader` function automatically clears the `chunking_started_at` database lock via the `ClearNarFileChunkingStarted` operation. This cleanup is performed through a deferred function that checks the success status. If the chunking operation completes successfully, the `chunking_started_at` field is cleared as part of the `UpdateNarFileTotalChunks` operation; if it fails, the deferred cleanup ensures the lock is removed to prevent subsequent requests from waiting indefinitely for chunks that will never arrive.
 
-This automatic lock cleanup prevents a failure scenario where stale chunking locks (previously locked for up to 1 hour) could cause subsequent requests to timeout after 30 seconds and fail with "truncated zstd input" errors. By immediately clearing the lock on failure, the system ensures that subsequent requests detect the failed state and trigger a fresh download rather than attempting to stream from non-existent chunks.
+This automatic lock cleanup prevents a failure scenario where stale chunking locks could cause subsequent requests to timeout and fail with "truncated zstd input" errors. By immediately clearing the lock on failure, the system ensures that subsequent requests detect the failed state and trigger a fresh download rather than attempting to stream from non-existent chunks.
+
+Background CDC goroutine errors are handled specially: `ErrMigrationInProgress` is treated as a benign retriable error (logged at debug level only, not propagated via `downloadState.setError`) rather than causing the NAR to be marked as failed. This error indicates that a peer holds the per-hash migration lock, which is a normal outcome in HA deployments — the in-flight client already received the bytes and the lock holder will persist the NAR. All other errors are logged at error level and propagated via `downloadState.setError`.
 
 **Truncation Detection:**
 
 Before committing CDC chunks, the system validates that the total number of bytes consumed by the chunker matches the expected `NarSize` declared in the narinfo (when `fileSize > 0`). This validation occurs at the commit site in `storeNarWithCDCFromReader`, after all chunks have been processed. If the total size does not match the expected size, the function returns `io.ErrUnexpectedEOF` with an error message indicating the mismatch: `"CDC chunking truncated: expected X uncompressed bytes, got Y"`. This prevents silent cache poisoning that could occur when upstream HTTP/2 streams drop early (e.g., Cloudflare GOAWAY) and FastCDC reads a clean `io.EOF` from the decompressor while the NAR is actually incomplete.
 
-When CDC chunking fails due to truncation detection, the code does NOT call `ClearNarFileChunkingStarted` immediately. Instead, it leaves the `chunking_started_at` lock set and relies on the stale lock recovery mechanism (1-hour TTL cleanup) to handle it. This behavior differs from other chunking failure paths, which clear the lock immediately via the deferred cleanup function.
+When CDC chunking fails due to truncation detection, the code does NOT call `ClearNarFileChunkingStarted` immediately. Instead, it leaves the `chunking_started_at` lock set. Orphaned mid-chunking states (where the producer died) are detected via the lock-liveness probe rather than waiting for the full timeout period.
 
 This separation ensures that transient client disconnections do not interfere with background caching operations, while genuine download and chunking failures are properly reported to all affected clients and cleaned up appropriately [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/cache/cache.go#L94-L677).
 
@@ -343,13 +345,15 @@
 
 When lazy chunking is enabled and ncps is restarted before background chunking completes, NARs can become stuck in a state with `total_chunks = 0` and `chunking_started_at = NULL`. To recover from this scenario, the system implements a recovery cron job (via `AddCDCLazyRecoveryCronJob`) that periodically scans for and recovers these stuck NAR files.
 
+The recovery mechanism detects orphaned NARs by checking if `total_chunks = 0` AND the migration lock is free (no active background chunker). The system no longer uses an age threshold between cron runs to determine which NARs to process. Instead, a free migration lock is treated as evidence that no chunker is actively working on the NAR, making it eligible for recovery regardless of age. For in-progress chunking rows (those with `chunking_started_at` set), the recovery job probes the per-hash migration lock (`migrationLockKey(hash)`) before acting. If the lock is held by a live chunker, the NAR is skipped and counted in the `stale_recovery_skip_count` metric. If the lock is free, the partial chunks are reclaimed and `chunking_started_at` is cleared, allowing a clean re-download.
+
 The recovery job:
 
 - Runs on a configurable schedule (default: every 5 minutes via `--cache-cdc-lazy-recovery-schedule`)
-- Uses the interval between runs as the age cutoff to identify genuinely stuck NARs (e.g., if it runs every 5 minutes, it only processes NARs older than 5 minutes)
 - Processes up to a configurable number of stuck NARs per run (default: 100 via `--cache-cdc-lazy-recovery-batch-size`)
 - Uses distributed locking to prevent duplicate processing across multiple ncps instances
 - Preserves query parameters from the original NAR URL when constructing the `nar.URL` structure for background migration, ensuring the recovery job can properly identify and process stuck NAR records that include query strings (e.g., `?fakesize=123`)
+- Tracks skipped NARs via distinct counters: `stale_recovery_skip_count` for NARs with an active chunker (lock held), and `lazy_chunking_disabled_skip_count` for NARs skipped because lazy chunking is disabled
 
 The `--cache-cdc-lazy-recovery-schedule` flag accepts either `@every X` format (e.g., `@every 5m`, `@every 10m`) or standard cron expressions. The corresponding Helm chart values are `config.cdc.lazyRecoverySchedule` and `config.cdc.lazyRecoveryBatchSize`.
 

How did I do? Any feedback?  Join Discord

@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/cache/orphan_startup_recovery_internal_test.go (1)

33-56: ⚡ Quick win

Strengthen the positive test to assert chunk reclamation.

This test confirms ChunkingStartedAt is cleared and the NarFileChunk links are deleted, but a stated objective of recovery is to reclaim the now-orphaned chunk blobs/records via cleanupStaleLockChunks. Currently nothing verifies the seeded Chunk rows (or store files) are actually reclaimed, so a regression in that path would go undetected. Consider adding an assertion on the remaining Chunk count for the orphaned NarFile.

💚 Suggested additional assertion
 	count, err := c.dbClient.Ent().NarFileChunk.Query().
 		Where(entnarfilechunk.NarFileIDEQ(orphaned.ID)).
 		Count(ctx)
 	require.NoError(t, err)
 	assert.Zero(t, count)
+
+	chunkCount, err := c.dbClient.Ent().Chunk.Query().
+		Where(entchunk.HasNarFileLinksWith(entnarfilechunk.NarFileID(orphaned.ID))).
+		Count(ctx)
+	require.NoError(t, err)
+	assert.Zero(t, chunkCount, "orphaned chunks must be reclaimed")
 }

This requires importing entchunk "github.com/kalbasit/ncps/ent/chunk".

🤖 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/cache/orphan_startup_recovery_internal_test.go` around lines 33 - 56, Add
an assertion to this test to verify chunk rows are reclaimed after
RecoverOrphanedChunkingOnStartup by querying the Chunk table for rows belonging
to the orphaned NarFile (use entchunk alias from
"github.com/kalbasit/ncps/ent/chunk") and asserting the count is zero; update
imports to include entchunk and call
c.dbClient.Ent().Chunk.Query().Where(entchunk.NarFileIDEQ(orphaned.ID)).Count(ctx)
and assert.Zero on that count to ensure cleanupStaleLockChunks actually removed
the Chunk records after RecoverOrphanedChunkingOnStartup completes.
🤖 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/cache/cache.go`:
- Around line 2248-2256: The current query that builds orphanedFiles
(c.dbClient.Ent().NarFile.Query() with entnarfile.TotalChunksEQ(0),
entnarfile.ChunkingStartedAtNotNil(), entnarfile.IDGT(cursorID)) can match a
live chunker on another replica; modify this predicate to require a
stale/ownership signal before mutating rows. Update the query used to populate
orphanedFiles (and the related logic around cursorID/batchSize) to also require
either (a) chunking_started_at older than a configurable TTL (e.g.,
Now().Add(-staleThreshold)) or (b) a stronger ownership/heartbeat key before
deleting nar_file_chunks / clearing chunking_started_at, and preserve the
existing in-transaction recheck. Ensure the new condition is configurable and
documented so shared-database deployments can tune the stale threshold or enable
heartbeat-based ownership checks.

In `@pkg/ncps/serve.go`:
- Around line 1185-1188: The log call at the end of the startup recovery block
exceeds the lll line-length limit; update the zerolog call (the chain using
zerolog.Ctx(ctx).Warn().Err(err).Msg(...)) so the Msg argument is split into
shorter string literals (or otherwise wrapped/concatenated) to keep the line
under 120 columns while preserving the same message text and context (keep
Err(err) and Warn()). After changing, run task fmt, task lint, and task test
before committing.

---

Nitpick comments:
In `@pkg/cache/orphan_startup_recovery_internal_test.go`:
- Around line 33-56: Add an assertion to this test to verify chunk rows are
reclaimed after RecoverOrphanedChunkingOnStartup by querying the Chunk table for
rows belonging to the orphaned NarFile (use entchunk alias from
"github.com/kalbasit/ncps/ent/chunk") and asserting the count is zero; update
imports to include entchunk and call
c.dbClient.Ent().Chunk.Query().Where(entchunk.NarFileIDEQ(orphaned.ID)).Count(ctx)
and assert.Zero on that count to ensure cleanupStaleLockChunks actually removed
the Chunk records after RecoverOrphanedChunkingOnStartup completes.
🪄 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: 4ed128e7-17b4-426a-9016-a99544a1a63d

📥 Commits

Reviewing files that changed from the base of the PR and between 822d656 and 8fc0945.

📒 Files selected for processing (3)
  • pkg/cache/cache.go
  • pkg/cache/orphan_startup_recovery_internal_test.go
  • pkg/ncps/serve.go

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/ncps/serve.go Resolved

@kalbasit kalbasit left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thank you for your contribution @mvanhorn, much appreciated!

I reviewed the PR and I have two concerns:

a) This blocks boot. Because the recovery scan runs synchronously before the HTTP listener starts, an instance with many or large orphaned NARs to recover can be slow to become ready — on Kubernetes this risks tripping the readiness/liveness probes and sending the pod into a crash loop.

b) It's unsafe in HA deployments. With multiple replicas sharing a database, a booting instance would interfere with NARs that another instance is actively chunking — deleting their partial chunks and clearing the lock, which can manufacture the very truncation error this PR is trying to fix.

I asked Opus to review the PR against the current codebase and validate these concerns; I've left its findings in the comments below.

I think this should instead be implemented in a way that's adjacent to (and shares code with) the lazy-CDC recovery path, using the same locking so that one instance can't step on another's in-flight work or block boot.

Comment thread pkg/ncps/serve.go Resolved
Comment thread pkg/cache/cache.go Resolved
kalbasit added a commit that referenced this pull request Jun 3, 2026
#1319)

## Summary

Production Nix clients were getting **truncated NAR downloads** from
ncps
(`unexpected end of nar`, `truncated input`, `SSL_read:
SSL_ERROR_SYSCALL`) on
responses that started as `HTTP 200`. Root cause, confirmed against the
live DB:

- `nar_file_chunks.chunk_id -> chunks(id)` is `ON DELETE CASCADE`.
Deleting a
shared `chunks` row strips its junction links from **completed** chunked
NARs
(`total_chunks > 0`) **without** resetting `total_chunks`. Nothing
enforced
  `count(links) == total_chunks`.
- The serve fast path only detected the gap (`expected N chunks but got
M`)
**inside the streaming goroutine**, after `server.go` had already
written
`200 OK` + `Content-Length` — so the client got a body it couldn't
fulfill and
  Nix could not fall back.
- This is **distinct from #1230/#1317** (those cover the `total_chunks =
0`
  mid-chunking orphans). Of 2499 completed chunked NARs in prod, 71 had
  `links < total_chunks`.

### Fix

`getNarFromChunks` now counts junction links in its init transaction on
the
`total_chunks > 0` fast path and returns `storage.ErrNotFound`
**synchronously**
when `links != total_chunks`, before the pipe/response are committed →
handler
responds `404` → Nix refetches upstream. `total_chunks` is the
completion latch
(written only after all links commit), so this is never a mid-chunking
race; the
progressive `total_chunks = 0` path is left untouched and stays HA-safe.

The `migrate-chunks-to-nar` driver already maps `ErrMissingChunk` to
`PurgeChunkedNar` + continue + report; the guard routes link-loss into
that path,
so the 71 broken NARs self-heal (purge → refetch) on the next drain.

Specs synced: new `chunked-nar-serving-integrity` capability + 2 added
requirements on `cdc-drain-mode`.

## Test plan

- [x] `task fmt` / `task lint` (0 issues) / `task test` (all packages
ok)
- [x] `go test -race ./pkg/cache ./pkg/server` — ok
- [x] New tests: serving 404-not-truncated-200, HA-safety on progressive
path,
missing-link → `ErrMissingChunk`, purge → clean cache-miss, and a CLI
      mix-migration test (skip broken + migrate good + report by hash)

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Per review: drop the synchronous startup scan (it blocked the HTTP
listener and raced other replicas in HA deployments). Orphaned
mid-chunking NAR state is now recovered inside the existing CDC
lazy-recovery cron job, sharing its code path and per-NAR migration
locking so a booting instance cannot delete chunks or clear locks
another replica holds. The recovery job arms for both CDC modes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mvanhorn

mvanhorn commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

Reworked per your review. The synchronous startup scan is gone entirely - boot no longer touches recovery. Orphaned mid-chunking state is now recovered inside the existing CDC lazy-recovery cron job (shared code path, same per-NAR migration locking), so a booting instance can't step on another replica's in-flight chunking and the recovery cadence follows --cache-cdc-lazy-recovery-schedule. The recovery job now arms for both CDC modes since orphans can exist in either. Full pkg/cache and pkg/ncps test suites pass locally, including the pre-existing lazy-recovery contract tests.

@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

🤖 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/cache/cache.go`:
- Around line 1953-1965: The current lock-miss branch in the TryLock result
returns ErrMigrationInProgress which surfaces as a hard GetNar failure; instead,
on !acquired the code should not return immediately but wait/re-check the
migration outcome — e.g. poll the existing migration result or block until the
lock is released and then call the same verification path (check downloadState
or re-run GetNar/cache lookup) before returning an error. Modify the block
around downloadLocker.TryLock, downloadLockTTL and ErrMigrationInProgress so
that a lock miss triggers a short wait/loop (with context cancellation/backoff)
that re-checks c.downloadState (or re-invokes the GetNar/cache check) and only
returns ErrMigrationInProgress after giving up, rather than returning
immediately.

In `@pkg/ncps/serve.go`:
- Around line 78-80: The ErrCDCLazyRecoveryScheduleRequired error text currently
says the flag is required "when CDC is enabled" but the code actually checks for
cdcLazyChunkingEnabled; update the error string in
ErrCDCLazyRecoveryScheduleRequired to reflect the real condition (e.g., mention
"when CDC lazy chunking is enabled" or reference cdcLazyChunkingEnabled) so the
message matches the guard used elsewhere (see ErrCDCLazyRecoveryScheduleRequired
and the cdcLazyChunkingEnabled validation).
🪄 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: ac8e8b4c-dd4a-4de9-a15e-7287e5234514

📥 Commits

Reviewing files that changed from the base of the PR and between 8fc0945 and 430bc18.

📒 Files selected for processing (3)
  • pkg/cache/cache.go
  • pkg/cache/orphan_lazy_recovery_internal_test.go
  • pkg/ncps/serve.go

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/ncps/serve.go Resolved

@kalbasit kalbasit left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Two things on top of the inline comments:

Title/description — please update them now to match what actually landed: cron-based, TTL-gated stale-lock recovery plus a per-hash migration-lock refactor — not the startup scan (RecoverOrphanedChunkingOnStartup, fresh-row reaping, serve.go wiring) the current description describes. Worth fixing before merge so the squash commit message is accurate.

PutNar upload path — putNarWithCDC (cache.go:1658) now goes through the lock-wrapping storeNarWithCDC, but its error handling only special-cases storage.ErrAlreadyExists; ErrMigrationInProgress falls through as a hard error. So a nix copy … /upload of hash X that collides with a concurrent background migration/recovery of the same hash now fails where it previously succeeded — a plausible regression given the recent …/upload abort history. Recommend treating errors.Is(err, ErrMigrationInProgress) the same as ErrAlreadyExists here.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
kalbasit and others added 2 commits June 6, 2026 18:54
…kalbasit#1230)

When CDC is enabled the chunker runs in the background after the client is
served. A SIGKILL/OOM mid-chunking leaves a nar_file row with total_chunks=0, a
FRESH chunking_started_at, and partial nar_file_chunks. The read path treated the
fresh lock as a live chunk and streamed chunks 0..M, then stalled maxWaitPerChunk
(30s) on a chunk no producer would write — the client got "Truncated zstd input".

The fix uses the per-hash migration lock (migrationLockKey, held by the
download-path chunker for the whole operation via withNarMigrationLock) as the
single cross-instance liveness signal, replacing the 1h cdcChunkingLockTTL age
that was a poor liveness proxy in three places:

- Read path (the symptom fix): isServable probes the migration lock for the
  ambiguous total_chunks==0 && fresh-lock case (new cdcChunkerLive helper:
  non-blocking TryLock+Unlock, fail-safe to live). A free lock means a dead
  chunker -> not servable -> GetNar re-downloads cleanly BEFORE any bytes are
  streamed. A held lock keeps the row servable so legitimate streaming works.

- Write path: findOrCreateNarFileForCDC always runs while holding the migration
  lock, so an in-progress row it sees is a dead orphan. It now reclaims and
  re-chunks regardless of age instead of refusing a fresh row with
  ErrAlreadyExists (which would strand the orphan and block the re-download).
  The redundant in-transaction age gate in clearStaleCDCChunkingLockWithEntTx is
  removed (callers gate liveness).

- Cron: runCDCLazyRecovery reaps in-progress orphans of ANY age, gated solely on
  the per-hash TryLock (skip if a peer holds it, reap if free); the staleCutoffTime
  predicate is dropped. Handles rows never re-requested + reclaims chunk blobs.

Also addresses the other open review threads on kalbasit#1317:
- Background CDC chunking returning ErrMigrationInProgress (a peer holds the lock)
  is a benign debug no-op via reportBackgroundCDCError, not error log + setError.
- Lazy-chunking-disabled skips use a distinct lazy_chunking_disabled_skip_count
  instead of inflating stale_recovery_skip_count.

Progressive-streaming tests now hold the migration lock (AcquireMigrationLockForTest
export seam) to faithfully simulate a live chunker.

Adds OpenSpec change cdc-orphan-chunking-recovery (modifies cdc-chunking).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 7, 2026
@kalbasit

kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Since the PR has been idle, I pushed 83b3245 to address the outstanding review feedback and complete the fix for #1230.

What was open vs. now

  • A — boot-blocking startup scan & E — ErrMigrationInProgress hard GetNar failure: already resolved earlier on the branch (430bc18 moved recovery into the lazy-recovery cron; coordinateDownload polls/takes over).
  • B — multi-instance premise / age gate, C — ErrMigrationInProgress log spam, D — skip-counter conflation: addressed in this push.

Key finding from the review

The cron-only recovery did not actually fix the user-visible symptom. The issue's own repro (restart → immediately re-fetch) lands before the first cron run, and the read path still treated a fresh dead-chunker orphan as servable on the 1h cdcChunkingLockTTL — so it streamed 200 + chunks 0..M then stalled maxWaitPerChunk on a chunk no producer would write (Truncated zstd input).

The fix is to use the per-hash migration lock (migrationLockKey, held by the download-path chunker for the whole operation via withNarMigrationLock) as the single cross-instance liveness signal, replacing the 1h age — which was a poor liveness proxy — in all three places it was used:

  1. Read path (the symptom fix) — isServable probes the lock (new cdcChunkerLive, fail-safe to "live") for the ambiguous total_chunks==0 && fresh-lock case. A free lock ⇒ dead chunker ⇒ not servable ⇒ GetNar re-downloads cleanly before any bytes are streamed. A held lock keeps the row servable so legitimate progressive chunking still streams.
  2. Write path — findOrCreateNarFileForCDC always runs while holding the migration lock, so a fresh in-progress row it sees is a dead orphan; it now reclaims and re-chunks regardless of age instead of refusing with ErrAlreadyExists (which would strand the orphan and block the re-download). The redundant in-transaction age gate in clearStaleCDCChunkingLockWithEntTx was removed.
  3. Cron — runCDCLazyRecovery reaps in-progress orphans of any age, gated solely on the per-row TryLock (skip if a peer holds it, reap if free); the staleCutoffTime predicate is gone. This still handles rows that are never re-requested and reclaims their chunk blobs.

Plus the two smaller threads: benign ErrMigrationInProgress background-chunk failures are now a debug no-op (reportBackgroundCDCError, no error log / no setError), and lazy-chunking-disabled skips use a distinct lazy_chunking_disabled_skip_count instead of inflating stale_recovery_skip_count.

Notes

  • New tests are TDD'd (read-path liveness, write-path takeover, benign-error handling, counter). The two progressive-streaming tests now hold the migration lock to faithfully simulate a live chunker.
  • task fmt / task lint (0 issues) / task test all pass.
  • Known residual (accepted): if a chunker dies after isServable passed but mid-stream, the wait loop still only fast-fails on >1h staleness — but bytes are already committed so a clean response isn't possible anyway. The dominant restart repro is fully fixed.
  • A spec was written for this under OpenSpec (cdc-orphan-chunking-recovery, modifying cdc-chunking).

@kalbasit kalbasit changed the title fix: recover orphaned mid-chunking NAR state on startup fix(cdc): heal orphaned mid-chunking NAR state via migration-lock liveness Jun 7, 2026
…g-recovery

Apply the cdc-orphan-chunking-recovery delta into the main cdc-chunking spec
(adds 4 requirements: orphan-recovery lock-liveness gating, distinct skip
counters, read-path dead-orphan servability gate, write-path orphan takeover;
modifies 3: stuck-records recovery, goroutine-error logging, ingestion byte
validation) and archive the completed change so the openspec-guard passes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@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)
openspec/changes/cdc-orphan-chunking-recovery/specs/cdc-chunking/spec.md (1)

109-109: 💤 Low value

Consider hyphenating "fail safe".

The compound adjective "fail safe" should be hyphenated as "fail-safe" when used before a noun.

📝 Suggested fix
-path). On a probe error, the row MUST be treated as live (fail safe: preserve the
+path). On a probe error, the row MUST be treated as live (fail-safe: preserve the
🤖 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/cdc-orphan-chunking-recovery/specs/cdc-chunking/spec.md` at
line 109, Replace the unhyphenated compound adjective "fail safe" with the
hyphenated form "fail-safe" in the sentence that reads "...On a probe error, the
row MUST be treated as live (fail safe: preserve the" so the phrase becomes
"(fail-safe: preserve the ...)" to use correct compound-adjective punctuation.
🤖 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 `@openspec/changes/cdc-orphan-chunking-recovery/design.md`:
- Around line 5-6: The heading-like text starting with "`#1317`" and other lines
beginning with "#" should be escaped so Markdown doesn't treat them as headings;
update occurrences of "`#1317`" and any lines that start with "#" (notably the
blocks at the current top and the block around lines 11-12) by prefixing them
with plain text such as "issue `#1317`" or "issue #..." to prevent MD018
violations and ensure the paragraphs render as normal text.

In `@pkg/cache/cache.go`:
- Around line 4221-4233: Currently servable is computed from
narFileServable(nr), which returns false when chunking_started_at is older than
cdcChunkingLockTTL so cdcChunkerLive is never consulted for long-running
chunkers; change the servable derivation to still mark the ambiguous case
(nr.TotalChunks == 0 && nr.ChunkingStartedAt != nil) as "potentially servable"
so the subsequent probe c.cdcChunkerLive(narURL.Hash) runs regardless of the
narFileServable TTL check — e.g. compute a baseServable := narFileServable(nr)
and then set servable := baseServable || (nr.TotalChunks == 0 &&
nr.ChunkingStartedAt != nil) so the existing conditional that calls
cdcChunkerLive and checks migrationLockKey(hash) will execute for long-running
chunkers.

---

Nitpick comments:
In `@openspec/changes/cdc-orphan-chunking-recovery/specs/cdc-chunking/spec.md`:
- Line 109: Replace the unhyphenated compound adjective "fail safe" with the
hyphenated form "fail-safe" in the sentence that reads "...On a probe error, the
row MUST be treated as live (fail safe: preserve the" so the phrase becomes
"(fail-safe: preserve the ...)" to use correct compound-adjective punctuation.
🪄 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: 359ebbe6-cdd0-402a-8c73-e3da5c17d223

📥 Commits

Reviewing files that changed from the base of the PR and between a93c02f and 83b3245.

📒 Files selected for processing (13)
  • openspec/changes/cdc-orphan-chunking-recovery/.openspec.yaml
  • openspec/changes/cdc-orphan-chunking-recovery/design.md
  • openspec/changes/cdc-orphan-chunking-recovery/proposal.md
  • openspec/changes/cdc-orphan-chunking-recovery/specs/cdc-chunking/spec.md
  • openspec/changes/cdc-orphan-chunking-recovery/tasks.md
  • pkg/cache/background_cdc_error_internal_test.go
  • pkg/cache/cache.go
  • pkg/cache/cache_prefetch_test.go
  • pkg/cache/cdc_chunker_takeover_internal_test.go
  • pkg/cache/export_test.go
  • pkg/cache/orphan_lazy_recovery_internal_test.go
  • pkg/cache/read_path_liveness_internal_test.go
  • pkg/cache/recovery_skip_counter_internal_test.go
✅ Files skipped from review due to trivial changes (2)
  • openspec/changes/cdc-orphan-chunking-recovery/.openspec.yaml
  • openspec/changes/cdc-orphan-chunking-recovery/tasks.md

Comment thread pkg/cache/cache.go Resolved
… in-progress rows

Addresses a PR review comment: isServable derived `servable` from narFileServable,
whose in-progress branch returns false once chunking_started_at is older than
cdcChunkingLockTTL. Because chunking_started_at is written once while the real
liveness signal is the refreshed migrationLockKey(hash), a healthy chunker running
longer than an hour was treated as dead before cdcChunkerLive could be consulted,
making peers fall back to a redundant re-download instead of piggybacking on the
live producer.

isServable now decides directly: total_chunks>0 -> servable; chunking_started_at
NULL -> not servable (placeholder); otherwise probe cdcChunkerLive regardless of
age. Removes the now-unused narFileServable helper.

Also escape leading kalbasit#1317/kalbasit#1230 issue refs in the archived design.md (MD018).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit dismissed their stale review June 7, 2026 03:10

all's good now

@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: 1

🤖 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 `@openspec/specs/cdc-chunking/spec.md`:
- Line 638: Change the compound adjective "fail safe" to "fail-safe" where it
appears in the sentence fragment "fail safe: preserve the" in the spec text so
the phrase reads "fail-safe: preserve the"; update the wording in the same
sentence in spec.md to use the hyphenated form.
🪄 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: 76905aa2-62eb-4741-834c-f87987718a23

📥 Commits

Reviewing files that changed from the base of the PR and between 83b3245 and 2c70461.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/.openspec.yaml
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/design.md
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/proposal.md
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/tasks.md
  • openspec/specs/cdc-chunking/spec.md
  • pkg/cache/cache.go
  • pkg/cache/read_path_liveness_internal_test.go
💤 Files with no reviewable changes (3)
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/proposal.md
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/.openspec.yaml
✅ Files skipped from review due to trivial changes (2)
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/design.md
  • openspec/changes/archive/2026-06-06-cdc-orphan-chunking-recovery/tasks.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/cache.go

Comment thread openspec/specs/cdc-chunking/spec.md Resolved
kalbasit added a commit to kalbasit/gh-actions that referenced this pull request Jun 7, 2026
The reusable build.yml "Validate registry inputs" step asserted that
`dockerhub_image` and `dockerhub_username` are both set or both empty,
unconditionally. On fork PRs the orchestrator forces `push_oci: false`
and the `dockerhub_username` variable is withheld (forks don't receive
repo variables) while `dockerhub_image` stays a literal, producing an
asymmetric pair (`image=true user=false`) that hard-failed the build leg
in ~8s — contradicting the existing "PR from a fork" spec scenario and
blocking consumer CI (e.g. kalbasit/ncps#1317).

Move the pairing check inside the existing `push_oci == true` guard,
alongside the at-least-one-registry check. When not pushing, an
asymmetric pair is harmless: every login/push/manifest step is already
gated on `push_oci`. Non-fork push behavior is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit to kalbasit/gh-actions that referenced this pull request Jun 7, 2026
## Summary

Fork PRs (and any run where the `dockerhub_username` repo variable is
not exposed) were failing the reusable `build.yml` workflow at its
**"Validate registry inputs"** step — even though the build is correctly
configured to skip pushing on forks. The symptom was the spurious, ~8s
failure:

```
::error::dockerhub_image and dockerhub_username must be set together (got image=true user=false)
```

This blocked consumer CI such as
[`kalbasit/ncps#1317`](kalbasit/ncps#1317).

## Root cause

Consumers pass `dockerhub_image` as a **literal** (e.g. `kalbasit/ncps`)
and `dockerhub_username` from a **repo variable** (`${{
vars.DOCKERHUB_USERNAME }}`). GitHub withholds that variable from fork
PRs, so the orchestrator forwards `dockerhub_image="kalbasit/ncps"` with
`dockerhub_username=""` → `image=true user=false`. The caller (`ci.yml`)
already forces `push_oci: false` for fork PRs, so nothing would push —
but the pairing check ran **unconditionally** and `exit 1`'d. This
directly contradicted the existing `oci-build` "PR from a fork"
scenario.

## Fix

Move the `dockerhub_image`/`dockerhub_username` pairing check **inside**
the existing `if [[ "$OCI_PUSH" == "true" ]]` block, alongside the "at
least one registry enabled" check.

- **`push_oci == false`** (fork PRs, non-pushing runs): validation is a
no-op. Every step that consumes the username/token (`Login to Docker
Hub`, `Push the OCI image`, the `oci-manifest` job) is already `if:
inputs.push_oci ...`, so a half-set pair can never reach an auth/push
step.
- **`push_oci == true`**: behavior is byte-for-byte identical to today —
a misconfigured consumer still fails fast with the same message.

No change to inputs, secrets, or non-fork push behavior.

## Verification

- `actionlint .github/workflows/build.yml` → clean (exit 0)
- Confirmed all login/push/manifest steps remain gated on
`inputs.push_oci`
- Post-merge: re-run CI on `kalbasit/ncps#1317`; the `shared / build
(x86_64-linux)` and `(aarch64-linux)` legs should go green.

## OpenSpec

Modifies the `oci-build` capability (tightens the "PR from a fork"
scenario to require registry-input validation not fail when pushing is
disabled). The change is archived in this PR so `openspec-guard` passes.

Co-authored-by: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit merged commit b5ea409 into kalbasit:main Jun 7, 2026
53 of 57 checks passed
@kalbasit

kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Thank you! @mvanhorn

kalbasit added a commit to bryandph/ncps that referenced this pull request Jun 7, 2026
* origin/main:
  fix(cdc): heal orphaned mid-chunking NAR state via migration-lock liveness (kalbasit#1317)
  chore(deps): update codecov/codecov-action action to v7 (kalbasit#1340)
  feat(fsck): reclaim CDC chunked-NAR residue (grace-period mark-then-purge) (kalbasit#1335)
  fix(ent): stop sqlite phantom narinfos/nar_files rebuild (kalbasit#1339)
  chore: update flake.lock and run go mod tidy (kalbasit#1338)
  fix(deps): update module github.com/mattn/go-sqlite3 to v1.14.45 (kalbasit#1336)
  fix(cache,fsck): self-completing CDC drain (de-chunk never strands NARs) (kalbasit#1334)
  fix(cache,fsck): reconcile narinfo<->nar_file links (drain-mode unblock + prevention) (kalbasit#1333)
  fix(cache): close the CDC url=none/xz-NAR desync (prevention + repair) (kalbasit#1332)
  fix(cache): durable-bytes marker for /upload reference presence (kalbasit#1330)
  fix(cache): non-destructive narinfo purge on root path (kalbasit#1326)

# Conflicts:
#	migrations/mysql/atlas.sum
#	migrations/postgres/atlas.sum
#	migrations/sqlite/atlas.sum
#	pkg/cache/cache.go
kalbasit added a commit that referenced this pull request Jun 8, 2026
## Summary

The `[Unreleased]` section was populated in #1309 but skewed toward the
recent CDC-drain, in-flight-staging, and Ent-migration work, omitting
several user-facing features and fixes that also landed since v0.9.4.
This backfills the missing notable changes, each cross-referenced by PR.

**Added**
- `ncps fsck` command + Helm fsck CronJob (#975, #996, #998, #999,
#1000, #1004, #1006, #1176)
- Closure pinning HTTP endpoints `POST`/`DELETE /pin/{hash}.narinfo`,
`GET /pins` (#1108)
- pprof server via `--pprof-addr` (#1063)
- CDC lazy chunking as a feature + `--cache-cdc-lazy-cleanup-schedule` +
recovery cron (#1082, #1083, #1089, #1096)
- Helm: auto `GOMEMLIMIT` (#1061), configurable temp volume /
`volumeClaimTemplate` (#1074, #1077), SQLite `Recreate` strategy (#1012)
- Startup storage reporting + deprecated-narinfo warning (#959, #961)
- `docker-dev` image (#1097)

**Fixed**
- `store/tmp` no longer wiped on startup (#1313)
- `nix-hash` NAR verification (#1101)
- Prometheus counters primed at startup (#1337, #1343)
- 404 on un-reassemblable chunked NARs (#1319), purged narinfo no longer
500 (#1318), fail-fast tmp validation (#1086)
- Further CDC/cache reliability fixes (#1317, #1346, #1341, #1342,
#1331, #1347)

**Changed**
- CDC config now persisted in the DB config table (#971)

Dependency bumps, CI/test-only changes, and the internal Ent-conversion
PRs are intentionally excluded; the existing Ent-migration entry already
covers that work.

## Test plan

- [x] `nix fmt` reports no changes (docs-only edit)
- [x] CHANGELOG section structure intact
(Added/Fixed/Changed/Removed/Migration/CI)
@mvanhorn

Copy link
Copy Markdown
Contributor Author

Much appreciated, @kalbasit. Healing orphaned mid-chunking NAR state via the migration lock closes that crash-window corruption.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CDC: async chunking can leave orphan state if server is killed mid-chunking

2 participants