Skip to content

feat(cache): convert remaining GetNarInfo* read paths to Ent - #1199

Merged
kalbasit merged 2 commits into
mainfrom
feat-cache-getnarinfo-ent-finish
May 22, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-cache-getnarinfo-ent-finish

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

feat(cache): convert remaining GetNarInfo* read paths to Ent

§11.2 completion. Three call sites that were left unconverted
by the prior commits because they read row fields downstream
(the "row-shape cascade") and so couldn't move in isolation.
All three now run through the Ent fluent API.

  • getNarInfoFromStore (line 3699): inside-tx GetNarInfoByHash

    • TouchNarInfo path. Switched from c.withTransaction
      (qtx-style) to c.withEntTransaction (Ent-tx style). The
      TouchNarInfo call becomes
      tx.NarInfo.Update().Where(HashEQ).SetLastAccessedAt(time.Now()) .Save(ctx), matching the same pattern populateNarInfoFromDatabase
      uses for touch.
  • CheckAndFixNarInfo + checkAndFixNarInfoNoCompression (line
    4285): consumes the entire narinfo row to inspect URL,
    FileSize, FileHash. Now reads from *ent.NarInfo (pointer
    fields) via the new derefInt64Ptr helper and direct
    pointer dereferences. The two "fix to NULL" paths in
    checkAndFixNarInfoNoCompression use
    tx.NarInfo.Update().ClearFileSize() / .ClearFileHash()
    to set the columns NULL — Ent's idiomatic way to do what
    UpdateNarInfoFileSize/UpdateNarInfoFileHash did with
    sql.NullInt64/sql.NullString{Valid: false}.

  • Closure-pinning BFS (line 7002): combines GetNarInfoByHash +
    GetNarInfoReferences(narinfo.ID) into one round-trip via
    tx.NarInfo.Query().Where(HashEQ).WithReferences().Only(ctx),
    iterating ni.Edges.References directly. Avoids the surrogate-id
    lookup the legacy path needed (sqlc's GetNarInfoReferences
    takes narinfo_id, which is irrelevant under Ent's edge model).

After this commit no c.db.GetNarInfo* or qtx.GetNarInfo*
call site remains in pkg/cache — §11.2 is complete and tasks.md
gets ticked. The same downstream-row-shape pattern (deref helpers

  • Ent UpdateOne mutators) will be reused for §11.3 (PutNarInfo)
    and §11.4 (GetNarFile).

go test -race ./pkg/cache/... passes against SQLite + Postgres +
MySQL + Redis. Lint clean.

docs(openspec): mark §11.2 tasks complete

§11.2 (Convert GetNarInfo* paths in pkg/cache/ to Ent fluent
API) finished across feat-cache-getnarinfo-to-ent, feat-cache-
populate-narinfo-ent, and feat-cache-getnarinfo-ent-finish. No
c.db.GetNarInfo* or qtx.GetNarInfo* call site remains
in pkg/cache.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 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-populate-narinfo-ent branch from d8ee4c7 to b1c416c Compare May 22, 2026 07:06
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-ent-finish branch from b8748eb to 15cfae6 Compare May 22, 2026 07:06
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from b1c416c to 3724df5 Compare May 22, 2026 18:07
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-ent-finish branch from 15cfae6 to fca78b0 Compare May 22, 2026 18:07
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Chores
    • Updated internal database infrastructure to improve system reliability and performance.

Walkthrough

Migrates narinfo DB access in pkg/cache from sqlc/legacy queries to Ent ORM (fetch/touch, validation/fix, pinned-closure traversal) and marks the related migration checklist item complete.

Changes

Cache layer Ent ORM migration

Layer / File(s) Summary
NarInfo fetch and update in getNarInfoFromStore
pkg/cache/cache.go
getNarInfoFromStore moves narinfo lookup and "touch" updates from legacy withTransaction(qtx Querier) to withEntTransaction(tx *ent.Tx), using Ent nullable pointer checks (ni.URL == nil) and Ent Update().SetLastAccessedAt(...).
NarInfo lookup and validation in CheckAndFixNarInfo
pkg/cache/cache.go
Initial narinfo fetch switches to Ent NarInfo.Query().Where(...).Only(ctx); early-return when URL is nil; size-mismatch logging uses dereferenced Ent nullable FileSize; checkAndFixNarInfoNoCompression now accepts *ent.NarInfo and clears FileSize/FileHash via Ent update inside withEntTransaction.
Pinned closure reference traversal in GetPinnedClosureHashes
pkg/cache/cache.go
BFS traversal replaces multiple legacy queries with a single Ent query per hash using WithReferences() and enqueues transitive references from ni.Edges.References.
Mark cache migration task as completed
openspec/changes/migrate-to-ent-and-atlas/tasks.md
Checklist task 11.2 ("Convert GetNarInfo* paths in pkg/cache/ to Ent fluent API; run package tests") is marked complete.

Estimated code review effort:
🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1198: Modifies pkg/cache/cache.go to use withEntTransaction and Ent-based narinfo touch logic; closely related migration work.
  • kalbasit/ncps#1194: Introduces or expands the withEntTransaction helper used to run cache operations in Ent transactions.
  • kalbasit/ncps#1193: Concurrently migrates additional GetNarInfo* narinfo lookup logic to Ent ORM in pkg/cache/cache.go.

Suggested labels

enhancement

Poem

🐇 I hopped from SQL to Ent today,
Nullable pointers led the way,
I touched the rows and fixed the size,
Followed edges to their ties,
Carrots for tests — let's run and play!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title directly matches the main change: converting remaining GetNarInfo* read paths in pkg/cache to Ent.
Description check ✅ Passed The PR description is detailed and clearly related to the changeset, explaining the three conversion sites and the completed §11.2 objectives.
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-populate-narinfo-ent branch from 3724df5 to 1a69830 Compare May 22, 2026 19:02
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-ent-finish branch from fca78b0 to 3ab6f68 Compare May 22, 2026 19:02

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

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/cache/cache.go`:
- Around line 4353-4386: The helper checkAndFixNarInfoNoCompression currently
only clears FileSize/FileHash when they are non-zero/non-empty; change it to
clear any non-NULL value (including 0 and "") so rows with zero/empty values are
normalized to NULL. Specifically, in checkAndFixNarInfoNoCompression inspect
niRow.FileSize and niRow.FileHash for != nil (not for != 0 / != ""), log the
current value, and call c.withEntTransaction (same "fixNarInfoFileSizeToNull" /
"fixNarInfoFileHashToNull" update blocks that use
tx.NarInfo.Update().Where(entnarinfo.HashEQ(hash)).ClearFileSize()/ClearFileHash().Save(ctx))
to clear them unconditionally when non-nil.
🪄 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: 8680b49b-aa22-49fc-9827-bb5fd312a180

📥 Commits

Reviewing files that changed from the base of the PR and between 1a69830 and 3ab6f68.

📒 Files selected for processing (2)
  • openspec/changes/migrate-to-ent-and-atlas/tasks.md
  • pkg/cache/cache.go

Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from 1a69830 to d394450 Compare May 22, 2026 20:44
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-ent-finish branch from 3ab6f68 to 9949687 Compare May 22, 2026 20:44
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from d394450 to dfd6326 Compare May 22, 2026 20:51
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-ent-finish branch from 9949687 to 8f24530 Compare May 22, 2026 20:51
@kalbasit
kalbasit force-pushed the feat-cache-populate-narinfo-ent branch from dfd6326 to 6589260 Compare May 22, 2026 21:04
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-ent-finish branch from 8f24530 to 8d9fd40 Compare May 22, 2026 21:04
Base automatically changed from feat-cache-populate-narinfo-ent to main May 22, 2026 21:16
@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
kalbasit added 2 commits May 22, 2026 21:16
§11.2 completion. Three call sites that were left unconverted
by the prior commits because they read row fields downstream
(the "row-shape cascade") and so couldn't move in isolation.
All three now run through the Ent fluent API.

- `getNarInfoFromStore` (line 3699): inside-tx GetNarInfoByHash
  + TouchNarInfo path. Switched from c.withTransaction
  (qtx-style) to c.withEntTransaction (Ent-tx style). The
  TouchNarInfo call becomes
  `tx.NarInfo.Update().Where(HashEQ).SetLastAccessedAt(time.Now())
  .Save(ctx)`, matching the same pattern populateNarInfoFromDatabase
  uses for touch.

- `CheckAndFixNarInfo` + `checkAndFixNarInfoNoCompression` (line
  4285): consumes the entire narinfo row to inspect URL,
  FileSize, FileHash. Now reads from `*ent.NarInfo` (pointer
  fields) via the new `derefInt64Ptr` helper and direct
  pointer dereferences. The two "fix to NULL" paths in
  checkAndFixNarInfoNoCompression use
  `tx.NarInfo.Update().ClearFileSize()` / `.ClearFileHash()`
  to set the columns NULL — Ent's idiomatic way to do what
  `UpdateNarInfoFileSize`/`UpdateNarInfoFileHash` did with
  sql.NullInt64/sql.NullString{Valid: false}.

- Closure-pinning BFS (line 7002): combines GetNarInfoByHash +
  GetNarInfoReferences(narinfo.ID) into one round-trip via
  `tx.NarInfo.Query().Where(HashEQ).WithReferences().Only(ctx)`,
  iterating `ni.Edges.References` directly. Avoids the surrogate-id
  lookup the legacy path needed (sqlc's GetNarInfoReferences
  takes narinfo_id, which is irrelevant under Ent's edge model).

After this commit no `c.db.GetNarInfo*` or `qtx.GetNarInfo*`
call site remains in pkg/cache — §11.2 is complete and tasks.md
gets ticked. The same downstream-row-shape pattern (deref helpers
+ Ent UpdateOne mutators) will be reused for §11.3 (PutNarInfo)
and §11.4 (GetNarFile).

`go test -race ./pkg/cache/...` passes against SQLite + Postgres +
MySQL + Redis. Lint clean.
§11.2 (Convert GetNarInfo* paths in pkg/cache/ to Ent fluent
API) finished across feat-cache-getnarinfo-to-ent, feat-cache-
populate-narinfo-ent, and feat-cache-getnarinfo-ent-finish. No
`c.db.GetNarInfo*` or `qtx.GetNarInfo*` call site remains
in pkg/cache.
@kalbasit
kalbasit force-pushed the feat-cache-getnarinfo-ent-finish branch from 8d9fd40 to ac82cc7 Compare May 22, 2026 21:16
@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 21:17

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

♻️ Duplicate comments (1)
pkg/cache/cache.go (1)

4353-4388: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Clear non-NULL compression=none metadata even when it is zero/empty.

Line 4355 and Line 4374 only repair file_size / file_hash when the stored value is non-zero / non-empty. Rows that already contain 0 or "" stay non-NULL forever, so this repair never fully normalizes legacy data.

Suggested fix
-	if niRow.FileSize != nil && *niRow.FileSize != 0 {
+	if niRow.FileSize != nil {
 		zerolog.Ctx(ctx).
 			Info().
 			Int64("current_size", *niRow.FileSize).
 			Msg("mismatch detected for compression=none, fixing narinfo file size to NULL")
@@
-	if niRow.FileHash != nil && *niRow.FileHash != "" {
+	if niRow.FileHash != nil {
 		zerolog.Ctx(ctx).
 			Info().
 			Str("current_file_hash", *niRow.FileHash).
 			Msg("mismatch detected for compression=none, fixing narinfo file hash to NULL")
🤖 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 4353 - 4388, The
checkAndFixNarInfoNoCompression function only clears FileSize/FileHash when
values are non-zero/non-empty, leaving zero or empty pointers non-NULL; change
the guards to clear whenever the pointer is non-nil (i.e., use niRow.FileSize !=
nil and niRow.FileHash != nil) so rows with 0 or "" get set to NULL too, keep
the existing logging (dereference safely) and the withEntTransaction calls
(fixNarInfoFileSizeToNull, fixNarInfoFileHashToNull) as-is to perform the
update.
🤖 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.

Duplicate comments:
In `@pkg/cache/cache.go`:
- Around line 4353-4388: The checkAndFixNarInfoNoCompression function only
clears FileSize/FileHash when values are non-zero/non-empty, leaving zero or
empty pointers non-NULL; change the guards to clear whenever the pointer is
non-nil (i.e., use niRow.FileSize != nil and niRow.FileHash != nil) so rows with
0 or "" get set to NULL too, keep the existing logging (dereference safely) and
the withEntTransaction calls (fixNarInfoFileSizeToNull,
fixNarInfoFileHashToNull) as-is to perform the update.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e55be3f1-f809-45b9-bcef-266338172c19

📥 Commits

Reviewing files that changed from the base of the PR and between 9949687 and ac82cc7.

📒 Files selected for processing (2)
  • openspec/changes/migrate-to-ent-and-atlas/tasks.md
  • pkg/cache/cache.go
✅ Files skipped from review due to trivial changes (1)
  • openspec/changes/migrate-to-ent-and-atlas/tasks.md

@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 (7c26ac7) to head (ac82cc7).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1199   +/-   ##
=====================================
  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 c7b53ee into main May 22, 2026
18 checks passed
@kalbasit
kalbasit deleted the feat-cache-getnarinfo-ent-finish branch May 22, 2026 21:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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