Skip to content

validate-image-cache: drive eviction through Store.EvictUnused + GC loop review follow-ups - #837

Merged
Dmitry Berkovich (dberkov) merged 10 commits into
agent-substrate:mainfrom
igooch:imagecache-validate-tool
Aug 12, 2026
Merged

Dmitry Berkovich (dberkov) merged 10 commits into
agent-substrate:mainfrom
igooch:imagecache-validate-tool

Conversation

@igooch

@igooch igooch commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

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.

@igooch
igooch force-pushed the imagecache-validate-tool branch 2 times, most recently from cccc8e7 to b0ead0b Compare August 11, 2026 15:59
igooch added a commit to igooch/substrate that referenced this pull request Aug 11, 2026
…gent-substrate#837 @ b0ead0b) into the POC

Brings the POC to parity with both open PRs in one merge (the tool
branch stacks on the loop branch): ErrIncompleteEnumeration sentinel
with engine-side gate logs dropped (single ERROR per gated pass, at
the caller), classifyGCPass + imageCacheGC receiver with snapshotted
flags, immediate first pass, honest CacheSize skip, negative-min-age
rejection, cleaned-path BasePath check, and the tool driving eviction
through the engine with WithActorsDir rooting live actors.
@igooch
igooch force-pushed the imagecache-validate-tool branch 2 times, most recently from df0b81d to bce9eab Compare August 11, 2026 17:28
igooch added 3 commits August 11, 2026 15:25
Deletes the evictIfLow prototype - a pre-engine placeholder that
removed the oldest layer trees by mtime with none of the engine's
protections (no refcounts, no two-phase rename, no restore protocol),
then dropped every manifest record to stay tidy. The tool now asks the
engine to reclaim the free-space shortfall, so validation runs get the
same semantics production will: record-driven refcounting, min-age
(--evict-idle maps to WithMinAge), two-phase retirement, and proper
record deletion.

Also adds --evict-all: run one free-everything pass and exit, without
a refs file or registry auth. This is the operator-facing home for
"flush the cache now" (the MaxInt64 path), deliberately a one-shot
tool command rather than a daemon flag.

With no actors dir configured the tool's root set is empty by design -
the corpus exercises refcounts, min-age, and restore-on-keep, not
bundle-spec rooting, which the e2e suite owns.
Review: with no actors dir configured, --evict-all pointed at a live
node's cache would retire lowerdirs under active mounts - a
long-running actor's record is cold, so min-age is no backstop; the
bundle spec is the only protection, and the tool was not reading it.
Both constructors now pass WithActorsDir(ateompath.ActorsDir): on a
live node placed actors root their images; on a validation host the
dir does not exist, which InUse treats as a legitimate empty root set.

Also per review: the package doc carries the live-node framing, and
evictIfLow documents why the tool skips the daemon loop's pool-size
cap (a dedicated validation disk just runs out of candidates).

The branch now stacks on imagecache-gc-loop for ateompath.ActorsDir.
- Reject a negative --image-cache-gc-period (it silently disabled the
  loop at the launch-site guard).
- Extract noteOutcome from runPass and unit-test the shortfall backoff
  cadence: warn x3, reminder every 12th, streak preserved across gated
  passes, reset re-arms the warnings.
- Demote the engine's per-pass Info line to Debug so a no-target loop
  pass is actually silent; the driving caller owns the pass-level line.
- Single-line sentinel wraps: fmt.Errorf("%w: %w") instead of
  errors.Join at the four enumeration gates.
- imageCacheDirOutsideBasePath helper: filepath.Abs before the prefix
  check, table-tested (the warn branch was never exercised).
- Flag help: period=0 leaves startup orphan recovery running; min-age
  governs the startup scan too. Run's doc states the root-context
  convention instead of implying a shutdown stop that never fires.
- README: caveats on the total-size cap (evict-everything under
  sustained foreign pressure; retention floor as the extension) and
  the raw-capacity watermark reading ~5 points above df on ext4.
@igooch
igooch force-pushed the imagecache-validate-tool branch from bce9eab to 22580f5 Compare August 11, 2026 22:26
@igooch igooch changed the title validate-image-cache: drive eviction through Store.EvictUnused validate-image-cache: drive eviction through Store.EvictUnused + GC loop review follow-ups Aug 11, 2026
igooch added 5 commits August 11, 2026 15:41
…est live-node docs

- Split gated vs per-item errors in both eviction paths on the
  ErrIncompleteEnumeration sentinel: evict-all no longer dies statless
  after a pass that ran (per-item errors print stats, then exit 1), and
  evictIfLow no longer calls a did-nothing gated pass "continuing".
- 30s cooldown after a pass that freed nothing, so workers stop running
  a full root-set scan + record enumeration each when nothing is
  evictable yet.
- Note that the statfs shortfall and FreedBytes are different estimates.
- Package doc: bundle-spec rooting protects mounted images, but the
  engine's locks are per-process — stop atelet for a clean flush.
- --evict-all documents min-age survival; --evict-all with --refs-file
  is a usage error; shared store options in one newStore helper.
gcStore (CacheSize + EvictUnused) is the two-method slice of Store the
loop uses; the constructor still takes *imagecache.Store. Tests cover
the statfs-failure and CacheSize-failure skips, target/dry-run
plumb-through, and panic recovery.
- Package doc: run as the cache/actors-dir owner (an unreadable actors
  dir gates every pass); gated-pass comments say unreadable-or-corrupt.
- lastFruitless comment covers the gated-pass case it also backs off.
- runPass target test tolerates a near-full host volume (>= 99, not ==)
  and pre-seeds consecutiveShortfalls so the reset assertion is real.
- listEviction doc states the invariant the %w gates rely on: complete
  is false only alongside a non-nil err.
- Live-node guidance corrected: atelet runs for the node lifetime, so
  "stop atelet first" is gone. The docs and a runtime warning now state
  the real contract: the pool cannot be corrupted (record-first pulls,
  two-phase retirement); worst case a concurrent actor start fails once
  and heals on re-pull.
- Fruitless-pass predicate includes EvictedLayers: a retired layer with
  an unreadable size file credits zero bytes, and bytes alone would
  call that productive pass fruitless.
- Run covered: immediate first pass then ticks, via the gcStore seam.
- Drop the bounded-failure guarantee from --evict-all's contract: the
  per-process locks can't bound the concurrent case (an already-mounted
  actor takes EIO, not a retryable start failure). The package doc
  states both outcomes and the intended end state (an atelet-owned
  flush); the live-node warning is one generic, non-derivable fact.
- Floor --evict-idle at 1m when an actors dir exists: min-age is the
  only protection that applies across processes, so on a live node it
  must not be tuned away. Validation hosts keep full freedom.
- Split the Run test: immediate-first-pass pinned deterministically
  (hour period, pre-cancelled context, exactly one call), ticking
  covered separately.
- Doc audit: --refs-file is not required with --evict-all; the tool
  README's flag table gains --evict-all and sheds the deleted
  prototype's vocabulary; gate comments say "path" (dirs gate too);
  the engine's platform-option comment describes callers generically.
Comment thread tools/validate-image-cache/main.go Outdated
// crash-debris orphans before the pass.
if _, err := os.Stat(ateompath.ActorsDir); err == nil {
// An actors dir is a decent proxy for a live node.
log.Printf("WARNING: %s exists — this looks like a live node, and this run is not synchronized with other processes using the cache", ateompath.ActorsDir)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Refs mode doesn't print this live-node warning, but the unsynchronized-pool caveat applies equally when evictIfLow fires during a validation run beside a live atelet — only the 1m --evict-idle floor guards that case. Consider emitting the same WARNING in refs mode when the actors dir exists, since the eviction path is identical.

Comment thread tools/validate-image-cache/main.go Outdated
// tuned away. Validation hosts (no actors dir) keep full freedom.
const liveNodeIdleFloor = time.Minute
if *evictIdle < liveNodeIdleFloor {
if _, err := os.Stat(ateompath.ActorsDir); err == nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This floor check is silently bypassed when Stat fails with something other than ENOENT (e.g. EACCES on the actors dir). It fails safe in practice — an unreadable actors dir gates every pass via InUse — but if err == nil || !errors.Is(err, os.ErrNotExist) would make the guard airtight and surface the permission problem at startup instead of as gated-pass log lines.

Comment thread tools/validate-image-cache/main.go Outdated
func main() {
flag.Parse()
if *refsFile == "" || *cacheDir == "" {
if *cacheDir == "" || (*refsFile == "" && !*evictAll) || (*refsFile != "" && *evictAll) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: --evict-all silently ignores --min-free-gb, --sample, --seed, --out, and --parallel. Harmless, but rejecting (or logging) non-default values would prevent "why didn't my min-free apply" confusion.

Comment thread tools/validate-image-cache/main.go Outdated
}
candidates = append(candidates, aged{filepath.Join(layersDir, e.Name()), info.ModTime()})
if stats.EvictedImages > 0 || stats.EvictedLayers > 0 {
log.Printf("evicted %d images / %d layers, %.1f GB credited (free now %.0f GB)",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Cosmetic: if freeBytes fails mid-run, its ^uint64(0) sentinel prints here (and in the evict-all summary) as ~18 billion GB. Not worth fixing unless you touch the file again.

igooch added 2 commits August 12, 2026 08:42
- Reject --evict-idle < 0 everywhere (mirrors atelet): a negative
  min-age puts the cutoff in the future, making even in-flight pulls'
  layers evictable — spurious FAILs in the tool's own CSV.
- Fix the inverted severity between the live-node checks: --evict-all
  with an actors dir present now refuses without --force (it was the
  higher-risk operation yet only warned, while the idle floor fataled).
- looksLikeLiveNode() treats anything but ENOENT as a node, so an
  EACCES actors dir no longer bypasses the floor or the force gate.
- Refs mode logs the same live-node caveat as flush mode: evictIfLow
  runs the same engine beside whatever else uses the pool.
- --evict-all rejects explicitly-set refs-mode flags (flag.Visit).
- Fruitless-pass predicate uses the same counters the log line gates
  on; freeGB names the statfs sentinel instead of printing ~18e9 GB.
- Refs mode was evict-all on a loop behind a warning: below
  --min-free-gb (default 150, larger than most node volumes) every
  worker slot triggers an uncapped eviction pass. Both modes now
  require --force on a node with an actors dir; the warning is gone.
- Flag validation extracted into runConfig.validate() and table-tested
  (14 cases): mode XOR, negative idle, live-node floor vs force
  ordering, stray flags, --min-free-gb overflow. Usage-class errors
  carry an errUsage sentinel.
- Stray-flag check inverted to an allowlist so future flags fail
  closed; looksLikeLiveNode parameterized (single stat, testable);
  freeGB sentinel branch tested.
- README: Live nodes section (force requirement, floor, both failure
  outcomes, refs mode flushes repeatedly); "in-flight images are not
  raced" scoped to this process.
@dberkov
Dmitry Berkovich (dberkov) merged commit aeeca4d into agent-substrate:main Aug 12, 2026
11 checks passed
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