Skip to content

fix(cache): never surface purged narinfo as HTTP 500 - #1318

Merged
kalbasit merged 3 commits into
mainfrom
fix-cache-never-surface-purged
Jun 3, 2026
Merged

kalbasit merged 3 commits into
mainfrom
fix-cache-never-surface-purged

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 3, 2026

Copy link
Copy Markdown
Owner

Summary

A narinfo present in the database but missing its backing NAR is purged by getNarInfoFromDatabase, which signals the internal errNarInfoPurged sentinel. After an upstream re-pull, GetNarInfo re-read that sentinel verbatim and the narinfo HTTP handler mapped it to HTTP 500 (the narinfo was purged). Nix treats a 500 as a hard error and aborts the build instead of falling back to its next substituter — fsck reported 3013 such backing-less narinfos, each a permanent 500.

A purge is internal cache maintenance, not a server fault, so it must never reach the client as a 500.

Changes

  • pkg/cache/cache.go — GetNarInfo's post-pull re-read now maps errNarInfoPurged → storage.ErrNotFound (HTTP 404 → Nix upstream fallback). The sentinel is exported as cache.ErrNarInfoPurged.
  • pkg/server/server.go — the narinfo GET error→status decision is extracted into narInfoErrorStatus, mapping the sentinel (and ErrNotFound) to 404 while writing only the generic status text, never the internal message.
  • Deterministic cache and server tests, using an unexported context-scoped test seam (withNarPrefetchDisabled) to reproduce the otherwise timing-racy bug.

Scoped to serving semantics only. Non-goals (deferred): the NAR background-download race under distributed-lock contention (root cause of missing NARs) and reconciliation of the existing orphaned-narinfo backlog.

OpenSpec capability: narinfo-purge-serving.

Test plan

  • task fmt clean
  • task lint — 0 issues
  • task test — all packages pass with -race
  • Verify ncps.nasreddine.com returns 404 (not 500) for an orphaned narinfo hash after deploy

🤖 Generated with Claude Code

A narinfo present in the database but missing its backing NAR is purged by
getNarInfoFromDatabase, which signals the internal errNarInfoPurged sentinel.
After an upstream re-pull, GetNarInfo re-read that sentinel verbatim and the
narinfo HTTP handler mapped it to a 500 ("the narinfo was purged"). Nix treats
a 500 as a hard error and aborts the build instead of falling back to its next
substituter; fsck reported 3013 such backing-less narinfos, each a permanent
500.

Why: a purge is internal cache maintenance, not a server fault. It must never
reach the client as a 500.

How: in GetNarInfo, the post-pull re-read now maps errNarInfoPurged to
storage.ErrNotFound (HTTP 404 -> Nix upstream fallback). The sentinel is
exported as cache.ErrNarInfoPurged, and the narinfo GET handler's error->status
decision is extracted into narInfoErrorStatus, which maps the sentinel (and
ErrNotFound) to 404 while writing only the generic status text, never the
internal message. Adds deterministic cache and server tests, using an
unexported context-scoped test seam to reproduce the otherwise timing-racy bug.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit

kalbasit commented Jun 3, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. bug Something isn't working go Pull requests that update go code labels Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 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: f55be6d0-84aa-400b-a279-deda459f271c

📥 Commits

Reviewing files that changed from the base of the PR and between a456d0e and 027727e.

📒 Files selected for processing (1)
  • openspec/specs/narinfo-purge-serving/spec.md
✅ Files skipped from review due to trivial changes (1)
  • openspec/specs/narinfo-purge-serving/spec.md

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Prevented an internal purge signal from causing HTTP 500 responses; such cases now resolve to HTTP 200 (when available) or HTTP 404 so clients can fall back safely.
  • Documentation

    • Added specification, design, and task docs describing the purge-handling behavior and rollback/testing plans.
  • Tests

    • Added regression tests ensuring purge cases map to not-found (404) and that error-to-status behavior is stable.

Walkthrough

This PR fixes a production issue where the internal narinfo-purge sentinel could leak to clients as HTTP 500. The fix exports the sentinel, maps it to storage.ErrNotFound (404) in the cache layer's post-upstream re-read path, and adds HTTP handler defense-in-depth. Includes comprehensive tests and a deterministic test seam for orphan-narinfo scenarios.

Changes

Narinfo Purge Sentinel Resolution

Layer / File(s) Summary
Specification and design documentation
openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/, openspec/specs/narinfo-purge-serving/spec.md
Adds archive metadata, design, proposal, spec, and tasks documenting required behavior: treat purge as cache miss, re-fetch upstream, or map purge sentinel to 404; includes TDD plan and test seam.
Cache sentinel export and test seam
pkg/cache/cache.go
Export ErrNarInfoPurged and add nar_prefetch_disabled context seam with helpers to disable background NAR prefetch for deterministic tests.
Cache purge→not-found mapping
pkg/cache/cache.go
Map ErrNarInfoPurged to storage.ErrNotFound during the post-upstream re-read in GetNarInfo; update comparisons/returns and conditionally skip prefetch.
Cache regression tests
pkg/cache/purge_serving_internal_test.go
Two integration tests reproduce orphan-narinfo scenarios and assert the purge sentinel never escapes and results map to storage.ErrNotFound.
Server HTTP error mapping and handler changes
pkg/server/server.go
Add narInfoErrorStatus(err) helper and refactor getNarInfo to use it: suppress responses on cancel/deadline, write generic status text for non-500 outcomes, and log/send error text only for 500s.
Server tests and test-only export
pkg/server/export_test.go, pkg/server/purge_serving_test.go
Expose NarInfoErrorStatus for tests and add TestNarInfoErrorStatus covering purge sentinel (wrapped), not-found, cancellation, and unknown errors mapping to expected HTTP behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • kalbasit/ncps#1279: Also modifies narinfo purge/upstream-job detection logic; related to purge behavior adjustments in pkg/cache/cache.go.

Poem

A rabbit tapped the cache one night,
Found a purged narinfo in the light,
"No 500s!" it cried,
"Upstream or 404," it sighed—
Now the client gets tidy answers bright 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: preventing internal purge sentinels from surfacing as HTTP 500 errors to clients.
Description check ✅ Passed The description is directly related to the changeset, explaining the problem, solution, and specific file changes that align with the provided summaries.
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 prevents internal narinfo purge events from surfacing to clients as HTTP 500 errors. It exports the internal ErrNarInfoPurged sentinel, maps it to storage.ErrNotFound (HTTP 404) in both the cache layer (GetNarInfo) and the server layer's error handler, and ensures that generic status text is returned instead of leaking internal error messages. Additionally, it introduces test-only context hooks to disable NAR prefetching, allowing deterministic testing of these edge cases, and adds comprehensive unit tests. No review comments were provided, so I have no feedback to address.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@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

🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/design.md (1)

106-109: 💤 Low value

Minor grammar issue in "Open Questions" section.

Line 108: "None blocking" is grammatically incomplete. Consider "None are blocking" or simply "None."

🤖 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 `@openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/design.md` around
lines 106 - 109, In the "Open Questions" section replace the grammatically
incomplete phrase "None blocking" with a correct form such as "None are
blocking" or simply "None" by editing the text under the Open Questions header
(look for the line containing "None blocking" in the document).
🤖 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 `@openspec/specs/narinfo-purge-serving/spec.md`:
- Around line 3-4: Replace the placeholder under the "## Purpose" header with a
complete purpose for the `narinfo-purge-serving` capability: explain that it
defines how the cache serves narinfo requests when the internal purge guard
fires (narinfo exists but backing NAR is missing and no download is in flight),
specify that purge events must not surface as HTTP 500 to clients, and state
that the system should re-fetch upstream and return HTTP 200 (if available) or
HTTP 404 (to trigger Nix substituter fallback); reference the related
capabilities `narinfo-concurrent-fetch` and `nar-cache-miss-recovery` to show
complementarity.

---

Nitpick comments:
In `@openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/design.md`:
- Around line 106-109: In the "Open Questions" section replace the grammatically
incomplete phrase "None blocking" with a correct form such as "None are
blocking" or simply "None" by editing the text under the Open Questions header
(look for the line containing "None blocking" in the document).
🪄 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: 14386aa5-3be2-4efe-9c56-333af0b267bd

📥 Commits

Reviewing files that changed from the base of the PR and between 822d656 and a456d0e.

📒 Files selected for processing (11)
  • openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/.openspec.yaml
  • openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/design.md
  • openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/proposal.md
  • openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/specs/narinfo-purge-serving/spec.md
  • openspec/changes/archive/2026-06-03-fix-purged-narinfo-500/tasks.md
  • openspec/specs/narinfo-purge-serving/spec.md
  • pkg/cache/cache.go
  • pkg/cache/purge_serving_internal_test.go
  • pkg/server/export_test.go
  • pkg/server/purge_serving_test.go
  • pkg/server/server.go

The main spec was created by archiving and left a TBD Purpose
placeholder. Replace it with a real Purpose describing the
purge-serving contract (never 500; re-fetch and serve 200, else 404
for Nix substituter fallback) and its relation to the
narinfo-concurrent-fetch and nar-cache-miss-recovery capabilities.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit enabled auto-merge (squash) June 3, 2026 20:23
@kalbasit
kalbasit merged commit 6233e78 into main Jun 3, 2026
34 checks passed
@kalbasit
kalbasit deleted the fix-cache-never-surface-purged branch June 3, 2026 20:32
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code 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