Skip to content

feat(cache): convert pinned closures, stale-chunk orphans, narinfo CDC update to Ent - #1209

Merged
kalbasit merged 1 commit into
mainfrom
feat-cache-pinned-orphan-narinfocdc-ent
May 23, 2026
Merged

kalbasit merged 1 commit into
mainfrom
feat-cache-pinned-orphan-narinfocdc-ent

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

§11.5 first batch. Covers the standalone Querier sites in
pkg/cache that don't sit inside the LRU eviction transaction —
the pinned-closure CRUD, the stale-CDC-chunking orphan
cleanup, and the post-CDC-migration narinfo URL/compression
update. The bigger LRU + orphaned-nar_files + orphaned-chunks
block (calculateCleanupSize / deleteLRURecordsFromDB inside
runLRU) stays on the legacy Querier in this commit because
the legacy GetLeastUsedNarInfos is a correlated-subquery
cumulative-size SQL that doesn't translate cleanly to Ent's
fluent API. That conversion lands in a follow-up commit on
top of this one.

Converted:

  • Pinned closures (PinClosure, UnpinClosure,
    ListPinnedClosures, IsNarInfoPinned, GetPinnedClosureHashes
    list path):

    • PinClosure: legacy CreatePinnedClosure +
      IsDuplicateKeyError tolerance → Create(). OnConflictColumns(Hash).Ignore().Exec(ctx). SQL-level
      idempotency, no Go-level error tolerance (which would
      leave the transaction in an aborted state on Postgres).
    • UnpinClosure: legacy DeletePinnedClosure →
      Delete().Where(HashEQ).Exec(ctx).
    • ListPinnedClosures + GetPinnedClosureHashes:
      Query().All(ctx). Return type goes from
      []database.PinnedClosure to []*ent.PinnedClosure.
      The Ent struct exposes the same .Hash field used by
      both callers.
    • IsNarInfoPinned: legacy GetPinnedClosure +
      ErrNotFound branch → Query().Where(HashEQ).Exist(ctx).
      Cleaner: no row materialisation, no error-shape juggling.
  • Post-CDC narinfo URL/compression update
    (*Cache.swapToCDCNormalized, line ~7124): legacy
    UpdateNarInfoCompressionFileSizeHashAndURL → Ent's
    Update().Where(URL(old)).SetCompression(...).SetURL(...) .ClearFileSize().ClearFileHash().SetUpdatedAt(time.Now()) .Save(ctx). Matches the legacy "set both to NULL when CDC
    normalises to compression=none" behaviour via Ent's Clear
    setters.

  • Stale CDC chunking-lock cleanup
    (*Cache.cleanupStaleLockChunks, line ~2300):

    • GetOrphanedChunks → Chunk.Query().Where(Not(HasNarFileLinks())).
      Ent's edge-existence negation maps directly to the legacy
      LEFT JOIN nar_file_chunks WHERE chunk_id IS NULL.
    • DeleteChunkByID → Chunk.Delete().Where(IDEQ(oc.ID)).
    • staleByID map keyed by int (Ent PK type) instead of
      int64; the previous int64-keyed map existed only to
      bridge the legacy Querier surface.

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

@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
This was referenced 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.

@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch from 6c36682 to 359ac06 Compare May 22, 2026 21:29
kalbasit added a commit that referenced this pull request May 22, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the gs-comments-1191-1207 branch from 8252bff to 24f0de5 Compare May 22, 2026 21:41
@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch from 359ac06 to 9a4822a Compare May 22, 2026 21:41
kalbasit added a commit that referenced this pull request May 22, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the gs-comments-1191-1207 branch from 24f0de5 to c34e715 Compare May 22, 2026 21:54
@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch from 9a4822a to 2c4cc5e Compare May 22, 2026 21:54
kalbasit added a commit that referenced this pull request May 22, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the gs-comments-1191-1207 branch from c34e715 to 6dbd2cb Compare May 22, 2026 23:02
@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch from 2c4cc5e to 77dfc49 Compare May 22, 2026 23:02
kalbasit added a commit that referenced this pull request May 22, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the gs-comments-1191-1207 branch from 6dbd2cb to ff12dbd Compare May 22, 2026 23:15
@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch from 77dfc49 to 798092d Compare May 22, 2026 23:15
kalbasit added a commit that referenced this pull request May 22, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the gs-comments-1191-1207 branch from ff12dbd to 9d7d600 Compare May 22, 2026 23:28
@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch from 798092d to 46a0899 Compare May 22, 2026 23:28
kalbasit added a commit that referenced this pull request May 22, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the gs-comments-1191-1207 branch from 9d7d600 to 32ad08d Compare May 22, 2026 23:54
@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch from 46a0899 to c666a31 Compare May 22, 2026 23:54
kalbasit added a commit that referenced this pull request May 22, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the gs-comments-1191-1207 branch from 32ad08d to b33e76c Compare May 23, 2026 00:07
@kalbasit
kalbasit force-pushed the feat-cache-pinned-orphan-narinfocdc-ent branch 3 times, most recently from c666a31 to e5ed9c3 Compare May 23, 2026 00:07
kalbasit added a commit that referenced this pull request May 23, 2026
Restrict the orphan-check query inside cleanupStaleLockChunks to the chunk
IDs we already know about from staleLockChunks, instead of pulling every
orphan in the database and filtering them in memory. The post-filter
`if _, ok := staleByID[oc.ID]; !ok` is no longer needed since the query
already returns only candidates.

Addresses gemini-code-assist comment on PR #1209 (PRRT_kwDONV6tZs6D3VF-).

Co-Authored-By: Claude Opus 4.7 <[email protected]>

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

🧹 Nitpick comments (1)
pkg/cache/cache.go (1)

7318-7319: ⚡ Quick win

Keep ListPinnedClosures on a cache-level type.

This exported method now leaks *ent.PinnedClosure to callers, which turns an internal Ent migration into a public API change and couples the cache layer to ORM-generated types. Mapping the rows back to the previous cache/database shape keeps the migration internal.

♻️ Suggested shape-preserving change
-func (c *Cache) ListPinnedClosures(ctx context.Context) ([]*ent.PinnedClosure, error) {
-	closures, err := c.dbClient.Ent().PinnedClosure.Query().All(ctx)
+func (c *Cache) ListPinnedClosures(ctx context.Context) ([]database.PinnedClosure, error) {
+	rows, err := c.dbClient.Ent().PinnedClosure.Query().All(ctx)
 	if err != nil {
 		return nil, fmt.Errorf("failed to list pinned closures: %w", err)
 	}
 
+	closures := make([]database.PinnedClosure, len(rows))
+	for i, row := range rows {
+		closures[i] = database.PinnedClosure{Hash: row.Hash}
+	}
+
 	return closures, nil
 }
🤖 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 7318 - 7319, The exported method
ListPinnedClosures on type Cache currently returns []*ent.PinnedClosure and thus
leaks the ORM type; change its signature to return the cache-level shape (e.g.,
[]PinnedClosure or the existing internal struct used elsewhere) and keep the ent
types internal. In the implementation of ListPinnedClosures (where it calls
c.dbClient.Ent().PinnedClosure.Query().All(ctx)), iterate the returned
[]*ent.PinnedClosure and map each row into the cache/local PinnedClosure struct
(copy fields, convert ids/timestamps as needed), then return the slice of those
cache structs and any error; keep all ent.* types confined to this function so
callers never see *ent.PinnedClosure.
🤖 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.

Nitpick comments:
In `@pkg/cache/cache.go`:
- Around line 7318-7319: The exported method ListPinnedClosures on type Cache
currently returns []*ent.PinnedClosure and thus leaks the ORM type; change its
signature to return the cache-level shape (e.g., []PinnedClosure or the existing
internal struct used elsewhere) and keep the ent types internal. In the
implementation of ListPinnedClosures (where it calls
c.dbClient.Ent().PinnedClosure.Query().All(ctx)), iterate the returned
[]*ent.PinnedClosure and map each row into the cache/local PinnedClosure struct
(copy fields, convert ids/timestamps as needed), then return the slice of those
cache structs and any error; keep all ent.* types confined to this function so
callers never see *ent.PinnedClosure.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bf4c1f7b-8036-486e-b702-751ed9ed5a84

📥 Commits

Reviewing files that changed from the base of the PR and between b1a01ac and 3c96983.

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

…C update to Ent

§11.5 first batch. Covers the standalone Querier sites in
pkg/cache that don't sit inside the LRU eviction transaction —
the pinned-closure CRUD, the stale-CDC-chunking orphan
cleanup, and the post-CDC-migration narinfo URL/compression
update. The bigger LRU + orphaned-nar_files + orphaned-chunks
block (calculateCleanupSize / deleteLRURecordsFromDB inside
runLRU) stays on the legacy Querier in this commit because
the legacy `GetLeastUsedNarInfos` is a correlated-subquery
cumulative-size SQL that doesn't translate cleanly to Ent's
fluent API. That conversion lands in a follow-up commit on
top of this one.

Converted:

- Pinned closures (PinClosure, UnpinClosure,
  ListPinnedClosures, IsNarInfoPinned, GetPinnedClosureHashes
  list path):

  * `PinClosure`: legacy CreatePinnedClosure +
    IsDuplicateKeyError tolerance → `Create().
    OnConflictColumns(Hash).Ignore().Exec(ctx)`. SQL-level
    idempotency, no Go-level error tolerance (which would
    leave the transaction in an aborted state on Postgres).
  * `UnpinClosure`: legacy DeletePinnedClosure →
    `Delete().Where(HashEQ).Exec(ctx)`.
  * `ListPinnedClosures` + `GetPinnedClosureHashes`:
    `Query().All(ctx)`. Return type goes from
    `[]database.PinnedClosure` to `[]*ent.PinnedClosure`.
    The Ent struct exposes the same `.Hash` field used by
    both callers.
  * `IsNarInfoPinned`: legacy GetPinnedClosure +
    ErrNotFound branch → `Query().Where(HashEQ).Exist(ctx)`.
    Cleaner: no row materialisation, no error-shape juggling.

- Post-CDC narinfo URL/compression update
  (`*Cache.swapToCDCNormalized`, line ~7124): legacy
  UpdateNarInfoCompressionFileSizeHashAndURL → Ent's
  `Update().Where(URL(old)).SetCompression(...).SetURL(...)
  .ClearFileSize().ClearFileHash().SetUpdatedAt(time.Now())
  .Save(ctx)`. Matches the legacy "set both to NULL when CDC
  normalises to compression=none" behaviour via Ent's Clear
  setters.

- Stale CDC chunking-lock cleanup
  (`*Cache.cleanupStaleLockChunks`, line ~2300):

  * `GetOrphanedChunks` → `Chunk.Query().Where(Not(HasNarFileLinks()))`.
    Ent's edge-existence negation maps directly to the legacy
    LEFT JOIN nar_file_chunks WHERE chunk_id IS NULL.
  * `DeleteChunkByID` → `Chunk.Delete().Where(IDEQ(oc.ID))`.
  * `staleByID` map keyed by `int` (Ent PK type) instead of
    `int64`; the previous int64-keyed map existed only to
    bridge the legacy Querier surface.

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

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@abbdbe8). Learn more about missing BASE report.

Additional details and impacted files
@@          Coverage Diff           @@
##             main   #1209   +/-   ##
======================================
  Coverage        ?   5.68%           
======================================
  Files           ?       6           
  Lines           ?     387           
  Branches        ?       0           
======================================
  Hits            ?      22           
  Misses          ?     361           
  Partials        ?       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.

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