Skip to content

feat(cache): polymorphic getNarFileFromDB on *ent.NarFileClient - #1206

Merged
kalbasit merged 2 commits into
mainfrom
feat-cache-getnarfilefromdb-polymorphic
May 23, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-cache-getnarfilefromdb-polymorphic

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

§11.4 continuation. getNarFileFromDB is the cache's central
"look up a nar_file by URL with compression-fallback" helper.
It was called from 10 sites — some passing c.db (non-tx),
others passing qtx (in-tx) — which previously prevented a
clean Ent conversion because the function shape was tied to
database.Querier.

The Ent codegen happens to make this conversion easier than
expected: c.dbClient.Ent().NarFile and tx.NarFile both
resolve to *ent.NarFileClient. One polymorphic parameter
unifies the two call shapes.

Signature change:

Before: getNarFileFromDB(ctx, q database.Querier, narURL)
(database.NarFile, error)
After: getNarFileFromDB(ctx, nfc *ent.NarFileClient, narURL)
(*ent.NarFile, error)

Behaviour preserved exactly: same try-first-then-fallback
compression sequence (CDC-on flips the order so "none" is
tried first), same ErrNotFound propagation (now
ent.NotFoundError instead of database.ErrNotFound).

Call-site updates (10 sites):

  • 8 non-tx callers swap c.db → c.dbClient.Ent().NarFile.
  • 2 in-tx callers (getNarFromStore, getNarFromChunks.init)
    swap c.withTransaction(..., qtx) → c.withEntTransaction(..., tx *ent.Tx) and use tx.NarFile. The qtx.TouchNarFile
    side-effects in both blocks become
    tx.NarFile.Update().Where(HashEQ, CompressionEQ, QueryEQ) .SetLastAccessedAt(now).SetUpdatedAt(now).Save(ctx).

Downstream row-shape adjustments:

  • nr.LastAccessedAt.Valid / .Time → nr != nil /
    *nr.LastAccessedAt (Ent uses *time.Time for nullable
    timestamps).
  • nr.ChunkingStartedAt.Valid / .Time → same.
  • nr.ID int64 → nr.ID int (Ent's PK type); the
    int64-typed receivers (CDC narFileID) cast at the
    boundary.
  • database.IsNotFoundError(err) → ent.IsNotFound(err) at
    every getNarFileFromDB error-check site (5 sites).

Test update:

  • TestCacheBackends/.../GetNarFileSize/nar_file_does_not_exist
    asserted on database.IsNotFoundError(err). Since
    GetNarFileSize now propagates *ent.NotFoundError, the
    assertion switches to ent.IsNotFound(err). No production
    behaviour change.

After this commit no c.getNarFileFromDB caller passes a
database.Querier, and no usage of the legacy
q.GetNarFileByHashAndCompressionAndQuery remains in pkg/cache.

go test -race ./pkg/cache/... passes against SQLite +
Postgres + MySQL + Redis. Lint clean.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@kalbasit

kalbasit commented May 21, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@kalbasit
kalbasit force-pushed the feat-cache-getnarfilefromdb-polymorphic branch from 8c8b943 to 38701b6 Compare May 22, 2026 23:02
@kalbasit
kalbasit force-pushed the feat-cache-cdc-narfile-ent branch from 1418f19 to 6b78673 Compare May 22, 2026 23:15
@kalbasit
kalbasit force-pushed the feat-cache-getnarfilefromdb-polymorphic branch from 38701b6 to 6435b8b Compare May 22, 2026 23:15
@kalbasit
kalbasit force-pushed the feat-cache-cdc-narfile-ent branch from 6b78673 to 8bd7bfe Compare May 22, 2026 23:28
@kalbasit
kalbasit force-pushed the feat-cache-getnarfilefromdb-polymorphic branch from 6435b8b to fbb297a Compare May 22, 2026 23:28
Base automatically changed from feat-cache-cdc-narfile-ent to main May 22, 2026 23:53
@kalbasit
kalbasit force-pushed the feat-cache-getnarfilefromdb-polymorphic branch from fbb297a to 76aea76 Compare May 22, 2026 23:53

@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 `@pkg/cache/cache.go`:
- Around line 6497-6518: The touch/update is filtering by narURL fields so it
can miss the actual row returned by getNarFileFromDB (which may be the fallback
compression=none row); change the update to touch the fetched record directly by
using the returned nr identifier (e.g., use nr.ID or nr.ID field in the
tx.NarFile.Update().Where(...) clause) instead of
entnarfile.HashEQ/CompressionEQ/QueryEQ narURL filters, and still
SetLastAccessedAt(time.Now()) and SetUpdatedAt(time.Now()) and Save(ctx) — this
ensures the exact row loaded (nr) is updated even when compression differs from
narURL.Compression.
🪄 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: 5c99c182-6028-42e4-87a3-e19ea22b50b8

📥 Commits

Reviewing files that changed from the base of the PR and between d530eae and 76aea76.

📒 Files selected for processing (2)
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go

Comment thread pkg/cache/cache.go Resolved
§11.4 continuation. `getNarFileFromDB` is the cache's central
"look up a nar_file by URL with compression-fallback" helper.
It was called from 10 sites — some passing `c.db` (non-tx),
others passing `qtx` (in-tx) — which previously prevented a
clean Ent conversion because the function shape was tied to
`database.Querier`.

The Ent codegen happens to make this conversion easier than
expected: `c.dbClient.Ent().NarFile` and `tx.NarFile` both
resolve to `*ent.NarFileClient`. One polymorphic parameter
unifies the two call shapes.

Signature change:

  Before: getNarFileFromDB(ctx, q database.Querier, narURL)
          (database.NarFile, error)
  After:  getNarFileFromDB(ctx, nfc *ent.NarFileClient, narURL)
          (*ent.NarFile, error)

Behaviour preserved exactly: same try-first-then-fallback
compression sequence (CDC-on flips the order so "none" is
tried first), same ErrNotFound propagation (now
`ent.NotFoundError` instead of `database.ErrNotFound`).

Call-site updates (10 sites):

- 8 non-tx callers swap `c.db` → `c.dbClient.Ent().NarFile`.
- 2 in-tx callers (`getNarFromStore`, `getNarFromChunks.init`)
  swap `c.withTransaction(..., qtx)` → `c.withEntTransaction(...,
  tx *ent.Tx)` and use `tx.NarFile`. The qtx.TouchNarFile
  side-effects in both blocks become
  `tx.NarFile.Update().Where(HashEQ, CompressionEQ, QueryEQ)
  .SetLastAccessedAt(now).SetUpdatedAt(now).Save(ctx)`.

Downstream row-shape adjustments:

- `nr.LastAccessedAt.Valid` / `.Time` → `nr != nil` /
  `*nr.LastAccessedAt` (Ent uses *time.Time for nullable
  timestamps).
- `nr.ChunkingStartedAt.Valid` / `.Time` → same.
- `nr.ID int64` → `nr.ID int` (Ent's PK type); the
  `int64`-typed receivers (CDC `narFileID`) cast at the
  boundary.
- `database.IsNotFoundError(err)` → `ent.IsNotFound(err)` at
  every `getNarFileFromDB` error-check site (5 sites).

Test update:

- `TestCacheBackends/.../GetNarFileSize/nar_file_does_not_exist`
  asserted on `database.IsNotFoundError(err)`. Since
  `GetNarFileSize` now propagates `*ent.NotFoundError`, the
  assertion switches to `ent.IsNotFound(err)`. No production
  behaviour change.

After this commit no `c.getNarFileFromDB` caller passes a
`database.Querier`, and no usage of the legacy
`q.GetNarFileByHashAndCompressionAndQuery` remains in pkg/cache.

`go test -race ./pkg/cache/...` passes against SQLite +
Postgres + MySQL + Redis. Lint clean.
@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.68%. Comparing base (982bee2) to head (5745cc9).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1206   +/-   ##
=====================================
  Coverage   5.68%   5.68%           
=====================================
  Files          6       6           
  Lines        387     387           
=====================================
  Hits          22      22           
  Misses       361     361           
  Partials       4       4           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

PutNarInfo holds narInfoLockKey while MigrateNarInfo holds
migrationLockKey — two different keys that don't synchronize
with each other. Both can race through the read-then-write
in upsertNarInfoFromParsed, each seeing "not found" and then
both attempting to insert the same hash, which produces a
duplicate-key constraint error and surfaces as a test failure
in GetNarInfoMultipleConcurrentPutsDuringMigration.

On a constraint error from the insert, re-fetch the row that
the concurrent writer already committed and return it so the
caller can continue linking references, signatures, and
nar_files against the real record.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-cache-getnarfilefromdb-polymorphic branch from 76aea76 to 5745cc9 Compare May 23, 2026 00:07

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

♻️ Duplicate comments (1)
pkg/cache/cache.go (1)

6511-6531: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Touch the fetched nar_file row directly.

getNarFileFromDB can return the fallback compression=none row here, but this update still filters on the originally requested narURL. In that case the touch is skipped and last_accessed_at stays stale for a NAR that was just served from chunks.

Suggested fix
-		if nr.LastAccessedAt == nil || time.Since(*nr.LastAccessedAt) > c.recordAgeIgnoreTouch {
-			if _, err := tx.NarFile.Update().
-				Where(
-					entnarfile.HashEQ(narURL.Hash),
-					entnarfile.CompressionEQ(narURL.Compression.String()),
-					entnarfile.QueryEQ(narURL.Query.Encode()),
-				).
-				SetLastAccessedAt(time.Now()).
-				SetUpdatedAt(time.Now()).
-				Save(ctx); err != nil {
+		if nr.LastAccessedAt == nil || time.Since(*nr.LastAccessedAt) > c.recordAgeIgnoreTouch {
+			now := time.Now()
+			if _, err := tx.NarFile.UpdateOneID(nr.ID).
+				SetLastAccessedAt(now).
+				SetUpdatedAt(now).
+				Save(ctx); err != nil {
 				return fmt.Errorf("error touching the nar record: %w", err)
 			}
 		}
🤖 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/cache.go` around lines 6511 - 6531, getNarFileFromDB may return a
fallback row (nr) that differs from the requested narURL, but the touch code
uses filters based on narURL (entnarfile.HashEQ/CompressionEQ/QueryEQ) so the
actual fetched row can be skipped; change the update in tx.NarFile.Update() to
target the fetched row directly (use the unique identifier from nr, e.g.
entnarfile.IDEQ(nr.ID) or equivalent) and keep SetLastAccessedAt/SetUpdatedAt so
the nr.LastAccessedAt is correctly updated when time.Since(*nr.LastAccessedAt) >
c.recordAgeIgnoreTouch.
🤖 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.

Duplicate comments:
In `@pkg/cache/cache.go`:
- Around line 6511-6531: getNarFileFromDB may return a fallback row (nr) that
differs from the requested narURL, but the touch code uses filters based on
narURL (entnarfile.HashEQ/CompressionEQ/QueryEQ) so the actual fetched row can
be skipped; change the update in tx.NarFile.Update() to target the fetched row
directly (use the unique identifier from nr, e.g. entnarfile.IDEQ(nr.ID) or
equivalent) and keep SetLastAccessedAt/SetUpdatedAt so the nr.LastAccessedAt is
correctly updated when time.Since(*nr.LastAccessedAt) > c.recordAgeIgnoreTouch.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6818827a-3c5b-49ab-a72b-4f639fd04b65

📥 Commits

Reviewing files that changed from the base of the PR and between 76aea76 and 5745cc9.

📒 Files selected for processing (2)
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go

@kalbasit
kalbasit enabled auto-merge (squash) May 23, 2026 00:12
@kalbasit
kalbasit merged commit 2460ac6 into main May 23, 2026
24 of 34 checks passed
@kalbasit
kalbasit deleted the feat-cache-getnarfilefromdb-polymorphic branch May 23, 2026 00:35
kalbasit added a commit that referenced this pull request May 24, 2026
Addresses PR #1206 thread PRRT_kwDONV6tZs6EQJXV:
Use UpdateOneID(nr.ID) to touch the nar_file row instead of
re-filtering by narURL fields. getNarFileFromDB may return a
compression=none fallback row whose key differs from narURL, so
the old Where(...HashEQ/CompressionEQ/QueryEQ...) filter could
silently miss it and leave last_accessed_at stale.

Addresses PR #1207 thread PRRT_kwDONV6tZs6ERJA1:
Treat link.Edges.Chunk == nil as corruption instead of silently
skipping the chunk. In streamCompleteChunks this produced a
count mismatch error anyway; in streamProgressiveChunks the
continue left chunkIndex behind, risking re-streaming or an
infinite loop on the same index. All three callsites now return
the errMissingChunkEdge sentinel wrapped with the link ID.

Addresses PR #1215 thread PRRT_kwDONV6tZs6ERsSu:
Add len(narURLsToRemove) == 0 to the early-return guard in the
LRU eviction loop. Previously, if only orphaned NarFile rows
were deleted (no narinfos and no chunks), parallelDeleteFromStores
was skipped and the backing blobs remained leaked in storage.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
kalbasit added a commit that referenced this pull request May 24, 2026
- runDialect returns (string, error); snapshots the migration directory
  before and after NamedDiff to detect the newly-created file and print
  its path to stdout — mirrors the sql-only path behavior.
- main() collects each file's 14-char timestamp prefix and warns when a
  second boundary falls between dialect runs so callers know to re-run.
- validateName: add "empty" to the placeholder reject list.
  Addresses PR #1215 thread PRRT_kwDONV6tZs6ERsSs.
- pkg/cache: log a warning when LRU candidate fetch hits the maxFetchRows
  cap so operators know eviction scanned only a partial window.
  Addresses PR #1206 LRU row-cap comment.
- openspec tasks.md §10/§11: update notes — database.Client threading
  was completed in §11, not deferred.
- openspec design.md: add language tag to decision-tree fence; fix
  grammar ("requires named CHECKs" → "requires CHECK constraints to
  be named").

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
kalbasit added a commit that referenced this pull request May 24, 2026
…1251)

## Summary

Consolidation branch addressing unresolved reviewer threads left open
across
merged PRs #1179–#1246. Each fix has its own atomic commit referencing
the
source PR and thread ID; all threads are resolved on GitHub after each
change.

### Bug fixes

- **cache:** touch `nar_file` by fetched row ID, not by narURL fields —
`getNarFileFromDB` can return a `compression=none` fallback whose key
differs
from `narURL`, causing stale `last_accessed_at` and LRU regressions
(#1206)
- **cache:** fail fast on `nil` eager-loaded chunk edges in
`streamCompleteChunks`
and `streamProgressiveChunks` instead of silently `continue`-ing, which
caused
  count mismatches or infinite re-streaming (#1207)
- **cache:** include `narURLsToRemove` in the LRU early-return guard so
orphaned
`NarFile` blobs are passed to `parallelDeleteFromStores` instead of
being
  silently leaked in storage (#1215)
- **cache:** log a warning when LRU candidate fetch hits the
`maxFetchRows` cap
  so operators know eviction scanned only a partial window (#1206)
- **cache/relink:** lower `relinkBatchSize` from 500 → 499 to stay under
SQLite's 999-placeholder limit (500 rows × 2 binds = 1000 > 999) (#1208)
- **database:** close `*sql.DB` in `Open()` when `NewClient` fails
(#1208)
- **migrate/adopt:** use `ErrUnknownState` (not `ErrUnknownDialect`) for
unrecognised `State` values — fixes false-positive `errors.Is` checks
(#1188)
- **generate-migrations:** `parseSkip` validates dialect names,
returning an error
on unknown values like `"myslq"` instead of silently skipping them
(#1187)
- **generate-migrations:** `--sql-only` path now calls `ensureAtlasSum`
after
  writing the stub so `atlas.sum` stays in sync (#1187)
- **generate-migrations:** `runDialect` now returns the generated file
path and
prints it to stdout; `main()` warns when a second boundary falls between
dialect runs so callers know to re-run for a consistent timestamp set
(#1215)
- **generate-migrations:** add `"empty"` to `validateName` reject list
(#1185)
- **nix/ent-lint-check:** add `set -o pipefail` so `ent-lint | tee`
propagates
  a non-zero exit through the pipeline (#1221)
- **e2e:** fix docstring path (`var/ncps/e2e-results/` →
`.e2e-results/`);
`mc mb` and `redis-cli flushall` now use `check=True` so reset failures
  abort the test immediately (#1233)
- **e2e:** `stop_ncps` now verifies the port closes within timeout;
`wait_ready`
  exits early if the child process dies before becoming ready (#1233)
- **run.py:** guard `dbmate` usage with a `shutil.which` check so a
missing
binary fails fast with a clear message instead of an obscure error
(#1234)
- **CI:** pin all external GitHub Action refs to immutable commit SHAs
to
  prevent supply-chain mutation (#1223)
- **CI:** remove `release-*` from pull_request/push triggers; add
`go.mod` and
  `go.sum` to the ent paths-filter (#1235)
- **docs:** replace distroless-incompatible `wget` healthcheck in Docker
Compose
  example with `garage status` (#1223)

### Test fixes

- Replace non-fatal `assert.Len` → `require.Len` before indexing
`stamps[0..2]`
  in `generate-migrations` tests (#1185)
- Add 60 s timeout to the one-time `go build` in the test setup (#1241)
- Fix `cache_prefetch_test.go` to look up `nar_file` by `(hash,
compression,
  query)` instead of hard-coded `id=1` (#1218)
- Apply `NarSize` fallback when `FileSize == 0` in
`testhelper/sqlite.go` to
avoid impossible `file_size=0` fixture rows for `compression=none`
narinfos (#1218)
- Increase `chunkingDelay` from 500 ms → 1 s in `cdc_test.go` to reduce
  flakiness on slow CI machines (#1217)
- Replace `Lock`-with-timeout with `TryLock` in
`cache_distributed_test.go` to
  avoid spurious failures when the lock-hold window is tight (#1217)

### Docs / skills

- Quote PostgreSQL DSNs in shell-command examples to prevent `?`-glob
expansion
  by shells (#1234)
- `migrate-new/SKILL.md`: ent-lint checks A1, A2, A4 — not all five
invariants
  as previously stated (#1225)
- `migrate-down/SKILL.md`: clarify that `DROP COLUMN` is
sensitive/forbidden DDL
per the migration spec and is only permissible as the terminal
expand-contract
step; add the missing "deploy code that always writes non-null" step to
the
  NOT NULL recipe (#1225)
- `openspec/changes/archive/2026-05-23-less-tests/`: fix stale paths,
add `bash`
fence tag, replace "branch coverage" with "statement/block coverage"
(#1245)
- `openspec/specs/test-suite-efficiency/spec.md`: same coverage
terminology
  fix (#1245)
-
`openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/design.md`:
  add language tag to decision-tree fence block; fix grammar (#1186)
-
`openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/tasks.md`:
update §10.1/§11.1 notes to reflect that `*database.Client` threading
was
  completed in §11, not deferred (#1191, #1192)

## Test plan

- [x] `nix flake check` (includes all unit + integration tests, lint,
ent-lint,
  atlas-sum, helm-unittest, schema-equivalence)
- [x] `go test -race ./...` locally with `eval
"$(enable-integration-tests)"`
- [x] Verify all referenced GitHub threads are marked resolved

🤖 Generated with [Claude Code](https://claude.ai/claude-code)

---------

Co-authored-by: Claude Sonnet 4.6 <[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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant