Skip to content

feat: add metadata updates and handler revalidation - #438

Merged
alecthomas merged 3 commits into
mainfrom
aat/oci-pull-through-cache
Nov 9, 2026
Merged

alecthomas merged 3 commits into
mainfrom
aat/oci-pull-through-cache

Conversation

@alecthomas

Copy link
Copy Markdown
Collaborator

This lays the groundwork for an OCI (Docker) pull-through cache. The strategy itself will follow in a separate PR. Registries need things the generic handler can't do today. Tag manifests are mutable and must be re-checked cheaply rather than expired. Blobs are content-addressed, so they can be verified before they are shared. Clients send HEAD and Range requests that should be served from the cache rather than bypassing it.

The changes, one commit each:

  • Cache.UpdateMetadata changes an entry's headers and resets its TTL without rewriting the body. Every backend, the tiered cache, the client, and a new PATCH /api/v1/object/{namespace}/{key} endpoint support it. It never changes the ETag, because tiers compare ETags to detect stale copies. It accepts If-Match, so an entry that was replaced after it was checked is not refreshed. The S3 expiry refresh now keeps all companion headers, not just the ETag, so updated headers survive it.
  • The handler gains four generic builder hooks:
    • Vary adds request-derived dimensions to the cache key.
    • Verify keeps corrupt or truncated bodies out of the cache. The requesting client still receives the bytes.
    • Revalidate(header, freshFor) keeps stale entries. It re-checks them with a HEAD request and serves the cached copy when the identifying header is unchanged or the upstream is rate limiting or failing.
    • ParallelFetch fills large objects with concurrent range requests by reusing client.ParallelGetReader. It follows redirects once and fetches every chunk from the final URL.
  • The handler's defaults change in two ways:
    • HEAD hits are served from Stat. HEAD misses are forwarded upstream without being cached, so a metadata check never triggers a download.
    • A Range request on a miss no longer bypasses the cache. The full object is fetched and cached, and the requested range is cut from the stream.
  • The git package has a test-only fix. Two cold snapshot tests hung forever when setup failed, for example with an outdated git-lfs. They now release their blocking scheduler job during cleanup, so the real error is reported.

🤖 Generated with Claude Code

alecthomas and others added 3 commits November 9, 2026 12:29
Revalidating a mutable entry should record the check and extend its
lifetime without rewriting the body. UpdateMetadata replaces the given
headers and resets the TTL on every backend, tier and the remote API
(PATCH /api/v1/object). It never changes the ETag, since tiers compare
ETags to detect stale copies, and accepts If-Match so an entry replaced
after validation is not refreshed.

The S3 expiry refresh now keeps every companion header rather than only
the ETag, so updated headers survive it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Protocol-aware strategies such as OCI need more from the generic
handler than a fixed TTL:

- Vary keys the cache on request headers that select a variant.
- Verify keeps corrupt or truncated bodies out of the shared cache.
- Revalidate keeps mutable entries, re-checks them with a HEAD once
  stale, and serves the cached copy when the upstream is unchanged,
  rate limited or failing.
- ParallelFetch fills large objects with concurrent range requests.

HEAD hits are now answered from Stat, and HEAD misses are forwarded
without caching so metadata probes never trigger downloads. Range
requests no longer bypass the cache on a miss: the whole object is
fetched and cached, and the range is cut from the stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two cold snapshot tests only released their blocking scheduler job at
the end of the test body. Any earlier failure, such as a missing
git-lfs, made cleanup wait on the scheduler forever, hiding the real
error behind a test timeout. Release the blocker from cleanup too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alecthomas
alecthomas marked this pull request as ready for review November 9, 2026 01:33
@alecthomas
alecthomas requested a review from a team as a code owner November 9, 2026 01:33
@alecthomas
alecthomas requested review from jrobotham-square and removed request for a team November 9, 2026 01:33
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T01:36:20.254263Z 8609ea1 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@alecthomas
alecthomas merged commit 2e69d3a into main Nov 9, 2026
7 checks passed
@alecthomas
alecthomas deleted the aat/oci-pull-through-cache branch November 9, 2026 01:35

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8609ea1156

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 312 to +314
if err != nil {
h.errorHandler(err, w, r)
return nil
logger.WarnContext(ctx, "Serving stale entry, revalidation request failed", "error", err)
return true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Return revalidation errors to the caller instead of logging them

When request transformation, the upstream HEAD, or the metadata update fails, revalidate logs the error internally and returns only a freshness decision. This violates the error-handling convention in AGENTS.md and prevents callers from controlling how those failures are reported. Return the error alongside the freshness decision and propagate it to the existing call-site logging in ServeHTTP, while preserving stale-serving behavior.

AGENTS.md reference: AGENTS.md:L24-L25

Useful? React with 👍 / 👎.

if err != nil {
return nil, errors.Wrap(err, "parallel fetch")
}
return &http.Response{StatusCode: http.StatusOK, Header: headers, Body: body, ContentLength: size}, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use the accepted full response's metadata after fallback

When the discovery response has no ETag, client.ParallelGet discards it and performs a new full GET; concurrency 1 also performs a new full GET. However, this wrapper always returns the discovery response's headers and size. If the resource changes between requests, the handler streams and caches the new body with the old digest, content type, or content length, potentially truncating the client response or poisoning cached metadata. Obtain metadata from the response whose body is actually accepted, rather than fixing it before the fallback is selected.

Useful? React with 👍 / 👎.

Comment on lines +393 to +395
if h.parallel != nil {
upstreamReq.Header.Set("Range", h.parallel.firstChunkRange())
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle empty objects when probing with an internal range

With ParallelFetch enabled, an ordinary GET is converted into a ranged upstream request. An upstream that answers a range over an empty object with 416 and Content-Range: bytes */0 then reaches the non-OK forwarding path unchanged, so the client receives 416 despite not requesting a range, and the empty object is never cached. Recognize the empty-object discovery outcome or retry without Range before forwarding the internally generated range error.

Useful? React with 👍 / 👎.

worstell added a commit that referenced this pull request Nov 9, 2026
Image pulls from CI and workstations fetch the same layers from Docker
Hub and other registries over and over. That is slow, and it runs into
pull rate limits. This adds an `oci` strategy that serves the OCI
Distribution API from cachew, so those pulls hit the local and tiered
caches instead. It builds on the handler groundwork from #438 and the
request coalescing from #440.

The changes, one commit each:

- The `oci` strategy, configured with one block per registry.
- Routes: clients reach a registry at `/oci/<registry>/v2/`, which suits
containerd with `override_path`, or on a dedicated hostname at `/v2/`,
which Docker and Podman need because they cannot use a path prefix.
`/v2/` is answered locally. Pushes and any other write method get a 405.
- Paths are parsed from the end, because repository names can contain
slashes. Configured rewrites, such as Docker Hub's implicit `library/`
namespace, are applied before the name and reference are validated.
- Blobs are keyed on registry plus digest, verified against their digest
before caching, and never revalidated. Large blob fills use
`ParallelFetch`, with configurable chunk size and concurrency (32 MB × 4
by default). Registry redirects to a CDN are followed on the server
side.
- Digest-addressed manifests are verified and treated as immutable. Tag
manifests are keyed on a normalised `Accept` header. After `tag-ttl`
(default 5m) they are revalidated with a HEAD request on
`Docker-Content-Digest`, since the cache replaces upstream ETags. Docker
Hub does not count HEADs against rate limits. A stale tag is served when
the upstream is unavailable or rate limiting.
  - Tag lists and referrers pass through uncached.
- Upstream auth uses go-containerregistry's token transport with the
strategy's own `username`/`password`, or anonymous access when they are
unset. One transport is kept per repository scope. Client
`Authorization` and `Cookie` headers are removed and never forwarded.
- The README has an `oci` section with a Docker Hub example and setup
notes for containerd and Docker.
- An integration test against the reference registry (`registry:3`,
Distribution 3.1.2) running in Docker. It pulls through cachew with
go-containerregistry's client and checks every blob digest. It covers
anonymous and htpasswd upstreams, tag updates, and serving from cache
after the registry container is removed. It runs under the `integration`
tag in CI and fails rather than skips when Docker is missing.

New dependencies:

- go-containerregistry v0.22.1 provides the token exchange. It also
brings in docker/cli's config code, docker-credential-helpers and
logrus.
- go-digest checks digests.
- `golang.org/x/crypto` was already an indirect dependency and is now
direct, because the integration test uses bcrypt to create the htpasswd
file.
- Module version selection also raised klauspost/compress, x/mod, x/sync
and x/sys.

Known limitations:

- A manifest fetched only by tag is not also cached under its digest. A
later pull by digest misses the cache, and fails if the upstream is
down.
- In `tags/list` responses, the `Link` header for the next page still
uses the upstream path. A path-prefixed client that follows it will go
around cachew.
- Blob keys do not include the repository. A cached blob can therefore
be fetched under any repository name on the same registry. That is
consistent with every client sharing the upstream credentials.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Elizabeth Worstell <worstell@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Elizabeth Worstell <worstell@squareup.com>
Co-authored-by: Chain <492cad42391b4a5c84d831885f468e6f1699c0a8c39241f1c002235ece37ee69@buzz>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant