Skip to content

imagecache: record layer sizes at unpack and image last-use on cache hit - #650

Merged
Dmitry Berkovich (dberkov) merged 3 commits into
agent-substrate:mainfrom
igooch:imagecache-size-lastuse
Aug 1, 2026
Merged

Dmitry Berkovich (dberkov) merged 3 commits into
agent-substrate:mainfrom
igooch:imagecache-size-lastuse

Conversation

@igooch

@igooch igooch commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator

First slice of #463 Phase 2 (GC): the two facts eviction will need, persisted in the
filesystem so they survive atelet restarts. Inert on its own — no behavior change for
any current caller, and nothing deletes anything.

  • Layer sizes: unpack counts the uncompressed tar stream and writes a per-layer
    size file before the atomic rename (best-effort; a missing file is healed by a
    lazy backfill). Backfill covers layers unpacked by older atelets: one walk, once
    ever, skipping unreadable dirs (atelet has no CAP_DAC_READ_SEARCH) and preserving
    the dir mtime.
  • Last use: cache hits touch the image record's mtime — the persisted LRU
    timestamp — under a new hitMu (shared side only; the eviction pass will be its
    exclusive holder).
  • Store.CacheSize(): sums recorded sizes; the accounting behind the future
    --image-cache-max-bytes.

On-disk changes are purely additive, so no cache-layout version bump and no
migration: an older atelet reads this cache dir fine (ignores size files), and
this atelet reads a pre-upgrade dir fine (backfill). Rollback-safe.

Testing: unit tests for size recording, backfill (incl. the unreadable-dir
contract and mtime preservation), hit-path touch, and CacheSize; go test -race
green standalone; the demo e2e suite passes unchanged on Kind against this build,
with size files and record-mtime updates verified on the node.

Data foundations for eviction (agent-substrate#463 Phase 2), inert on their own:

- unpack counts the uncompressed tar stream and writes a per-layer
  'size' file before the atomic rename, so sizing the pool never walks
  a layer tree; the write is best-effort (a missing size file is
  recovered by the lazy backfill); layers from older atelets are
  backfilled on first sizing (one walk, once ever), skipping unreadable
  dirs (atelet has no CAP_DAC_READ_SEARCH) and preserving the dir mtime
- the cache-hit path touches the image record's mtime, persisting
  last-use for LRU ordering across atelet restarts; the touch happens
  under a new hitMu (shared side only — the eviction pass will be its
  exclusive holder)
- Store.CacheSize sums recorded sizes, the accounting behind the
  future --image-cache-max-bytes

Extracted from the phase2-gc-record-first prototype branch. This slice:
go test -race green standalone; gofmt/vet clean; no behavior change for
any current caller.
Comments now describe the mechanism's purpose (eviction, the GC
root-set scan) without pointing at agent-substrate#463 phases, which would go stale
once the work lands.
Comment thread internal/imagecache/sizes.go Resolved
Comment thread internal/imagecache/sizes.go Resolved
@dberkov
Dmitry Berkovich (dberkov) merged commit 51235e6 into agent-substrate:main Aug 1, 2026
11 checks passed
Dmitry Berkovich (dberkov) pushed a commit that referenced this pull request Aug 1, 2026
…ep (#658)

Third foundation slice of #463 Phase 2 (GC), independent of #650 and
#656. The
primitives are uncalled until the eviction engine PR; the only live
behavior is
the startup sweep, which only ever sees `.rm-*` dirs the engine will
create.

- **`retireLayer`**: evicts a layer with one atomic rename to a `.rm-*`
name
inside the layer singleflight; the slow `RemoveAll` is the caller's job,
outside all locks. Existence/mtime pre-flight runs *outside* the flight
(a
retire must never block behind an in-progress download) and both checks
are
re-run inside it before the rename. Returns gone/vetoed/retired so the
engine
  can distinguish "nothing there" from "must keep".
- **Reuse interlock**: `ensureLayer` now refreshes the layer dir mtime
inside
the same flight, so a retirement and a reuse cannot interleave — either
the
retire wins (the pull re-unpacks) or the touch wins (the retire vetoes).
- **Startup sweep**: `.rm-*` dirs (a crash between rename and removal)
are
reclaimed alongside the existing `.tmp-*` dirs, via `RemoveAllWritable`
since
  layer trees legitimately contain read-only content.
- **`isLayerDirName`** validates names read from disk or records.

Divergence from the prototype: `retireLayer` reports no freed size —
size
crediting belongs to the engine's call sites and arrives with it.

**Testing**: unit tests for the status contract, startup-sweep recovery
and
non-interference, and a retire-vs-pull race test; `go test -race` green.
Dmitry Berkovich (dberkov) pushed a commit that referenced this pull request Aug 1, 2026
…Spec (#656)

Second foundation slice of #463 Phase 2 (GC), independent of #650 and
inert on its
own: nothing reads the new field and nothing deletes anything.

- **`OverlaySpec.ImageDigest`** (optional, `omitempty`): the manifest
digest the
bundle's image ref resolved to, populated in `prepareOCIDirectory`. The
GC
root-set scan will use it to root the whole image record while the
bundle
exists. Compatible in both directions: ateom consumers never read the
field
(old binaries drop the unknown JSON key), and specs written by older
atelets
keep parsing with the field empty — so there is no deploy-ordering
constraint.
- **Atomic `WriteSpec`** (temp file + rename in the bundle dir): the
root-set scan
will read specs concurrently with bundle preparation, and a torn spec
would
  under-report the layers an actor is using — an error in the dangerous
direction (toward deleting in-use layers). With the rename, a reader
sees the
  complete old spec or the complete new one, never a fragment.

Landing early matters: every bundle written from now on carries the
digest,
shrinking the digestless-spec population the GC's compatibility fallback
has to
cover.

**Testing**: round-trip + old-spec compat and no-temp-files-left unit
tests;
`go test -race` green on both affected packages.
igooch added a commit to igooch/substrate that referenced this pull request Aug 10, 2026
… 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.
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.
@igooch
igooch deleted the imagecache-size-lastuse branch October 27, 2026 18:26
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.

2 participants