Repository navigation
fix(ncps): drop dbURL from createDatabaseQuerier error wraps - #1208
Conversation
ff12dbd to
9d7d600
Compare
b41539a to
ab1df74
Compare
9d7d600 to
32ad08d
Compare
ab1df74 to
8a7bc14
Compare
32ad08d to
b33e76c
Compare
8a7bc14 to
bdc9eed
Compare
b33e76c to
b1a01ac
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)
6113-6169:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftMatch CDC cleanup candidates on
(hash, query), not justhash.This file treats
nar_filesidentity as(hash, compression, query), but Lines 6123-6161 collapse the chunked side tohashand then fetch every old compressed row with that hash. If one query variant has been chunked and another has not, the still-live compressed row is also selected here and then deleted at Line 6187.🤖 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 6113 - 6169, The code currently collapses chunked candidates to just chunkedHashes and then uses entnarfile.HashIn(...) which ignores the query variant; instead select both entnarfile.FieldHash and entnarfile.FieldQuery into chunkedRows (e.g., change chunkedHashRows to a struct { Hash, Query string }) and build batch predicates per pair: for each (h,q) create entnarfile.And(entnarfile.HashEQ(h), entnarfile.QueryEQ(q)) and then query compressed rows with entnarfile.Or(preds...) in the same batching loop (use entClient.NarFile.Query().Where(entnarfile.Or(...), entnarfile.TotalChunksEQ(0), entnarfile.CompressionNEQ("none"), entnarfile.CreatedAtLT(cutoffTime)).All(ctx)) so you only match rows with the same (hash, query) identity rather than any row with that hash.
🤖 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 2368-2397: The relink batch size currently set by relinkBatchSize
causes up to 1000 bound parameters (2 per row) which can exceed older SQLite's
999 limit; update the batching logic used around narInfoIDs and
tx.NarInfoNarFile.CreateBulk so the batch size is computed from the parameter
cap (e.g., maxParams := 999; maxRows := maxParams/2) or simply reduce
relinkBatchSize to 499; ensure the CreateBulk loop uses that computed batch size
so OnConflictColumns(entnarinfonarfile.FieldNarinfoID,
entnarinfonarfile.FieldNarFileID).Ignore().Exec(ctx) never exceeds the parameter
limit.
---
Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 6113-6169: The code currently collapses chunked candidates to just
chunkedHashes and then uses entnarfile.HashIn(...) which ignores the query
variant; instead select both entnarfile.FieldHash and entnarfile.FieldQuery into
chunkedRows (e.g., change chunkedHashRows to a struct { Hash, Query string })
and build batch predicates per pair: for each (h,q) create
entnarfile.And(entnarfile.HashEQ(h), entnarfile.QueryEQ(q)) and then query
compressed rows with entnarfile.Or(preds...) in the same batching loop (use
entClient.NarFile.Query().Where(entnarfile.Or(...), entnarfile.TotalChunksEQ(0),
entnarfile.CompressionNEQ("none"), entnarfile.CreatedAtLT(cutoffTime)).All(ctx))
so you only match rows with the same (hash, query) identity rather than any row
with that hash.
🪄 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: c7ee1849-0528-4e32-be28-b25752322bae
⛔ Files ignored due to path filters (1)
migrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (3)
migrations/sqlite/20260521021523_ent_baseline.sqlpkg/cache/cache.gopkg/ncps/serve.go
bdc9eed to
7b317b3
Compare
b1a01ac to
ce10e89
Compare
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)
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.
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.
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.
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.
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.
ce10e89 to
00bd518
Compare
There was a problem hiding this comment.
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/ncps/serve.go`:
- Around line 997-1005: The code opens a DB with database.Open (db) but returns
early on errors from database.DetectFromDatabaseURL and database.NewClient,
leaking the open DB; update the initialization to ensure db.Close() is called on
any early return after database.Open succeeds: after calling database.Open(...)
and assigning db, defer or explicitly call db.Close() before returning on errors
from database.DetectFromDatabaseURL(dbURL) and database.NewClient(db.DB(),
dbType), or convert the single immediate defer into a conditional cleanup that
only persists on successful startup (e.g., remove the defer and call db.Close()
on each error path, or keep defer and cancel it on success) so the connection
pool is always closed when initialization fails.
🪄 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: f50f9254-00ce-429b-98cd-fd326595be19
⛔ Files ignored due to path filters (1)
migrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (3)
migrations/sqlite/20260521021523_ent_baseline.sqlpkg/cache/cache.gopkg/ncps/serve.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1208 +/- ##
=====================================
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. 🚀 New features to boost your workflow:
|
relinkBatchSize was 500, but the upsert binds 2 values per row (narinfoID + narFileID), producing 1000 placeholders per batch — one over older SQLite's hard limit of 999. Lower to 499 (998 placeholders) to stay safely under the limit. Also close the *sql.DB in database.Open when NewClient fails, so the connection pool is not leaked on rare init-path errors. Addresses PR #1208 (PRRT_kwDONV6tZs6EQXUg). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…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]>
fix(ncps): drop dbURL from createDatabaseQuerier error wraps
PR #1192 review: 3 sec-high comments flagged that
createDatabaseQuerier's error wraps embeddbURLvia%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:
fix(cache): preserve tx debug logs + use time.Timer in retry
PR #1194 review surfaced two issues in withEntTransaction:
(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.
(PRRT_kwDONV6tZs6DsQzo) Replace
case <-time.After(delay):inside the retry select with
time.NewTimer(delay)+t.Stop()in the ctx-cancellation branch to avoid leakingthe 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 TRANSACTIONdirective was dropped from theSQLite ent_baseline bridge when
fix-ent-preserve-current- timestamp-defaultregenerated the migration viacmd/generate-migrations.In SQLite,
PRAGMA foreign_keys = offis a no-op inside atransaction. 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 Xswapswould 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.sumso Atlas'schecksum validator accepts the file.
Postgres and MySQL bridges don't need an equivalent — they
use real
ALTER TABLEfor column changes (not SQLite'sshadow-table-recreate pattern) and don't depend on a PRAGMA
to disable referential integrity mid-migration.
Note:
TestSchemaEquivalence/sqliteis currently broken atHEAD for a separate, pre-existing reason traced to the
cf28126regen (the test fails both with and without thisfix). 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 byMigrateNarInfo and the
ncps migrate-narinfoCLI) calleddbClient.WithTransactiondirectly, skipping thedeadlock-retry loop the
*Cache.withEntTransactionprovides.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.withEntTransactioninto a package-level
withEntTransactionRetry(ctx, dbClient, operation, fn)helper.*Cache.withEntTransactionnowforwards to it;
storeNarInfoInDatabaseuses 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 retryis 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):(PRRT_kwDONV6tZs6DsRgI, high) The CDC delayed-cleanup
replacement for
GetOldCompressedNarFileswas a two-stepquery that paged ALL chunked NAR hashes into Go memory then
passed them to a single
entnarfile.HashIn(...). On cacheswith 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.
(PRRT_kwDONV6tZs6DsRgL, medium) The metrics-observer SUM
aggregator scanned into a plain
int64. SQLSUMover anempty set returns NULL, which fails to scan into
int64("sql: Scan, storing driver.Value type into type
*int64"). The metric callback would have started failing
the moment any deployment booted with an empty nar_files
table. Switched to
sql.NullInt64with a Valid check;NULL is treated as zero. The
sql:"sum"tag matches thealias Ent emits via
ent.Sum.(PRRT_kwDONV6tZs6DsRgO, medium) Local var
entshadowedthe
entpackage import inside the cron handler closure.No actual breakage in the current code (no
ent.Xuseinside 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):
relinkNarInfosToNarFileWithEntTxpassed every queried narinfoID into a single
tx.NarInfoNarFile.CreateBulk(...)call. Eachrow 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.