Repository navigation
feat(cache): convert CDC nar_file write paths to Ent - #1205
Conversation
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.
ba36bb4 to
5cf720f
Compare
122e321 to
1418f19
Compare
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.
5cf720f to
da1e366
Compare
1418f19 to
6b78673
Compare
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.
§11.4 continuation. The in-tx NarFile write call sites that drive CDC chunking — ensureNarFileRecord, the chunking state machine in findOrCreateNarFileForCDC, recordChunkBatch, storeNarWithCDC.MarkComplete, and storeNarWithCDC.RelinkAndCleanup — all migrate to *ent.Tx-based helpers. Converted: - `ensureNarFileRecord` (line ~1440): collapses the legacy Create-then-conditional-Update into a single `OnConflictColumns(hash, compression, query).Update(SetFileSize, SetUpdatedAt).ID(ctx)`. Idempotent and atomic. - `findOrCreateNarFileForCDC` (line ~2149): the CDC entry point. Upserts with OnConflict.Update(SetUpdatedAt) for the touch, then `tx.NarFile.Get(ctx, id)` to inspect the current row state (TotalChunks, ChunkingStartedAt) — Ent's OnConflict only returns the ID, so a follow-up read is required where the legacy CreateNarFile RETURNING gave us the row in one round-trip. The state machine is preserved: total_chunks > 0 → ErrAlreadyExists; chunking_started_at fresh → ErrAlreadyExists; chunking_started_at stale → collect partial chunks via `tx.Chunk.Query().Where(HasNarFileLinksWith(NarFileID))` and delete the junction rows via `tx.NarFileChunk.Delete().Where(NarFileID(...))`. The lock bump becomes `tx.NarFile.UpdateOneID(...).SetChunkingStartedAt(now)`. Return type changes from `[]database.Chunk` to `[]*ent.Chunk`. - `cleanupStaleLockChunks` (line ~2281): updated to accept `[]*ent.Chunk`. The staleByID lookup stays keyed on int64 because the orphan-discovery path still uses `c.db.GetOrphanedChunks` (legacy Querier) which returns database.Chunk — that path migrates in §11.5. - `recordChunkBatch` (line ~2347): bulk chunk persistence. The per-chunk Create uses OnConflictColumns(Hash).Update( SetUpdatedAt).ID(ctx) — matches the legacy CreateChunk's `ON CONFLICT(hash) DO UPDATE SET updated_at = CURRENT_TIMESTAMP`. The link batch uses `tx.NarFileChunk.CreateBulk(...).OnConflictColumns(NarFileID, ChunkIndex).Ignore().Exec(ctx)` for the legacy `ON CONFLICT (nar_file_id, chunk_index) DO NOTHING`. - `storeNarWithCDC.MarkComplete` (line ~2050): `tx.NarFile.UpdateOneID(...).SetTotalChunks(...).SetFileSize(...) .SetUpdatedAt(now).ClearChunkingStartedAt().Save(ctx)` — the legacy UpdateNarFileTotalChunks composite update. - `storeNarWithCDC.RelinkAndCleanup` (line ~2080): `tx.NarFile.Delete().Where(HashEQ, CompressionEQ, QueryEQ)` + the new `relinkNarInfosToNarFileWithEntTx` helper. The helper queries narinfo IDs by URL then bulk-inserts narinfo_nar_files links with `OnConflictColumns(NarinfoID, NarFileID).Ignore()`, which is the Ent counterpart of the legacy `INSERT … SELECT … ON CONFLICT DO NOTHING`. The old Querier-shaped `relinkNarInfosToNarFileWithQuerier` is removed. New ent imports: `entchunk`, `entnarfilechunk`. The `entnarinfonarfile`, `entnarinfo`, `entnarinforeference`, `entnarinfosignature`, `entnarfile` already there from §11.2-3. Deferred to follow-up §11.4 commits: - `getNarFileFromDB` (line ~3654) and all its callers (about 10 sites). It currently takes `database.Querier`; many call sites pass `c.db` (non-tx) while others pass `qtx` (in-tx). Converting it polymorphically over `*ent.NarFileClient` (which is shared by `*ent.Client.NarFile` and `*ent.Tx.NarFile`) is a wide but mechanical edit; its own commit keeps the diff reviewable. - `TouchNarFile` (lines ~2970, ~6499) — small but blocked on the getNarFileFromDB conversion since both share the same tx. - The non-CDC GetChunksByNarFileID / GetChunksByNarFileIDFromIndex reads at lines ~6559, ~6687, ~6773 — §11.5 territory. `go test -race ./pkg/cache/...` passes against SQLite + Postgres + MySQL + Redis. Lint clean.
6b78673 to
8bd7bfe
Compare
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.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
pkg/cache/cache.go (2)
2200-2229:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon't let a losing chunker clobber
file_size.Line 2203 updates
file_sizebefore thechunking_started_atownership check. A contender that arrives withfileSize == 0can overwrite the size on a row another worker is already chunking, then immediately returnErrAlreadyExists. Progressive chunk serving reads that size back fromnar_files, so this can transiently advertise0bytes and leaves the row wrong if the active worker later fails beforeMarkComplete.Suggested change
- // If the record existed but had a different size, update it to reflect the truth. - // However, in CDC mode, once chunked, FileSize holds the uncompressed size. - // We should only update it if it's not yet fully chunked. - if nr.FileSize != fileSize && nr.TotalChunks == 0 { - if _, err := tx.NarFile.UpdateOneID(nr.ID). - SetFileSize(fileSize). - SetUpdatedAt(time.Now()). - Save(ctx); err != nil { - return err - } - } - narFileID = int64(nr.ID) @@ if nr.ChunkingStartedAt != nil { age := time.Since(*nr.ChunkingStartedAt) if age < cdcChunkingLockTTL { // Another in-progress attempt is still within the TTL — skip. return storage.ErrAlreadyExists @@ } } + + // Only the worker that is about to own chunking should rewrite file_size. + if fileSize > 0 && nr.FileSize != fileSize { + if _, err := tx.NarFile.UpdateOneID(nr.ID). + SetFileSize(fileSize). + SetUpdatedAt(time.Now()). + Save(ctx); err != nil { + return 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 2200 - 2229, The file_size update is happening before checking chunking ownership, so a competing caller with fileSize==0 can overwrite the size and then abort; move the file-size update (the tx.NarFile.UpdateOneID(...).SetFileSize(...).SetUpdatedAt(...).Save call and its nr.FileSize != fileSize && nr.TotalChunks == 0 guard) to after the logic that checks nr.TotalChunks and nr.ChunkingStartedAt (the ownership/TTL checks using cdcChunkingLockTTL and returning storage.ErrAlreadyExists) so that you only update file_size when this goroutine has determined it will proceed (i.e., did not return ErrAlreadyExists or otherwise abandon ownership).
2075-2092:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftMake relink failure fatal or explicitly retryable.
If this transaction rolls back, the code still proceeds with the later cleanup path, which rewrites narinfo URLs and deletes the whole-file asset while
narinfo_nar_filesis still pointing at the old row. That leaves the metadata graph inconsistent, and I don’t see a later path that repairs those links. This is exactly the invariant covered bypkg/cache/cdc_test.go:729-803andpkg/cache/cdc_test.go:1158-1249.Either fail the migration here, or make the idempotent cleanup path retry the relink before it mutates URLs/storage.
🤖 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 2075 - 2092, The relink transaction failure must not be a non-fatal Warn; change the current behavior so that if c.withEntTransaction(..., "storeNarWithCDC.RelinkAndCleanup", ...) returns an error you propagate/return that error to abort the migration instead of logging and continuing; specifically replace the warn-and-continue branch around the call to c.withEntTransaction (and the Msg("failed to atomically clean up ...")) with a propagated error return from the enclosing function (or wrap and return the error), ensuring callers of the enclosing function will not proceed to the later cleanup; alternatively, if you prefer retry semantics implement an explicit retry loop (with limited attempts/backoff) that re-invokes c.relinkNarInfosToNarFileWithEntTx via c.withEntTransaction before any URL rewrite/storage delete, so that the cleanup path always verifies/retries relinking before mutating narinfo URLs or deleting assets.
🤖 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.
Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 2200-2229: The file_size update is happening before checking
chunking ownership, so a competing caller with fileSize==0 can overwrite the
size and then abort; move the file-size update (the
tx.NarFile.UpdateOneID(...).SetFileSize(...).SetUpdatedAt(...).Save call and its
nr.FileSize != fileSize && nr.TotalChunks == 0 guard) to after the logic that
checks nr.TotalChunks and nr.ChunkingStartedAt (the ownership/TTL checks using
cdcChunkingLockTTL and returning storage.ErrAlreadyExists) so that you only
update file_size when this goroutine has determined it will proceed (i.e., did
not return ErrAlreadyExists or otherwise abandon ownership).
- Around line 2075-2092: The relink transaction failure must not be a non-fatal
Warn; change the current behavior so that if c.withEntTransaction(...,
"storeNarWithCDC.RelinkAndCleanup", ...) returns an error you propagate/return
that error to abort the migration instead of logging and continuing;
specifically replace the warn-and-continue branch around the call to
c.withEntTransaction (and the Msg("failed to atomically clean up ...")) with a
propagated error return from the enclosing function (or wrap and return the
error), ensuring callers of the enclosing function will not proceed to the later
cleanup; alternatively, if you prefer retry semantics implement an explicit
retry loop (with limited attempts/backoff) that re-invokes
c.relinkNarInfosToNarFileWithEntTx via c.withEntTransaction before any URL
rewrite/storage delete, so that the cleanup path always verifies/retries
relinking before mutating narinfo URLs or deleting assets.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1205 +/- ##
=====================================
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:
|
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.
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.
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.
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.
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.
§11.4 continuation. The in-tx NarFile write call sites that
drive CDC chunking — ensureNarFileRecord, the chunking
state machine in findOrCreateNarFileForCDC, recordChunkBatch,
storeNarWithCDC.MarkComplete, and
storeNarWithCDC.RelinkAndCleanup — all migrate to
*ent.Tx-based helpers.
Converted:
ensureNarFileRecord(line ~1440): collapses the legacyCreate-then-conditional-Update into a single
OnConflictColumns(hash, compression, query).Update(SetFileSize, SetUpdatedAt).ID(ctx). Idempotent and atomic.findOrCreateNarFileForCDC(line ~2149): the CDC entrypoint. Upserts with OnConflict.Update(SetUpdatedAt) for the
touch, then
tx.NarFile.Get(ctx, id)to inspect thecurrent row state (TotalChunks, ChunkingStartedAt) — Ent's
OnConflict only returns the ID, so a follow-up read is
required where the legacy CreateNarFile RETURNING gave us
the row in one round-trip. The state machine is preserved:
total_chunks > 0 → ErrAlreadyExists; chunking_started_at
fresh → ErrAlreadyExists; chunking_started_at stale →
collect partial chunks via
tx.Chunk.Query().Where(HasNarFileLinksWith(NarFileID))and delete the junction rows via
tx.NarFileChunk.Delete().Where(NarFileID(...)). The lockbump becomes
tx.NarFile.UpdateOneID(...).SetChunkingStartedAt(now).Return type changes from
[]database.Chunkto[]*ent.Chunk.cleanupStaleLockChunks(line ~2281): updated to accept[]*ent.Chunk. The staleByID lookup stays keyed on int64because the orphan-discovery path still uses
c.db.GetOrphanedChunks(legacy Querier) which returnsdatabase.Chunk — that path migrates in §11.5.
recordChunkBatch(line ~2347): bulk chunk persistence.The per-chunk Create uses OnConflictColumns(Hash).Update(
SetUpdatedAt).ID(ctx) — matches the legacy CreateChunk's
ON CONFLICT(hash) DO UPDATE SET updated_at = CURRENT_TIMESTAMP.The link batch uses
tx.NarFileChunk.CreateBulk(...).OnConflictColumns(NarFileID, ChunkIndex).Ignore().Exec(ctx)for the legacyON CONFLICT (nar_file_id, chunk_index) DO NOTHING.storeNarWithCDC.MarkComplete(line ~2050):tx.NarFile.UpdateOneID(...).SetTotalChunks(...).SetFileSize(...) .SetUpdatedAt(now).ClearChunkingStartedAt().Save(ctx)—the legacy UpdateNarFileTotalChunks composite update.
storeNarWithCDC.RelinkAndCleanup(line ~2080):tx.NarFile.Delete().Where(HashEQ, CompressionEQ, QueryEQ)relinkNarInfosToNarFileWithEntTxhelper. Thehelper queries narinfo IDs by URL then bulk-inserts
narinfo_nar_files links with
OnConflictColumns(NarinfoID, NarFileID).Ignore(), whichis the Ent counterpart of the legacy
INSERT … SELECT … ON CONFLICT DO NOTHING. The oldQuerier-shaped
relinkNarInfosToNarFileWithQuerierisremoved.
New ent imports:
entchunk,entnarfilechunk. Theentnarinfonarfile,entnarinfo,entnarinforeference,entnarinfosignature,entnarfilealready there from §11.2-3.Deferred to follow-up §11.4 commits:
getNarFileFromDB(line ~3654) and all its callers (about10 sites). It currently takes
database.Querier; manycall sites pass
c.db(non-tx) while others passqtx(in-tx). Converting it polymorphically over
*ent.NarFileClient(which is shared by
*ent.Client.NarFileand*ent.Tx.NarFile) is a wide but mechanical edit; its owncommit keeps the diff reviewable.
TouchNarFile(lines ~2970, ~6499) — small but blocked onthe getNarFileFromDB conversion since both share the same
tx.
The non-CDC GetChunksByNarFileID / GetChunksByNarFileIDFromIndex
reads at lines ~6559, ~6687, ~6773 — §11.5 territory.
go test -race ./pkg/cache/...passes against SQLite +Postgres + MySQL + Redis. Lint clean.