carlos / platform Public

host: bounded build-output retention for demo apps

Demo disk bound, slice 1. After every adoption of a demo version (the
hourly pass and -stage-only, which adopts relayed versions) and on the
hourly pass as a backstop, root deletes the demo outputs nothing on the
box names: per app, <ver>/<account>/<app> and its manifest, never a
version directory. Pins from every source: live and previous links,
every registry row and its settings references, the generations file
and root's generation ledger; a source that does not read deletes
nothing. Only under the adopt pass lock. A version staged after the
app's newest adoption is kept as in flight. Before a demo app's new
output is staged, its unadopted, unpinned outputs go first; a cleanup
that cannot run refuses the stage. Root records the outputs held and
the backlog, with its start, for box status.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ed8116a7d1693bb1654c5383d8524db35388e6be parent 2e5e222
4 files changed, +1,318 −2
  • internal/host/agent.go +9 −2
  • internal/host/demoretention.go +559 −0
  • internal/host/demoretention_linux_test.go +164 −0
  • internal/host/demoretention_test.go +586 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 2b5947037..d6c3aa485 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -6363,8 +6363,15 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni
// adopt a proven head over it (final review H4). After it, mint on a
// proving box and, on the hourly pass, say when a requirement is off;
// a route the pass changed is looked at again first.
- passErr := pr.around(ctx, func() error {
- return release.Pass(ctx, reg, store, pub, release.OptDir(), restart, passOpts...)
+ // The demo disk bound's build-output retention (demoretention.go): the
+ // pending-output cleanup before a demo app's new output is staged, and
+ // retention after a pass that adopted a demo version, or on the hourly
+ // pass. Both only under this pass's lock, held until the pass returns.
+ demoRet := productionDemoRetention(reg, generationPins, passLockErr == nil)
+ passErr := demoRet.wrap(ctx, !*stageOnly, func(stage release.PassOption) error {
+ return pr.around(ctx, func() error {
+ return release.Pass(ctx, reg, store, pub, release.OptDir(), restart, append(passOpts, stage)...)
+ })
})
if passErr != nil {
log.Printf("adopt: %v", passErr)
diff --git a/internal/host/demoretention.go b/internal/host/demoretention.go
new file mode 100644
index 000000000..c622fbf8e
--- /dev/null
+++ b/internal/host/demoretention.go
@@ -0,0 +1,559 @@
+// Bounded build-output retention for demo apps (demo disk bound plan,
+// slice 1; spec 2026-11-29-demo-disk-bound-design.md §15 Q4).
+//
+// Every demo update stages a new build of up to 32 MiB under
+// <opt>/versions/<ver>/<account>/<app>, and before this nothing removed one
+// until the demo's purge: up to 61 builds a demo. Retention deletes a demo
+// app's outputs that nothing on the box still names, after every adoption of
+// a demo version and on the hourly pass, and the pending-output cleanup
+// below keeps at most one output a demo app never adopted.
+//
+// The deletion-safety contract:
+// - pins from every source, read in full: the live links (and their
+// previous links), every registry row's Version, PrevVersion and
+// GoodVersion and its settings references (release.BoxPins), the
+// generations file (release.GenerationPins) and root's generation
+// ledger (productionRootGenerationPins). A source that does not read in
+// full deletes nothing;
+// - only with the adopt pass lock held (lockAdoptPass), which RunAdopt
+// holds from before the first pin read until after the last removal;
+// - per app: <ver>/<account>/<app> and its .manifest.json, beneath the
+// version store with no symlinks, as purgeDemoVersions removes them.
+// Never a whole version directory, which can hold other apps; the
+// time-graced sweep (release.SweepStaged) stays the only remover of
+// those;
+// - a version staged after the app's newest adopted one is in flight and
+// kept by retention, until a later pass sees it adopted or superseded;
+// - non-demo apps are never touched.
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rootstate"
+)
+
+// demoRetentionDir is root's public record of the last retention run, which
+// the agent reads for box status. Root-owned and written by descriptor
+// (rootstate), so nothing the agent can write is ever read back by root as
+// a pin or a decision: the record is status only.
+const (
+ demoRetentionDir = "/var/lib/carlos-release/demo-retention"
+ demoRetentionRecord = "status"
+ // demoBacklogStale is how old a retention backlog may get before box
+ // status gives it a line of its own.
+ demoBacklogStale = 24 * time.Hour
+)
+
+// demoRetentionStatus is the record: what the last run left, and the
+// backlog, the demo outputs held beyond the bound because a run could not
+// delete them, with when that began.
+type demoRetentionStatus struct {
+ Schema int `json:"schema"`
+ At time.Time `json:"at"`
+ Outputs int `json:"outputs"`
+ OutputBytes int64 `json:"output_bytes"`
+ Backlog int `json:"backlog"`
+ BacklogSince time.Time `json:"backlog_since,omitzero"`
+ Reason string `json:"reason,omitempty"`
+}
+
+type demoRetention struct {
+ box demo.Config
+ reg routeLister
+ optDir string
+ genPath string
+ rootPins release.PinSource
+ // locked: the caller holds the adopt pass lock. Without it retention
+ // deletes nothing and the pending-output cleanup refuses the stage.
+ locked bool
+ record func() (rootstate.Store, error)
+ now func() time.Time
+ remove func(dir, name string) error
+ logf func(string, ...any)
+ // Witness seams: called before the first pin read of a selection and
+ // before each removal.
+ onPins func()
+ onRemove func(path string)
+}
+
+// productionDemoRetention is RunAdopt's: the box's demo settings from
+// host.env, the version store and generations file, root's generation
+// ledger and its public record directory.
+func productionDemoRetention(reg routeLister, rootPins release.PinSource, locked bool) *demoRetention {
+ box, err := demo.BoxConfig(os.Getenv)
+ if err != nil {
+ log.Printf("adopt: demo build retention off: %v", err)
+ box = demo.Config{}
+ }
+ return &demoRetention{box: box, reg: reg, optDir: release.OptDir(), genPath: release.GenerationsPath(dataDir()),
+ rootPins: rootPins, locked: locked, now: time.Now, remove: instancefs.RemoveAllBeneath, logf: log.Printf,
+ record: func() (rootstate.Store, error) { return rootstate.Open(demoRetentionDir, true, true) }}
+}
+
+type demoAppKey struct{ acct, app string }
+
+// demoOutput is one app's build at one version: the executable and its
+// manifest, either of which may be all that is left.
+type demoOutput struct {
+ demoAppKey
+ version string
+ bytes int64
+ keep bool
+}
+
+func (o demoOutput) path(optDir string) string {
+ return release.VersionPath(optDir, o.acct, o.version, o.app)
+}
+
+// demoApp reports the app a demo route runs on this demo box, or false.
+func (r *demoRetention) demoApp(rt registry.Route) (demoAppKey, bool) {
+ if !r.box.BoxMode() || !rt.IsDemo() || rt.App == "" || !strings.HasPrefix(rt.App, demo.AppPrefix) {
+ return demoAppKey{}, false
+ }
+ acct := release.RouteAccount(rt)
+ if acct != r.box.Account {
+ return demoAppKey{}, false
+ }
+ return demoAppKey{acct, rt.App}, true
+}
+
+// demoGeneration reads the console's demo version name (v0.0.0-demo.<n>,
+// internal/console's demoVersion) as its generation.
+func demoGeneration(v string) (uint64, bool) {
+ rest, ok := strings.CutPrefix(v, "v0.0.0-demo.")
+ if !ok {
+ return 0, false
+ }
+ n, err := strconv.ParseUint(rest, 10, 64)
+ if err != nil || strconv.FormatUint(n, 10) != rest {
+ return 0, false
+ }
+ return n, true
+}
+
+// inFlight: v was staged after every version the app's routes adopted. A
+// name this cannot order is kept: the cautious answer, and the
+// pending-output cleanup still bounds it.
+func inFlight(v string, adopted []string) bool {
+ g, ok := demoGeneration(v)
+ if !ok {
+ return true
+ }
+ for _, a := range adopted {
+ if a == "" {
+ continue
+ }
+ n, ok := demoGeneration(a)
+ if !ok {
+ return true
+ }
+ if n >= g {
+ return false
+ }
+ }
+ return true
+}
+
+// pinSet is every pin path from every source. strict: any source that does
+// not read in full is an error. Otherwise (the backlog estimate) a failed
+// source adds nothing.
+func (r *demoRetention) pinSet(ctx context.Context, routes []registry.Route, strict bool) ([]string, error) {
+ var out []string
+ add := func(name string, paths release.StagedPaths, err error) error {
+ if err != nil {
+ if strict {
+ return fmt.Errorf("%s: %w", name, err)
+ }
+ return nil
+ }
+ for p := range paths {
+ out = append(out, filepath.Clean(p))
+ }
+ return nil
+ }
+ box, err := release.BoxPins(r.optDir, routes)
+ if err := add("live links and registry rows", box, err); err != nil {
+ return nil, err
+ }
+ if !strict {
+ // BoxPins answers nothing when one live link does not read; the
+ // estimate still knows what the rows name.
+ for _, rt := range routes {
+ refs, _ := release.SettingsRefs(rt)
+ for _, v := range append([]string{rt.Version, rt.PrevVersion, rt.GoodVersion}, refs...) {
+ if rt.App != "" && release.ValidVersion(v) {
+ out = append(out, release.VersionPath(r.optDir, release.RouteAccount(rt), v, rt.App))
+ }
+ }
+ }
+ }
+ prev, err := previousLinkPins(r.optDir)
+ if err := add("previous links", prev, err); err != nil {
+ return nil, err
+ }
+ gen, err := release.GenerationPins(r.genPath, func() ([]registry.Route, error) { return routes, nil }).StagedPins(ctx, r.optDir)
+ if err := add("generations file", gen, err); err != nil {
+ return nil, err
+ }
+ var root release.StagedPaths
+ err = os.ErrPermission
+ if r.rootPins != nil {
+ root, err = r.rootPins.StagedPins(ctx, r.optDir)
+ }
+ if err := add("root generation pins", root, err); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// previousLinkPins is every <opt>/previous link's target, as release.LivePins
+// reads them for the sweep, at the path it names and its real path.
+func previousLinkPins(optDir string) (release.StagedPaths, error) {
+ dir := filepath.Join(optDir, "previous")
+ entries, err := os.ReadDir(dir)
+ if errors.Is(err, os.ErrNotExist) {
+ return release.StagedPaths{}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ pins := release.StagedPaths{}
+ for _, e := range entries {
+ link := filepath.Join(dir, e.Name())
+ target, err := os.Readlink(link)
+ if err != nil {
+ return nil, err
+ }
+ if !filepath.IsAbs(target) {
+ target = filepath.Join(dir, target)
+ }
+ pins[filepath.Clean(target)] = true
+ real, err := filepath.EvalSymlinks(link)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ if err == nil {
+ pins[real] = true
+ }
+ }
+ return pins, nil
+}
+
+// pinned: a pin names the output, its manifest or something inside it,
+// under the store's own spelling or its real path. A pin on a directory
+// holding it (a root generation's Tree, <ver>/<account>) pins that
+// directory's identity, which removing a sibling app's file leaves as it
+// was, so it does not keep the sibling.
+func pinned(pins []string, optDir string, o demoOutput) bool {
+ exe := o.path(optDir)
+ names := []string{exe, exe + ".manifest.json"}
+ if real, err := filepath.EvalSymlinks(filepath.Dir(exe)); err == nil {
+ base := filepath.Join(real, o.app)
+ names = append(names, base, base+".manifest.json")
+ }
+ for _, p := range pins {
+ for _, n := range names {
+ if p == n || strings.HasPrefix(p, n+string(filepath.Separator)) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// selection is one look at the store for the demo apps (only, when set):
+// every output present, each marked kept or not.
+func (r *demoRetention) selection(ctx context.Context, only *demoAppKey, keepInFlight, strict bool, except string) ([]demoOutput, error) {
+ if r.onPins != nil {
+ r.onPins()
+ }
+ if r.reg == nil {
+ return nil, os.ErrPermission
+ }
+ routes, err := r.reg.List()
+ if err != nil {
+ return nil, fmt.Errorf("list routes: %w", err)
+ }
+ adopted := map[demoAppKey][]string{}
+ for _, rt := range routes {
+ if k, ok := r.demoApp(rt); ok && (only == nil || *only == k) {
+ adopted[k] = append(adopted[k], rt.Version)
+ }
+ }
+ if len(adopted) == 0 {
+ return nil, nil
+ }
+ pins, err := r.pinSet(ctx, routes, strict)
+ if err != nil {
+ return nil, err
+ }
+ versions, err := os.ReadDir(filepath.Join(r.optDir, "versions"))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ apps := make([]demoAppKey, 0, len(adopted))
+ for k := range adopted {
+ apps = append(apps, k)
+ }
+ sort.Slice(apps, func(i, j int) bool { return apps[i].app < apps[j].app })
+ var out []demoOutput
+ for _, v := range versions {
+ if !v.IsDir() || !release.ValidVersion(v.Name()) {
+ continue
+ }
+ for _, k := range apps {
+ o := demoOutput{demoAppKey: k, version: v.Name()}
+ exe := o.path(r.optDir)
+ present := false
+ for _, p := range []string{exe, exe + ".manifest.json"} {
+ fi, err := os.Lstat(p)
+ // ENOTDIR: <ver>/<account> is an ops app's file of that name.
+ if errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) {
+ continue
+ }
+ if err != nil {
+ return nil, err
+ }
+ present = true
+ if fi.Mode().IsRegular() {
+ o.bytes += fi.Size()
+ }
+ }
+ if !present {
+ continue
+ }
+ o.keep = o.version == except || pinned(pins, r.optDir, o) || (keepInFlight && inFlight(o.version, adopted[k]))
+ out = append(out, o)
+ }
+ }
+ return out, nil
+}
+
+// removeOutput deletes one output beneath its version directory, the
+// executable first, as purgeDemoVersions does.
+func (r *demoRetention) removeOutput(o demoOutput) error {
+ exe := o.path(r.optDir)
+ if r.onRemove != nil {
+ r.onRemove(exe)
+ }
+ for _, name := range []string{o.app, o.app + ".manifest.json"} {
+ if err := r.remove(filepath.Dir(exe), name); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ }
+ return nil
+}
+
+// demoRetentionResult is one run's outcome, for the log and the record.
+type demoRetentionResult struct {
+ removed []string
+ outputs int
+ outputBytes int64
+ backlog int
+ err error
+}
+
+// retain is one retention run, deleting only under the lock and on a
+// complete pin set.
+func (r *demoRetention) retain(ctx context.Context) demoRetentionResult {
+ var res demoRetentionResult
+ var outs []demoOutput
+ if !r.locked {
+ res.err = errors.New("the adopt pass lock is not held")
+ } else {
+ outs, res.err = r.selection(ctx, nil, true, true, "")
+ }
+ if res.err != nil {
+ // Deletes nothing. The backlog is estimated on what does read.
+ est, err := r.selection(ctx, nil, true, false, "")
+ if err != nil {
+ res.backlog = -1
+ return res
+ }
+ for _, o := range est {
+ res.outputs++
+ res.outputBytes += o.bytes
+ if !o.keep {
+ res.backlog++
+ }
+ }
+ return res
+ }
+ var failed []error
+ for _, o := range outs {
+ if !o.keep {
+ if err := r.removeOutput(o); err != nil {
+ failed = append(failed, fmt.Errorf("%s: %w", o.path(r.optDir), err))
+ res.backlog++
+ } else {
+ res.removed = append(res.removed, o.app+"@"+o.version)
+ continue
+ }
+ }
+ res.outputs++
+ res.outputBytes += o.bytes
+ }
+ if len(failed) > 0 {
+ res.err = errors.Join(failed...)
+ }
+ return res
+}
+
+// run is retention as RunAdopt calls it: retain, log, and record.
+func (r *demoRetention) run(ctx context.Context) demoRetentionResult {
+ if r == nil || !r.box.BoxMode() {
+ return demoRetentionResult{}
+ }
+ res := r.retain(ctx)
+ switch {
+ case res.err != nil:
+ r.logf("adopt: demo build retention deleted nothing it could not prove unused: %v (backlog %d)", res.err, res.backlog)
+ case len(res.removed) > 0:
+ r.logf("adopt: demo build retention: removed %d demo builds, %d kept (%d bytes): %v", len(res.removed), res.outputs, res.outputBytes, res.removed)
+ }
+ r.writeRecord(res)
+ return res
+}
+
+// writeRecord records res, carrying the backlog's start across runs. A
+// record that cannot be written is logged: it is status, never a gate.
+func (r *demoRetention) writeRecord(res demoRetentionResult) {
+ if r.record == nil {
+ return
+ }
+ s, err := r.record()
+ if err != nil {
+ r.logf("adopt: demo build retention: record: %v", err)
+ return
+ }
+ defer s.Close()
+ now := r.now().UTC()
+ var prev demoRetentionStatus
+ if raw, err := s.Read(demoRetentionRecord); err == nil {
+ _ = json.Unmarshal(raw, &prev)
+ }
+ next := demoRetentionStatus{Schema: 1, At: now, Outputs: res.outputs, OutputBytes: res.outputBytes, Backlog: res.backlog}
+ if res.backlog < 0 {
+ // Nothing read at all: keep the last known numbers.
+ next.Outputs, next.OutputBytes, next.Backlog = prev.Outputs, prev.OutputBytes, max(prev.Backlog, 1)
+ }
+ if res.err != nil {
+ next.Reason = res.err.Error()
+ }
+ if next.Backlog > 0 {
+ next.BacklogSince = now
+ if prev.Backlog > 0 && !prev.BacklogSince.IsZero() {
+ next.BacklogSince = prev.BacklogSince
+ }
+ }
+ raw, err := json.Marshal(next)
+ if err == nil {
+ err = s.Write(demoRetentionRecord, raw)
+ }
+ if err != nil {
+ r.logf("adopt: demo build retention: record: %v", err)
+ }
+}
+
+// beforeStage is the pending-output cleanup (plan slice 1, step 4), run
+// through release.WithBeforeStage before a demo app's new output is
+// staged: every staged output of that app that is neither adopted nor
+// pinned (a failed job's leftover) goes first. If that cannot run in full,
+// the stage is refused and nothing is deleted; the next attempt retries.
+func (r *demoRetention) beforeStage(ctx context.Context, rt registry.Route, ver string) error {
+ if r == nil {
+ return nil
+ }
+ k, ok := r.demoApp(rt)
+ if !ok {
+ return nil
+ }
+ if !r.locked {
+ return errors.New("demo build cleanup: the adopt pass lock is not held")
+ }
+ outs, err := r.selection(ctx, &k, false, true, ver)
+ if err != nil {
+ return fmt.Errorf("demo build cleanup: %w", err)
+ }
+ for _, o := range outs {
+ if o.keep {
+ continue
+ }
+ if err := r.removeOutput(o); err != nil {
+ return fmt.Errorf("demo build cleanup: %s: %w", o.path(r.optDir), err)
+ }
+ r.logf("adopt: demo build cleanup: removed %s@%s, never adopted, before staging %s", o.app, o.version, ver)
+ }
+ return nil
+}
+
+// demoAdoptions is the demo routes' adopted versions by host, read before
+// a pass so afterPass can tell whether it adopted one. nil when there is
+// nothing to compare (no demo box, or the registry did not list).
+func (r *demoRetention) demoAdoptions() map[string]string {
+ if r == nil || !r.box.BoxMode() || r.reg == nil {
+ return nil
+ }
+ routes, err := r.reg.List()
+ if err != nil {
+ return nil
+ }
+ out := map[string]string{}
+ for _, rt := range routes {
+ if _, ok := r.demoApp(rt); ok {
+ out[rt.Host] = rt.Version
+ }
+ }
+ return out
+}
+
+// afterPass runs retention after a pass that adopted a demo version, and
+// on every hourly pass as the backstop. before is demoAdoptions from before
+// the pass; nil (unknown) counts as an adoption.
+func (r *demoRetention) afterPass(ctx context.Context, hourly bool, before map[string]string) {
+ if r == nil || !r.box.BoxMode() {
+ return
+ }
+ if !hourly && before != nil {
+ after := r.demoAdoptions()
+ changed := after == nil
+ for host, v := range after {
+ if before[host] != v {
+ changed = true
+ }
+ }
+ if !changed {
+ return
+ }
+ }
+ r.run(ctx)
+}
+
+// wrap is one release pass as RunAdopt runs it on any box: pass gets the
+// pending-output cleanup as its WithBeforeStage option, and retention runs
+// after it when it adopted a demo version, or on the hourly pass.
+func (r *demoRetention) wrap(ctx context.Context, hourly bool, pass func(stage release.PassOption) error) error {
+ before := r.demoAdoptions()
+ err := pass(release.WithBeforeStage(r.beforeStage))
+ r.afterPass(ctx, hourly, before)
+ return err
+}
diff --git a/internal/host/demoretention_linux_test.go b/internal/host/demoretention_linux_test.go
new file mode 100644
index 000000000..a004514e6
--- /dev/null
+++ b/internal/host/demoretention_linux_test.go
@@ -0,0 +1,164 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rootstate"
+ "golang.org/x/sys/unix"
+)
+
+// A demo build that only root's generation ledger names (a worker launched
+// from it, and the row and the links have moved on) survives retention.
+// The pin comes from the production source (generationPinSource over the
+// ledger), not a stand-in.
+func TestDemoRetentionKeepsARootOnlyGenerationPin(t *testing.T) {
+ f, disk, _ := generationLaunchFixture(t)
+ permit, err := f.root.generations.reserve(t.Context(), f.root, f.peer, f.req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := newRetentionBox(t, f.root.generations.optDir)
+ b.rootPins = generationPinSource{open: func() (rootstate.Store, error) { return disk, nil }, verify: func(context.Context, []release.GenerationReservation) error { return nil }}
+ app := demoAppName("red")
+ b.addDemo("red", true)
+ b.ship("shop", app, demoVer(1))
+ b.pass(b.retention(true), true)
+
+ held := permit.reservation.Binding
+ held.Attempt, held.Invocation = "demo-worker", "demo-worker"
+ held.Binding.Account, held.Binding.App, held.Version = "shop", app, demoVer(1)
+ held.Path = release.VersionPath(b.opt, "shop", demoVer(1), app)
+ held.Tree = filepath.Dir(held.Path)
+ for path, dst := range map[string]*rootstate.FileIdentity{held.Path: &held.Executable, held.Tree: &held.TreeIdentity} {
+ file, err := os.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ *dst, err = rootstate.Identity(file)
+ file.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := permit.ledger.Reserve(held); err != nil {
+ t.Fatal(err)
+ }
+ for i := 2; i <= 4; i++ {
+ b.ship("shop", app, demoVer(i))
+ b.pass(b.retention(true), true)
+ }
+ rt := b.route("red")
+ if slices.Contains(rowPins(rt), demoVer(1)) {
+ t.Fatalf("fixture: the row still names v1: %+v", rowPins(rt))
+ }
+ got := b.outputs("shop", app)
+ if !slices.Contains(got, demoVer(1)) {
+ t.Fatalf("the root generation's build was removed: %v", got)
+ }
+ if slices.Contains(got, demoVer(2)) {
+ t.Fatalf("v2, which nothing names, survived: %v", got)
+ }
+}
+
+// lockHeld reports whether some other open file description holds the adopt
+// pass lock: a non-blocking exclusive flock from a fresh descriptor fails.
+func lockHeld(t *testing.T, dataDir string) bool {
+ t.Helper()
+ f, err := os.OpenFile(adoptPassLockPath(dataDir), os.O_RDWR|os.O_CREATE, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
+ if err == nil {
+ _ = unix.Flock(int(f.Fd()), unix.LOCK_UN)
+ return false
+ }
+ if !errors.Is(err, unix.EWOULDBLOCK) {
+ t.Fatal(err)
+ }
+ return true
+}
+
+// Concurrent adoption. The first pass holds the adopt pass lock (as RunAdopt
+// takes it) from before its first pin read until after its last removal:
+// at each of those seams, a second pass cannot take it. The second pass,
+// blocked on the lock until the first releases it, then runs its own
+// adoption and retention and deletes nothing the first adopted.
+func TestDemoRetentionConcurrentAdoptionIsSerialized(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ b.addDemo("red", true)
+ b.addDemo("blue", true)
+ for i := 1; i <= 2; i++ {
+ b.ship("shop", app, demoVer(i))
+ b.pass(b.retention(true), true)
+ }
+ b.ship("shop", app, demoVer(3))
+
+ unlock, err := lockAdoptPass(b.data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ first := b.retention(true)
+ var seams, removals int
+ first.onPins = func() {
+ seams++
+ if !lockHeld(t, b.data) {
+ t.Error("a pin read ran without the adopt pass lock held")
+ }
+ }
+ first.onRemove = func(string) {
+ removals++
+ if !lockHeld(t, b.data) {
+ t.Error("a removal ran without the adopt pass lock held")
+ }
+ }
+ // The second pass starts now and blocks on the lock.
+ b.ship("shop", demoAppName("blue"), demoVer(1))
+ waiting := make(chan struct{})
+ done := make(chan []string)
+ go func() {
+ close(waiting)
+ unlock2, err := lockAdoptPass(b.data)
+ if err != nil {
+ t.Error(err)
+ done <- nil
+ return
+ }
+ defer unlock2()
+ second := b.retention(true)
+ ctx := context.Background()
+ if err := second.wrap(ctx, false, func(stage release.PassOption) error {
+ return release.Pass(ctx, b.reg, b.store, b.pub, b.opt, nil, release.BakeDir(b.data), stage)
+ }); err != nil {
+ t.Error(err)
+ }
+ done <- b.outputs("shop", app)
+ }()
+ <-waiting
+ b.pass(first, false)
+ if seams == 0 || removals == 0 {
+ t.Fatalf("the first pass read pins %d times and removed %d builds; the witness needs both", seams, removals)
+ }
+ adopted := b.route("red")
+ unlock()
+ got := <-done
+ if adopted.Version != demoVer(3) {
+ t.Fatalf("first pass left red at %q", adopted.Version)
+ }
+ for _, v := range rowPins(adopted) {
+ if !slices.Contains(got, v) {
+ t.Fatalf("the second pass deleted %s, which the first adopted or kept as its rollback: %v", v, got)
+ }
+ }
+ if b.route("blue").Version != demoVer(1) {
+ t.Fatal("the second pass did not run")
+ }
+}
diff --git a/internal/host/demoretention_test.go b/internal/host/demoretention_test.go
new file mode 100644
index 000000000..aa351528d
--- /dev/null
+++ b/internal/host/demoretention_test.go
@@ -0,0 +1,586 @@
+package host
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "sort"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rootstate"
+)
+
+// retentionBox is a demo box for the retention witnesses: a real registry,
+// a real release store and version store, root's adopt pass as RunAdopt
+// runs it (release.Pass inside demoRetention.wrap), and root generation
+// pins from whatever source the test hands it.
+type retentionBox struct {
+ t *testing.T
+ store release.Store
+ pub ed25519.PublicKey
+ priv ed25519.PrivateKey
+ reg *registry.Registry
+ lister routeLister
+ opt string
+ data string
+ record *rollbackDisk
+ rootPins release.PinSource
+ clock time.Time
+ restart func(host string) error
+}
+
+var retentionDemo = demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}
+
+func newRetentionBox(t *testing.T, opt string) *retentionBox {
+ t.Helper()
+ pub, priv, err := ed25519.GenerateKey(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if opt == "" {
+ opt = t.TempDir()
+ }
+ b := &retentionBox{t: t, store: release.NewDirStore(t.TempDir()), pub: pub, priv: priv, reg: restartTestRegistry(t),
+ opt: opt, data: t.TempDir(), record: &rollbackDisk{dir: t.TempDir()}, clock: time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC),
+ rootPins: release.PinSourceFunc(func(context.Context, string) (release.StagedPaths, error) { return release.StagedPaths{}, nil })}
+ b.lister = b.reg
+ return b
+}
+
+// retention is productionDemoRetention with this box's paths.
+func (b *retentionBox) retention(locked bool) *demoRetention {
+ return &demoRetention{box: retentionDemo, reg: b.lister, optDir: b.opt, genPath: release.GenerationsPath(b.data),
+ rootPins: b.rootPins, locked: locked, now: func() time.Time { return b.clock }, remove: instancefs.RemoveAllBeneath,
+ logf: b.t.Logf, record: func() (rootstate.Store, error) { return b.record, nil }}
+}
+
+func demoHost(name string) string { return name + "." + retentionDemo.Domain }
+func demoAppName(name string) string { return demo.AppPrefix + name }
+
+func (b *retentionBox) addDemo(name string, hibernate bool) {
+ b.t.Helper()
+ if err := b.reg.Upsert(registry.Route{Host: demoHost(name), Kind: "instance", Account: retentionDemo.Account, App: demoAppName(name),
+ Channel: "edge", Status: "ready", Hibernate: hibernate, Socket: provision.NestedSocket(demoHost(name)), DemoID: "id-" + name, DemoHost: demoHost(name), DemoLifetime: "24h",
+ DemoExpiresAt: b.clock.Add(24 * time.Hour).Unix()}); err != nil {
+ b.t.Fatal(err)
+ }
+}
+
+func demoVer(n int) string { return fmt.Sprintf("v0.0.0-demo.%d", n) }
+
+func (b *retentionBox) ship(acct, app, ver string) {
+ b.t.Helper()
+ plat := runtime.GOOS + "-" + runtime.GOARCH
+ ctx := context.Background()
+ m := release.Manifest{App: app, Version: ver, Kind: "binary", Artifacts: map[string]release.Artifact{plat: {}}}
+ if err := release.Ship(ctx, b.store, acct, m, map[string][]byte{plat: []byte(app + " build " + ver)}); err != nil {
+ b.t.Fatal(err)
+ }
+ if err := release.Promote(ctx, b.store, b.priv, acct, app, "edge", ver); err != nil {
+ b.t.Fatal(err)
+ }
+}
+
+// pass is one root adopt pass as RunAdopt runs it: hourly, or -stage-only.
+func (b *retentionBox) pass(r *demoRetention, hourly bool) {
+ b.t.Helper()
+ ctx := context.Background()
+ err := r.wrap(ctx, hourly, func(stage release.PassOption) error {
+ return release.Pass(ctx, b.reg, b.store, b.pub, b.opt, b.restart, release.BakeDir(b.data), stage)
+ })
+ if err != nil {
+ b.t.Fatalf("pass: %v", err)
+ }
+}
+
+// outputs is every version the store holds an output of app at.
+func (b *retentionBox) outputs(acct, app string) []string {
+ b.t.Helper()
+ entries, err := os.ReadDir(filepath.Join(b.opt, "versions"))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ b.t.Fatal(err)
+ }
+ var out []string
+ for _, e := range entries {
+ for _, p := range []string{release.VersionPath(b.opt, acct, e.Name(), app), release.VersionPath(b.opt, acct, e.Name(), app) + ".manifest.json"} {
+ if _, err := os.Lstat(p); err == nil {
+ out = append(out, e.Name())
+ break
+ }
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+func (b *retentionBox) route(name string) registry.Route {
+ b.t.Helper()
+ rt, err := b.reg.Get(demoHost(name))
+ if err != nil || rt == nil {
+ b.t.Fatalf("route %s: %+v %v", name, rt, err)
+ }
+ return *rt
+}
+
+func (b *retentionBox) status() demoRetentionStatus {
+ b.t.Helper()
+ raw, err := b.record.Read(demoRetentionRecord)
+ if err != nil {
+ b.t.Fatalf("retention record: %v", err)
+ }
+ var s demoRetentionStatus
+ if err := json.Unmarshal(raw, &s); err != nil {
+ b.t.Fatal(err)
+ }
+ return s
+}
+
+func sameSet(got, want []string) bool {
+ g, w := slices.Clone(got), slices.Clone(want)
+ sort.Strings(g)
+ sort.Strings(w)
+ return slices.Equal(slices.Compact(g), slices.Compact(w))
+}
+
+// rowPins is the set of versions a route's own row pins.
+func rowPins(rt registry.Route) []string {
+ var out []string
+ for _, v := range []string{rt.Version, rt.PrevVersion, rt.GoodVersion} {
+ if v != "" {
+ out = append(out, v)
+ }
+ }
+ return out
+}
+
+// Sixty-one updates of one demo through the hourly pass: after each, the
+// store holds the demo's row pins and nothing else, and at the end that is
+// the live build and its rollback. An ordinary app in the same store keeps
+// every build.
+func TestDemoRetentionSixtyOneUpdatesKeepPinsAndOneRollback(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ if err := b.reg.Upsert(registry.Route{Host: "blog.example.org", Kind: "instance", Account: "other", App: "blog", Channel: "edge", Status: "ready", Hibernate: true}); err != nil {
+ t.Fatal(err)
+ }
+ for i := 1; i <= 61; i++ {
+ b.ship("shop", demoAppName("red"), demoVer(i))
+ b.ship("other", "blog", demoVer(i))
+ b.pass(b.retention(true), true)
+ rt := b.route("red")
+ if rt.Version != demoVer(i) {
+ t.Fatalf("update %d: route at %q", i, rt.Version)
+ }
+ if got := b.outputs("shop", demoAppName("red")); !sameSet(got, rowPins(rt)) {
+ t.Fatalf("update %d: store holds %v, want the row's pins %v", i, got, rowPins(rt))
+ }
+ }
+ if got, want := b.outputs("shop", demoAppName("red")), []string{demoVer(60), demoVer(61)}; !sameSet(got, want) {
+ t.Fatalf("after 61 updates the demo keeps %v, want %v", got, want)
+ }
+ if got := b.outputs("other", "blog"); len(got) != 61 {
+ t.Fatalf("the ordinary app kept %d builds, want all 61 (retention is demo-only)", len(got))
+ }
+ if s := b.status(); s.Outputs != 2 || s.Backlog != 0 || s.OutputBytes <= 0 {
+ t.Fatalf("record = %+v", s)
+ }
+}
+
+// Ten relayed updates in a row, each through a -stage-only pass and no
+// hourly pass between them: the bound holds after every one.
+func TestDemoRetentionSuccessiveRelayedUpdatesWithoutAnHourlyPass(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ for i := 1; i <= 10; i++ {
+ b.ship("shop", demoAppName("red"), demoVer(i))
+ b.pass(b.retention(true), false)
+ rt := b.route("red")
+ if got := b.outputs("shop", demoAppName("red")); rt.Version != demoVer(i) || !sameSet(got, rowPins(rt)) || len(got) > 3 {
+ t.Fatalf("relayed update %d: route %q, store %v, want %v", i, rt.Version, got, rowPins(rt))
+ }
+ }
+}
+
+// A -stage-only pass that adopted no demo version does not run retention;
+// the hourly pass does, as the backstop.
+func TestDemoRetentionRunsAfterAnAdoptionAndOnTheHourlyPass(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.ship("shop", demoAppName("red"), demoVer(1))
+ b.pass(b.retention(true), false)
+ // A leftover nobody names, older than the live build.
+ if err := release.StageArtifact(b.opt, "shop", "v0.0.0-demo.0", demoAppName("red"), []byte("old")); err != nil {
+ t.Fatal(err)
+ }
+ b.pass(b.retention(true), false)
+ if got := b.outputs("shop", demoAppName("red")); !slices.Contains(got, "v0.0.0-demo.0") {
+ t.Fatalf("a stage-only pass that adopted nothing ran retention: %v", got)
+ }
+ b.pass(b.retention(true), true)
+ if got := b.outputs("shop", demoAppName("red")); slices.Contains(got, "v0.0.0-demo.0") {
+ t.Fatalf("the hourly backstop kept an unpinned build: %v", got)
+ }
+}
+
+// A version staged and not yet adopted (the pass that staged it ended
+// before it repointed, so no link names it) is in flight: retention keeps
+// it, on the hourly pass and after another demo's adoption, until a later
+// version of its app is staged and adopted.
+func TestDemoRetentionKeepsAStagedNotYetAdoptedVersion(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.addDemo("blue", true)
+ for i := 1; i <= 2; i++ {
+ b.ship("shop", demoAppName("red"), demoVer(i))
+ b.pass(b.retention(true), true)
+ }
+ if err := release.StageArtifact(b.opt, "shop", demoVer(3), demoAppName("red"), []byte("staged, not adopted")); err != nil {
+ t.Fatal(err)
+ }
+ b.pass(b.retention(true), true)
+ b.ship("shop", demoAppName("blue"), demoVer(1))
+ b.pass(b.retention(true), false)
+ if b.route("blue").Version != demoVer(1) {
+ t.Fatal("fixture: blue did not adopt")
+ }
+ if got := b.outputs("shop", demoAppName("red")); !slices.Contains(got, demoVer(3)) {
+ t.Fatalf("the in-flight build was removed: %v", got)
+ }
+ b.ship("shop", demoAppName("red"), demoVer(4))
+ b.pass(b.retention(true), false)
+ rt := b.route("red")
+ if got := b.outputs("shop", demoAppName("red")); rt.Version != demoVer(4) || !sameSet(got, rowPins(rt)) {
+ t.Fatalf("superseded: route %q, store %v, want %v", rt.Version, got, rowPins(rt))
+ }
+}
+
+// A version directory shared with an ordinary app (and another demo) loses
+// only the retired demo's files: the directory and its other apps stay.
+func TestDemoRetentionSharedVersionKeepsTheOtherApps(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.addDemo("blue", true)
+ if err := b.reg.Upsert(registry.Route{Host: "blog.example.org", Kind: "instance", Account: "shop", App: "blog", Channel: "edge", Status: "ready", Hibernate: true}); err != nil {
+ t.Fatal(err)
+ }
+ b.ship("shop", demoAppName("red"), demoVer(1))
+ b.ship("shop", demoAppName("blue"), demoVer(1))
+ b.ship("shop", "blog", demoVer(1))
+ // An ops-account app named like the demo account: <ver>/shop is a file.
+ if err := release.StageArtifact(b.opt, "", "v9", "shop", []byte("ops")); err != nil {
+ t.Fatal(err)
+ }
+ b.pass(b.retention(true), true)
+ if got := b.outputs("shop", demoAppName("red")); !slices.Equal(got, []string{demoVer(1)}) {
+ t.Fatalf("fixture: red holds %v", got)
+ }
+ // red moves on twice; v1 is now nobody's but blue's and blog's.
+ for i := 2; i <= 3; i++ {
+ b.ship("shop", demoAppName("red"), demoVer(i))
+ b.pass(b.retention(true), true)
+ }
+ if got := b.outputs("shop", demoAppName("red")); slices.Contains(got, demoVer(1)) {
+ t.Fatalf("red's v1 survived: %v", got)
+ }
+ for _, app := range []string{demoAppName("blue"), "blog"} {
+ if got := b.outputs("shop", app); !slices.Contains(got, demoVer(1)) {
+ t.Fatalf("%s lost its v1 with red's: %v", app, got)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(b.opt, "versions", demoVer(1))); err != nil {
+ t.Fatalf("the shared version directory: %v", err)
+ }
+ if _, err := os.Stat(release.VersionPath(b.opt, "", "v9", "shop")); err != nil {
+ t.Fatalf("the ops app: %v", err)
+ }
+ if s := b.status(); s.Reason != "" {
+ t.Fatalf("record = %+v", s)
+ }
+}
+
+// Every distinct pin of one demo route names a different build: Version,
+// PrevVersion, GoodVersion, the settings pin, last_executed and the
+// resolved target, plus a root generation pin on a seventh. All seven
+// survive the hourly pass; the two older builds nothing names go.
+func TestDemoRetentionDistinctPinValues(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ for i := 1; i <= 9; i++ {
+ if err := release.StageArtifact(b.opt, "shop", demoVer(i), app, []byte("build")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ b.addDemo("red", true)
+ settings, err := json.Marshal(release.UpdateSettings{Updates: release.UpdatesManual, Pin: demoVer(6)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ state := release.BuildStateCopy{Known: true, State: &release.BuildState{Schema: 1, Host: demoHost("red"), LastExecuted: demoVer(5),
+ Resolved: &release.ResolvedRequest{ID: 1, Target: demoVer(4)}}}
+ if err := b.reg.SetUpdateSettings(demoHost("red"), string(settings)); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.reg.SetBuildState(demoHost("red"), state.Column()); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.reg.SetVersions(demoHost("red"), demoVer(9), demoVer(8)); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.reg.SetGoodBuild(demoHost("red"), registry.GoodBuild{}, registry.GoodBuild{Version: demoVer(7)}); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.PointLive(context.Background(), nil, b.opt, demoHost("red"), "shop", demoVer(9), app); err != nil {
+ t.Fatal(err)
+ }
+ root := release.VersionPath(b.opt, "shop", demoVer(3), app)
+ b.rootPins = release.PinSourceFunc(func(context.Context, string) (release.StagedPaths, error) {
+ return release.StagedPaths{root: true}, nil
+ })
+ rt := b.route("red")
+ if rt.Version != demoVer(9) || rt.PrevVersion != demoVer(8) || rt.GoodVersion != demoVer(7) {
+ t.Fatalf("row = %q %q %q", rt.Version, rt.PrevVersion, rt.GoodVersion)
+ }
+ b.pass(b.retention(true), true)
+ want := []string{demoVer(3), demoVer(4), demoVer(5), demoVer(6), demoVer(7), demoVer(8), demoVer(9)}
+ if got := b.outputs("shop", app); !sameSet(got, want) {
+ t.Fatalf("store holds %v, want exactly the seven pinned %v", got, want)
+ }
+}
+
+// A build that only the settings pin names survives.
+func TestDemoRetentionKeepsASettingsOnlyPin(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ b.addDemo("red", true)
+ b.ship("shop", app, demoVer(1))
+ b.pass(b.retention(true), true)
+ settings, _ := json.Marshal(release.UpdateSettings{Updates: release.UpdatesManual, Pin: demoVer(1)})
+ if err := b.reg.SetUpdateSettings(demoHost("red"), string(settings)); err != nil {
+ t.Fatal(err)
+ }
+ state := release.BuildStateCopy{Known: true, State: &release.BuildState{Schema: 1, Host: demoHost("red")}}
+ if err := b.reg.SetBuildState(demoHost("red"), state.Column()); err != nil {
+ t.Fatal(err)
+ }
+ for i := 2; i <= 4; i++ {
+ b.ship("shop", app, demoVer(i))
+ b.pass(b.retention(true), true)
+ }
+ if got := b.outputs("shop", app); !sameSet(got, []string{demoVer(1), demoVer(3), demoVer(4)}) {
+ t.Fatalf("store holds %v, want the settings pin v1 kept beside v3 and v4", got)
+ }
+}
+
+type failingLister struct{ err error }
+
+func (f failingLister) List() ([]registry.Route, error) { return nil, f.err }
+
+// Any pin source that does not read in full deletes nothing, and the record
+// says why and how much is held beyond the bound.
+func TestDemoRetentionUnreadableSourceDeletesNothing(t *testing.T) {
+ for _, source := range []string{"registry", "live", "previous", "generations", "root", "settings"} {
+ t.Run(source, func(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ b.addDemo("red", true)
+ for i := 1; i <= 3; i++ {
+ b.ship("shop", app, demoVer(i))
+ b.pass(b.retention(true), true)
+ }
+ // v1 is beyond the bound again: an output nothing names.
+ if err := release.StageArtifact(b.opt, "shop", demoVer(1), app, []byte("left over")); err != nil {
+ t.Fatal(err)
+ }
+ before := b.outputs("shop", app)
+ if len(before) != 3 {
+ t.Fatalf("fixture: %v", before)
+ }
+ r := b.retention(true)
+ switch source {
+ case "registry":
+ r.reg = failingLister{errors.New("registry busy")}
+ case "live":
+ if err := os.WriteFile(filepath.Join(b.opt, "live", "broken"), []byte("not a link"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ case "previous":
+ if err := os.MkdirAll(filepath.Join(b.opt, "previous"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(b.opt, "previous", "broken"), []byte("not a link"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ case "generations":
+ gen := release.GenerationsPath(b.data)
+ if err := os.MkdirAll(filepath.Dir(gen), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(gen, []byte(`{"schema":1,"hosts":{"x`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ case "root":
+ r.rootPins = release.PinSourceFunc(func(context.Context, string) (release.StagedPaths, error) {
+ return nil, errors.New("ledger unreadable")
+ })
+ case "settings":
+ settings, _ := json.Marshal(release.UpdateSettings{Updates: release.UpdatesManual})
+ if err := b.reg.SetUpdateSettings(demoHost("red"), string(settings)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ res := r.run(context.Background())
+ if res.err == nil {
+ t.Fatal("an unreadable source was not reported")
+ }
+ if got := b.outputs("shop", app); !slices.Equal(got, before) {
+ t.Fatalf("deleted with an incomplete pin set: %v -> %v", before, got)
+ }
+ if s := b.status(); s.Reason == "" || (source != "registry" && s.Backlog != 1) || s.BacklogSince.IsZero() {
+ t.Fatalf("record = %+v", s)
+ }
+ })
+ }
+}
+
+// Without the adopt pass lock, retention deletes nothing and the cleanup
+// refuses the stage.
+func TestDemoRetentionWithoutTheLockDeletesNothing(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ b.addDemo("red", true)
+ for i := 1; i <= 4; i++ {
+ b.ship("shop", app, demoVer(i))
+ b.pass(b.retention(i < 4), true)
+ }
+ // The fourth pass had no lock: its cleanup refused v4's stage.
+ if rt := b.route("red"); rt.Version != demoVer(3) {
+ t.Fatalf("a stage ran without the lock: route at %q", rt.Version)
+ }
+ got := b.outputs("shop", app)
+ if !sameSet(got, []string{demoVer(2), demoVer(3)}) {
+ t.Fatalf("store = %v", got)
+ }
+ b.retention(false).run(context.Background())
+ if again := b.outputs("shop", app); !slices.Equal(again, got) {
+ t.Fatalf("an unlocked run deleted: %v -> %v", got, again)
+ }
+}
+
+// A failed run (no lock), then another (an unreadable source), deletes
+// nothing and reports a backlog that keeps its start; the next good run
+// clears it.
+func TestDemoRetentionBacklogAcrossFailedRuns(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ b.addDemo("red", true)
+ // Four builds staged, v4 adopted over v3: v1 and v2 are beyond the bound.
+ for i := 1; i <= 4; i++ {
+ if err := release.StageArtifact(b.opt, "shop", demoVer(i), app, []byte("build")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := b.reg.SetVersions(demoHost("red"), demoVer(4), demoVer(3)); err != nil {
+ t.Fatal(err)
+ }
+ start := b.clock
+ b.retention(false).run(context.Background())
+ if s := b.status(); s.Backlog != 2 || !s.BacklogSince.Equal(start) {
+ t.Fatalf("after the lock-less run: %+v", s)
+ }
+ b.clock = b.clock.Add(25 * time.Hour)
+ r := b.retention(true)
+ r.rootPins = release.PinSourceFunc(func(context.Context, string) (release.StagedPaths, error) { return nil, os.ErrPermission })
+ r.run(context.Background())
+ if s := b.status(); s.Backlog != 2 || !s.BacklogSince.Equal(start) || len(b.outputs("shop", app)) != 4 {
+ t.Fatalf("after the unreadable-source run: %+v, store %v", s, b.outputs("shop", app))
+ }
+ b.clock = b.clock.Add(time.Hour)
+ b.retention(true).run(context.Background())
+ if s := b.status(); s.Backlog != 0 || !s.BacklogSince.IsZero() || s.Reason != "" {
+ t.Fatalf("after the good run: %+v", s)
+ }
+ if got := b.outputs("shop", app); !sameSet(got, []string{demoVer(3), demoVer(4)}) {
+ t.Fatalf("store = %v", got)
+ }
+}
+
+// Three jobs for one demo each stage an output that is never adopted (the
+// restart fails, so settlement fails). Before each next stage the previous
+// leftover goes, so the store holds the pins plus at most one unadopted
+// output after every step. A cleanup that cannot read a pin source refuses
+// the stage and deletes nothing.
+func TestDemoRetentionFailedOutputsDoNotAccumulate(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ b.addDemo("red", false)
+ b.restart = func(string) error { return nil }
+ b.ship("shop", app, demoVer(1))
+ b.pass(b.retention(true), false)
+ b.restart = func(string) error { return errors.New("did not come up") }
+ for job := 2; job <= 4; job++ {
+ b.ship("shop", app, demoVer(job))
+ b.pass(b.retention(true), false)
+ rt := b.route("red")
+ got := b.outputs("shop", app)
+ routes, err := b.reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pins, err := b.retention(true).pinSet(context.Background(), routes, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var loose []string
+ for _, v := range got {
+ if !pinned(pins, b.opt, demoOutput{demoAppKey: demoAppKey{"shop", app}, version: v}) {
+ loose = append(loose, v)
+ }
+ }
+ if rt.Version != demoVer(1) || len(loose) > 1 || !slices.Contains(got, demoVer(job)) {
+ t.Fatalf("job %d: route %q, store %v (unadopted and unpinned %v)", job, rt.Version, got, loose)
+ }
+ }
+ before := b.outputs("shop", app)
+ r := b.retention(true)
+ r.rootPins = release.PinSourceFunc(func(context.Context, string) (release.StagedPaths, error) { return nil, os.ErrPermission })
+ b.ship("shop", app, demoVer(5))
+ b.pass(r, false)
+ if got := b.outputs("shop", app); !slices.Equal(got, before) {
+ t.Fatalf("an unreadable pin source: store %v -> %v (want the stage refused and nothing deleted)", before, got)
+ }
+}
+
+// The cleanup and retention touch only demo apps of this box's demo
+// account, and nothing at all on a box that is not a demo box.
+func TestDemoRetentionLeavesNonDemoBoxesAndAppsAlone(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ b.addDemo("red", true)
+ for i := 1; i <= 4; i++ {
+ b.ship("shop", app, demoVer(i))
+ r := b.retention(true)
+ r.box = demo.Config{}
+ b.pass(r, true)
+ }
+ if got := b.outputs("shop", app); len(got) != 4 {
+ t.Fatalf("a box that is not a demo box ran retention: %v", got)
+ }
+ if _, err := b.record.Read(demoRetentionRecord); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("a non-demo box wrote the record: %v", err)
+ }
+}