All posts

8 min readPost 35

Replacing 25 Docker checks with one provider contract—and the two bugs review caught after

When Docker container branches spread to 25+ call sites across four packages, every future resource gets locked out by hardcoding. On 29 November we unified obit doctor, proposal views, and background discovery behind a stdlib-only 6-method extres.Provider plus optional Doctor and Discoverer traits—and independent read-only review caught two sharp bugs before merge: volume.go crossing 500 lines with a decorator purge trap, and auto discovery missing zero CreatedAt and relative Project paths.

On this page
  1. Six methods, zero Docker imports, and opt-in capabilities
  2. Moving the last three Docker-only callers onto extres.Registry
  3. Two bugs independent review caught before merge

Obituary started by attaching countdowns to local files and folders and moving expired items into a restorable graveyard. Later, because developer disks fill up fastest from containers and volumes, we added Docker container lifespans and explicit Docker volume archival.

At first, dropping if item.Kind == KindContainer into a function or two felt fast and harmless. By late November, that shortcut had multiplied into more than 25 hardcoded Docker checks spread across the ledger, lifecycle engine, auto-registration, app views, and obit doctor.

The cost showed up right away on Docker volumes: four separate cleanup and registration paths broke because someone checked for containers and forgot volumes. Adding a second runtime like Podman under that setup would mean hunting through every switch in the repo and hoping none got missed.

On 29 November we finished unifying external-resource dispatch (5bbee23, 5125530, 2135cbe, e684c40) behind a standard-library-only contract—and then ran independent read-only review that caught two concrete bugs before the branch hit main.

Architecture and review-fix diagram: top shows app.ProposalViews, obit doctor, and auto.Engine.Finish dispatching through stdlib-only extres.Registry to ContainerProvider, VolumeProvider (explicitly omitting Discoverer), and future providers; bottom contrasts the two pre-merge review fixes for auto secondary-guard bypasses and volume.go splitting plus rooted decorator purge
Three callers dispatching through stdlib-only extres.Registry by capability (top), and the two bugs independent review caught before merge (bottom).

Six methods, zero Docker imports, and opt-in capabilities ​

The usual trap when abstracting external resources is inventing a bloated CRUD interface—or letting the contract package import Docker types, which guarantees import cycles the moment another runtime arrives.

internal/core/extres imports only four Go standard-library packages (context, encoding/json, io, time) and splits the contract into a tiny core plus opt-in traits:

  • A 6-method Provider (plus Kind()): Validate, Inspect, Verify, Bury, Resurrect, and Purge. The methods mirror Obituary's safety state machine directly: external calls outside ledger locks, durable pre-send intents, and read-back verification. Validate is explicitly restricted to pure in-memory checks because lifecycle calls it inside a store.lock transaction, where blocking I/O or subprocesses are forbidden.
  • Three opt-in capability interfaces: RetentionPolicy (retention and recycle-mode rules), Doctor (live availability and diagnostics), and Discoverer (session-end auto-discovery).

Making Discoverer opt-in lets the Go type system enforce a product safety boundary. docker.ContainerProvider implements Provider + RetentionPolicy + Doctor + Discoverer, while docker.VolumeProvider intentionally does not implement Discoverer. Docker volumes stay explicit --docker-volume opt-in forever; TestVolumeProviderDoctorDiagnoseAndNoDiscoverer asserts that VolumeProvider never satisfies extres.Discoverer, turning any accidental wiring into an immediate test failure.

Moving the last three Docker-only callers onto extres.Registry ​

An interface only earns its keep once the callers stop knowing which concrete runtime sits behind it:

  1. app.ProposalViews drops direct Docker probes: Previously, proposal view rendering checked specifically for container candidates and probed Docker directly. internal/app/proposals.go now filters on c.IsExternal(), looks up an extres.Doctor from the service's registry, caches results per (kind, target), and calls Available(ctx) to populate Blocked. TestProposalViewsDispatchesCustomNonDockerDoctorProvider registers a synthetic podman-container provider and gets podman-unavailable back without changing a single line of app code.
  2. obit doctor reads ledger state through a read-only projection: internal/cli/doctor used to pass raw ledger.State into Docker-specific availability, legacy v14 target, and volume-recovery checks. Now lifecycle.ExternalResourceRecords(st) projects items, burials, proposals, and intents into stdlib-only extres.ResourceRecord snapshots. doctor walks registered extres.Doctor providers in deterministic sorted order and localizes structured Summary + Data fields at the CLI edge. One subtle regression surfaced immediately (5125530): moving volume-recovery scanning into VolumeProvider.Diagnose broke the existing volume-recovery mutation anchor that targeted the path constant in internal/cli/doctor/volume.go. Wiring VolumeDir explicitly through DiagnoseRequest from volumeArchiveRelDir() kept unified dispatch intact while preserving mutation coverage.
  3. auto.Engine.Finish dispatches across registered Discoverers: Background finish (ExternalLeftovers) now loops through every registered extres.Discoverer with a SessionWindow carrying Started, Ended, and project lookup callbacks. Foreground hook entry points still write only their timestamp and never invoke external engines.

Five edge cases got tightened in the same sweep:

  • VolumeProvider.Resurrect forbids raw os.Open(grave.Path): It now requires hooks.OpenGrave, keeping every restore confined inside os.Root even when wrapped by a decorator.
  • VolumeProvider.Purge rejects a nil BeforeSend hook and validates burial volume identity before writing PurgeIntent, so invalid metadata never leaves a half-written intent behind.
  • Mixed Docker overrides suppress stale default volume providers: When a caller or test overrides Service.Docker with a container-only stub, adaptOverriddenDockerProvider treats only zero-value docker.CLI{} as the default placeholder and drops the default VolumeProvider instead of falling through to the host docker binary (TestAdaptOverriddenDockerProviderMixedOverrides).
  • Recycle-mode policy runs before dryRun: settleDockerVolume checks ExcludeFromRecycleMode() ahead of dryRun so dry runs match real execution.
  • Error-free Verify verdicts still gate approval: ApproveContainer maps VerdictNotFound, VerdictIdentity, and VerdictUnavailable even when a provider returns err == nil (TestApproveContainerMapsVerdictWithoutError).

Two bugs independent review caught before merge ​

All tests were green after the refactor, yet an independent read-only review before merging into main uncovered two real defects (2135cbe).

Catch 1: auto's secondary guard let zero CreatedAt and relative Project paths through ​

Even when a Discoverer promises to enforce session windows and absolute project roots, externalCandidate in internal/auto/container.go is the core's second line of defense against a buggy future provider.

Review read two quiet lines in the initial patch and built working bypasses for both:

go
if cand.Project == "" || cand.Reason == "" {
    return "", ledger.Candidate{}, false
}
if !cand.CreatedAt.IsZero() && (cand.CreatedAt.Before(window.Started) || cand.CreatedAt.After(window.Ended)) {
    return "", ledger.Candidate{}, false
}

Both checks had real holes:

  • Relative Project: "." sailed past cand.Project == "": pathutil.LongAbs(".") then resolved "." against whatever working directory the background process happened to be running in, attaching a container to an unrelated project.
  • A zero CreatedAt bypassed the time window completely: If a provider omitted Candidate.CreatedAt, an old container whose encoded id.Created predated the session by two hours—or a candidate where both timestamps were zero—skipped the window check and slipped straight into a proposal.

Before touching the implementation, we added three probe candidates to TestFinishDispatchesCustomDiscovererAndRequiresEvidence—zeroCreatedAtOldID (zero outer timestamp, 2-hour-old credential), bothZeroID (both timestamps zero), and relProjectID (Project: ".")—and watched the test fail on the exact bypasses. Then we hardened externalCandidate:

  • Require filepath.IsAbs(cand.Project) up front so relative paths are rejected outright.
  • Decode the credential first and fall back from a zero cand.CreatedAt to id.Created.
  • Route the final timestamp through withinExternalWindow, which rejects zero timestamps and anything outside [window.Started, window.Ended].

Catch 2: volume.go hit 505 lines and hid a decorator purge trap ​

The second review catch paired a structural guardrail breach with a subtle state-machine failure:

  • Past the 500-line ceiling: Wiring provider dispatch pushed internal/core/lifecycle/volume.go to 505 lines, crossing our ~500-line per-file split limit.
  • Plain extres.Provider decorators got stuck on PurgeIntent: Tracing purgeDockerVolume revealed what happened if a caller wrapped docker.VolumeProvider in a plain 6-method decorator (for logging or metrics) without forwarding the unexported UsesLocalGraveArchive() method. The old usesLocalGraveArchive returned false, routing the burial into purgeCustomVolumeProvider. That path persisted PurgeIntent, called VolumeProvider.Purge with an empty MutateHooks{}, and immediately errored because BeforeSend was nil—leaving a stuck PurgeIntent on disk that permanently blocked obit resurrect as well.

We fixed both cleanly in one pass:

  • Extracted volume purging into internal/core/lifecycle/volume_purge.go (105 lines), bringing volume.go back down to 407 lines.
  • Flipped usesLocalGraveArchive to default to true for KindDockerVolume unless a provider explicitly opts out with false. Any plain decorator around a Docker volume provider now keeps os.Root-confined resurrection and purge by default and never strands a PurgeIntent (TestWrappedVolumeProviderKeepsRootedResurrectAndPurge).
Real terminal output running 10 extres unified dispatch and review-guard contract tests across internal/auto, internal/core/lifecycle, internal/app, internal/cli/doctor, and internal/docker, all passing
Live go test run of all 10 unified dispatch and review-guard contract tests across five packages: zero-timestamp and relative-path rejection, rooted purge under plain decorators, and custom non-Docker provider dispatch.

Existing Docker containers, local volumes, v14–v18 ledgers, and mutation anchors kept their exact behavior. The difference is that doctor, auto, and proposal views no longer know any container engine by name—bringing in the next external runtime now means writing one adapter, not chasing 25 branches across the repo.

All posts