Skip to content

feat(cache): convert non-tx GetNarInfo* lookups to Ent - #1193

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

kalbasit merged 1 commit into
mainfrom
feat-cache-getnarinfo-to-ent

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

§11.2 partial: convert the GetNarInfo* call sites in
pkg/cache/cache.go that don't sit inside the legacy
*sql.Tx-based transaction wrapper and don't cascade into
sqlc-row-shape consumers.

Converted (5 sites):

  • GetNarInfoCount → dbClient.Ent().NarInfo.Query().Count(ctx)
    (and the metrics observer now casts the int result to int64).
  • GetNarInfoURLByNarFileHash (a 3-table join through
    narinfo_nar_files → nar_files) → an entnarinfo.HasNarInfoNarFilesWith (entnarinfonarfile.HasNarFileWith(...)) predicate. The result
    shape changes from sql.NullString to a *ent.NarInfo whose
    URL *string field is read directly.
  • GetNarInfoHashByNarURL → Query().Where(URL(...)).First(ctx),
    with ni.Hash taking the place of the prior string return.
  • GetNarInfoHashesByURL → Query().Where(URL(...)).All(ctx),
    iterating ni.Hash instead of the prior []string slice.
  • deleteNarInfoFromStore's existence-check + PinClosure's
    pre-pin existence check both use
    Query().Where(HashEQ(hash)).First(ctx) with
    ent.IsNotFound(err) replacing database.IsNotFoundError.

Deferred (still on the original c.db/qtx API):

  • CheckAndFixNarInfo and lookupNarInfoForFix (line 4282
    area) cascade into niRow.URL.Valid/niRow.FileSize.Int64
    consumers and into checkAndFixNarInfoNoCompression. That
    conversion needs to flow row shape changes through several
    helpers; left for a follow-up commit.
  • The closure-pinning narinfo + references lookup (lines 6897,
    6907) reads ni.ID and feeds it back into
    GetNarInfoReferences. Same row-shape cascade — follow-up.
  • Every qtx.GetNarInfo* site inside c.executeTransaction
    blocks (~6 sites) needs the transaction wrapper to first
    switch from func(qtx database.Querier) error to
    func(tx *ent.Tx) error. That's an infrastructure change
    pre-requisite, also follow-up.

Imports: adds ent, entnarfile, entnarinfo,
entnarinfonarfile. The legacy database import stays — most
of pkg/cache still references it.

Full -race test suite passes on SQLite + Postgres + MySQL with
the deps stack running. Lint clean.

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

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. enhancement New feature or request 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
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from a6b6331 to 753ab18 Compare May 22, 2026 15:33
@kalbasit
kalbasit force-pushed the feat-cache-thread-db-client branch from 2317fcd to 8f98494 Compare May 22, 2026 15:47
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 753ab18 to 2c3ae9a Compare May 22, 2026 15:47
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 06b57531-041e-4e76-a57c-25cd25b195ae

📥 Commits

Reviewing files that changed from the base of the PR and between df2363d and 38fa3fa.

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

📝 Walkthrough

Summary by CodeRabbit

Release Notes

  • Refactor
    • Optimized database query efficiency for metrics collection
    • Improved NAR URL resolution and recovery during file serving
    • Enhanced data integrity verification for stored narinfo records
    • Refined upstream URL lookup operations
    • Strengthened closure pinning verification processes

Walkthrough

pkg/cache/cache.go replaces multiple database.Querier API calls with direct Ent queries, updating metric collection, URL lookups, and data existence checks. The migration adds Ent-generated imports, refactors five functions, and consistently maps Ent's NotFound exceptions to existing downstream error semantics.

Changes

Ent Client Migration in Cache Service

Layer / File(s) Summary
Ent package imports
pkg/cache/cache.go
Ent-generated packages for narfile, narinfo, and narinfonarfile models are imported to enable direct Ent query operations.
Metrics observation via Ent
pkg/cache/cache.go
Metric scraper for ncps_narinfo_count queries Ent for NarInfo count and converts the result to int64, replacing the previous c.db helper.
URL recovery and preference via Ent relations
pkg/cache/cache.go
lookupOriginalNarURL and lookupPreferredUpstreamURL traverse Ent model relations to resolve URLs, replacing direct database queries and handling Ent NotFound distinctly.
Ent-based data validation and existence checks
pkg/cache/cache.go
checkAndFixNarInfosForNar, deleteNarInfoFromStore, and PinClosure refactored to use Ent queries for collection and existence verification, mapping Ent NotFound to downstream behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1191: Introduces the pkg/database/client.go Ent client surface that this PR depends on for dbClient.Ent() access.

Poem

🐰 From queriers old to Ent so bright,
We skip the schemas, traverse relations right,
Each NotFound mapped with careful care,
URLs and counts now flow through Ent's air—
A cache reborn, cleaner, fair!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: converting GetNarInfo* lookups from the legacy database.Querier API to direct Ent queries in pkg/cache/cache.go.
Description check ✅ Passed The description provides detailed context about the conversion work, including specific call sites changed, deferred changes, and testing confirmation, directly relating to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

@kalbasit
kalbasit force-pushed the feat-cache-thread-db-client branch from 8f98494 to f06e4ff Compare May 22, 2026 16:02
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 2c3ae9a to 51e7fb8 Compare May 22, 2026 16:02
@kalbasit
kalbasit force-pushed the feat-cache-thread-db-client branch from f06e4ff to 786cdd9 Compare May 22, 2026 16:15
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 51e7fb8 to 6c3b640 Compare May 22, 2026 16:15
@kalbasit
kalbasit force-pushed the feat-cache-thread-db-client branch from 786cdd9 to f816b5d Compare May 22, 2026 16:27
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 6c3b640 to 22010ad Compare May 22, 2026 16:27
@kalbasit
kalbasit force-pushed the feat-cache-thread-db-client branch from f816b5d to 1b26d1f Compare May 22, 2026 16:42
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 22010ad to 33fa5e8 Compare May 22, 2026 16:42
@kalbasit
kalbasit force-pushed the feat-cache-thread-db-client branch from 1b26d1f to 419453f Compare May 22, 2026 16:57
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 33fa5e8 to 7537892 Compare May 22, 2026 16:57
@kalbasit
kalbasit force-pushed the feat-cache-thread-db-client branch from 419453f to 28d20fc Compare May 22, 2026 17:18
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 7537892 to 2c22541 Compare May 22, 2026 17:18
Base automatically changed from feat-cache-thread-db-client to main May 22, 2026 17:39
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 22, 2026
§11.2 partial: convert the GetNarInfo* call sites in
pkg/cache/cache.go that don't sit inside the legacy
*sql.Tx-based transaction wrapper and don't cascade into
sqlc-row-shape consumers.

Converted (5 sites):

- `GetNarInfoCount` → `dbClient.Ent().NarInfo.Query().Count(ctx)`
  (and the metrics observer now casts the int result to int64).
- `GetNarInfoURLByNarFileHash` (a 3-table join through
  narinfo_nar_files → nar_files) → an `entnarinfo.HasNarInfoNarFilesWith
  (entnarinfonarfile.HasNarFileWith(...))` predicate. The result
  shape changes from `sql.NullString` to a `*ent.NarInfo` whose
  `URL *string` field is read directly.
- `GetNarInfoHashByNarURL` → `Query().Where(URL(...)).First(ctx)`,
  with `ni.Hash` taking the place of the prior string return.
- `GetNarInfoHashesByURL` → `Query().Where(URL(...)).All(ctx)`,
  iterating `ni.Hash` instead of the prior `[]string` slice.
- `deleteNarInfoFromStore`'s existence-check + `PinClosure`'s
  pre-pin existence check both use
  `Query().Where(HashEQ(hash)).First(ctx)` with
  `ent.IsNotFound(err)` replacing `database.IsNotFoundError`.

Deferred (still on the original `c.db`/`qtx` API):

- `CheckAndFixNarInfo` and `lookupNarInfoForFix` (line 4282
  area) cascade into `niRow.URL.Valid`/`niRow.FileSize.Int64`
  consumers and into `checkAndFixNarInfoNoCompression`. That
  conversion needs to flow row shape changes through several
  helpers; left for a follow-up commit.
- The closure-pinning narinfo + references lookup (lines 6897,
  6907) reads `ni.ID` and feeds it back into
  `GetNarInfoReferences`. Same row-shape cascade — follow-up.
- Every `qtx.GetNarInfo*` site inside `c.executeTransaction`
  blocks (~6 sites) needs the transaction wrapper to first
  switch from `func(qtx database.Querier) error` to
  `func(tx *ent.Tx) error`. That's an infrastructure change
  pre-requisite, also follow-up.

Imports: adds `ent`, `entnarfile`, `entnarinfo`,
`entnarinfonarfile`. The legacy `database` import stays — most
of pkg/cache still references it.

Full -race test suite passes on SQLite + Postgres + MySQL with
the deps stack running. Lint clean.
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-to-ent branch from 2c22541 to 38fa3fa Compare May 22, 2026 17:39
@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:39
@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 4.94%. Comparing base (df2363d) to head (38fa3fa).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1193   +/-   ##
=====================================
  Coverage   4.94%   4.94%           
=====================================
  Files          6       6           
  Lines        445     445           
=====================================
  Hits          22      22           
  Misses       419     419           
  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 b5ecf38 into main May 22, 2026
18 checks passed
@kalbasit
kalbasit deleted the feat-cache-getnarinfo-to-ent branch May 22, 2026 17:52
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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant