Skip to content

fix(proxy): ref-count shared blobs and refresh TTL on cache hit - #4872

Open
greeddj wants to merge 3 commits into
distribution:mainfrom
greeddj:main
Open

greeddj wants to merge 3 commits into
distribution:mainfrom
greeddj:main

Conversation

@greeddj

@greeddj greeddj commented May 21, 2026 •

Copy link
Copy Markdown

Hi

This PR fixes two bugs in the pull-through cache:

  • When the TTL of a blob expired in one repository, the cache removed the blob data, although other repositories still linked to it. Pulls from those repositories then got HTTP 200 with an empty body, and Docker failed with short read: expected N bytes but got 0: unexpected EOF. Because the status is 200, Docker does not fall back to the upstream registry.
  • A blob expired on the TTL of its first pull, even when clients pulled it often.

Root cause

The scheduler is keyed by repo@digest. A blob in N repositories has N independent timers. The first timer to fire called Vacuum.RemoveBlob and ignored the other references. The other repositories kept their links and their cached descriptors, so they served the descriptor of a blob that had no data. AddBlob ran only on a cache miss, so a cache hit did not refresh the TTL.

What changed

  • Reference count per digest. The scheduler counts its entries for each digest. When an entry expires, the callback deletes the link of that repository. It removes the blob data only when no other entry has the digest (Shared).
  • Per-digest lock. LockDigest uses a fixed pool of 256 mutexes, so its memory does not grow with the number of digests. The scheduler holds the lock for the full expiry of an entry. ServeBlob and Get hold the same lock while they create a link and its entry. Thus a pull cannot link a blob between the reference check and the removal of the data.
  • TTL refresh on a cache hit. ServeBlob starts the TTL again before it sends a cached blob. If a refresh replaces an entry after its timer fired, the old timer does nothing.
  • Startup reconcile. In the background, the scheduler walks the repositories tree one time. It schedules the blob links that scheduler-state.json does not contain, for example links from older binaries or from an unclean shutdown. Expiry waits until the reconcile succeeds. If the reconcile fails, the scheduler tries again each minute. The registry start does not wait for the reconcile. There is no storage walk during an eviction.
  • Failed link deletion. If the callback cannot delete the link, it schedules the entry again. Thus the link continues to count as a reference to the blob data.
  • In-memory descriptor cache. A clear in one repository now also clears the global descriptor, and a repository descriptor is valid only while the global descriptor exists. This is the same behaviour as the redis cache. After the cache removes blob data, no repository can serve a stale descriptor for it.
  • Documentation. configuration.md describes the TTL refresh, the shared blob data and the startup reconcile.

Compatibility

  • The format of scheduler-state.json does not change. Patched and unpatched binaries can read the state of each other.
  • With proxy.ttl: 0 or with storage.delete.enabled: false, the behaviour does not change.
  • After an upgrade, blob links that have no entry get the full TTL from the registry start. On a large object storage, the first reconcile can take some minutes. During that time, no blob expires.

Earlier review comments

  • There is no repositories walk for each eviction. The only walk is the reconcile at startup, which runs in the background.
  • The lock pool has a fixed size.
  • No named return values and no else if.

Tests

  • Scheduler: reference count, refresh after the timer fired, expiry that waits for a failing reconcile.
  • Proxy: shared blob data, concurrent expiries, a pull that races an expiry, a link that the expiry cannot delete, an entry without a link, reconcile of stored links, TTL refresh on a cache hit, Get.
  • Cache: a new check in the cachecheck suite. A clear in one repository invalidates the descriptor in the other repositories.
  • Handlers: an HTTP test with two repositories that share a layer, with blobdescriptor: inmemory.
  • TestSchedule: its callback read a map without the lock. Expiry callbacks for different digests can run at the same time, so the race detector found this race.

Fixes: #2367, #3247
Related: #4191

The fixed example below was recorded with the first version of this PR. The current version does not write the "skipping blob vacuum" log line. TestProxySharedBlobExpiry tests the same scenario.

@github-actions github-actions Bot added area/storage area/proxy Related to registry as a pull-through cache area/docs labels May 21, 2026

@milosgajdos milosgajdos left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the thorough writeup and the before/after repro. The PR seems like legit good fix; My one blocking concern is the cost of the slow path on object storage — details inline. Everything else is more or less minor.

Comment thread registry/proxy/scheduler/scheduler.go Resolved
Comment thread registry/proxy/scheduler/scheduler.go Resolved
Comment thread registry/proxy/proxyblobstore.go Resolved
Comment thread registry/proxy/proxyregistry.go Resolved
Comment thread registry/proxy/proxyregistry.go Resolved
Comment thread registry/proxy/scheduler/scheduler.go Resolved
@greeddj

greeddj commented Jun 6, 2026

Copy link
Copy Markdown
Author

Hi @milosgajdos

Could you please continue the review?
Or, if not, could you advise who I might reach out to?

Thx!

@milosgajdos

Copy link
Copy Markdown
Member

You need to have a bit of patience, alas; I've tagged other maintainers on the review but his is a large change, 1.4k+ LOC diff - it takes time to review; I'll do my best to have another look this week

@greeddj

greeddj commented Jun 8, 2026

Copy link
Copy Markdown
Author

You need to have a bit of patience, alas; I've tagged other maintainers on the review but his is a large change, 1.4k+ LOC diff - it takes time to review; I'll do my best to have another look this week

I understand and I'll wait.

Thx!

@greeddj

greeddj commented Jun 25, 2026

Copy link
Copy Markdown
Author

Hello,

Just a friendly reminder: could you please take a look at this PR when you get a chance?

@glaming1

Copy link
Copy Markdown

Hello - we are hitting a similar issue and will benefit from this fix. Please let me know if there is anything we can do to expedite the process. Thanks

@greeddj

greeddj commented Aug 6, 2026

Copy link
Copy Markdown
Author

Hi,

This is an update rather than a ping. Rebased onto current main.

You noted the 1.4k LOC diff is a lot to review. If it would help, I can
split it into smaller PRs.

@thelooter

Copy link
Copy Markdown

Hey, anyone know what the status is here? I would benefit from this fix too.

@alekz91

alekz91 commented Sep 17, 2026

Copy link
Copy Markdown

Hey there. I’m also waiting for this fix. I’d appreciate a quick review. Thx!

lhns pushed a commit to lhns/docker-registry-cache that referenced this pull request Oct 24, 2026
When the proxy TTL expires a blob for one repository, the registry deletes
the shared blob data although other repositories still link to it. Their
cached descriptors make the registry answer with 200 and an empty body,
so pulls fail with "unexpected EOF" until a restart
(distribution/distribution#4872). Without the cache the missing blob is
detected and fetched from upstream again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TErVLGDWfULocSss5sCH7c
@MrGiga

MrGiga commented Nov 17, 2026

Copy link
Copy Markdown
Config
storage:
  cache:
    blobdescriptor: inmemory
  filesystem:
    rootdirectory: /var/lib/registry
  delete:
    enabled: true
proxy:
  remoteurl: https://registry-1.docker.io
  ttl: 168h

What we saw

  • When a blob expired for one repository, the vacuum removed the shared blob data, but other repositories still had _layers links to the same digest. 14 of 1,298 layer links in our cache were left dangling, across library/python, library/node, library/telegraf, library/eclipse-temurin, library/docker and grafana/k6.
  • With the in-memory descriptor cache, GET /v2/<repo>/blobs/<digest> returns 200 with the full Content-Length and an empty body. Docker clients then fail with:
    short read: expected 3864189 bytes but got 0: unexpected EOF
    
  • Because the response is a 200, Docker doesn't fall back to the upstream registry, so CI jobs fail on every retry until the dangling links are removed and the registry is restarted.
  • The expiry timer isn't reset when a blob is served from the cache, so heavily used shared base layers are the ones most likely to be removed.

Workaround

proxy:
  ttl: 0s

It has to be an explicit zero; leaving ttl out falls back to the 168h default. That stops expiry entirely, so the cache grows until it's cleared by hand.

Ask

This change would let us turn expiry back on. Is there anything blocking it, or anything we can help with, such as testing or a rebase? We'd be glad to test a build.

Related: #4191, #2367

@greeddj

greeddj commented Nov 17, 2026

Copy link
Copy Markdown
Author

Hi, @MrGiga

Thanks for the detailed report and for the offer to help!
I've rebased the branch onto the current main and resolved the conflicts, so it's ready for testing.

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

Hi @greeddj

I had an AI agent review your code. It read through b81292e (reading the code only; It didn't run the tests). The common shared-layer case looks handled, but I think a few gaps could still lead to deleting data that's in use.

Correctness

  1. A pull can race with expiry. The per-digest lock in proxyregistry.go (L329–370) covers only the expiry callbacks. Blob commits, link creation in proxyBlobStore, and cache-hit refreshes don't take it, so a pull can create a link after the reference check and before RemoveBlob. Also, ClaimVacuum (scheduler.go L258–265) deletes the entry by key, so a timer refreshed between the check and the claim seems to get dropped.
  2. References are incomplete. proxyBlobStore.Get (L234–253) can create a link without scheduling an entry, and after reconciliation eviction relies only on the scheduler index. Before reconciliation, the storage walk prunes _manifests, so configs and layers referenced only by manifests in other repositories aren't considered.
  3. Reconciliation fails open. scheduler.go L324–330 marks reconciliation complete even when the walk returns an error, so later evictions trust an incomplete index. Also, callback errors drop the entry without retrying, and ClaimVacuum removes the entry before the vacuum succeeds.
  4. Descriptor cache invalidation. Vacuum.RemoveBlob deletes the data without invalidating the global descriptor or other repositories' descriptors. With blobdescriptor: inmemory, any remaining unsafe path still produces the 200-with-empty-body symptom.

Smaller points

  • Local manifest cache hits don't refresh the TTL, but the docs say "every successful cache hit" refreshes it.
  • hasOtherRefsLocked (L273–288) scans every scheduler entry for each expiry while holding a single mutex.
  • Reconciliation gives rediscovered links a fresh TTL rather than restoring their original expiry.

Tests

It would help to have:

  • an end-to-end HTTP test with two repositories sharing a layer, where one expires and the other is pulled
  • a deterministic test of a pull racing a vacuum
  • a test where the reconciliation walk fails
  • a test that checks descriptor cache invalidation

Suggestion

Use one per-digest protocol for link creation, refresh and vacuum, make reconciliation fail closed with retries, and invalidate the global and per-repository descriptors when data is removed.

I'm happy to help with the locking and invalidation changes. I can send a PR to your branch if that's useful.

The pull-through cache scheduler is keyed by repo@digest, so a blob
shared by N repositories had N independent timers. The first to fire
called Vacuum.RemoveBlob on the underlying file regardless of the
other surviving references; the remaining repos kept their per-repo
descriptor cache valid and started returning HTTP 200 with a zero-byte
body to every subsequent pull. Hot blobs also expired on their
first-pull TTL because AddBlob was only called on cache miss, never
on cache hit.

Three coordinated changes, all in registry/proxy/, on-disk state
format unchanged:

* OnBlobExpire now deletes the per-repository link first (clears the
  expiring repo's descriptor cache regardless of the outcome), then
  asks the scheduler whether any other live entry references the
  digest (fast path), then walks the storage tree with pruning over
  /_layers/<alg>/<hex>/ for any surviving on-disk link (slow path).
  The shared blob is vacuumed only when both checks come back empty.
  The full sequence runs under a per-digest scheduler.EvictionLock
  so that N concurrent expiries for the same digest serialise rather
  than racing each other into a leak. HasOtherReferencesToDigest
  ignores entries whose timer has already fired so the fast path is
  not misled by in-flight callbacks.

* proxyBlobStore.ServeBlob refreshes the scheduler entry through
  AddBlob on every cache hit, so frequently-pulled blobs no longer
  expire while traffic continues. Touch failures are logged but do
  not fail the response (the body has already been streamed to the
  client).

* On Start the scheduler runs a one-shot Reconciler hook that walks
  the repositories tree once and registers any orphan blob/manifest
  link not already present in scheduler-state.json. State written by
  earlier binaries that under-tracked links is now picked up rather
  than leaked.

The startTimer lock is split: the user callback runs without the
scheduler mutex held (the new ref-count check would otherwise
deadlock on the non-reentrant sync.Mutex), and the entry is dropped
only when the map still holds the same pointer (so a concurrent
AddBlob cannot have its fresh entry evicted by the old timer).

Three minimal additive exports in registry/storage (BlobLinkPath,
ManifestRevisionLinkPath, RepositoriesRootPath) keep all path
construction inside the storage package; nothing in proxy hardcodes
storage layout strings.

scheduler-state.json keeps the existing repo@digest keys, no new
fields, no version bump - patched and unpatched binaries can read
each other's state in both directions.

Refs: distribution#2367, distribution#3247

Signed-off-by: Dmitrij Shishkin <[email protected]>
Shared-blob eviction in the pull-through cache did per-eviction work
that does not scale on object storage: a full repositories-tree LIST
on every expiry, an unbounded per-digest lock map, and a synchronous
reconcile walk at startup. This makes the eviction path bounded and
walk-free in steady state. On-disk state format is unchanged;
scheduler-state.json keys are unchanged.

* The per-digest eviction lock pool was an unbounded sync.Map keyed by
  digest - slow unbounded growth on a long-lived mirror with many
  distinct layers rather than the working set. Replace it with a fixed
  *[256]sync.Mutex striped pool indexed by the first byte of the
  digest's hex encoding. Memory is O(1) in the number of distinct
  digests; a stripe collision only over-serialises unrelated digests
  and never affects correctness.

* anyRepoHasBlobLink walked the whole repositories tree on every blob
  eviction - a full recursive LIST per expiry, expensive on object
  storage like S3. It now runs only while the scheduler is not yet
  Reconciled(): a startup safety net for orphan links absent from
  scheduler-state.json. Once bootstrap reconcile has registered every
  on-disk link the in-memory scheduler is the authoritative reference
  count and the per-eviction walk is skipped entirely.

* OnBlobExpire now calls ClaimVacuum(selfKey, digest): under the
  per-digest eviction lock it atomically drops the caller's own entry
  and reports whether any sibling entry still references the digest. N
  concurrent expiries for one digest form a serial chain in which only
  the last one observes an empty map and vacuums, removing the
  mutual-skip race the previous Expiry filter guarded against.
  HasOtherReferencesToDigest is retained only as a read-only query.

* reconcileFromStorage runs in a background goroutine launched from
  Start; an atomic Reconciled() flag flips on completion, so registry
  start no longer blocks on the repositories walk. Evictions during
  that window fall back to the on-disk walk above.

* AddBlobIfAbsent / AddManifestIfAbsent drop their named return
  parameters; the ServeBlob cache-hit refresh is extracted into
  refreshSchedulerOnCacheHit with early exits.

Signed-off-by: Dmitrij Shishkin <[email protected]>
The shared-blob eviction used two mechanisms: the scheduler index and
a storage walk that ran until the startup reconcile completed. The
joins between them left ways to remove blob data that a repository
still used. This change keeps one mechanism, the scheduler index, and
closes those ways. The format of scheduler-state.json does not change.

* A pull could link a blob between the reference check and the
  removal of the blob data. ServeBlob and Get now hold the per-digest
  lock while they create the link and its scheduler entry. The
  scheduler holds the same lock for the full expiry of an entry.
  LockDigest replaces EvictionLock.

* A cache hit that refreshed an entry after its timer fired lost the
  refresh, because the expiry removed the entry by key. The timer now
  does nothing when the entry was replaced. ServeBlob refreshes the
  TTL before it sends the blob, so the blob cannot expire during the
  response.

* A failed reconcile marked the index as complete. Expiry now waits
  until the reconcile succeeds, and the scheduler runs the reconcile
  again each minute after a failure. The registry start does not
  wait. The storage walk for each eviction before the end of the
  reconcile is gone, and with it anyRepoHasBlobLink and Reconciled.

* An expiry that could not delete its link dropped the entry, so the
  link no longer counted as a reference. The callback now schedules
  the entry again. A link that is already absent is not an error, and
  the expiry continues to the blob data. If deletion is disabled, the
  behaviour is the same as before.

* The scheduler counts the entries of each digest. Shared answers in
  constant time. It replaces ClaimVacuum, HasOtherReferencesToDigest
  and the scan of all entries.

* The in-memory descriptor cache kept the descriptor of a repository
  after another repository cleared the same digest. It now follows
  the redis cache: a clear in one repository clears the global
  descriptor, and a repository descriptor is known only while the
  global descriptor exists.

* The reconcile schedules blob links only. Manifest links do not take
  part in the reference count. AddManifestIfAbsent, BlobLinkPath and
  ManifestRevisionLinkPath are removed.

Expiry callbacks for different digests can run at the same time. The
callback of TestSchedule read its map without the lock and is fixed.
The "Adding new scheduler entry" log line is written for new entries
only, not for each cache hit. The documentation now says that only a
blob pull starts the TTL again.

New tests: a pull that races an expiry, a refresh after the timer
fired, a failing reconcile, a link that the expiry cannot delete, an
entry without a link, a clear of a shared descriptor, and an HTTP
test with two repositories that share a layer.

Signed-off-by: Dmitrij Shishkin <[email protected]>
@greeddj

greeddj commented Dec 4, 2026

Copy link
Copy Markdown
Author

Hi @MrGiga

Thanks a lot for the review. I checked each point against the code, and most of them were right. I reworked the fix in 61323c4 and rebased the branch onto the current main. The diff is now about 860 lines, down from about 1.4k.

Correctness

  1. Pull vs. expiry. Fixed. The scheduler holds a per-digest lock (LockDigest) for the full expiry. ServeBlob and Get hold the same lock while they create the link and its entry. A refresh that replaces an entry after its timer fired now wins: the old timer sees that the entry changed and does nothing. ClaimVacuum is gone.
  2. Incomplete references. Get now schedules the blob that it stores. The storage walk during an eviction is gone, so the _manifests pruning no longer applies. A repository that has a manifest but no _layers link gets a cache miss and fetches the layer again, so no data is lost.
  3. Reconcile fails open. Fixed. Expiry waits until the reconcile succeeds, and the scheduler tries again each minute after a failure. If the callback cannot delete the link, it schedules the entry again, so the link still counts as a reference. One case stays: if RemoveBlob fails, the data stays without a link until the next pull of that blob. That is a storage leak, not a data loss.
  4. Descriptor cache. Fixed for inmemory. A clear in one repository now clears the global descriptor, and a repository descriptor is valid only while the global descriptor exists. This is the same behaviour as the redis cache.

Smaller points

  • Manifest TTL: the docs now say that only a blob pull starts the TTL again. The proxy resolves tags against the upstream first, so a manifest that expires is fetched again by digest.
  • hasOtherRefsLocked: replaced by a reference count per digest.
  • Reconcile TTL: rediscovered links still get the full TTL. Their original expiry is not in scheduler-state.json, so there is nothing to restore.

Tests

All four tests that you suggested are in: an HTTP test with two repositories that share a layer (with blobdescriptor: inmemory), a pull that races an expiry, a failing reconcile, and descriptor cache invalidation.

If you can, please test a build of 61323c4 with your setup. You can remove the ttl: 0s workaround for it. If you have kept the scheduler-state.json from the time before the workaround, remove it before the start. Otherwise all entries from that time expire right after the start.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/docs area/proxy Related to registry as a pull-through cache area/storage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mirror cann't pull with 0 size file pull through cache (proxy): docker pull error "unexpected EOF" due to common blob expiration

6 participants