Skip to content

feat: replace the bash cleaner with a Go eviction manager (stage 1) - #197

Draft
masontikhonov wants to merge 85 commits into
masterfrom
cleaner-redesign-stage-1
Draft

masontikhonov wants to merge 85 commits into
masterfrom
cleaner-redesign-stage-1

Conversation

@masontikhonov

@masontikhonov masontikhonov commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

What

Stage 1 of the dind cleaner redesign: the bash cleaner (cleaner-agent.sh, docker-clean.sh, docker-clean-sigterm.sh, functions.sh, the retain and period settings) is replaced by one Go process, dind-cleaner, that owns every eviction.

Draft until the integration suite has run on the merged base (see Verification).

Behaviour

  • Evicts by need, not by age. Nothing is removed while free space and free inodes are above minFree (20% by default). A pass removes the least recently used cache first, across images, volumes and build cache, and stops at targetFree (25%).
  • Last use comes from Docker's live event stream, kept in a small state file on the volume. At start the cleaner replays the pod's events before it removes anything.
  • Two tiers. Tier 1 removes cache from before this build that nothing uses. Tier 2 opens only below emergencyFree (10%) with tier 1 empty, and removes this build's idle cache in order of harm: recreatable cache, exited containers, then unpushed local images.
  • Never evicted: anything in use, a named volume this build created or mounted, pinned items (CLEANER_KEEP_IMAGES, CLEANER_KEEP_VOLUMES).
  • BuildKit GC becomes a backstop at half the emergency level plus the root reserve, written to an effective daemon.json. A customer's own builder.gc wins.
  • run.sh generates the effective daemon config, supervises the cleaner (restart on failure) and gives it a bounded shutdown routine on SIGTERM.
  • Optional age limit, CLEANER_MAX_UNUSED_AGE_HOURS, off by default; meant for local storage.
  • Dry run, CLEANER_DRY_RUN: logs what it would remove and removes nothing.

Configuration

New variables, all optional, documented in cleaner/README.md: CLEANER_ENABLED, CLEANER_DRY_RUN, CLEANER_SPACE_{MIN,TARGET,EMERGENCY}_FREE, CLEANER_INODES_{MIN,TARGET,EMERGENCY}_FREE, CLEANER_KEEP_IMAGES, CLEANER_KEEP_VOLUMES, CLEANER_MAX_UNUSED_AGE_HOURS, and the _SECONDS timing variables.

Old variables: DISK_USAGE_THRESHOLD, INODES_USAGE_THRESHOLD, CLEAN_DOCKER and DISABLE_CLEANER_AGENT are still read as fallbacks, with a log line saying what was done. The retain and period settings are ignored.

What changes for operators

  • Cache is no longer removed after a fixed number of hours.
  • The metrics docker_volume_last_cleaned_ts, docker_volume_last_pruned_ts and docker_volume_cleaner_agent_actions_* are gone until stage 2.
  • The cleaner's log lines are structured (msg=evicted, start and end summaries); cleaner/README.md has a section on reading them.

Tests

  • Unit tests for every package, run by the new "Unit tests" workflow (go vet, go test -race, bash -n run.sh) and by make test.
  • An integration suite against a real daemon in a dind pod, make integration (23 tests: fact tests for the Docker behaviour the design relies on, lifecycle and eviction scenarios). It is not in CI in this stage; it is the manual gate before the release.

Documents

  • Design: docs/superpowers/specs/2026-11-27-dind-cleaner-redesign-design.md, with a "Changes after approval" section.
  • Comparison with the old cleaner: docs/superpowers/specs/2026-11-27-dind-cleaner-redesign-comparison.md.
  • Operator documentation: cleaner/README.md.

Verification

  • Before merging master, on Docker 29.9.3 (404d86b): make test passes; make integration passes 23 of 23.
  • After merging master (feat: upgrade to Docker 29.10; use DHI #192, Docker 29.10 and DHI base images): make test passes on Go 1.27 with moby/client v0.6.3.
  • Not yet run: make integration on the merged base (Docker 29.10.1, DHI). It needs pull access to the private DHI base images. Two things to watch there: the fact tests on the new Docker version, and the test helper image, which is built with apk add e2fsprogs.

Known limits and open points

  • On local storage, a node filled by other volumes puts every pod on it into tier 2.
  • An image used only as a BuildKit FROM base emits no Docker event, so it ages as unused.
  • A restarted cleaner can replay at most Docker's last 256 events; it warns when it detects a lost window.
  • The + 2 second kill margin and the 0.1 second poll in run.sh are hard-coded; whether they become variables is still open.
  • Follow-ups: the venona chart variables, stage 2 (metrics, traces, integration tests in CI), the rootless port.

PR Comments

Add the following comments to the PR:

  • /e2e - to trigger E2E build
  • /bump patch - to bump the patch version
  • /bump minor - to bump the minor version
  • /bump major - to bump the major version

🤖 Generated with Claude Code

Security report

codefresh/dind — fixed 0 CVEs, 0 tickets

Scan

https://g.codefresh.io/build/6b0def879f9f1fa571abefc7

Fixed CVEs: 0

Fixed issues: 0

masontikhonov and others added 30 commits November 27, 2026 23:32
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Add a Makefile with test, image, facts and integration targets, and an
integration test harness that runs the dind image privileged on a
1G loop-mounted ext4 data root formatted by a helper image built from
the image under test. Remove the stale cleaner/dind-cleaner/test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BuildKit counts the filesystem's root reserve as free space, so the
backstop rule as first designed would act only at about 0% free as df
shows it. Confirmed against Docker 29.9.3.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Add integration tests that check, against the dind image's Docker
daemon: the event stream for container, image and volume actions;
registry digests after pull, build, import, load and push; build-cache
prune with an until filter and with a space bound; and that the
BuildKit backstop rule, with the root reserve added to minFreeSpace,
stays inert above its level and acts below it.

Add BuildKit, classic-build, build-cache and root-reserve helpers to
the harness, log cleanup failures, and keep waiting when inspecting a
starting pod fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… run

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s of removed containers

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Wire the internal packages into the binary, build it from the module's
cmd and internal trees, and drop glog. An integration test runs the
binary against a real daemon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
run.sh writes the effective dockerd config with dind-cleaner daemon-config,
starts dockerd with it, supervises dind-cleaner run with restarts, and on
SIGTERM waits for the cleaner's shutdown routine within its timeout. The old
cleaner scripts and their metrics are gone. Lifecycle integration tests cover
the effective config, the disabled cleaner, restarts, shutdown and removal of
the old cleaner's files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A SIGTERM that reaches the supervisor between its loop check and the
cleaner's start is now forwarded to the new cleaner. The shutdown trap
checks /proc for the supervisor instead of kill -0, so a supervisor that
exited early (cleaner disabled) is neither waited for nor confused with a
reused PID. The lifecycle tests assert both, and that a restarted cleaner
keeps the same --pod-start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…wn path

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ail it

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… vacuous checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd Tests sections

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
masontikhonov and others added 30 commits November 30, 2026 21:08
Three causes kept it busy on a volume it could not free:

- Tick stamped the idle recheck from a clock reading taken before the pass,
  so a pass longer than the interval was due again at once. The interval now
  counts from the end of the pass.
- Every container die or destroy woke a full pass on the next tick, one per
  second under a build that churns containers. Those wakes are now spaced
  by CLEANER_WAKE_RECHECK_INTERVAL_SECONDS, 5 by default. Dropping below
  the emergency level still wakes at once.
- A dry-run pass or sweep took a full snapshot per candidate although
  nothing it does changes what Docker holds. It now takes one for its whole
  queue.

A candidate that failed is still tried and logged again on every pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The tracker applied events one at a time and waited for a container
inspect, up to the Docker call timeout, on every container create and
start. A volume's mount event could wait behind that, so a pass could see a
named volume the running build had just mounted as unreferenced cache from
before the build, and remove it.

After the catch-up the tracker now follows two streams: volumes, and
containers with images. A volume event needs no Docker call, so its use is
recorded at once whatever the inspects on the other stream do. An image's
use can still lag behind a slow inspect; that costs a re-pull.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The backstop's minFreeSpace adds the root reserve, measured as free minus
available blocks. A volume the previous build filled into the reserve
reports no available blocks, so the difference was only what was left of
the reserve, and the backstop acted when df already showed nothing free.

With no available space the reserve is now taken as at least 5% of the
size, ext4's default, and daemon-config logs a warning. On a full
filesystem that keeps no reserve this makes the backstop act at about the
emergency level for that pod.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A level that was not set took its fixed default, and the trio then had to
satisfy emergency < min < target. Setting one level alone therefore
usually reverted all three: CLEANER_SPACE_MIN_FREE=5GB on a 16Gi volume,
the documented example, ended above the default target.

The three variables of a resource are now set together or not at all. With
one or two set, all three fall back to the defaults, the note names the
missing ones, and the old threshold is not used. With none set the old
threshold still decides. loadLevels loses its parallel arrays on the way.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…is found

With USE_DIND_IMAGES_LIB, run.sh points DOCKERD_DATA_ROOT at the directory a
library is moved to before it knows one is available. Without a library that
directory does not exist and dockerd runs on its default root. The old
scripts read the variable from the environment, where it was exported only
after a successful move, so they mostly saw the default root. The new
commands were given the missing directory: daemon-config failed and the
cleaner exited 1 and was restarted for the life of the pod.

run.sh now keeps the root dockerd really runs on in a variable of its own
and passes that to both commands. DOCKERD_DATA_ROOT is left alone, because
the SIGTERM trap removes it in this mode.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A prune was bounded by the bytes missing to the target. When a pass ran
because inodes were short and bytes were not, that was zero and the prune
had no bound: tier 1 removed its whole batch, and an inode emergency
removed all unused build cache, this build's included.

BuildKit cannot bound a prune by inodes, so such a prune is now bounded to
the bytes between the minimum and the target level. The pass already
re-reads inodes after each prune and prunes the same batch again, so the
cache goes in steps until the inode level is met. The Pressure fields are
renamed to say what they hold: the bytes a prune is to free.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…t use

Tier 1 queues a build-cache record by its own last use and expects a prune
bounded after that time to delete it. That may not hold for a record that
newer records were built on: Docker may list it as unused while BuildKit
keeps it until those are gone. TestFactBuildCacheChain builds three steps,
then a fourth on top after the bound, and fails if a record listed as
unused and last used before the bound survives the prune. It has not run
yet.

Whatever the answer, a prune that deletes nothing is an ordinary outcome.
It still takes the batch out of the pass, but it is now logged at info
level and no longer as a failed eviction.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A pattern without a wildcard must equal the whole reference, and Docker
lists an image as repository:tag or repository@digest. A pin written as a
bare repository name, the style of the removed preserved-images file,
therefore pinned nothing and said nothing.

Matching stays exact. The cleaner now logs a note at startup for each
CLEANER_KEEP_IMAGES pattern with no tag, no digest and no *, naming the
pattern that pins every tag.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The sweep recorded its time before its first listing, so one Docker timeout
postponed it by a full CLEANER_AGE_SWEEP_INTERVAL_SECONDS. The interval now
counts from a sweep whose listing succeeded; one that could not list is
tried again on the next tick.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- cleaner_supervisor kept the dead cleaner's PID during the restart sleep,
  and a SIGTERM in that window sent kill -TERM to it. The PID is cleared
  once the child is reaped.
- seconds_or_default accepted any positive integer, while the cleaner
  rejects a CLEANER_SHUTDOWN_TIMEOUT_SECONDS too large for a duration. It
  now applies the same upper bound, so the two cannot disagree.
- The comment on cleaner_supervisor_running states what the check relies
  on: the script being started under the name run.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The cleaner counts the space df shows as available, which leaves out
ext4's 5% root reserve. With the default levels the cache therefore
holds at 70 to 75% of the volume, not at the 75 to 80% the README, the
design and the comparison gave, and DISK_USAGE_THRESHOLD=0.8 acts five
points earlier than under the old cleaner. The basis and the defaults
stay; the documents now say what they amount to.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The review found that a prune bounded by BuildKit's own minFreeSpace
would do the arithmetic the cleaner does today, on a fresher reading.
It rests on source reading and changes what TestFactBuildCachePruneBound
pins, so the computed bound stays and the idea goes under Follow-ups.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
On local storage the node agent of dind-volume-utils deletes idle
volumes at the level where the in-pod cleaner starts, and the cleaner
checks sixty times as often, so hot cache goes before cold volumes.
What to advise operators is left open; the design now names the
interaction and the lever under Follow-ups.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A build that fills the volume itself runs between the emergency level
and the tier-2 target for the rest of its life. That is by design, and
it is the first place to look after a no-space report, so stage 2
should measure it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The script defined DIND_VOLUME_STAT_DIR and created the directory for
the old cleaner's files. The metrics read from those files are gone,
so nothing in the script uses the variable; run.sh creates the
directory itself.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Docker's default builder GC removes cache mounts, local sources and git
checkouts that were unused for 48 hours. The backstop is a single rule
that replaces the defaults, so that expiry no longer happens. It is the
intended behaviour, but an operator who relied on it should be able to
read it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Every line of the manager went through two single-letter fields, o for
its options and d for its dependencies, on a receiver named m. The
manager now holds what it uses directly (manager.docker, manager.usage,
manager.config, manager.thresholds), as the kubelet's managers do. New
keeps its two arguments, so callers do not change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
evict took seven parameters and remove five, because a candidate named
only what to remove: remove looked the container's volumes up in the
snapshot, computed the prune bound from the snapshot and the pressure,
and took "tier 0" to mean "force".

The policy now fills that in. Tier1 and Tier2 take the bytes a prune is
to free and put the bound on the build-cache candidate, a container
candidate carries its volumes, and the startup leftovers come from
policy.Leftovers, marked as forced. remove needs only the candidate.

The skip rule is stated once: whatever evict tries is skipped for the
rest of the pass, except a build-cache batch whose prune deleted
records. Candidate.Key returns a comparable struct in place of a
formatted string.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The tier went through evict as a bare 0, 1 or 2 next to the reason,
although the reason already decides it: a leftover is tier 0, an
emergency eviction tier 2, everything else tier 1. The report rebuilt
the tier's name from a rune.

report.Tier names the three stages and Reason.Tier returns the one a
reason belongs to, so callers pass only the reason and an eviction
cannot be reported with a tier that contradicts it. The log lines are
unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The tracker was free functions that handed the same source, usage log,
resolver and options to each other, five to seven arguments at a time,
and its caller passed the Docker client twice by position.

tracker.New takes its settings and its dependencies as two structs, as
the manager does, and Run, catchUp, follow, consume, record and apply
are methods that receive only what changes from call to call: the time
to continue from and the stream's event types. Apply is no longer
exported; only the tests called it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The Docker adapter handed events to the tracker over two channels fed
by a goroutine, and the tracker drained them in three select branches,
with a nested select to tell a failed stream from one that ended.

Events now returns an iter.Seq2 that yields each event and, if the
stream breaks, the error last. The adapter's goroutine and channels are
gone, the tracker's consume is a for-range loop, and Replay ranges over
the same sequence with an until. Stopping the loop cancels the request.
A stream that ends because the cleaner is stopping is no longer logged
as failed.

The integration adapter test follows the new shape; it is compiled, not
run.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- report.NothingLeft holds the policy's counts instead of six fields
  that the manager copied over one by one.
- The manager reads free space through diskStat, which logs a failure.
  "cannot read free space" was logged from seven places, three of them
  only to log the one error evict can return.
- policy.Tier2 returns its queue as one slice. It returned three, and
  its only caller joined them at once.
- docker.Client.Snapshot is built from images, volumes and buildCache,
  each with a deferred cancel like the rest of the file, where it
  repeated the timeout handling inline three times. call is now
  withTimeout, which says what it returns.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- Structs declare one field per line. Config had up to seven on one,
  and the same habit was in disk.Stat, the report's summaries and
  several small types.
- The two levelVars literals name their fields; they ended in a bare
  false and true.
- config.Load returns its notes next to the Config, as Resolve already
  did. Notes are not configuration, and the command now logs both lists
  the same way.
- A local named min no longer shadows the builtin.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The config package had four type names for two ideas. Level and Levels
are what was configured, a percentage or a size. Triple held one
resource's resolved numbers, Thresholds the resolved pair for space and
inodes, and the start summary kept a Thresholds in a field named
Levels.

Levels are now what is configured and thresholds what they resolve to:
Triple becomes Thresholds, the pair becomes DiskThresholds, and the
start summary's field is Thresholds. The log fields are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Each write created state.json.tmp-<random>. A cleaner killed between
creating that file and renaming it left it on the persistent volume,
and nothing ever removed it, so a volume could collect them over many
pods.

Saves are serialized, so one name is enough. The next write truncates
whatever a killed cleaner left under that name and renames it into
place.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- usage.Load returns nil with an error. It returned a usable log next
  to a non-nil error and the command relied on that; the fallback to an
  empty log is now the caller's, in loadUsage, with a test.
- The manager declares the Docker interface it needs, as the tracker
  already did, and the ten-method docker.API next to its implementation
  is gone.
- RemoveContainer takes RemoveContainerOptions, named as Docker's own
  client names them, in place of two adjacent booleans.
- Docker's words have names: the event types and actions come from
  moby's constants, the container state and the cache record types the
  policy compares are constants in inventory.
- removeAllContainers and removeExportImages return a plain int. They
  named the result and then returned it explicitly.
- In the command, the dispatcher is dispatch, no longer run next to
  runCommand, and the usage log is not held in a variable named log.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Two rules, applied once on the final shape of the code, tests included.

Names are words. Receivers, parameters, locals and unexported fields
that were one or two letters are spelled out: cli for the Docker
client, log for the usage log, candidate, pressure, input, snapshot,
thresholds, and manager, fake, recorder and clock in the tests. Loop
indices, counts named n, and err, ok and ctx stay. Two types changed so
that a variable does not carry its type's name: state is inputState and
loader is envLoader.

Booleans read as is or has: Config.IsEnabled and IsDryRun,
DiskThresholds.HasInodes, Volume.IsAnonymous, CacheRecord.IsInUse and
IsShared, the Pressure fields, Meta.IsFound and IsSamePod, Log.IsDirty,
Candidate.IncludesShared, and the manager's isIdle, isWoken and
wasBelowEmergency. Fields that mirror Docker's own names (All, Enabled,
Force, RemoveVolumes) keep them.

Renames only; the log output does not change. The integration tests
are renamed with the rest and compile.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The workflow runs go vet and the tests but no linter. The module gets a
.golangci.yml with the default linters plus revive, gocritic, unparam
and predeclared, over the integration tests' code too, and make lint
runs it. Errors of Close, os.Remove and printing to stdout are not
checked, as usual, and a test helper may take *testing.T before its
context.

What it found is fixed: a test helper's parameter named min, a
parameter that was always 1, and an event sequence ranged without
looking at its error. The workflow step itself is left to the CI work.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
ADD . /dind put the Go sources and tests, the Makefile and whatever else
the build context held into the production image. At run time the image
needs run.sh, docker/ and monitor/, so those are copied by name. The old
cleaner's scripts, which were the reason for copying everything, are
gone.

.git, .github and the top-level Markdown files are left out of the
build context as well.

Not built here: the base images are private. make integration builds
the image and covers it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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.

1 participant