Skip to content

feat: add closure pinning to protect narinfos from LRU eviction - #1108

Merged
kalbasit merged 5 commits into
mainfrom
feat-add-closure-pinning-to
Mar 18, 2026
Merged

kalbasit merged 5 commits into
mainfrom
feat-add-closure-pinning-to

Conversation

@kalbasit

@kalbasit kalbasit commented Mar 18, 2026 •

Copy link
Copy Markdown
Owner

This adds the ability to pin closures (narinfo + all transitive references) to
protect them from LRU eviction. The implementation includes:

  • New 'pinned_closures' database table to store pinned narinfo hashes
  • New cache methods: PinClosure, UnpinClosure, ListPinnedClosures, IsNarInfoPinned
  • GetPinnedClosureHashes to compute transitive closure at eviction time
  • Modified LRU eviction to exclude pinned closures and their references
  • New HTTP endpoints: POST/DELETE /pin/{hash}.narinfo, GET /pins

The reference format -- is handled by extracting the
first 52 characters (Nix base32 hash) when traversing the closure graph.

ref #1021

@kalbasit

kalbasit commented Mar 18, 2026 •

Copy link
Copy Markdown
Owner Author

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code labels Mar 18, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant new feature allowing users to protect specific data closures from being evicted by the cache's LRU mechanism. This is achieved through a new database table to track pinned items, updated cache logic to respect these pins during eviction, and a set of new API endpoints for users to manage their pinned closures. The changes ensure that essential data can be reliably retained in the cache, enhancing data availability and system stability for critical dependencies.

Highlights

  • Closure Pinning Feature: Introduced the ability to 'pin' closures (narinfo and all its transitive references) to protect them from LRU (Least Recently Used) eviction, ensuring critical data remains in the cache.
  • Database Schema and Queries: Added a new pinned_closures table across MySQL, PostgreSQL, and SQLite databases to store pinned narinfo hashes, along with corresponding CRUD (Create, Read, Update, Delete) SQL queries.
  • Cache Layer Enhancements: Implemented new cache methods including PinClosure, UnpinClosure, ListPinnedClosures, IsNarInfoPinned, and GetPinnedClosureHashes to manage pinned closures and compute their transitive references during eviction.
  • LRU Eviction Logic Update: Modified the LRU eviction process to identify and exclude narinfos that are part of a pinned closure, preventing their removal from the cache.
  • New HTTP API Endpoints: Exposed new HTTP endpoints: POST /pin/{hash}.narinfo to pin a closure, DELETE /pin/{hash}.narinfo to unpin, and GET /pins to list all currently pinned closures.
  • Comprehensive Testing: Added extensive unit and integration tests covering pinning/unpinning operations, closure computation, HTTP endpoint functionality, and verification that LRU eviction correctly skips pinned items.
  • Design and Specification Documents: Included detailed design, proposal, and specification documents outlining the context, goals, decisions, risks, and requirements for the closure pinning feature.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@dosubot

dosubot Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

Documentation Updates

2 document(s) were updated by changes in this PR:

OpenTelemetry Instrumentation and Metrics
View Changes
@@ -135,6 +135,8 @@
 - `ncps_lru_chunks_evicted_total`: Counter tracking the total number of CDC chunks evicted by the LRU policy.
 - `ncps_lru_bytes_freed_total`: Counter tracking the total bytes freed by LRU eviction operations.
 
+**Note on Pinned Closures**: Closures can be pinned to protect them from LRU eviction. The LRU eviction metrics above only count items that were actually evicted and do not include items protected by pinning. Before eviction, the LRU process computes the transitive closure graph of all pinned narinfos using breadth-first search (BFS) traversal with a maximum depth of 1000 levels. Any narinfo in the pinned closure set and all its transitive references are excluded from eviction candidates. If the maximum traversal depth is reached during closure computation, a warning is logged indicating that some pinned references may not be fully protected.
+
 #### Upstream Fetch Duration Metrics
 
 - `ncps_upstream_narinfo_fetch_duration`: Histogram measuring the duration of NarInfo fetch operations from upstream caches, enabling latency analysis.
@@ -146,6 +148,24 @@
 
 ### Tracing Spans for NAR and NarInfo Operations
 In addition to tracing spans for NAR and NarInfo operations, lock operations are now instrumented with OpenTelemetry metrics. Both local and distributed (Redis-based) lock implementations record metrics for acquisition attempts, contention, failures (with detailed reasons), retry attempts, and lock hold durations. While lock operations do not create tracing spans, the emitted metrics provide fine-grained observability into lock behavior, including contention events and failure diagnostics for distributed systems.
+
+### Tracing Spans for Closure Pinning Operations
+The closure pinning feature provides HTTP endpoints for protecting closures from LRU eviction and is instrumented with OpenTelemetry tracing. The following tracing spans are created for pin operations:
+
+- `server.pinClosure`: Traces the pinning of a closure and all its transitive references, with attribute `narinfo_hash` indicating the root hash being pinned.
+- `server.unpinClosure`: Traces the unpinning of a closure, with attribute `narinfo_hash` indicating the hash being unpinned. This operation is idempotent.
+- `server.listPins`: Traces the listing of all currently pinned closures.
+
+These spans provide detailed observability into pinning operations, including request timing, success/failure status, and the specific hashes being managed. The spans follow standard HTTP server span conventions with `SpanKindServer` and are integrated into the broader OpenTelemetry trace context.
+
+#### Closure Pinning HTTP Endpoints
+The following HTTP endpoints are available for managing pinned closures:
+
+- `POST /pin/{hash}.narinfo`: Pin a closure by its narinfo hash. The specified narinfo and all its transitive references will be protected from LRU eviction. Returns HTTP 404 if the narinfo does not exist in the cache, or HTTP 200 if successfully pinned (idempotent operation).
+- `DELETE /pin/{hash}.narinfo`: Unpin a closure by its narinfo hash. This operation is idempotent and returns HTTP 200 whether or not the closure was previously pinned.
+- `GET /pins`: List all currently pinned closures. Returns a JSON array of narinfo hashes (e.g., `["hash1", "hash2"]`).
+
+When a closure is pinned, the LRU eviction process excludes the pinned narinfo and all its transitive references from eviction candidates. The closure graph is computed using breadth-first search traversal with a maximum depth of 1000 levels to prevent runaway recursion on circular or very deep dependency graphs.
 
 ### Enabling and Accessing Observability Features
 To enable tracing, metrics, and profiling:
Prometheus Metrics Integration
View Changes
@@ -49,6 +49,8 @@
 
 These metrics help track cache cleanup activity and understand how effectively the LRU policy is managing disk space.
 
+**Pinned Closures and LRU Eviction**: Pinned closures and all their transitive references are automatically excluded from LRU eviction candidates. When a closure is pinned via `POST /pin/{hash}.narinfo`, the narinfo and all packages it references (recursively) are protected from eviction. The LRU eviction metrics above count only items that were successfully evicted and do not include any pinned items that were skipped during the eviction process. If the LRU process is unable to meet its cleanup size targets, this may indicate that too many closures are pinned, leaving insufficient reclaimable space in the cache.
+
 #### Cache Utilization Metrics
 
 - `ncps_cache_utilization_ratio`: Gauge indicating the current cache utilization as a ratio (current size / max size).
@@ -68,6 +70,16 @@
 - `ncps_background_migration_objects_total`: Count of objects (narinfos) migrated from legacy storage to the database in the background.
 
 This counter tracks the progress of background migration operations for legacy narinfo storage [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/cache/cache.go#L1-L1887).
+
+#### Monitoring Pinned Closures
+
+The server provides HTTP endpoints for managing and inspecting pinned closures:
+
+- `POST /pin/{hash}.narinfo` - Pin a closure by its narinfo hash to protect it and all its transitive references from LRU eviction.
+- `DELETE /pin/{hash}.narinfo` - Unpin a previously pinned closure, making it eligible for eviction again.
+- `GET /pins` - List all currently pinned closure hashes. Returns a JSON array of hash strings.
+
+**Note on Metrics**: Currently, there are no built-in Prometheus metrics specifically tracking the count of pinned closures or pinning/unpinning operations. Users who need to monitor the number of pinned closures can implement custom metrics by periodically polling the `GET /pins` endpoint and recording the count. If the LRU eviction process logs warnings about being unable to meet cleanup size targets, this often indicates that a large portion of the cache is protected by pinned closures, and you may want to review your pinning strategy or increase cache capacity.
 
 ### Instrumentation with OpenTelemetry
 

How did I do? Any feedback?  Join Discord

@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 introduces a valuable feature for pinning closures to prevent LRU eviction. The implementation is comprehensive, adding database migrations, new API endpoints, and updating the cache logic. The code is well-structured and includes tests for the new functionality.

My review focuses on a couple of areas. The main point is a deviation from the provided specification in the PinClosure implementation, which currently doesn't validate the existence of a narinfo before pinning or fetch the full closure as required. I've provided a suggestion to address the validation part. Additionally, I've included a medium-severity comment regarding the robustness of the LRU eviction logic when dealing with a high number of pinned items.

Overall, this is a solid implementation of a complex feature, and addressing these points will make it even more robust and compliant with the design.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Base automatically changed from fix-openspec-specs-are-not-found to main March 18, 2026 08:05
@kalbasit
kalbasit force-pushed the feat-add-closure-pinning-to branch from 17096c6 to 9c5b701 Compare March 18, 2026 08:22
This adds the ability to pin closures (narinfo + all transitive references) to
protect them from LRU eviction. The implementation includes:

- New 'pinned_closures' database table to store pinned narinfo hashes
- New cache methods: PinClosure, UnpinClosure, ListPinnedClosures, IsNarInfoPinned
- GetPinnedClosureHashes to compute transitive closure at eviction time
- Modified LRU eviction to exclude pinned closures and their references
- New HTTP endpoints: POST/DELETE /pin/{hash}.narinfo, GET /pins

The reference format <hash>-<name>-<version> is handled by extracting the
first 52 characters (Nix base32 hash) when traversing the closure graph.
@kalbasit
kalbasit force-pushed the feat-add-closure-pinning-to branch from 9c5b701 to d5c5119 Compare March 18, 2026 16:34
@kalbasit
kalbasit enabled auto-merge (squash) March 18, 2026 16:35
@kalbasit

Copy link
Copy Markdown
Owner Author

/gemini review

@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

The pull request introduces closure pinning functionality, allowing users to protect narinfos and their transitive references from LRU eviction. The changes include new database tables and queries for MySQL, PostgreSQL, and SQLite, as well as new API endpoints and modifications to the cache's LRU eviction logic. The design documents clearly outline the goals, decisions, and risks associated with this feature. Overall, the implementation appears robust, with good consideration for idempotency and concurrency. However, there are a few areas where efficiency could be improved, particularly in the LRU eviction process and transitive closure computation.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
kalbasit and others added 2 commits March 18, 2026 15:52
- Fix loop condition to properly handle cleanupSize=0 (delete all case)
- Add overflow protection for fetchSize calculation
- Cap fetchSize to prevent excessive memory usage

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Document known performance limitations in closure pinning code:
- N+1 query pattern when fetching nar_file sizes
- BFS traversal making multiple DB calls per level

These will be addressed in future optimization work.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@codecov

codecov Bot commented Mar 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (a1f0655) to head (531213d).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1108   +/-   ##
=====================================
  Coverage   5.04%   5.04%           
=====================================
  Files          6       6           
  Lines        436     436           
=====================================
  Hits          22      22           
  Misses       410     410           
  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.

Comment thread pkg/cache/cache.go
}

// Get the file size for this narinfo to track cleanup size
// TODO: This is an N+1 query pattern. Consider optimizing by fetching all

Check notice

Code scanning / devskim

A "TODO" or similar was left in source code, possibly indicating incomplete functionality Note

Suspicious comment
Comment thread pkg/cache/cache.go Dismissed
@kalbasit
kalbasit merged commit 6a00f38 into main Mar 18, 2026
16 checks passed
@kalbasit
kalbasit deleted the feat-add-closure-pinning-to branch March 18, 2026 23:10
kalbasit added a commit that referenced this pull request Jun 8, 2026
## Summary

The `[Unreleased]` section was populated in #1309 but skewed toward the
recent CDC-drain, in-flight-staging, and Ent-migration work, omitting
several user-facing features and fixes that also landed since v0.9.4.
This backfills the missing notable changes, each cross-referenced by PR.

**Added**
- `ncps fsck` command + Helm fsck CronJob (#975, #996, #998, #999,
#1000, #1004, #1006, #1176)
- Closure pinning HTTP endpoints `POST`/`DELETE /pin/{hash}.narinfo`,
`GET /pins` (#1108)
- pprof server via `--pprof-addr` (#1063)
- CDC lazy chunking as a feature + `--cache-cdc-lazy-cleanup-schedule` +
recovery cron (#1082, #1083, #1089, #1096)
- Helm: auto `GOMEMLIMIT` (#1061), configurable temp volume /
`volumeClaimTemplate` (#1074, #1077), SQLite `Recreate` strategy (#1012)
- Startup storage reporting + deprecated-narinfo warning (#959, #961)
- `docker-dev` image (#1097)

**Fixed**
- `store/tmp` no longer wiped on startup (#1313)
- `nix-hash` NAR verification (#1101)
- Prometheus counters primed at startup (#1337, #1343)
- 404 on un-reassemblable chunked NARs (#1319), purged narinfo no longer
500 (#1318), fail-fast tmp validation (#1086)
- Further CDC/cache reliability fixes (#1317, #1346, #1341, #1342,
#1331, #1347)

**Changed**
- CDC config now persisted in the DB config table (#971)

Dependency bumps, CI/test-only changes, and the internal Ent-conversion
PRs are intentionally excluded; the existing Ent-migration entry already
covers that work.

## Test plan

- [x] `nix fmt` reports no changes (docs-only edit)
- [x] CHANGELOG section structure intact
(Added/Fixed/Changed/Removed/Migration/CI)
kalbasit added a commit that referenced this pull request Jun 8, 2026
## Summary

Closure pinning shipped in #1108 — the `POST`/`DELETE
/pin/{hash}.narinfo` and `GET /pins` endpoints that protect a narinfo
and its transitive references from LRU eviction — but was never
documented, leaving #1021 open. This PR documents it.

- **New page** `docs/docs/User Guide/Features/Pinning.md` (modeled on
the existing CDC feature page): overview of why to pin, the three HTTP
endpoints with status codes, idempotency notes, the unknown-hash `404`
case, and worked `curl` examples (including the empty `/pins` response).
All behavior is derived from `pkg/server/server.go` and
`pkg/cache/cache.go` so the docs match the spec.
- **Published in the nav tree**: registered the page in the Trilium
export index (`docs/!!!meta.json`) under the `features` note with a
`pinning` slug.
- **Cross-links**: from Cache Management (new "Protecting Paths from
Eviction" subsection + Related Documentation) and Getting Started →
Concepts (Storage Requirements) where LRU eviction is introduced.
- **Spec + OpenSpec**: added a documentation requirement to the
`closure-pinning` spec and archived the `document-closure-pinning`
change.

No code, API, schema, or runtime behavior changes.

Closes #1021.

## Test plan

- [x] `task fmt` clean (0 files changed)
- [x] `docs/!!!meta.json` parses as valid JSON; Pinning note registered
with a unique `noteId`
- [x] `openspec validate --specs` passes for `closure-pinning`
- [x] Reviewer: confirm documented endpoints/status codes match the
implementation
- n/a `task lint` / `task test` — documentation-only change, no Go/SQL
touched

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
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 size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants