Skip to content

refactor(cache): extract repeated Ent query helpers - #1286

Merged
kalbasit merged 2 commits into
mainfrom
refactor/extract-cache-query-helpers
May 29, 2026
Merged

kalbasit merged 2 commits into
mainfrom
refactor/extract-cache-query-helpers

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

pkg/cache/cache.go (~7,500 lines) inlined the same Ent queries repeatedly: the single NarInfo-by-hash lookup at several sites against both the client and *ent.Tx, two chunk-by-hashes batch reads, and the total-NAR-size aggregate (SUM(file_size) + sql.NullInt64 unpack) duplicated as a multi-line block at two call sites.

  • Add pkg/cache/queries.go with three unexported helpers — narInfoByHash, chunksByHashes, totalNarFileSize — that take the Ent entity client (*ent.NarInfoClient etc.), which both *ent.Client and *ent.Tx expose, so one helper serves transactional and non-transactional callers.
  • Replace only the byte-identical inline sites; eager-loaded / multi-predicate variants are left untouched.
  • totalNarFileSize returns (int64, error) so each caller keeps its own error policy (metrics warns and continues; cleanup returns).
  • Behavior-preserving: identical SQL and error semantics. Dropped the now-unused database/sql import from cache.go; added two justified gosec nolints on uint64(narTotalSize) (file_size is a uint64 column, so the SUM is non-negative).

Test plan

  • task fmt / task lint (0 issues) / task test (full suite green; pkg/cache ~30s)
  • Existing cache suite covers get/insert-by-hash, chunk batch reads, and cleanup/metrics size paths

@kalbasit

kalbasit commented May 29, 2026 •

Copy link
Copy Markdown
Owner Author

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. go Pull requests that update go code labels May 29, 2026
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kalbasit, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 9 minutes and 47 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 57942720-9d21-4847-8e9c-128dcca1752b

📥 Commits

Reviewing files that changed from the base of the PR and between 8a4b3eb and d887e91.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-05-29-extract-cache-query-helpers/.openspec.yaml
  • openspec/changes/archive/2026-05-29-extract-cache-query-helpers/design.md
  • openspec/changes/archive/2026-05-29-extract-cache-query-helpers/proposal.md
  • openspec/changes/archive/2026-05-29-extract-cache-query-helpers/specs/database-orm/spec.md
  • openspec/changes/archive/2026-05-29-extract-cache-query-helpers/tasks.md
  • openspec/specs/database-orm/spec.md
  • pkg/cache/cache.go
  • pkg/cache/queries.go
📝 Walkthrough

Walkthrough

This PR extracts three duplicated Ent query patterns from pkg/cache/cache.go into reusable helper functions in a new pkg/cache/queries.go, replacing inline queries across multiple cache operations while preserving all semantics and error handling.

Changes

Cache Query Helper Refactor

Layer / File(s) Summary
Specification and Design
openspec/changes/archive/2026-05-29-extract-cache-query-helpers/.openspec.yaml, openspec/changes/archive/2026-05-29-extract-cache-query-helpers/design.md, openspec/changes/archive/2026-05-29-extract-cache-query-helpers/proposal.md, openspec/changes/archive/2026-05-29-extract-cache-query-helpers/specs/database-orm/spec.md, openspec/changes/archive/2026-05-29-extract-cache-query-helpers/tasks.md, openspec/specs/database-orm/spec.md
Specification files and design documentation define the scope of extracting three duplicated Ent query patterns into helpers (by-hash NarInfo lookup, batch Chunk reads, total NAR file-size aggregation), their signatures accepting entity clients for both transactional and non-transactional use, expected semantics including not-found error propagation and null-safe zero return for aggregates, and the refactoring task checklist.
Query Helper Functions
pkg/cache/queries.go
New file adds three unexported helpers: narInfoByHash for single-row by-hash lookup, chunksByHashes for multi-row hash-list lookup, and totalNarFileSize for aggregating file-size sum with null-safe zero return, each accepting an appropriate Ent entity client parameter.
Cache Refactoring Integration
pkg/cache/cache.go
Refactors multiple functions to use the new query helpers: removes database/sql import, updates metric callbacks and calculateCleanupSize to use totalNarFileSize, updates recordChunkBatch to use chunksByHashes for existing and newly-inserted chunk IDs, and updates getNarInfoFromStore, upsertNarInfoFromParsed, and CheckAndFixNarInfo to use narInfoByHash, preserving all caller-specific error handling and metrics behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1279: Alters getNarInfoFromDatabase-adjacent NarInfo lookup behavior; related to this PR's narinfo-by-hash extraction.
  • kalbasit/ncps#1199: Refactors NarInfo lookup and repair flows in pkg/cache, overlapping the sites updated here to use narInfoByHash.
  • kalbasit/ncps#1204: Modifies total NAR size aggregation in setupMetricCallbacks/cleanup sizing, related to this PR's totalNarFileSize extraction.

Suggested labels

enhancement, size:M, merge-stack

Poem

🐰 Hopped through code with nimble paws so light,
Pulled three queries out and put them right,
By hash, by hashes, and total size too—
Cleaner cache paths, nothing broke, nothing new.
A tiny refactor, tidy and spry. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: extracting repeated Ent query helpers from pkg/cache/cache.go into a new queries.go file, which is the core focus of this refactoring PR.
Description check ✅ Passed The description is directly related to the changeset, explaining the rationale for extraction, the three helpers being added, their signatures, replacement strategy, and test validation—all of which align with the files modified in the PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.


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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors pkg/cache/cache.go by extracting duplicated inline Ent queries into shared, unexported helper functions in a new file pkg/cache/queries.go. Specifically, it introduces narInfoByHash, chunksByHashes, and totalNarFileSize helpers that accept Ent entity clients, enabling seamless reuse across both transactional and non-transactional callers. The review feedback suggests a valuable optimization in chunksByHashes to return early when the input slice of hashes is empty, preventing unnecessary database queries and potential dialect-specific SQL errors.

Comment thread pkg/cache/queries.go Resolved
kalbasit added a commit that referenced this pull request May 29, 2026
Return early with no rows when the hashes slice is empty, rather than
issuing a query with an empty SQL IN (). For the current callers this
case is unreachable (recordChunkBatch early-returns on an empty batch,
and newHashes is built only inside len(creates) > 0), but guarding the
shared helper's contract avoids a needless round-trip and the
dialect-specific pitfalls of an empty IN for any future caller.

Addresses review comment on PR #1286 (thread PRRT_kwDONV6tZs6FvzoU).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Base automatically changed from refactor/consolidate-dialect-mappers to main May 29, 2026 17:54
kalbasit and others added 2 commits May 29, 2026 17:54
cache.go (~7,500 lines) inlined the same Ent queries repeatedly: the
single NarInfo-by-hash lookup at several sites against both the client
and *ent.Tx, two chunk-by-hashes batch reads, and the total-NAR-size
aggregate (SUM(file_size) + sql.NullInt64 unpack) duplicated as a
multi-line block at two call sites.

Add pkg/cache/queries.go with three unexported helpers —
narInfoByHash, chunksByHashes, totalNarFileSize — that take the Ent
entity client (*ent.NarInfoClient etc.), which both *ent.Client and
*ent.Tx expose, so one helper serves transactional and
non-transactional callers. Replace only the byte-identical inline
sites; eager-loaded and multi-predicate variants are left untouched.
totalNarFileSize returns (int64, error) so each caller keeps its own
error policy (metrics warns and continues; cleanup returns the error).

Behavior-preserving: identical SQL and error semantics. Dropped the
now-unused database/sql import from cache.go and added two justified
gosec nolints on uint64(narTotalSize) (file_size is a uint64 column,
so the SUM is non-negative). Records a database-orm spec requirement
for the shared-helper contract.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Return early with no rows when the hashes slice is empty, rather than
issuing a query with an empty SQL IN (). For the current callers this
case is unreachable (recordChunkBatch early-returns on an empty batch,
and newHashes is built only inside len(creates) > 0), but guarding the
shared helper's contract avoids a needless round-trip and the
dialect-specific pitfalls of an empty IN for any future caller.

Addresses review comment on PR #1286 (thread PRRT_kwDONV6tZs6FvzoU).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the refactor/extract-cache-query-helpers branch from 8a4b3eb to d887e91 Compare May 29, 2026 17:54
@kalbasit
kalbasit enabled auto-merge (squash) May 29, 2026 17:54
@kalbasit
kalbasit merged commit bbc6808 into main May 29, 2026
35 of 43 checks passed
@kalbasit
kalbasit deleted the refactor/extract-cache-query-helpers branch May 29, 2026 18:42
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: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