Skip to content

feat(cache): thread *database.Client into Cache - #1192

Merged
kalbasit merged 1 commit into
mainfrom
feat-cache-thread-db-client
May 22, 2026
Merged

kalbasit merged 1 commit into
mainfrom
feat-cache-thread-db-client

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

§11.1 of migrate-to-ent-and-atlas. Lays the threading plumbing
for the Querier → Ent.Client migration without converting any
call sites yet — that work is split across §11.2-§11.7.

Changes:

  • pkg/cache/cache.Cache gains a dbClient *database.Client
    field alongside the existing db database.Querier. Both share
    a single *sql.DB (one connection pool). The dbClient field
    is unused for now; subsequent §11 commits will progressively
    replace c.db.<Method>(…) call sites with c.dbClient.Ent().….
  • cache.New and pkg/ncps.createCache accept the dbClient as
    a new parameter; pkg/ncps/serve.createDatabaseQuerier now
    also constructs the Client (via database.NewClient(db.DB(), detected_type)) and returns it alongside the Querier.
  • testhelper.Setup{SQLite,Postgres,MySQL} likewise yield the
    dbClient; every Setup caller (cache, cache/healthcheck, cache
    distributed, server, ncps test files) destructures it
    accordingly. Wrapper helpers — newTestCache,
    setupTestComponents, the cacheFactory type, the
    distributedDBFactory type, setup{SQLite,Postgres,MySQL}Factory,
    and runTestsWithDB in cache_internal_test.go — gain the
    Client in their return tuples / parameter lists. Tests that
    don't need the Client discard it with _.
  • Sites that open SQLite directly (without testhelper) construct
    the Client inline next to database.Open.

Why now and not later: every test file calling cache.New
already breaks the moment the constructor changes shape, so the
threading has to land atomically. The conversion of actual
Querier method calls is deferred to §11.2-§11.7 to keep each
commit reviewable.

No behaviour change. Full go test -race ./... passes against
SQLite + Postgres + MySQL + MinIO + Redis.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. go Pull requests that update go code labels May 21, 2026
@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.

This was referenced May 21, 2026
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 22, 2026
@kalbasit
kalbasit enabled auto-merge (squash) May 22, 2026 17:18
Comment thread pkg/server/security_test.go Dismissed
coderabbitai[bot]
coderabbitai Bot previously requested changes May 22, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openspec/changes/migrate-to-ent-and-atlas/tasks.md`:
- Line 116: The checklist entry overstates the change: update the wording to
reflect that pkg/cache/cache.go was prepared for migration by threading a
parallel dbClient while retaining the original db (database.Querier) rather than
fully replacing it with *database.Client; change the sentence mentioning storage
rewrite from "storage of `database.Querier` to `*database.Client`" to something
like "threaded a parallel `dbClient` (*database.Client) through `cache.New`,
testhelpers, and call sites while retaining the existing `db`
(`database.Querier`) to prepare for a later migration", and ensure the text
references the symbols `pkg/cache/cache.go`, `dbClient`, `db`, `cache.New`, and
`testhelpers` so the checklist accurately reflects the scope.

In `@pkg/ncps/serve.go`:
- Around line 996-1004: The opened DB stored in variable db is not closed on
error paths; ensure you close it before returning when
database.DetectFromDatabaseURL or database.NewClient fails. After db is opened
(variable db), call db.Close() (or db.DB().Close() if using a wrapped DB) in
each error branch before returning so the connection is not leaked (i.e., close
db right before the fmt.Errorf return in the DetectFromDatabaseURL and NewClient
error cases).
🪄 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: 23cfe1d9-fe79-4d16-8514-6dc9d240a239

📥 Commits

Reviewing files that changed from the base of the PR and between 57b22af and 28d20fc.

📒 Files selected for processing (25)
  • openspec/changes/migrate-to-ent-and-atlas/tasks.md
  • pkg/cache/cache.go
  • pkg/cache/cache_distributed_test.go
  • pkg/cache/cache_internal_test.go
  • pkg/cache/cache_prefetch_test.go
  • pkg/cache/cache_test.go
  • pkg/cache/cdc_test.go
  • pkg/cache/healthcheck/healthcheck_test.go
  • pkg/cache/upload_only_test.go
  • pkg/config/config_test.go
  • pkg/database/backends_test.go
  • pkg/database/schema_parity_test.go
  • pkg/ncps/fsck.go
  • pkg/ncps/fsck_test.go
  • pkg/ncps/migrate_nar_to_chunks.go
  • pkg/ncps/migrate_nar_to_chunks_test.go
  • pkg/ncps/migrate_narinfo.go
  • pkg/ncps/migrate_narinfo_test.go
  • pkg/ncps/serve.go
  • pkg/server/security_test.go
  • pkg/server/server_internal_test.go
  • pkg/server/server_test.go
  • testhelper/mysql.go
  • testhelper/postgres.go
  • testhelper/sqlite.go

Comment thread pkg/ncps/serve.go Resolved
@codecov

codecov Bot commented May 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 4.94%. Comparing base (40afcbb) to head (28d20fc).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
testhelper/mysql.go 0.00% 5 Missing ⚠️
testhelper/postgres.go 0.00% 5 Missing ⚠️
testhelper/sqlite.go 0.00% 5 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##            main   #1192      +/-   ##
========================================
- Coverage   5.04%   4.94%   -0.11%     
========================================
  Files          6       6              
  Lines        436     445       +9     
========================================
  Hits          22      22              
- Misses       410     419       +9     
  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 dismissed coderabbitai[bot]’s stale review May 22, 2026 17:39

need to merge now

@kalbasit
kalbasit merged commit df2363d into main May 22, 2026
16 of 18 checks passed
@kalbasit
kalbasit deleted the feat-cache-thread-db-client branch May 22, 2026 17:39
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 22, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 23, 2026
PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)
kalbasit added a commit that referenced this pull request May 23, 2026
fix(ncps): drop dbURL from createDatabaseQuerier error wraps

PR #1192 review: 3 sec-high comments flagged that
`createDatabaseQuerier`'s error wraps embed `dbURL` via `%q`.
Practical database URLs include credentials, leaking them into
server logs. Drop the URL from the three new wraps the §11.1
thread-through commit introduced.

Resolves:
- PR #1192 PRRT_kwDONV6tZs6DsTQ7 (line 990)
- PR #1192 PRRT_kwDONV6tZs6DsTRK (line 998)
- PR #1192 PRRT_kwDONV6tZs6DsTRQ (line 1003)

fix(cache): preserve tx debug logs + use time.Timer in retry

PR #1194 review surfaced two issues in withEntTransaction:

1. (PRRT_kwDONV6tZs6DsQzn) Restore "starting transaction" /
   "committed successfully" debug logs that the legacy
   executeTransaction emitted. Behind Debug level so noise
   stays opt-in; restores observability parity.

2. (PRRT_kwDONV6tZs6DsQzo) Replace `case <-time.After(delay):`
   inside the retry select with `time.NewTimer(delay)` +
   `t.Stop()` in the ctx-cancellation branch to avoid leaking
   the underlying timer when ctx wins the race.

Behaviour-preserving on the happy path.

fix(migrations): restore +goose NO TRANSACTION on sqlite bridge

PR #1196 (PRRT_kwDONV6tZs6DsQXZ, high): the
`-- +goose NO TRANSACTION` directive was dropped from the
SQLite ent_baseline bridge when `fix-ent-preserve-current-
timestamp-default` regenerated the migration via
`cmd/generate-migrations`.

In SQLite, `PRAGMA foreign_keys = off` is a no-op inside a
transaction. Goose wraps migrations in a transaction by
default, so without the NO TRANSACTION directive the PRAGMA
silently has no effect — and the subsequent
`DROP TABLE <parent>` / `ALTER TABLE new_X RENAME TO X` swaps
would fail in production against any database with existing
FK-referenced rows. The original §8 bridge had this directive;
the regeneration lost it because Atlas's GooseFormatter
doesn't emit it automatically.

Restored the directive plus its explanatory comment, and
regenerated `migrations/sqlite/atlas.sum` so Atlas's
checksum validator accepts the file.

Postgres and MySQL bridges don't need an equivalent — they
use real `ALTER TABLE` for column changes (not SQLite's
shadow-table-recreate pattern) and don't depend on a PRAGMA
to disable referential integrity mid-migration.

Note: `TestSchemaEquivalence/sqlite` is currently broken at
HEAD for a separate, pre-existing reason traced to the
`cf28126` regen (the test fails both with and without this
fix). Will be investigated as a follow-up.

fix(cache): add retry-on-deadlock to storeNarInfoInDatabase

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.

fix(cache): batch HashIn + null-safe SUM + unshadow ent

PR #1204 surfaced three concerns in §11.4's non-tx NarFile
conversion (`feat-cache-narfile-non-tx-to-ent`):

1. (PRRT_kwDONV6tZs6DsRgI, high) The CDC delayed-cleanup
   replacement for `GetOldCompressedNarFiles` was a two-step
   query that paged ALL chunked NAR hashes into Go memory then
   passed them to a single `entnarfile.HashIn(...)`. On caches
   with many chunked NARs that risks (a) loading megabytes of
   hashes into memory and (b) blowing past driver parameter
   limits (Postgres ≤ 65535, modern SQLite ≤ 32766, older
   SQLite ≤ 999). Fixed by batching HashIn in chunks of
   `cdcCleanupHashBatchSize` (= 500, a new package const).
   The batch size is well below all known limits and well
   above typical chunked-hash counts, so the job stays a
   single round-trip for any practical install.

2. (PRRT_kwDONV6tZs6DsRgL, medium) The metrics-observer SUM
   aggregator scanned into a plain `int64`. SQL `SUM` over an
   empty set returns NULL, which fails to scan into `int64`
   ("sql: Scan, storing driver.Value type <nil> into type
   *int64"). The metric callback would have started failing
   the moment any deployment booted with an empty nar_files
   table. Switched to `sql.NullInt64` with a Valid check;
   NULL is treated as zero. The `sql:"sum"` tag matches the
   alias Ent emits via `ent.Sum`.

3. (PRRT_kwDONV6tZs6DsRgO, medium) Local var `ent` shadowed
   the `ent` package import inside the cron handler closure.
   No actual breakage in the current code (no `ent.X` use
   inside that scope) but it makes the scope brittle for
   future edits. Renamed to `entClient`.

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

fix(cache): batch relinkNarInfosToNarFile bulk insert

PR #1205 (PRRT_kwDONV6tZs6DsRuq, medium):
`relinkNarInfosToNarFileWithEntTx` passed every queried narinfo
ID into a single `tx.NarInfoNarFile.CreateBulk(...)` call. Each
row sends 2 parameters (narinfo_id, nar_file_id), so a closure
with N narinfos sharing a NAR URL sends 2N placeholders. On
older SQLite builds (limit 999) that fails for any N > 499;
even on Postgres (limit 65535) very large closures could
silently overflow.

Fixed by chunking the loop into batches of 500 rows = 1000
placeholders per batch, well below all driver limits and well
above realistic closure sizes — so the common case stays a
single round-trip.

batch size is a local const inside the helper rather than a
package constant because the limit derives from this specific
row's placeholder count (2 cols × batch size); other bulk
inserts with different column counts get their own limit.

`go test -race ./pkg/cache/...` passes against SQLite +
Postgres + MySQL + Redis. Lint clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code merge-stack size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants