Skip to content

feat(cache): in-flight NAR staging foundation (flags, schema, state) - #1351

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-issue-1289
Jun 8, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-issue-1289

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

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]

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 7, 2026
@dosubot dosubot Bot added enhancement New feature or request go Pull requests that update go code labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • In-flight NAR staging: serve NARs while still downloading (HA-safe when using a distributed lock).
  • Configuration

    • New cache settings to enable staging, set retention grace period, and configure per-part object size.
  • Database

    • New persistent staging table to track cross-pod staging state (with indexes and constraints).
  • CLI

    • New serve flags to configure in-flight staging and validation errors for invalid retention/part-size.

Walkthrough

This PR introduces a new StagingState Ent entity with database schema, migrations, and generated ORM infrastructure to coordinate in-flight NAR staging across pods. It adds cache configuration and database helper methods, integrates staging state management into the cache layer, and wires the feature into the CLI serve command with feature flags and initialization logic.

Changes

In-Flight NAR Staging State Entity and Cache Coordination

Layer / File(s) Summary
Schema Definition, Configuration, and Migrations
ent/schema/staging_state.go, config.example.yaml, migrations/mysql/20260607182925_add_staging_state.sql, migrations/postgres/20260607182925_add_staging_state.sql, migrations/sqlite/20260607182925_add_staging_state.sql
StagingState Ent schema defines a hash-keyed table for cross-pod NAR staging coordination with fields for parts availability, compression, and workflow status; migrations add the table with indexes and constraints for all three supported databases.
Ent Generated ORM Infrastructure
ent/client.go, ent/tx.go, ent/stagingstate.go, ent/mutation.go, ent/hook/hook.go, ent/stagingstate_query.go, ent/stagingstate_create.go, ent/stagingstate_update.go, ent/stagingstate_delete.go, ent/stagingstate/stagingstate.go, ent/stagingstate/where.go, ent/ent.go, ent/migrate/schema.go, ent/runtime.go, ent/predicate/predicate.go
Complete Ent-generated ORM layer: Client wires StagingStateClient for create/query/update/delete operations, transactional clients initialize staging support, StagingStateMutation and predicate builders enable filtering and bulk operations, schema integration registers the table in migration and runtime systems, and hook adapters propagate lifecycle hooks across the staging entity.
Cache Staging Configuration and Helpers
pkg/cache/cache.go, pkg/cache/inflight_staging.go, pkg/cache/inflight_staging_internal_test.go
Cache stores in-flight NAR staging configuration (enabled flag, retention window, part size, distributed-locker status) with getter/setter API; database helpers provide idempotent markStagingRequested, atomic advanceStagingParts with status transition, fetch-with-nil-sentinel getStagingState, and resetStagingState rewind; integration tests verify enablement guard, idempotent row creation, and state advancement/reset lifecycle.
CLI Integration for In-Flight Staging
pkg/ncps/serve.go, pkg/ncps/lock_backend_internal_test.go
Serve command gains cache-inflight-staging-enabled, cache-inflight-staging-retention, and cache-inflight-staging-part-size flags; cache initialization detects distributed locker backend (Redis vs local), validates parameters when enabled, logs effective configuration, and calls SetInflightStaging.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • kalbasit/ncps#1200: The newly generated ent/stagingstate_create.go relies on Ent's OnConflict/upsert builders that PR #1200 enables.

Suggested labels

merge-stack

Poem

🐇 In hash we trust, a row to keep,
Parts march in while downloads sleep,
Ent creates the schema bright,
Cache and CLI set flags just right,
Rabbity cheers — staging takes flight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding the foundational infrastructure for in-flight NAR staging (flags, schema, state) to the cache system.
Description check ✅ Passed The description provides detailed context about the feature's purpose, motivation, implementation approach, and the specific changes made, all of which are directly related to the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 97.41% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

Comment thread pkg/cache/inflight_staging.go Resolved
@dosubot

dosubot Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Documentation Updates

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

Cache and Storage Configuration Flags
View Changes
@@ -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`) |

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

🧹 Nitpick comments (1)
pkg/cache/inflight_staging_internal_test.go (1)

78-103: ⚡ Quick win

Consider 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-existent staging_state row (lines 80-82 in inflight_staging.go handle this by returning errStagingStateMissing). 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

📥 Commits

Reviewing files that changed from the base of the PR and between 945e68b and c4ad41d.

⛔ Files ignored due to path filters (3)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/postgres/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (24)
  • config.example.yaml
  • ent/client.go
  • ent/ent.go
  • ent/hook/hook.go
  • ent/migrate/schema.go
  • ent/mutation.go
  • ent/predicate/predicate.go
  • ent/runtime.go
  • ent/schema/staging_state.go
  • ent/stagingstate.go
  • ent/stagingstate/stagingstate.go
  • ent/stagingstate/where.go
  • ent/stagingstate_create.go
  • ent/stagingstate_delete.go
  • ent/stagingstate_query.go
  • ent/stagingstate_update.go
  • ent/tx.go
  • migrations/mysql/20260607182925_add_staging_state.sql
  • migrations/postgres/20260607182925_add_staging_state.sql
  • migrations/sqlite/20260607182925_add_staging_state.sql
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_internal_test.go
  • pkg/ncps/serve.go

Comment thread ent/stagingstate_create.go Resolved
Comment thread ent/stagingstate_delete.go Resolved
Comment thread ent/stagingstate_update.go Resolved
Comment thread ent/stagingstate.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/ncps/serve.go Resolved
Comment thread pkg/ncps/serve.go Resolved
kalbasit and others added 2 commits June 7, 2026 17:11
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-issue-1289 branch from c4ad41d to 86502af Compare June 8, 2026 00:11
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
Comment thread pkg/ncps/lock_backend_internal_test.go Dismissed
@kalbasit
kalbasit enabled auto-merge (squash) June 8, 2026 00:12

@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

🧹 Nitpick comments (1)
pkg/cache/inflight_staging.go (1)

87-105: ⚡ Quick win

Consider checking whether a row was actually reset.

advanceStagingParts returns errStagingStateMissing when n == 0, but resetStagingState silently 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

📥 Commits

Reviewing files that changed from the base of the PR and between c4ad41d and 86502af.

⛔ Files ignored due to path filters (3)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/postgres/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (25)
  • config.example.yaml
  • ent/client.go
  • ent/ent.go
  • ent/hook/hook.go
  • ent/migrate/schema.go
  • ent/mutation.go
  • ent/predicate/predicate.go
  • ent/runtime.go
  • ent/schema/staging_state.go
  • ent/stagingstate.go
  • ent/stagingstate/stagingstate.go
  • ent/stagingstate/where.go
  • ent/stagingstate_create.go
  • ent/stagingstate_delete.go
  • ent/stagingstate_query.go
  • ent/stagingstate_update.go
  • ent/tx.go
  • migrations/mysql/20260607182925_add_staging_state.sql
  • migrations/postgres/20260607182925_add_staging_state.sql
  • migrations/sqlite/20260607182925_add_staging_state.sql
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_internal_test.go
  • pkg/ncps/lock_backend_internal_test.go
  • pkg/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

Comment thread ent/stagingstate_query.go Resolved
@kalbasit
kalbasit merged commit 541a25c into main Jun 8, 2026
39 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-issue-1289 branch June 8, 2026 00:19
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants