Repository navigation
imagecache: write the image record before unpacking layers - #717
Merged
Dmitry Berkovich (dberkov) merged 1 commit intoAug 4, 2026
Merged
Dmitry Berkovich (dberkov) merged 1 commit into
Dmitry Berkovich (dberkov) merged 1 commit into
Conversation
Inverts the pull's write order: the image record (whose diffID list is known from the config before any download) is written before the unpack loop, touched as each layer completes, and rewritten after the loop. A final re-verify confirms every returned layer dir is on disk. Why: the record's diffID list is what eviction's refcounts will trust, so writing it first means every layer of a pull is referenced before it can exist — the pull needs no other protection, and that protection survives atelet restarts. The per-layer touch makes liveness progress-based: a pull that is advancing keeps its record fresh indefinitely, while a wedged pull ages out and is reclaimed as an ordinary LRU entry. The end-of-pull rewrite guarantees success always leaves a record even if eviction removed it mid-flight, and the re-verify turns the residual failure case into a clean retry instead of a bundle spec naming a nonexistent lowerdir. Semantics note: a record now means 'known image, possibly partially present' — which is what it always meant to readers: cachedImage verifies every layer and re-pulls only what is missing, so an interrupted pull's record is resumable progress. Also new: the config diffID list is cross-checked against each layer's actual diffID, and a config/manifest layer-count mismatch fails the pull up front. Tests: a gated registry holds real pulls mid-flight by blocking chosen blob downloads — record removed mid-pull is rewritten on success; per-layer completions touch the record while later layers are still gated; a yanked layer dir fails the pull with a retryable error. Extracted from the phase2-gc-record-first prototype branch. This slice: go test -race green standalone; behavior-visible change even without GC: an interrupted pull now leaves a valid partial record.
Dmitry Berkovich (dberkov)
approved these changes
Aug 4, 2026
Dmitry Berkovich (dberkov)
merged commit Aug 4, 2026
848b75b
into
agent-substrate:main
11 checks passed
Dmitry Berkovich (dberkov)
pushed a commit
that referenced
this pull request
Aug 10, 2026
…ecovery (#735) Phase 2 of #463 (image-cache GC + observability): this is the eviction engine itself — the root set, the eviction pass, and startup orphan recovery — assembled from the foundations merged in #650 (sizes/last-use), #656 (spec digest), #658 (retirement primitives), and #717 (record-first pull). What remains after this is the watermark loop + flags that turn it on, then metrics and e2e. **Inert in production**: nothing calls `EvictUnused` yet — the watermark GC loop and its flags come in the next PR. The only behavior `New` gains is the startup orphan scan. ## What - **`Store.InUse()`** — the root set: scans bundle overlay specs under the actors dir (opt-in via `WithActorsDir`) for image digests, layer dirs, and exact layer-set signatures. The exact-set rule roots the multi-arch twin record and digestless (pre-`imageDigest`) specs' records without making every subset image unevictable. Returns `(RootSet, error)`: a non-nil error means the root set may be incomplete, and deleting callers must do nothing. - **`Store.EvictUnused(ctx, targetBytes, dryRun)`** — LRU eviction of unprotected images and the layers their removal leaves unreferenced. Min-age vetoes; per-victim re-checks under `hitMu` held exclusive against the cache-hit touch; two-phase deletion via `retireLayer`, with the slow `RemoveAll` outside all locks. If any layer of a deleted record must be kept (still referenced, rooted, fresh, or failed to retire), the record is atomically restored from bytes captured at listing time — a kept layer is never left unreachable. - **`Store.RecoverOrphans`**, called once from `New` — reclaims layers no record references. Startup is the one moment this scan is race-free (no pull can be in flight); a failure never fails `New`. - **Everything fails toward retention.** Both passes skip entirely, at ERROR naming the culprit, when their inputs can't be fully enumerated: an unreadable/undecodable image record, a garbled diffID inside a valid record, or an unenumerable root set (actors dir, bundles dir, or bundle spec). Refcounts and roots from partial data would retire layers that unread records still reference or running actors still mount — and for a long-running actor, the bundle spec is the only protection (its record mtime can be arbitrarily old, so min-age is no backstop). Missing dirs/specs remain legitimate emptiness, not errors. - **Eviction never writes into the live pool.** Retired layers are credited from the size file that rides along with the rename-aside (O(1), read-only, consistent with `CacheSize`); the size-file backfill exists only on the `CacheSize` path, where it bumps the dir mtime rather than restoring it (restoring could rewind a concurrent reuse-touch). - Per-item log lines are Debug behind an `Enabled` gate (level control via #677); pass summaries, evictions, and restores are Info. - `internal/imagecache/README.md` now documents the GC: pass structure, protection rules, failure direction, startup recovery, and two-phase deletion, plus the on-disk layout entries (`size`, `.tmp-*`, `.rm-*`) that shipped with #650/#658. ## Notes for reviewers - The gc tests reuse the helpers merged with #650 (`backdate`, `mustEnsure`) and #717's gated-registry harness — no duplicated symbols. The slow-pull gated test gains the eviction-veto assertion deferred from #717. - Dry-run mutates nothing, including size-file backfills (`layerSizeReadOnly`). - A `Store` built without `WithActorsDir` has an empty root set (deliberate for tools/tests). - Carried to the wiring PR: pass `WithActorsDir` in atelet; handle `EvictUnused`'s error before any shortfall accounting (a gated pass returns zero stats plus an error and must not be logged as a shortfall); and surface skipped passes as a counter in the observability PR so a wedged node alerts rather than scrolling ERROR lines. ## Testing - `go test -race ./internal/imagecache/`: every veto, shared-layer survival, both restore-on-keep shapes, orphan reclaimed at startup and ignored by the periodic pass, all enumeration gates — unreadable record (shared-layer scenario), undecodable record, garbled diffID, and the three unreadable root-set shapes (actors dir / bundles dir / spec, each against a rooted image with an arbitrarily old record) — dry-run purity, 25-iteration ensure-vs-evict race loop. - Kind, via the integration branch that stacks the watermark loop on this PR (the loop and flags are **not** part of this PR): full gVisor e2e suite green; a planted backdated orphan layer (no size file) was reclaimed at atelet startup with the expected log lines, its size credited read-only from the retired dir. - GKE (6 nodes), same integration branch: demo lifecycle + snapshot-continuity suites green; under aggressive watermarks the idle pool was evicted and subsequent actor resumes cold-pulled cleanly. No enumeration-gate false positives on either cluster.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fourth slice of #463 Phase 2, and the semantic pivot of the GC design: the pull
now writes the image record before unpacking, touches it as each layer
completes, rewrites it after the loop, and re-verifies every returned layer dir.
Why record-first: the record's diffID list (known from the config before any
download) is what the eviction engine's refcounts will trust — writing it first
makes every layer referenced before it can exist, so pulls need no separate
protection mechanism, and the protection survives atelet restarts. The
per-layer touch makes liveness progress-based: a wedged pull ages out through
ordinary LRU; the end-of-pull rewrite means success always implies a record;
the re-verify turns the residual race into a clean RPC retry instead of a
bundle spec naming a missing lowerdir.
Also new: the config's diffID list is cross-checked against the manifest's
layer count up front and against each layer's actual diffID as it lands, so a
record can never reference something different from what is on disk.
Note for Dmitry Berkovich (@dberkov): this inverts Phase 1's record-last ordering, which
appears incidental (amendment 4 in the Phase 2 comment on #463 — please
contradict if there was intent). A record now explicitly means "known image,
possibly partially present", which is what every reader already handles:
cachedImageverifies each layer and re-pulls only gaps. The one behaviorchange observable without GC: an interrupted pull leaves a valid partial
record — resumable progress — instead of nothing.
Testing: a gated registry holds real pulls mid-flight by blocking chosen
blob downloads — interrupted pull leaves a resumable record and a retry
completes it; a record deleted mid-pull is rewritten on success; per-layer
completions freshen the record while later layers are still gated; a yanked
layer dir fails the pull with a retryable error.
go test -racegreen.