Repository navigation
imagecache: eviction engine — root set, EvictUnused, startup orphan recovery - #735
Merged
Dmitry Berkovich (dberkov) merged 10 commits intoAug 10, 2026
Merged
Dmitry Berkovich (dberkov) merged 10 commits into
Dmitry Berkovich (dberkov) merged 10 commits into
Conversation
Collaborator
Author
|
For reviewers: How a pass decides, and specifically how running actors are protected. Protection is based on use, not age: an image is protected while any actor on this node references it (i.e., while that actor's bundle spec exists on disk). mtime only orders images that nothing references. flowchart TD
subgraph inuse ["Store.InUse() — LOOP over every container bundle of every actor on this node"]
SPEC["read actors/<uid>/bundles/<container>/rootfs-overlay.json"]
SPEC --> MAPS["ImageDigests: spec.imageDigest<br/>LayerHexes: each layer dir the spec names<br/>LayerSets: exact layer-set signature"]
end
inuse --> G0{"root set fully enumerated?<br/>(actors dir, bundles dirs, specs<br/>all readable)"}
G0 -- "no" --> SKIP["⛔ skip entire pass (ERROR) —<br/>partial roots/refcounts would retire layers<br/>running actors still mount or<br/>unread records still name"]
G0 -- "yes" --> listing
subgraph listing ["Store.listEviction() — LOOP over every image record (image-cache/manifests/sha256/*.json)"]
REC["read + decode record;<br/>refcount++ each of its layers<br/>(rooted and fresh records count too)"]
REC --> G1{"this record rooted?<br/>ImageDigests[digest] OR<br/>LayerSets[signature(its diffIDs)]"}
G1 -- "yes — running actors exit here;<br/>mtime never consulted" --> NXT1["next record ↩"]
G1 -- "no" --> G2{"record mtime younger<br/>than min-age?"}
G2 -- "yes" --> NXT1
G2 -- "no" --> CAND["→ candidate list"]
end
listing --> COMPLETE{"was every record read + decoded?"}
COMPLETE -- "no" --> SKIP
COMPLETE -- "yes" --> SORT["sort candidates by mtime, oldest first<br/>(order among evictables — never permission)"]
SORT --> evict
subgraph evict ["Store.EvictUnused() — LOOP over candidates until targetBytes freed"]
RM["removeStaleRecord: re-check under hitMu<br/>(gone? fresh again?) then delete record"]
RM --> layers
subgraph layers ["retireCandidateLayers — LOOP over the deleted record's layers"]
L1{"refcount-- still > 0?<br/>(another image uses it)"}
L1 -- "yes" --> KEEP["layer kept"]
L1 -- "no" --> L2{"LayerHexes[hex]?<br/>(a bundle spec names this layer)"}
L2 -- "yes" --> KEEP
L2 -- "no" --> L3{"layer dir mtime fresh?"}
L3 -- "yes" --> KEEP
L3 -- "no" --> MARK["retireLayer: rename → .rm-* (the mark)"]
end
layers --> KEPT{"anything kept?"}
KEPT -- "yes" --> RESTORE["restoreRecord — record rewritten,<br/>image NOT evicted; next candidate ↩"]
KEPT -- "no" --> EVICTED["image evicted ✓; next candidate ↩"]
end
evict --> RRD["removeRetiredDirs — slow RemoveAll of .rm-* dirs,<br/>outside all locks; crash debris swept at next startup"]
Edited after d1c806a: added the root-set enumeration gate (G0) and corrected the |
igooch
added a commit
to igooch/substrate
that referenced
this pull request
Aug 6, 2026
… the POC Brings the POC's engine to parity with the PR branch: enumeration gate in both passes, undecodable records never candidates, read-only dry-run sizing (layerSizeReadOnly), the decomposed EvictUnused helpers, cachedImageHit, and the tightened comments. Also fast-forwards the POC over everything upstream/main gained since the last sync. The POC's duplicated gated harness (gc_gated_test.go) is dropped: the merged pull_gated_test.go carries the same tests including the EvictUnused-veto assertion.
Dmitry Berkovich (dberkov)
left a comment
Collaborator
There was a problem hiding this comment.
Could you please update internal/imagecache/README.md with the logic how the GC works.
…ecovery The engine that reclaims cache disk, built on the primitives from the size/last-use, spec-digest, record-first-pull, and layer-retirement PRs. Inert in production: nothing calls EvictUnused yet (the watermark GC loop and its flags come separately); the only behavior New gains is the startup orphan scan. - Store.InUse: scans bundle overlay specs under the actors dir (opt-in via WithActorsDir) for the root set — image digests, layer hexes, and exact layer-set signatures. The exact-set rule roots the multi-arch twin record and digestless (pre-ImageDigest) specs' records, without making every superset image unevictable. - Store.EvictUnused: LRU eviction of unprotected images and the layers their removal leaves unreferenced, with min-age vetoes, per-victim re-checks under hitMu held exclusive against the cache-hit touch, and a restore-on-keep commit protocol: if any layer of a deleted record must be kept (still referenced, rooted, fresh, or failed to retire), the record is rewritten from bytes captured at listing time so the kept layer is never stranded unreachable. Freed bytes are credited optimistically from recorded sizes; dry-run mutates nothing. - Store.RecoverOrphans, called once from New: reclaims layer dirs no record references. Runs only at startup, the one moment the scan is race-free (no pull in flight), and skips itself entirely when the record enumeration is incomplete — refcounts from partial data make referenced layers look like garbage. Failure never fails New. - Per-item log lines (root-set entries, per-layer keep/retire, skips) are Debug and gated on Enabled so suppressed passes don't pay for attr construction; pass summaries, evictions, and restores stay Info. - pull_gated_test.go: the slow-pull progress-touch test now asserts the freshened record vetoes a concurrent EvictUnused pass (deferred from the record-first-pull PR, which had no engine to call). Tests cover every veto, shared-layer survival, both restore-on-keep shapes (wedged-pull-fresh-layer and rooted-subset), orphan reclaimed at startup but ignored by the periodic pass, the enumeration completeness gate, dry-run purity, and an ensure-vs-evict race loop under -race.
…erated Review fixes, all in the error paths around unreadable records: - EvictUnused now gates on complete record enumeration, like the startup scan already did. Refcounts from a partial listing understate references - a layer shared with an unreadable record hits zero and is retired while that record still names it - so the doc claim that a partial listing "only ever skips work" was inverted. The pass skips entirely, logs at ERROR naming the records, and returns the error; every later pass retries. Skipping only layer retirement instead would strand the evicted records' layers as orphans until restart, so the whole pass fails toward retention. - An undecodable record is never an eviction candidate: deleting it would strand its (unknown) layers the same way. It stays in place, surfaced in the enumeration error for the operator. - Dry-run no longer writes size-file backfills: dryRunRetire sizes via a read-only variant of layerSize (split into recordedLayerSize + walkLayerSize). The affected population is exactly the pre-size-file layers a dry-run soak on upgraded nodes exists to observe. - restoreRecord documents the cost of its mtime bump: the record's true last-use is lost, accepted because preserving it would churn the same doomed candidate through delete-and-restore every pass. One test per finding: gated pass with an unreadable shared-layer record (root-gated on euid 0), undecodable record survival, and dry-run leaving no size file behind.
The bulleted summary duplicated the per-test comments; sibling test files carry at most a short note on what distinguishes the file.
…oped The hit block in EnsureImage released hitMu.RUnlock explicitly because a defer would have held the read lock across the pull path. Extracting the block into cachedImageHit makes lock scope equal function scope, so defer works - and a panic between lock and unlock can no longer leak a read lock. That leak was free before this PR (hitMu had no exclusive holder); now it would wedge removeStaleRecord, and with it every future eviction pass, in a process whose RPC layer survives panics. Mirrors removeStaleRecord on the write side: both parties to the hitMu contract are now named functions whose body is their critical section, and the field comment points at each.
The hitMu field comment picked up a 123-column line when the function names were inserted; rather than reflowing, shrink it to the invariant - the two named functions (cachedImageHit, removeStaleRecord) now carry the mechanics, so the field comment restating them was duplication. retireCandidateLayers takes dbg as a parameter again instead of recomputing Enabled per candidate, restoring the once-per-pass hoist the extraction had quietly undone.
… in README Review: an unreadable actors dir, bundles dir, or bundle spec silently rooted nothing, failing toward deletion - asymmetric with how unreadable records gate the whole pass. Worse than the record case, because a long-running actor's spec is its only protection: the record mtime can be arbitrarily old, so min-age would not save its layers from being retired under an active mount. InUse now returns (RootSet, error): a non-nil error means the root set may be incomplete, and both EvictUnused and RecoverOrphans skip entirely at ERROR, exactly like the record gate. A missing dir or spec file stays a legitimate empty contribution (no actor placed, torn down, or pre-spec-write); everything else fails toward retention. One table test covers all three unreadable shapes against a rooted image with an arbitrarily old record. Also documents the GC in internal/imagecache/README.md (review ask): replaces the "not implemented yet" section with the engine's pass structure, protection rules, failure direction, startup recovery, and two-phase deletion, and brings the on-disk layout table up to date with the size file and .rm-* entries that shipped in agent-substrate#650/agent-substrate#658.
igooch
force-pushed
the
imagecache-evict-engine
branch
from
August 10, 2026 16:26
34518e6 to
d1c806a
Compare
- Eviction paths now size a layer AFTER retiring it, by walking the renamed-aside tree, so GC never writes a size-file backfill (or its mtime bump) into the live pool. This goes one step past the review's suggestion of bump-without-restore: applied at the eviction call sites, that bump would make the startup orphan scan veto every pre-size-file orphan - the exact population RecoverOrphans exists for on upgraded nodes, and startup only runs once per process. The backfill (now bump-without-restore, per the review) remains only on the CacheSize path, where the one-time freshness bump is harmless and the restore's rewind race is gone. - removeRetiredDirs collects an error per failed dir instead of errgroup.Wait's first-only: each failure is a .rm-* dir sitting invisible until the next restart, so all deserve surfacing. - A garbled diffID in an otherwise-valid record now sets complete=false and gates the pass, matching the undecodable-record handling: a layer referenced only through the garbled entry would otherwise look unreferenced. - Doc fixes: SkippedRooted only fires during the pass (listing-time rooted images count into RootedImages); the listEviction rooted check described as the exact-set match it is, not "every layer rooted".
The rename that retires a layer moves its size file along with it, so sizing the retired dir needs no tree walk: layerSizeReadOnly reads the recorded size in O(1) (walking only when the file is absent, read-only either way). This keeps the no-write-into-the-live-pool property from the previous commit while restoring the O(1) common case - a pass retiring 50 layers no longer does 50 synchronous tree walks - and keeps FreedBytes consistent with CacheSize, which reads the same size files (the walk counted on-disk bytes, the file records tar-stream bytes; the two could disagree by 2x). Also reflows the rooted-record comment left ragged by the previous edit.
igooch
added a commit
to igooch/substrate
that referenced
this pull request
Aug 10, 2026
… the POC Brings the POC to parity with the reviewed PR branch: the root-set enumeration gate (InUse returns an error; both passes skip on it), garbled-diffID gating, per-dir removal errors, size-after-retire crediting from the renamed dir's size file, CacheSize backfill with bump-without-restore, and the README GC documentation — plus everything upstream/main gained since 08-06 (including the new CSI volume plugin). README reconciled: the PR's gate-aware GC section with the POC's loop/flags intro, since the loop exists here. ateompath resolved to main's version with the POC's ActorsDir re-added.
The gate landed without a test. Folded into a table with the undecodable-record case (TestEvictUnusedSkipsPassOnBadRecord): the two share one skeleton - plant a layer and a bad record, assert the pass gates and both survive - differing only in the record bytes.
igooch
force-pushed
the
imagecache-evict-engine
branch
from
August 10, 2026 21:30
9c62b68 to
a046e87
Compare
Dmitry Berkovich (dberkov)
merged commit Aug 10, 2026
596cfb8
into
agent-substrate:main
11 checks passed
This was referenced Aug 10, 2026
Dmitry Berkovich (dberkov)
pushed a commit
that referenced
this pull request
Aug 11, 2026
Phase 2 of #463, continuing from #735 (the eviction engine): the watermark-driven loop in atelet that turns eviction on, plus the flags that govern it. After this: observability (metrics/spans), the ops-tool swap, and the e2e suite. ## What - A serialized, panic-recovered pass every `--image-cache-gc-period` (default 5m; `0` disables the loop entirely). Each tick: `statfs` the cache volume + sum the pool's recorded sizes, compute a byte target — down to `--image-cache-low-percent` when usage crossed `--image-cache-high-percent`, and/or down to `--image-cache-max-bytes` — and hand it to `Store.EvictUnused`. - **The target is capped at the pool's own size.** The cache is one tenant of a shared volume; uncapped kubelet-style watermark math on a pressured volume asks a tiny cache to fix pressure it didn't cause, evicting everything every tick. - **Gated passes are detected by contract, not inference**: the engine exports `ErrIncompleteEnumeration` (wrapped into every gate return), and `classifyGCPass` — a pure, table-tested function — maps each pass to skipped/shortfall/complete/quiet. A gated pass logs ERROR "pass skipped" and never feeds the shortfall backoff. - **Genuine shortfall warns with backoff** then decays to a periodic reminder: on a volume under foreign pressure, shortfall is the steady state and must not ERROR every tick. - atelet passes `WithActorsDir(ateompath.ActorsDir)` so the root set sees placed actors (the wiring #735's notes required); `ateompath` gains the `ActorsDir` constant. - The first pass runs immediately at boot (a node starting under disk pressure shouldn't wait a full period), and a `CacheSize` failure skips the pass explicitly rather than silently zeroing the target. - `--image-cache-gc-dry-run` computes and logs every decision while deleting nothing — the production soak mechanism. A cache dir outside `BasePath` logs a warning (its watermarks would measure a different volume than actor state). - README: the GC section's "loop lands next" intro replaced with the loop/flag documentation. ## For reviewers: the enabled-by-default question Defaults ship **enabled** (5m / 85% / 80%, mirroring kubelet so operator intuition transfers), with dry-run as the opt-out soak path. The alternative is dry-run-by-default for a release. The target cap removes the known pathological case; happy to flip the default if you'd rather soak first. ## Testing - `imagegc_test.go`: watermark/cap target-math table (including the capped-target cases), flag validation. - Loop + engine together, Kind: full gVisor e2e suite green under aggressive flags (15s period, 1-byte cap); planted orphan ignored by periodic passes and reclaimed at startup; shortfall backoff observed against an impossible cap; no enumeration-gate false positives. - GKE (6 nodes): idle pool evicted under aggressive watermarks, subsequent resumes cold-pulled cleanly with snapshot memory continuity; flags restored to defaults after.
Dmitry Berkovich (dberkov)
pushed a commit
that referenced
this pull request
Aug 12, 2026
…oop review follow-ups (#837) Phase 2 of #463, following #735 and #836: `validate-image-cache` drives eviction through `Store.EvictUnused`, deleting its pre-engine prototype. Also carries #836's post-merge review follow-ups. ## Tool - **Prototype evictor deleted** (mtime-sorted tree removal, then dropping every manifest record — no refcounts, no two-phase rename, no restore). The tool now asks the engine to reclaim the shortfall below `--min-free-gb`, so corpus runs exercise production semantics. `--evict-idle` maps to `WithMinAge`. - **`--evict-all`**: one-shot flush, no refs file or auth. Unlike `rm -rf`, running actors' images survive via bundle-spec rooting (`WithActorsDir`). It is not synchronized with a running atelet (the engine's locks are per-process): the pool can't be corrupted, but a layer reused mid-pass can be evicted from under an actor — a not-yet-mounted start fails once and heals; an already-mounted actor can take EIO. Documented, warned at runtime; the intended end state is an atelet-owned flush (RPC or trigger), not a second process in the pool. - **`--evict-idle` floors at 1m when an actors dir exists**: min-age is the only protection that applies across processes, so on a live node it can't be tuned away. Validation hosts (no actors dir) keep full freedom. - Gate-aware errors in both eviction paths (`ErrIncompleteEnumeration` = "did nothing, repair the named path" vs per-item errors = stats still print, exit 1); a 30s cooldown after fruitless passes so workers don't serialize full engine passes when nothing is evictable. ## Carried #836 follow-ups - Negative `--image-cache-gc-period` rejected (was silently disabling the loop); `noteOutcome` extracted with the backoff cadence unit-tested; engine per-pass line demoted to DEBUG (no-target ticks are now silent); single-line sentinel wraps; `filepath.Abs` + table test for the outside-BasePath warning; `runPass`/`Run` covered behind a `gcStore` seam; flag help and README made truthful (`period=0` still runs startup recovery; watermark reads ~5 pts above `df`; the total-size cap still evicts everything evictable under sustained foreign pressure — retention floor named as the extension). ## Testing - Unit: `-race` clean; new tests for backoff cadence, flag validation, path check, `runPass` skip/panic paths, and `Run` (immediate first pass pinned deterministically; ticking covered separately). - Kind: full e2e green; gated-pass arc verified live (one ERROR per tick naming the corrupt record; startup scan gates and recovers; planted orphan reclaimed at restart); `--evict-all` on a live node evicted 4 unrooted images while all rooted images survived. - GKE (6 nodes): zero image-cache log lines fleet-wide at default log level across ticks. - **Corpus sweep** (7.9 GB volume, always-low-water, `--evict-idle=10s` on a host with no actors dir, parallel pulls): 64/64 images validated with two eviction episodes mid-run (62 img / 103 layers / 5.2 GB, then 46 img / 65 layers / 2.7 GB) — continuous eviction under concurrent real pulls, zero races.
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.
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
EvictUnusedyet — the watermark GC loop and its flags come in the next PR. The only behaviorNewgains is the startup orphan scan.What
Store.InUse()— the root set: scans bundle overlay specs under the actors dir (opt-in viaWithActorsDir) 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 underhitMuheld exclusive against the cache-hit touch; two-phase deletion viaretireLayer, with the slowRemoveAlloutside 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 fromNew— reclaims layers no record references. Startup is the one moment this scan is race-free (no pull can be in flight); a failure never failsNew.CacheSize); the size-file backfill exists only on theCacheSizepath, where it bumps the dir mtime rather than restoring it (restoring could rewind a concurrent reuse-touch).Enabledgate (level control via serverboot: dynamic --log-level flag for the server binaries #677); pass summaries, evictions, and restores are Info.internal/imagecache/README.mdnow 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 imagecache: record layer sizes at unpack and image last-use on cache hit #650/imagecache: two-phase layer retirement primitives + .rm-* startup sweep #658.Notes for reviewers
backdate,mustEnsure) and imagecache: write the image record before unpacking layers #717's gated-registry harness — no duplicated symbols. The slow-pull gated test gains the eviction-veto assertion deferred from imagecache: write the image record before unpacking layers #717.layerSizeReadOnly).Storebuilt withoutWithActorsDirhas an empty root set (deliberate for tools/tests).WithActorsDirin atelet; handleEvictUnused'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.