Skip to content

feat(cache): convert storeInDatabase to Ent - #1202

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

kalbasit merged 1 commit into
mainfrom
feat-cache-storeindatabase-ent

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

§11.3 continuation. Replaces the legacy storeInDatabase
withTransaction closure (which composed CreateNarInfo +
AddNarInfoReferences + AddNarInfoSignatures + createOrUpdateNarFile

  • LinkNarInfoToNarFile) with an Ent-fluent pipeline.

Conditional UPSERT for narinfos

The legacy SQL was INSERT … ON CONFLICT (hash) DO UPDATE … WHERE url IS NULL — stub records (URL NULL) get overwritten;
records with a real URL stay untouched. Ent's UpsertOne API
doesn't expose the WHERE-on-update clause directly, so the new
upsertNarInfoFromParsed helper does a read + branch:

  • row absent → Create with the supplied fields
  • row present, URL nil → UpdateOneID overwriting every field
    (ClearX for empty source values, to
    match the legacy NULL semantics)
  • row present, URL set → keep existing row

This is safe because the surrounding *ent.Tx serialises the
read and write, and the cache-level write lock on
PutNarInfo prevents two same-hash callers from racing.

Two parallel helpers — applyNarInfoCreate and
applyNarInfoUpdate — keep the field-population code DRY between
the insert and stub-update branches.

Bulk reference / signature inserts

addNarInfoReferences / addNarInfoSignatures use
tx.NarInfoReference.CreateBulk(...).OnConflictColumns(...). Ignore().Exec(ctx). Ignore() compiles to
ON CONFLICT DO UPDATE SET col = col (a no-op update) rather
than DO NOTHING; both express the legacy
ON CONFLICT (narinfo_id, reference) DO NOTHING behaviour but
DO NOTHING combined with RETURNING returns no rows on Postgres,
which Ent treats as sql.ErrNoRows — Ignore() always returns
a row, so the surrounding tx stays valid.

Resolving the conflict at the SQL layer (rather than tolerating
duplicate-key errors in Go) is required: Postgres puts the
transaction into an aborted state after any failed statement
("current transaction is aborted, commands ignored until end
of transaction block"). The previous version's
IsDuplicateKeyError tolerance broke storeInDatabase on Postgres
the moment a re-call (e.g. shared-NAR concurrent PutNarInfo)
triggered a duplicate.

NarFile upsert

createOrUpdateNarFileEnt collapses the legacy read-then-create
into a single
tx.NarFile.Create().OnConflictColumns(hash, compression, query).Update(SetLastAccessedAt(now)).ID(ctx). Atomic by
construction, no Go-level race window. Returns int (Ent's PK
type for strong entities) instead of int64; the §11.4 CDC
conversions will retire the int64-typed callers.

NarFile<->NarInfo link

The legacy LinkNarInfoToNarFile was a plain INSERT … ON
CONFLICT (narinfo_id, nar_file_id) DO NOTHING. Becomes Ent's
tx.NarInfoNarFile.Create()...OnConflictColumns(…).Ignore(). Exec(ctx).

Verified

go test -race ./pkg/cache/... passes against SQLite + Postgres

  • MySQL + Redis, including the concurrency-heavy distributed
    tests (PutNarInfoConcurrentSharedNar) that exercise the
    conflict-resolution paths. Lint clean.

Deferred

  • The parallel PutNarInfo helper at line ~4631 (still uses
    the qtx pattern). It's nearly the same shape; will convert
    on top of this commit reusing the new helpers.
  • createOrUpdateNarFile (the legacy helper) is still
    referenced from CDC code (§11.4 work). Left in place
    alongside the new createOrUpdateNarFileEnt.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@kalbasit

kalbasit commented May 21, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 26bfbde to bd54887 Compare May 22, 2026 05:59
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from e5d9040 to 435ce97 Compare May 22, 2026 06:47
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from bd54887 to 5027242 Compare May 22, 2026 06:47
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from 435ce97 to e73fdb1 Compare May 22, 2026 07:06
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 5027242 to 5bb2ddd Compare May 22, 2026 07:06
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from e73fdb1 to ff60258 Compare May 22, 2026 18:07
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 5bb2ddd to 636824a Compare May 22, 2026 18:07
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@kalbasit has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 48 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 41630a34-f9e3-49e6-8907-eec985aaab6b

📥 Commits

Reviewing files that changed from the base of the PR and between 77c522a and 304598b.

📒 Files selected for processing (1)
  • pkg/cache/cache.go

Comment @coderabbitai help to get the list of available commands and usage tips.

@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from ff60258 to 65ea5a4 Compare May 22, 2026 19:02
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 636824a to a728305 Compare May 22, 2026 19:02
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from 65ea5a4 to e4ebb15 Compare May 22, 2026 20:44
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from a728305 to 36a2e1b Compare May 22, 2026 20:44
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from e4ebb15 to 71fda8d Compare May 22, 2026 20:51
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 36a2e1b to 5edd5b1 Compare May 22, 2026 20:51
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from 71fda8d to 32d47d0 Compare May 22, 2026 21:04
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 5edd5b1 to 6a6b439 Compare May 22, 2026 21:04
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from 32d47d0 to bf73661 Compare May 22, 2026 21:16
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 6a6b439 to 42b3c9d Compare May 22, 2026 21:16
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from bf73661 to 44acb3d Compare May 22, 2026 21:29
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 42b3c9d to e90b426 Compare May 22, 2026 21:29
@kalbasit
kalbasit force-pushed the feat-cache-delete-narinfo-ent branch from 44acb3d to 2cfb023 Compare May 22, 2026 21:41
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from e90b426 to 39f2fd6 Compare May 22, 2026 21:41
Base automatically changed from feat-cache-delete-narinfo-ent to main May 22, 2026 21:53
§11.3 continuation. Replaces the legacy storeInDatabase
withTransaction closure (which composed CreateNarInfo +
AddNarInfoReferences + AddNarInfoSignatures + createOrUpdateNarFile
+ LinkNarInfoToNarFile) with an Ent-fluent pipeline.

Conditional UPSERT for narinfos
-------------------------------

The legacy SQL was `INSERT … ON CONFLICT (hash) DO UPDATE …
WHERE url IS NULL` — stub records (URL NULL) get overwritten;
records with a real URL stay untouched. Ent's UpsertOne API
doesn't expose the WHERE-on-update clause directly, so the new
upsertNarInfoFromParsed helper does a read + branch:

  - row absent          → Create with the supplied fields
  - row present, URL nil → UpdateOneID overwriting every field
                           (ClearX for empty source values, to
                           match the legacy NULL semantics)
  - row present, URL set → keep existing row

This is safe because the surrounding *ent.Tx serialises the
read and write, and the cache-level write lock on
PutNarInfo prevents two same-hash callers from racing.

Two parallel helpers — applyNarInfoCreate and
applyNarInfoUpdate — keep the field-population code DRY between
the insert and stub-update branches.

Bulk reference / signature inserts
----------------------------------

addNarInfoReferences / addNarInfoSignatures use
`tx.NarInfoReference.CreateBulk(...).OnConflictColumns(...).
Ignore().Exec(ctx)`. Ignore() compiles to
`ON CONFLICT DO UPDATE SET col = col` (a no-op update) rather
than DO NOTHING; both express the legacy
`ON CONFLICT (narinfo_id, reference) DO NOTHING` behaviour but
DO NOTHING combined with RETURNING returns no rows on Postgres,
which Ent treats as `sql.ErrNoRows` — Ignore() always returns
a row, so the surrounding tx stays valid.

Resolving the conflict at the SQL layer (rather than tolerating
duplicate-key errors in Go) is required: Postgres puts the
transaction into an aborted state after any failed statement
("current transaction is aborted, commands ignored until end
of transaction block"). The previous version's
IsDuplicateKeyError tolerance broke storeInDatabase on Postgres
the moment a re-call (e.g. shared-NAR concurrent PutNarInfo)
triggered a duplicate.

NarFile upsert
--------------

createOrUpdateNarFileEnt collapses the legacy read-then-create
into a single
`tx.NarFile.Create().OnConflictColumns(hash, compression,
query).Update(SetLastAccessedAt(now)).ID(ctx)`. Atomic by
construction, no Go-level race window. Returns int (Ent's PK
type for strong entities) instead of int64; the §11.4 CDC
conversions will retire the int64-typed callers.

NarFile<->NarInfo link
----------------------

The legacy `LinkNarInfoToNarFile` was a plain INSERT … ON
CONFLICT (narinfo_id, nar_file_id) DO NOTHING. Becomes Ent's
`tx.NarInfoNarFile.Create()...OnConflictColumns(…).Ignore().
Exec(ctx)`.

Verified
--------

`go test -race ./pkg/cache/...` passes against SQLite + Postgres
+ MySQL + Redis, including the concurrency-heavy distributed
tests (PutNarInfoConcurrentSharedNar) that exercise the
conflict-resolution paths. Lint clean.

Deferred
--------

- The parallel PutNarInfo helper at line ~4631 (still uses
  the qtx pattern). It's nearly the same shape; will convert
  on top of this commit reusing the new helpers.
- `createOrUpdateNarFile` (the legacy helper) is still
  referenced from CDC code (§11.4 work). Left in place
  alongside the new createOrUpdateNarFileEnt.
@kalbasit
kalbasit force-pushed the feat-cache-storeindatabase-ent branch from 39f2fd6 to 304598b Compare May 22, 2026 21:53
@kalbasit
kalbasit enabled auto-merge (squash) May 22, 2026 21:54
@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 (77c522a) to head (304598b).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1202   +/-   ##
=====================================
  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 982bee2 into main May 22, 2026
25 of 30 checks passed
@kalbasit
kalbasit deleted the feat-cache-storeindatabase-ent branch May 22, 2026 23:02
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