Skip to content

feat(cache): convert MigrateNarInfo + storeNarInfoInDatabase to Ent - #1203

Merged
kalbasit merged 2 commits into
mainfrom
feat-cache-migrate-narinfo-ent
May 22, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-cache-migrate-narinfo-ent

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

feat(cache): convert MigrateNarInfo + storeNarInfoInDatabase to Ent

§11.3 completion of the PutNarInfo write paths. The Cache-free
storeNarInfoInDatabase (used by MigrateNarInfo from the
background-migration goroutine and the CLI migrate-narinfo
command) is collapsed into the same Ent-fluent pipeline that
Cache.storeInDatabase adopted in the previous commit, reusing
upsertNarInfoFromParsed, addNarInfoReferences,
addNarInfoSignatures, and createOrUpdateNarFileEnt.

Key changes:

  • MigrateNarInfo gains a dbClient *database.Client parameter
    alongside its existing db database.Querier. The Querier
    stays for the pre-lock double-check
    (db.GetNarInfoByHash(ctx, hash) looking for already-migrated
    rows) until §11.6 retires that surface entirely. Callers
    updated: (*Cache).MigrateNarInfoToDatabase already had the
    field; pkg/ncps/migrate_narinfo.go's
    migrateNarInfoCommand extracts the Client out of
    createDatabaseQuerier's second return value and passes it
    along.
  • storeNarInfoInDatabase's body is replaced wholesale with a
    dbClient.WithTransaction(...) block that runs the same Ent
    helpers as Cache.storeInDatabase. Same conflict-resolution
    primitives (OnConflictColumns + Ignore for references,
    signatures, and the narinfo<->nar_file link), same conditional
    read-then-update UPSERT for the narinfo row, same atomic
    Create+SetLastAccessedAt for nar_files.
  • The legacy createOrUpdateNarFile(qtx) helper is now
    fully unused — both production call sites (the old
    storeInDatabase and storeNarInfoInDatabase) migrated to
    createOrUpdateNarFileEnt(tx). Deleted.

Test infrastructure

testBackgroundMigrateNarInfoThunderingHerd counts the number
of NarInfo create operations to detect "more than one
migration goroutine acquired the lock". The legacy spy
embedded database.Querier and counted CreateNarInfo calls;
since the migration path now flows through dbClient (Ent),
the spy never saw the conversion. The test now installs an
Ent mutation hook via
dbClient.Ent().NarInfo.Use(func(next ent.Mutator) ent.Mutator { … if m.Op() == ent.OpCreate { spy.createNarInfoCalls++ } … })
and keeps the spy struct purely for the
GetNarInfoByHash count (which still goes through Querier
during the pre-lock double-check).

After this commit no Querier-style CreateNarInfo /
AddNarInfoReference / AddNarInfoSignature /
LinkNarInfoToNarFile / DeleteNarInfoByHash call site remains
in pkg/cache. The §11.3 PutNarInfo* conversion is complete.

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

docs(openspec): mark §11.3 tasks complete

§11.3 (Convert PutNarInfo* paths) finished across feat-cache-
delete-narinfo-ent, feat-cache-storeindatabase-ent, and feat-
cache-migrate-narinfo-ent. No qtx-style CreateNarInfo /
DeleteNarInfoBy* / AddNarInfoReferences / AddNarInfoSignatures /
LinkNarInfoToNarFile call site remains in pkg/cache.

Stack tip is feat-cache-migrate-narinfo-ent.

@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-storeindatabase-ent branch from e90b426 to 39f2fd6 Compare May 22, 2026 21:41
@kalbasit
kalbasit force-pushed the feat-cache-migrate-narinfo-ent branch from 2680ac4 to 05e3683 Compare May 22, 2026 21:41
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 39f2fd6 to 304598b Compare May 22, 2026 21:53
@kalbasit
kalbasit force-pushed the feat-cache-migrate-narinfo-ent branch from 05e3683 to 97bcb10 Compare May 22, 2026 21:53
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
Base automatically changed from feat-cache-storeindatabase-ent to main May 22, 2026 23:02
@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 May 22, 2026
kalbasit added 2 commits May 22, 2026 23:02
§11.3 completion of the PutNarInfo write paths. The Cache-free
`storeNarInfoInDatabase` (used by `MigrateNarInfo` from the
background-migration goroutine and the CLI migrate-narinfo
command) is collapsed into the same Ent-fluent pipeline that
`Cache.storeInDatabase` adopted in the previous commit, reusing
`upsertNarInfoFromParsed`, `addNarInfoReferences`,
`addNarInfoSignatures`, and `createOrUpdateNarFileEnt`.

Key changes:

- `MigrateNarInfo` gains a `dbClient *database.Client` parameter
  alongside its existing `db database.Querier`. The Querier
  stays for the pre-lock double-check
  (`db.GetNarInfoByHash(ctx, hash)` looking for already-migrated
  rows) until §11.6 retires that surface entirely. Callers
  updated: `(*Cache).MigrateNarInfoToDatabase` already had the
  field; `pkg/ncps/migrate_narinfo.go`'s
  `migrateNarInfoCommand` extracts the Client out of
  `createDatabaseQuerier`'s second return value and passes it
  along.
- `storeNarInfoInDatabase`'s body is replaced wholesale with a
  `dbClient.WithTransaction(...)` block that runs the same Ent
  helpers as `Cache.storeInDatabase`. Same conflict-resolution
  primitives (OnConflictColumns + Ignore for references,
  signatures, and the narinfo<->nar_file link), same conditional
  read-then-update UPSERT for the narinfo row, same atomic
  Create+SetLastAccessedAt for nar_files.
- The legacy `createOrUpdateNarFile(qtx)` helper is now
  fully unused — both production call sites (the old
  storeInDatabase and storeNarInfoInDatabase) migrated to
  `createOrUpdateNarFileEnt(tx)`. Deleted.

Test infrastructure
-------------------

`testBackgroundMigrateNarInfoThunderingHerd` counts the number
of NarInfo create operations to detect "more than one
migration goroutine acquired the lock". The legacy spy
embedded `database.Querier` and counted `CreateNarInfo` calls;
since the migration path now flows through `dbClient` (Ent),
the spy never saw the conversion. The test now installs an
Ent mutation hook via
`dbClient.Ent().NarInfo.Use(func(next ent.Mutator) ent.Mutator
{ … if m.Op() == ent.OpCreate { spy.createNarInfoCalls++ } … })`
and keeps the spy struct purely for the
GetNarInfoByHash count (which still goes through Querier
during the pre-lock double-check).

After this commit no Querier-style CreateNarInfo /
AddNarInfoReference / AddNarInfoSignature /
LinkNarInfoToNarFile / DeleteNarInfoByHash call site remains
in pkg/cache. The §11.3 PutNarInfo* conversion is complete.

`go test -race ./pkg/cache/... ./pkg/ncps/...` passes against
SQLite + Postgres + MySQL + Redis. Lint clean.
§11.3 (Convert PutNarInfo* paths) finished across feat-cache-
delete-narinfo-ent, feat-cache-storeindatabase-ent, and feat-
cache-migrate-narinfo-ent. No qtx-style CreateNarInfo /
DeleteNarInfoBy* / AddNarInfoReferences / AddNarInfoSignatures /
LinkNarInfoToNarFile call site remains in pkg/cache.

Stack tip is feat-cache-migrate-narinfo-ent.
@kalbasit
kalbasit force-pushed the feat-cache-migrate-narinfo-ent branch from 97bcb10 to d884322 Compare May 22, 2026 23:02
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 22, 2026
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
@kalbasit
kalbasit enabled auto-merge (squash) May 22, 2026 23:03

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

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

4787-4828: 💤 Low value

Consider adding deadlock retry consistency with Cache.storeInDatabase.

The Cache.storeInDatabase method (line 4139) uses c.withEntTransaction which includes a 5-attempt deadlock retry loop. This new storeNarInfoInDatabase calls dbClient.WithTransaction directly, bypassing the retry logic.

In practice, the distributed migration lock acquired at line 4675 prevents concurrent migrations of the same hash, which significantly reduces contention. However, for consistency with the rest of the codebase and resilience against transient database lock contention from unrelated operations, you may want to add similar retry semantics.

If the current approach is intentional (relying on the migration lock for protection), consider adding a brief comment explaining why retry isn't needed here.

🤖 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 4787 - 4828, storeNarInfoInDatabase calls
dbClient.WithTransaction directly and bypasses the 5-attempt deadlock retry used
by Cache.storeInDatabase via c.withEntTransaction; change storeNarInfoInDatabase
to use the same retry semantics (either call c.withEntTransaction wrapping the
body or add a 5-attempt retry loop with small backoff around
dbClient.WithTransaction) so transient deadlock errors are retried, referencing
the existing retry logic in Cache.storeInDatabase/c.withEntTransaction; if the
omission is intentional, add a short comment in storeNarInfoInDatabase
explaining why the migration lock makes retries unnecessary.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pkg/cache/cache.go`:
- Around line 4787-4828: storeNarInfoInDatabase calls dbClient.WithTransaction
directly and bypasses the 5-attempt deadlock retry used by Cache.storeInDatabase
via c.withEntTransaction; change storeNarInfoInDatabase to use the same retry
semantics (either call c.withEntTransaction wrapping the body or add a 5-attempt
retry loop with small backoff around dbClient.WithTransaction) so transient
deadlock errors are retried, referencing the existing retry logic in
Cache.storeInDatabase/c.withEntTransaction; if the omission is intentional, add
a short comment in storeNarInfoInDatabase explaining why the migration lock
makes retries unnecessary.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 100abdad-7833-4683-9df6-16d8f90142f1

📥 Commits

Reviewing files that changed from the base of the PR and between 982bee2 and d884322.

📒 Files selected for processing (4)
  • openspec/changes/migrate-to-ent-and-atlas/tasks.md
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go
  • pkg/ncps/migrate_narinfo.go

@codecov

codecov Bot commented May 22, 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 (d884322).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1203   +/-   ##
=====================================
  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.

@kalbasit
kalbasit merged commit a980d99 into main May 22, 2026
18 checks passed
@kalbasit
kalbasit deleted the feat-cache-migrate-narinfo-ent branch May 22, 2026 23:15
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1203 (PRRT_kwDONV6tZs6DsScG, medium): standalone
`storeNarInfoInDatabase` (Cache-free entry used by
MigrateNarInfo and the `ncps migrate-narinfo` CLI) called
`dbClient.WithTransaction` directly, skipping the
deadlock-retry loop the `*Cache.withEntTransaction` provides.
Under load — concurrent migrations of many narinfos against
SQLite, or contended PostgreSQL deployments — that meant
transient SQLITE_BUSY / serialization failures bubbled all the
way out, where the legacy path would have retried.

Fix: extract the retry policy from `*Cache.withEntTransaction`
into a package-level `withEntTransactionRetry(ctx, dbClient,
operation, fn)` helper. `*Cache.withEntTransaction` now
forwards to it; `storeNarInfoInDatabase` uses it directly.
Same retry parameters (5 attempts, 50ms initial back-off
doubling per attempt, ctx-aware via time.Timer + Stop).

No behaviour change for any caller already going through
`*Cache.withEntTransaction`; the previously-missing retry
is now present for MigrateNarInfo / CLI migrations.
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