Repository navigation
feat(cache): in-flight NAR staging foundation (flags, schema, state) - #1351
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR introduces a new ChangesIn-Flight NAR Staging State Entity and Cache Coordination
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces in-flight NAR staging to allow serving NARs cross-pod while they are still downloading. It adds a new StagingState schema in ent along with database migrations for MySQL, PostgreSQL, and SQLite, and integrates configuration flags and helper methods into the cache package. The review feedback highlights a critical issue in resetStagingState where deleting the staging state row during a takeover reset clears the requested signal and can leave cross-pod waiters stranded. The reviewer recommends resetting the progress and status back to requested instead of deleting the row, and updating the corresponding unit tests to reflect this change.
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@@ -145,6 +145,57 @@
## Mutual Exclusivity
Local and S3 storage options are mutually exclusive. You must configure either `--cache-storage-local` or `--cache-storage-s3-bucket`, but not both. Attempting to set both will result in a configuration error [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/cmd/serve.go#L38-L412).
+
+## In-Flight NAR Staging
+In-flight NAR staging serves a NAR cross-pod while it is still downloading by staging it to shared storage as part-objects once another replica waits for it. This is an HA-safe alternative to CDC that preserves lazy chunking's CPU savings by avoiding content-defined hashing. Staging is only active when both the feature is enabled and a distributed (Redis) lock is configured, since single-instance deployments cannot have cross-pod waiters.
+
+### Configuration Flags
+
+#### `--cache-inflight-staging-enabled`
+**Type:** boolean
+**Default:** `false`
+**YAML key:** `cache.inflight-staging.enabled`
+**Environment variable:** `CACHE_INFLIGHT_STAGING_ENABLED`
+
+Enable in-flight staging to serve a NAR cross-pod while it is still downloading by staging it to shared storage as part-objects once another replica waits for it. An HA-safe alternative to CDC. Only active with a distributed (Redis) lock.
+
+#### `--cache-inflight-staging-retention`
+**Type:** duration
+**Default:** `5m`
+**YAML key:** `cache.inflight-staging.retention`
+**Environment variable:** `CACHE_INFLIGHT_STAGING_RETENTION`
+
+Grace period to retain staging part-objects after the NAR's final representation is committed, so in-flight readers can drain first. Must be greater than 0 when in-flight staging is enabled.
+
+#### `--cache-inflight-staging-part-size`
+**Type:** integer (bytes)
+**Default:** `8388608` (8 MiB)
+**YAML key:** `cache.inflight-staging.part-size`
+**Environment variable:** `CACHE_INFLIGHT_STAGING_PART_SIZE`
+
+Size in bytes of each staging part-object, a transport unit distinct from CDC chunk sizes. Must be greater than 0 when in-flight staging is enabled.
+
+### CLI Example
+```bash
+ncps serve \
+ --cache-inflight-staging-enabled \
+ --cache-inflight-staging-retention 10m \
+ --cache-inflight-staging-part-size 16777216
+```
+
+### YAML Example
+```yaml
+cache:
+ inflight-staging:
+ enabled: true
+ retention: 10m
+ part-size: 16777216
+```
+
+### Requirements
+
+- In-flight staging is only active when both the `enabled` flag is true AND the lock backend is Redis (distributed lock).
+- When enabled, both `retention` and `part-size` must be positive values; the server will fail to start if these validation checks fail.
## CDC (Content-Defined Chunking) Configuration Immutability
@@ -543,6 +594,9 @@
| S3 secret key | `--cache-storage-s3-secret-access-key`| `cache.storage.s3.secret-access-key` | N/A | Yes** |
| S3 force path style | `--cache-storage-s3-force-path-style` | `cache.storage.s3.force-path-style` | N/A | No |
| LRU schedule timezone | `--cache-lru-schedule-timezone` | `cache.lru.schedule.timezone` | N/A | No |
+| In-flight staging enabled | `--cache-inflight-staging-enabled` | `cache.inflight-staging.enabled` | N/A | No (default: `false`) |
+| In-flight staging retention | `--cache-inflight-staging-retention` | `cache.inflight-staging.retention` | N/A | No (default: `5m`) |
+| In-flight staging part size | `--cache-inflight-staging-part-size` | `cache.inflight-staging.part-size` | N/A | No (default: `8388608`) |
| CDC lazy recovery schedule | `--cache-cdc-lazy-recovery-schedule` | `cache.cdc.lazy-recovery-schedule` | `config.cdc.lazyRecoverySchedule` | No (default: `@every 5m`) |
| CDC lazy recovery batch size | `--cache-cdc-lazy-recovery-batch-size` | `cache.cdc.lazy-recovery-batch-size` | `config.cdc.lazyRecoveryBatchSize` | No (default: `100`) |
| CDC lazy cleanup schedule | `--cache-cdc-lazy-cleanup-schedule` | `cache.cdc.lazy-cleanup-schedule` | `config.cdc.lazyCleanupSchedule` | No (default: `@every 1h`) | |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (1)
pkg/cache/inflight_staging_internal_test.go (1)
78-103: ⚡ Quick winConsider adding a test for the missing-row error path.
The test verifies the happy path for
advanceStagingParts, but doesn't cover the case where it's called on a non-existentstaging_staterow (lines 80-82 ininflight_staging.gohandle this by returningerrStagingStateMissing). Testing this edge case would prevent regressions if the error-handling logic changes.🧪 Proposed test addition
Add a test case after line 103:
func TestStagingState_AdvancePartsMissingRow(t *testing.T) { t.Parallel() c, _, _, _, _, cleanup := setupSQLiteFactory(t) t.Cleanup(cleanup) ctx := context.Background() const hash = "1234567890abcdef1234567890abcdef" // Advance parts without marking requested first err := c.advanceStagingParts(ctx, hash, 1, nar.CompressionTypeXz.String()) require.Error(t, err) assert.ErrorIs(t, err, errStagingStateMissing, "advancing parts on a missing row must return errStagingStateMissing") }🤖 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/inflight_staging_internal_test.go` around lines 78 - 103, Add a test that exercises the missing-row error path for advanceStagingParts: create a test (e.g., TestStagingState_AdvancePartsMissingRow) that uses setupSQLiteFactory and a new hash but does NOT call markStagingRequested, then call c.advanceStagingParts(ctx, hash, 1, nar.CompressionTypeXz.String()) and assert it returns an error and specifically assert.ErrorIs(err, errStagingStateMissing) to ensure the missing-row branch in advanceStagingParts is covered.
🤖 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 `@ent/stagingstate_create.go`:
- Around line 126-133: Replace panic-based helper signatures so they return
errors instead of panicking: change StagingStateCreate.SaveX (and the other X
helpers referenced: ExecX, IDX variants) to return (*StagingState, error) (or
(int, error) for Exec/ID variants) and propagate the underlying error from
_c.Save/_c.Exec/_c.ID instead of calling panic(err); update all internal returns
to return the value and nil error on success and return nil (or zero) plus err
on failure, and update any call sites to handle the returned error accordingly.
In `@ent/stagingstate_delete.go`:
- Around line 33-39: The generated ExecX helpers (e.g.,
StagingStateDelete.ExecX) currently call panic(err) which violates the repo rule
banning panic outside main; remove or change these helpers in the generator so
generated code does not call panic: either stop emitting ExecX methods entirely
(force callers to use Exec(ctx) which returns (int, error)), or change the
generated ExecX implementation to not panic (for example, call a non-panicking
error handler or log the error and return zero) and ensure any “must” behavior
is only provided from code in cmd/*/main.go; update the generator location that
produces StagingStateDelete.ExecX (and the other similar ExecX methods)
accordingly.
In `@ent/stagingstate_update.go`:
- Around line 145-151: The generated helpers like StagingStateUpdate.SaveX (and
similar ExecX/SaveX methods referenced at lines ~160, 361-368, 377-381)
currently call panic(err); change their APIs to return errors instead of
panicking: update SaveX to return (int, error) and any ExecX counterparts to
return their result plus error, replace panic(err) with returning the error from
the underlying Save/Exec call, and propagate callers to handle the error; ensure
signatures and all call sites are updated to compile and follow the repo rule
“Do not use panic outside of main.”
In `@ent/stagingstate.go`:
- Around line 136-139: The Unwrap method in StagingState currently panics when
the entity is not transactional; replace the panic-based flow with an
error-returning flow: change Unwrap (method on StagingState) to return
(/*existing return type*/, error) instead of panicking when _m.config.driver is
not a *txDriver (the code using _tx, ok := _m.config.driver.(*txDriver)); return
a descriptive error like fmt.Errorf("ent: StagingState is not a transactional
entity") and update all callers of StagingState.Unwrap to handle the returned
error accordingly so generated code no longer uses panic outside main
(alternatively, if you prefer not to modify generated files, exclude
Ent-generated files from the lint rule at generation/template level).
In `@pkg/cache/cache.go`:
- Around line 821-833: In SetInflightStaging, validate inputs before persisting:
when enabled is true, ensure partSize > 0 and retention >= 0; if those checks
fail, do not flip inflightStagingFlag to true (leave existing state) and return
early (while still holding c.cdcMu) or alternatively coerce to safe defaults;
only assign c.inflightStagingFlag, c.inflightStagingRetention,
c.inflightStagingPartSize and c.lockerIsDistributed after validation; include a
log call (via the cache's logger) when rejecting invalid values so callers can
see why staging wasn’t enabled.
In `@pkg/ncps/serve.go`:
- Around line 424-446: Add a table-driven unit test for
determineEffectiveLockBackend that pins the staging/lock matrix driven by the
CLI flags: "cache-inflight-staging-enabled" (off vs on), with on+local lock,
on+explicit Redis lock, and on+legacy fallback via "cache-redis-addrs"; for each
case set up flag values and any legacy env/flag inputs used by
determineEffectiveLockBackend and assert the exact lock backend/type and any
relevant config (e.g., Redis addresses) returned. Place the test alongside
pkg/ncps tests, follow TDD (write test first), and exercise the flag parsing
path that reads cache-inflight-staging flags so regressions in
determineEffectiveLockBackend are caught.
- Around line 1207-1227: When inflight staging is enabled (check
inflightStagingEnabled from cmd.Bool("cache-inflight-staging-enabled")),
validate that cmd.Duration("cache-inflight-staging-retention") > 0 and
cmd.Int("cache-inflight-staging-part-size") > 0 before calling
c.SetInflightStaging; if either is non-positive, fail fast (return an error or
exit with a clear message via zerolog) referencing the staging settings. Keep
the existing determination of stagingDistributed via
determineEffectiveLockBackend and lockBackendRedis, but short-circuit boot with
an explicit validation error when retention or partSize are invalid so invalid
values are not propagated to c.SetInflightStaging.
---
Nitpick comments:
In `@pkg/cache/inflight_staging_internal_test.go`:
- Around line 78-103: Add a test that exercises the missing-row error path for
advanceStagingParts: create a test (e.g.,
TestStagingState_AdvancePartsMissingRow) that uses setupSQLiteFactory and a new
hash but does NOT call markStagingRequested, then call
c.advanceStagingParts(ctx, hash, 1, nar.CompressionTypeXz.String()) and assert
it returns an error and specifically assert.ErrorIs(err, errStagingStateMissing)
to ensure the missing-row branch in advanceStagingParts is covered.
🪄 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: 2e047364-624c-4931-9b63-3c4212ab1d63
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (24)
config.example.yamlent/client.goent/ent.goent/hook/hook.goent/migrate/schema.goent/mutation.goent/predicate/predicate.goent/runtime.goent/schema/staging_state.goent/stagingstate.goent/stagingstate/stagingstate.goent/stagingstate/where.goent/stagingstate_create.goent/stagingstate_delete.goent/stagingstate_query.goent/stagingstate_update.goent/tx.gomigrations/mysql/20260607182925_add_staging_state.sqlmigrations/postgres/20260607182925_add_staging_state.sqlmigrations/sqlite/20260607182925_add_staging_state.sqlpkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_internal_test.gopkg/ncps/serve.go
Lay the groundwork for serving a NAR cross-pod while it is still downloading (GitHub #660, #1289), without forcing CDC. This commit adds only the inert foundation; the download/serve wiring follows in later commits and stays dormant until the feature is enabled. Why: on the S3 backend a replica cannot read another replica's in-progress download, so a second request waits past client timeouts. The fix is to stage the in-flight NAR to shared storage as part-objects once a cross-pod waiter appears. This is an HA-safe alternative to CDC that preserves lazy chunking's CPU savings (no content-defined hashing). How: - Flags --cache-inflight-staging-{enabled,retention,part-size} (default off / 5m / 8 MiB) wired into Cache via SetInflightStaging. The InflightStagingEnabled() guard is true only when the flag is set AND the locker is distributed, so single-instance deployments pay nothing. - New staging_states table (Ent + per-dialect migrations): one row per NAR hash carrying the request marker, parts_available, compression and status. Keyed by hash alone so it is writable during the download window before any nar_file row exists. - Data-access helpers (mark-requested, get, advance-parts, reset) with an idempotent ON CONFLICT DO NOTHING request marker. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1351: - resetStagingState now rewinds the staging_state row to (parts_available=0, status=requested) instead of deleting it, so a cross-pod waiter that recorded its request before its poll loop is not stranded when a takeover holder re-stages (thread PRRT_kwDONV6tZs6Hr3H1, PRRT_kwDONV6tZs6Hr3H3). Aligns with the spec's "re-stage if contention persists" (D5). - SetInflightStaging defensively clamps a negative retention to 0 and a non-positive part size to the 8 MiB default so an out-of-band caller cannot install nonsensical runtime state (PRRT_kwDONV6tZs6Hr4Ui). - createCache fails fast when staging is enabled with a non-positive retention or part size, via static sentinel errors (PRRT_kwDONV6tZs6Hr4Ul). - Add a table-driven test for determineEffectiveLockBackend pinning the lock-backend / staging-distributed matrix, including the legacy cache-redis-addrs fallback (PRRT_kwDONV6tZs6Hr4Uk). Co-Authored-By: Claude Opus 4.8 <[email protected]>
c4ad41d to
86502af
Compare
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/cache/inflight_staging.go (1)
87-105: ⚡ Quick winConsider checking whether a row was actually reset.
advanceStagingPartsreturnserrStagingStateMissingwhenn == 0, butresetStagingStatesilently succeeds even if no row exists for the hash. This asymmetry could mask bugs where reset is called on a non-existent staging record.Proposed consistency fix
func (c *Cache) resetStagingState(ctx context.Context, hash string) error { - _, err := c.dbClient.Ent().StagingState.Update(). + n, err := c.dbClient.Ent().StagingState.Update(). Where(stagingstate.HashEQ(hash)). SetPartsAvailable(0). SetStatus(stagingStatusRequested). Save(ctx) if err != nil { return fmt.Errorf("reset staging state for %q: %w", hash, err) } + + if n == 0 { + return fmt.Errorf("reset staging state for %q: %w", hash, errStagingStateMissing) + } return nil }🤖 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/inflight_staging.go` around lines 87 - 105, resetStagingState currently always returns success even if no staging_state row exists, causing asymmetry with advanceStagingParts which returns errStagingStateMissing when n==0; change resetStagingState (in pkg/cache/inflight_staging.go) to execute the update with an Exec/RowsAffected-style call (use c.dbClient.Ent().StagingState.Update().Where(stagingstate.HashEQ(hash)).SetPartsAvailable(0).SetStatus(stagingStatusRequested).Exec(ctx) or the Ent equivalent that exposes affected rows), check the number of rows affected and if zero return errStagingStateMissing, otherwise return nil. Ensure you reference resetStagingState, stagingstate.HashEQ, stagingStatusRequested and errStagingStateMissing in the change.
🤖 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 `@ent/stagingstate_query.go`:
- Around line 74-81: The generated X helpers (e.g., StagingStateQuery.FirstX,
OnlyX, AllX and the other X variants) must not call panic(err) directly; update
the ent codegen template to replace direct panic(err) with a call to a small
helper (e.g., must(err)) and implement that helper in a separate file with two
build-tag variants: a main-only file (build tag for cmd/*/main.go or main.go)
that panics on non-nil error, and a default non-main implementation that
returns/Logs the error or handles it safely without panicking; change the
template to call must(err) after invoking First/Only/All so regeneration uses
the safe behavior.
---
Nitpick comments:
In `@pkg/cache/inflight_staging.go`:
- Around line 87-105: resetStagingState currently always returns success even if
no staging_state row exists, causing asymmetry with advanceStagingParts which
returns errStagingStateMissing when n==0; change resetStagingState (in
pkg/cache/inflight_staging.go) to execute the update with an
Exec/RowsAffected-style call (use
c.dbClient.Ent().StagingState.Update().Where(stagingstate.HashEQ(hash)).SetPartsAvailable(0).SetStatus(stagingStatusRequested).Exec(ctx)
or the Ent equivalent that exposes affected rows), check the number of rows
affected and if zero return errStagingStateMissing, otherwise return nil. Ensure
you reference resetStagingState, stagingstate.HashEQ, stagingStatusRequested and
errStagingStateMissing in the change.
🪄 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: f8200829-f2d9-424b-ade2-7c3c138acee6
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (25)
config.example.yamlent/client.goent/ent.goent/hook/hook.goent/migrate/schema.goent/mutation.goent/predicate/predicate.goent/runtime.goent/schema/staging_state.goent/stagingstate.goent/stagingstate/stagingstate.goent/stagingstate/where.goent/stagingstate_create.goent/stagingstate_delete.goent/stagingstate_query.goent/stagingstate_update.goent/tx.gomigrations/mysql/20260607182925_add_staging_state.sqlmigrations/postgres/20260607182925_add_staging_state.sqlmigrations/sqlite/20260607182925_add_staging_state.sqlpkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_internal_test.gopkg/ncps/lock_backend_internal_test.gopkg/ncps/serve.go
✅ Files skipped from review due to trivial changes (6)
- ent/ent.go
- migrations/sqlite/20260607182925_add_staging_state.sql
- config.example.yaml
- ent/migrate/schema.go
- ent/mutation.go
- ent/client.go
🚧 Files skipped from review as they are similar to previous changes (7)
- ent/hook/hook.go
- ent/predicate/predicate.go
- migrations/postgres/20260607182925_add_staging_state.sql
- migrations/mysql/20260607182925_add_staging_state.sql
- pkg/ncps/serve.go
- ent/runtime.go
- pkg/cache/cache.go
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Lay the groundwork for serving a NAR cross-pod while it is still
downloading (GitHub #660, #1289), without forcing CDC. This commit adds
only the inert foundation; the download/serve wiring follows in later
commits and stays dormant until the feature is enabled.
Why: on the S3 backend a replica cannot read another replica's in-progress
download, so a second request waits past client timeouts. The fix is to
stage the in-flight NAR to shared storage as part-objects once a cross-pod
waiter appears. This is an HA-safe alternative to CDC that preserves lazy
chunking's CPU savings (no content-defined hashing).
How:
off / 5m / 8 MiB) wired into Cache via SetInflightStaging. The
InflightStagingEnabled() guard is true only when the flag is set AND the
locker is distributed, so single-instance deployments pay nothing.
hash carrying the request marker, parts_available, compression and
status. Keyed by hash alone so it is writable during the download window
before any nar_file row exists.
idempotent ON CONFLICT DO NOTHING request marker.
Co-Authored-By: Claude Opus 4.8 [email protected]