Skip to content

feat(cache): convert CDC nar_file write paths to Ent - #1205

Merged
kalbasit merged 1 commit into
mainfrom
feat-cache-cdc-narfile-ent
May 22, 2026
Merged

kalbasit merged 1 commit into
mainfrom
feat-cache-cdc-narfile-ent

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

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

@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 added a commit that referenced this pull request May 22, 2026
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.
@kalbasit
kalbasit force-pushed the feat-cache-narfile-non-tx-to-ent branch from ba36bb4 to 5cf720f Compare May 22, 2026 23:02
@kalbasit
kalbasit force-pushed the feat-cache-cdc-narfile-ent branch from 122e321 to 1418f19 Compare May 22, 2026 23:02
kalbasit added a commit that referenced this pull request May 22, 2026
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.
@kalbasit
kalbasit force-pushed the feat-cache-narfile-non-tx-to-ent branch from 5cf720f to da1e366 Compare May 22, 2026 23:15
@kalbasit
kalbasit force-pushed the feat-cache-cdc-narfile-ent branch from 1418f19 to 6b78673 Compare May 22, 2026 23:15
kalbasit added a commit that referenced this pull request May 22, 2026
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.
Base automatically changed from feat-cache-narfile-non-tx-to-ent to main May 22, 2026 23:28
§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.
@kalbasit
kalbasit force-pushed the feat-cache-cdc-narfile-ent branch from 6b78673 to 8bd7bfe Compare May 22, 2026 23:28
kalbasit added a commit that referenced this pull request May 22, 2026
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.
@kalbasit
kalbasit enabled auto-merge (squash) May 22, 2026 23:29

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

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 win

Don't let a losing chunker clobber file_size.

Line 2203 updates file_size before the chunking_started_at ownership check. A contender that arrives with fileSize == 0 can overwrite the size on a row another worker is already chunking, then immediately return ErrAlreadyExists. Progressive chunk serving reads that size back from nar_files, so this can transiently advertise 0 bytes and leaves the row wrong if the active worker later fails before MarkComplete.

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 lift

Make 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_files is 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 by pkg/cache/cdc_test.go:729-803 and pkg/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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b282d11a-0795-45ae-9f13-662b5c0b80e9

📥 Commits

Reviewing files that changed from the base of the PR and between 2e93a90 and 8bd7bfe.

📒 Files selected for processing (1)
  • pkg/cache/cache.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 (8bd7bfe).
⚠️ Report is 2 commits behind head on main.

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.
📢 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 d530eae into main May 22, 2026
20 of 23 checks passed
@kalbasit
kalbasit deleted the feat-cache-cdc-narfile-ent branch May 22, 2026 23:53
kalbasit added a commit that referenced this pull request May 22, 2026
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.
kalbasit added a commit that referenced this pull request May 23, 2026
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.
kalbasit added a commit that referenced this pull request May 23, 2026
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.
kalbasit added a commit that referenced this pull request May 23, 2026
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.
kalbasit added a commit that referenced this pull request May 23, 2026
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

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