carlos / platform Public

host: demo retention decides deletion from root's own facts

Fix round 2 of demo disk slice 1. Eligibility now comes from the box's
demo account in host.env and tmp-demo-<public name> outputs root lists in
its own store, names validated before use; registry rows only add
protection (a row that is not a valid demo binding keeps its app). A pin
on any ancestor keeps an output, under either spelling. The demo account
on the ops layout is refused loudly. Retention keeps one pending output
and removes older ones; another app's unread settings references hold
only that app. adoptPassRetention composes mode and lock, tested.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 0231edef903a8756f1b19b434e6613e54f4cc588 parent d32445f
4 files changed, +793 −162
  • internal/host/agent.go +1 −1
  • internal/host/demoretention.go +397 −147
  • internal/host/demoretention_linux_test.go +87 −0
  • internal/host/demoretention_test.go +308 −14
diff --git a/internal/host/agent.go b/internal/host/agent.go
index c97d2e5be..fe6dbe345 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -6369,7 +6369,7 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni
// 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.
- passErr := pr.around(ctx, productionDemoRetention(reg, generationPins, passLockErr == nil).around(ctx, !*stageOnly, func(stage release.PassOption) error {
+ passErr := pr.around(ctx, adoptPassAround(ctx, *configOnly, *restartOnly, *stageOnly, passLockErr, reg, generationPins, func(stage release.PassOption) error {
return release.Pass(ctx, reg, store, pub, release.OptDir(), restart, append(passOpts, stage)...)
}))
if passErr != nil {
diff --git a/internal/host/demoretention.go b/internal/host/demoretention.go
index 8310cc9a3..16a0517a6 100644
--- a/internal/host/demoretention.go
+++ b/internal/host/demoretention.go
@@ -9,12 +9,27 @@
// below keeps at most one output a demo app never adopted.
//
// The deletion-safety contract:
+// - what may be deleted is decided from root's own facts only: the box's
+// demo account from host.env (demo.BoxConfig, the whole tuple valid)
+// and the tmp-demo-<public name> outputs root lists under
+// <ver>/<demo account>/ in its own version store, each name validated
+// (demo.ValidPublicName: one path component, no "." or "..") before it
+// is used in any path. The demo account is the dedicated holding
+// account (README, demo setup); the console reserves the tmp-demo-
+// prefix for demos in every account (reservedAppName) and never places
+// a demo in the ops account. Registry rows are the service's, so they
+// only ADD protection: their pins, and a row that runs one of these
+// apps as anything but a valid demo binding keeps all of its builds;
// - 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;
+// full deletes nothing, except that an app whose own settings
+// references did not read (release.IncompleteRefsError) holds only
+// that app. A pin keeps every output at, inside or beneath it, under
+// the store's spelling or its real path, so a reserved tree
+// (<ver>/<account>, <ver>) keeps everything in it;
// - 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
@@ -22,9 +37,29 @@
// 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;
+// - pending outputs: a version staged after every version the app's live
+// links name is in flight. Retention keeps the newest one and removes
+// older ones (a box upgraded with failed outputs piled up); names it
+// cannot order are kept and counted as backlog;
// - non-demo apps are never touched.
+//
+// Outside the lock and the hook: the agent's own stage passes (adoptLoop
+// and fastTick in agent.go, passLegs.run in changeindex.go) stage without
+// lockAdoptPass and without beforeStage, and a move's held stage
+// (heldStagePass, release.stageHeld in internal/release/materializeheld.go)
+// stages without beforeStage. This is safe only because a hardened demo
+// box's agent cannot write the version store: there every demo stage is
+// root's adopt pass, relayed through carlos-stage.service. Where an agent
+// could write the store, neither the pending-output bound nor the lock
+// would hold, and a cleanup could remove a build an agent pass is
+// adopting.
+//
+// The bound per demo app is (8 + G + R) x 32 MiB: six registry and
+// settings pins (Version, PrevVersion, GoodVersion, the settings pin,
+// LastExecuted, the resolved target), the previous link (after a failed
+// adoption rolls back it names the failed build, which no row names), one
+// pending output, G generations-file pins and R root generation pins. With
+// G = R = 0 under gVisor that is 256 MiB a demo, 5.0 GiB for 20.
package host
import (
@@ -35,6 +70,7 @@ import (
"log"
"os"
"path/filepath"
+ "slices"
"sort"
"strconv"
"strings"
@@ -111,23 +147,75 @@ type demoOutput struct {
demoAppKey
version string
bytes int64
- keep bool
+ // pinned: a pin names it or a path above or inside it, it is the
+ // version about to be staged, or a registry row runs its app as
+ // something other than a valid demo binding.
+ pinned bool
+ // held: its app's settings references did not read in full
+ // (release.IncompleteRefsError), so nothing of that app is removed.
+ held bool
+ // inFlight: staged after every version its app's live links name.
+ inFlight 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
+// spellings is the output's path under the store's own name and, when its
+// directory resolves, under its real path.
+func (o demoOutput) spellings(optDir string) []string {
+ exe := o.path(optDir)
+ out := []string{exe}
+ if real, err := filepath.EvalSymlinks(filepath.Dir(exe)); err == nil {
+ if p := filepath.Join(real, o.app); p != exe {
+ out = append(out, p)
+ }
}
- return demoAppKey{acct, rt.App}, true
+ return out
+}
+
+// errDemoAccountIsOps refuses a demo box whose demo account is the ops
+// account: its builds would share <ver>/ with every ops app (VersionPath's
+// pre-accounts layout), and the console never places a demo there
+// (internal/console demo_store.go refuses the ops account), so such a box is
+// misconfigured. Every demo stage is refused and retention deletes nothing.
+var errDemoAccountIsOps = errors.New("the demo account is the ops account, which never holds demos; demo builds are refused on this box until CARLOS_DEMO_ACCOUNT names the holding account")
+
+// demoAccount is the account whose tmp-demo- apps are this box's demos:
+// host.env's CARLOS_DEMO_ACCOUNT, which demo.BoxConfig validated with the
+// rest of the tuple, and never the ops account.
+func (r *demoRetention) demoAccount() (string, error) {
+ acct := r.box.Account
+ if acct == release.OpsAccount {
+ return "", errDemoAccountIsOps
+ }
+ if !oneStoreName(acct) {
+ return "", fmt.Errorf("the demo account %q is not one path name", acct)
+ }
+ return acct, nil
+}
+
+// oneStoreName: s is exactly one path component, neither "." nor "..".
+func oneStoreName(s string) bool {
+ return s != "" && s != "." && s != ".." && !strings.ContainsAny(s, "/\\\x00")
+}
+
+// validDemoName reports whether app is a demo app name the console makes:
+// tmp-demo- and a public name (demo.ValidPublicName, words and two digits
+// joined by hyphens), so one path component with no dots. Checked before a
+// name is used in any path.
+func validDemoName(app string) bool {
+ name, ok := strings.CutPrefix(app, demo.AppPrefix)
+ return ok && oneStoreName(app) && demo.ValidPublicName(name)
+}
+
+// validDemoRow reports whether rt is a complete, valid demo binding of this
+// box (demo.Config.ValidateBinding over its descriptor). Only a row that is
+// not protects anything more: it never makes a build eligible.
+func (r *demoRetention) validDemoRow(rt registry.Route) bool {
+ d := demo.Descriptor{ID: rt.DemoID, Host: rt.DemoHost, Lifetime: rt.DemoLifetime, ExpiresAt: rt.DemoExpiresAt}
+ return rt.IsDemo() && r.box.ValidateBinding(d, release.RouteAccount(rt), rt.App, rt.Host, rt.DemoLifetime, r.box.Fleet) == nil
}
// demoGeneration reads the console's demo version name (v0.0.0-demo.<n>,
@@ -144,18 +232,14 @@ func demoGeneration(v string) (uint64, bool) {
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.
+// inFlight: v was staged after every version the app's live links name. A
+// name this cannot order is in flight: the cautious answer.
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
@@ -168,9 +252,11 @@ func inFlight(v string, adopted []string) bool {
}
// 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) {
+// not read in full is an error, except BoxPins' IncompleteRefsError, whose
+// pins are complete for every app it does not cover and which is returned
+// for the caller to hold those apps. Otherwise (the backlog estimate) a
+// failed source adds nothing.
+func (r *demoRetention) pinSet(ctx context.Context, routes []registry.Route, strict bool) ([]string, *release.IncompleteRefsError, error) {
var out []string
add := func(name string, paths release.StagedPaths, err error) error {
if err != nil {
@@ -185,8 +271,14 @@ func (r *demoRetention) pinSet(ctx context.Context, routes []registry.Route, str
return nil
}
box, err := release.BoxPins(r.optDir, routes)
+ var inc *release.IncompleteRefsError
+ if errors.As(err, &inc) && box != nil {
+ err = nil
+ } else {
+ inc = nil
+ }
if err := add("live links and registry rows", box, err); err != nil {
- return nil, err
+ return nil, nil, err
}
if !strict {
// BoxPins answers nothing when one live link does not read; the
@@ -200,13 +292,13 @@ func (r *demoRetention) pinSet(ctx context.Context, routes []registry.Route, str
}
}
}
- prev, err := previousLinkPins(r.optDir)
+ prev, err := linkTargets(filepath.Join(r.optDir, "previous"))
if err := add("previous links", prev, err); err != nil {
- return nil, err
+ return nil, 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
+ return nil, nil, err
}
var root release.StagedPaths
err = os.ErrPermission
@@ -214,15 +306,15 @@ func (r *demoRetention) pinSet(ctx context.Context, routes []registry.Route, str
root, err = r.rootPins.StagedPins(ctx, r.optDir)
}
if err := add("root generation pins", root, err); err != nil {
- return nil, err
+ return nil, nil, err
}
- return out, nil
+ return out, inc, 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")
+// linkTargets is every link's target in dir (<opt>/previous or <opt>/live,
+// both root's), as release.LivePins reads them for the sweep, at the path
+// it names and its real path.
+func linkTargets(dir string) (release.StagedPaths, error) {
entries, err := os.ReadDir(dir)
if errors.Is(err, os.ErrNotExist) {
return release.StagedPaths{}, nil
@@ -252,21 +344,18 @@ func previousLinkPins(optDir string) (release.StagedPaths, error) {
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.
+// pinned: a pin names the output or its manifest, a path inside it, or a
+// directory above it (a root generation's reserved Tree, <ver>/<account>
+// or <ver>, keeps everything in it, as generationWriteCheck refuses writes
+// there), under the store's own spelling or its real path.
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")
+ var names []string
+ for _, p := range o.spellings(optDir) {
+ names = append(names, p, p+".manifest.json")
}
for _, p := range pins {
for _, n := range names {
- if p == n || strings.HasPrefix(p, n+string(filepath.Separator)) {
+ if within(n, p) || within(p, n) {
return true
}
}
@@ -274,75 +363,195 @@ func pinned(pins []string, optDir string, o demoOutput) bool {
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) {
+// within: path is base or beneath it.
+func within(path, base string) bool {
+ return path == base || strings.HasPrefix(path, strings.TrimSuffix(base, string(filepath.Separator))+string(filepath.Separator))
+}
+
+// listOutputs is root's own listing of the demo account's outputs in the
+// version store: every <ver>/<acct>/<name> (and its manifest) whose name is
+// a valid demo app name (only that app, when only is set). Names come from
+// the listing and are validated before any further use, so nothing a
+// registry row says reaches a path here.
+func (r *demoRetention) listOutputs(acct, only string) ([]demoOutput, error) {
+ root := filepath.Join(r.optDir, "versions")
+ versions, err := os.ReadDir(root)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ var out []demoOutput
+ for _, v := range versions {
+ if !v.IsDir() || !release.ValidVersion(v.Name()) {
+ continue
+ }
+ entries, err := os.ReadDir(filepath.Join(root, v.Name(), acct))
+ // 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
+ }
+ at := map[string]int{}
+ for _, e := range entries {
+ app := strings.TrimSuffix(e.Name(), ".manifest.json")
+ if !validDemoName(app) || (only != "" && app != only) {
+ continue
+ }
+ info, err := e.Info()
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ return nil, err
+ }
+ i, ok := at[app]
+ if !ok {
+ i = len(out)
+ at[app] = i
+ out = append(out, demoOutput{demoAppKey: demoAppKey{acct, app}, version: v.Name()})
+ }
+ if info.Mode().IsRegular() {
+ out[i].bytes += info.Size()
+ }
+ }
+ }
+ return out, nil
+}
+
+// selection is one look at the store for the demo account's apps (only,
+// when set): every output present, marked. except is the version about to
+// be staged, which is kept. The IncompleteRefsError, when not nil, names
+// the apps held.
+func (r *demoRetention) selection(ctx context.Context, only, except string, strict bool) ([]demoOutput, *release.IncompleteRefsError, error) {
if r.onPins != nil {
r.onPins()
}
+ acct, err := r.demoAccount()
+ if err != nil {
+ return nil, nil, err
+ }
if r.reg == nil {
- return nil, os.ErrPermission
+ return nil, nil, os.ErrPermission
}
routes, err := r.reg.List()
if err != nil {
- return nil, fmt.Errorf("list routes: %w", err)
+ return nil, 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)
+ pins, inc, err := r.pinSet(ctx, routes, strict)
+ if err != nil {
+ return nil, nil, err
+ }
+ live, liveErr := linkTargets(filepath.Join(r.optDir, "live"))
+ if liveErr != nil {
+ if strict {
+ return nil, nil, fmt.Errorf("live links: %w", liveErr)
}
+ live = release.StagedPaths{}
}
- if len(adopted) == 0 {
- return nil, nil
+ guarded := map[string]bool{}
+ for _, rt := range routes {
+ if release.RouteAccount(rt) == acct && !r.validDemoRow(rt) {
+ guarded[rt.App] = true
+ }
}
- pins, err := r.pinSet(ctx, routes, strict)
+ outs, err := r.listOutputs(acct, only)
if err != nil {
- return nil, err
+ return nil, nil, err
}
- versions, err := os.ReadDir(filepath.Join(r.optDir, "versions"))
- if errors.Is(err, os.ErrNotExist) {
- return nil, nil
+ adopted := map[string][]string{}
+ for _, o := range outs {
+ for _, p := range o.spellings(r.optDir) {
+ if live[p] {
+ adopted[o.app] = append(adopted[o.app], o.version)
+ break
+ }
+ }
}
- if err != nil {
- return nil, err
+ if liveErr != nil {
+ // The estimate, with the live links unread: what the rows say was
+ // adopted. It only counts.
+ for _, rt := range routes {
+ if release.RouteAccount(rt) == acct && release.ValidVersion(rt.Version) {
+ adopted[rt.App] = append(adopted[rt.App], rt.Version)
+ }
+ }
}
- apps := make([]demoAppKey, 0, len(adopted))
- for k := range adopted {
- apps = append(apps, k)
+ for i := range outs {
+ o := &outs[i]
+ o.pinned = o.version == except || guarded[o.app] || pinned(pins, r.optDir, *o)
+ o.held = inc != nil && inc.Covers(acct, o.app)
+ o.inFlight = inFlight(o.version, adopted[o.app])
}
- 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
+ return outs, inc, nil
+}
+
+// planRemovals is what retention removes from outs: every output nothing
+// pins that is not its app's newest pending output, and nothing of a held
+// app. backlog counts what it keeps beyond the bound: a held app's
+// outputs it would otherwise remove, and pending outputs beyond one where
+// the names cannot be ordered.
+func planRemovals(outs []demoOutput) (remove []int, backlog int) {
+ pending := map[string][]int{}
+ var apps []string
+ for i, o := range outs {
+ switch {
+ case o.pinned:
+ case o.inFlight:
+ if pending[o.app] == nil {
+ apps = append(apps, o.app)
+ }
+ pending[o.app] = append(pending[o.app], i)
+ case o.held:
+ backlog++
+ default:
+ remove = append(remove, i)
}
- 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()
- }
+ }
+ for _, app := range apps {
+ idx := pending[app]
+ newest, ordered := -1, true
+ var top uint64
+ for _, i := range idx {
+ g, ok := demoGeneration(outs[i].version)
+ if !ok {
+ ordered = false
+ break
}
- if !present {
- continue
+ if newest < 0 || g > top {
+ newest, top = i, g
+ }
+ }
+ if !ordered {
+ backlog += len(idx) - 1
+ continue
+ }
+ for _, i := range idx {
+ switch {
+ case i == newest:
+ case outs[i].held:
+ backlog++
+ default:
+ remove = append(remove, i)
}
- o.keep = o.version == except || pinned(pins, r.optDir, o) || (keepInFlight && inFlight(o.version, adopted[k]))
- out = append(out, o)
}
}
- return out, nil
+ sort.Ints(remove)
+ return remove, backlog
+}
+
+// heldApps names the apps of outs held by unread settings references.
+func heldApps(outs []demoOutput) []string {
+ var apps []string
+ for _, o := range outs {
+ if o.held && !slices.Contains(apps, o.app) {
+ apps = append(apps, o.app)
+ }
+ }
+ return apps
}
// removeOutput deletes one output beneath its version directory, the
@@ -377,37 +586,45 @@ func (r *demoRetention) retain(ctx context.Context) demoRetentionResult {
if !r.locked {
res.err = errors.New("the adopt pass lock is not held")
} else {
- outs, res.err = r.selection(ctx, nil, true, true, "")
+ outs, _, res.err = r.selection(ctx, "", "", true)
}
if res.err != nil {
// Deletes nothing. The backlog is estimated on what does read.
- est, err := r.selection(ctx, nil, true, false, "")
+ est, _, err := r.selection(ctx, "", "", false)
if err != nil {
res.backlog = -1
return res
}
+ remove, backlog := planRemovals(est)
+ res.backlog = len(remove) + backlog
for _, o := range est {
res.outputs++
res.outputBytes += o.bytes
- if !o.keep {
- res.backlog++
- }
}
return res
}
+ remove, backlog := planRemovals(outs)
+ res.backlog = backlog
+ gone := map[int]bool{}
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
- }
+ for _, i := range remove {
+ o := outs[i]
+ if err := r.removeOutput(o); err != nil {
+ failed = append(failed, fmt.Errorf("%s: %w", o.path(r.optDir), err))
+ res.backlog++
+ continue
}
- res.outputs++
- res.outputBytes += o.bytes
+ gone[i] = true
+ res.removed = append(res.removed, o.app+"@"+o.version)
+ }
+ for i, o := range outs {
+ if !gone[i] {
+ res.outputs++
+ res.outputBytes += o.bytes
+ }
+ }
+ if held := heldApps(outs); len(held) > 0 {
+ failed = append(failed, fmt.Errorf("kept every build of %s: settings references did not read in full", strings.Join(held, ", ")))
}
if len(failed) > 0 {
res.err = errors.Join(failed...)
@@ -421,12 +638,12 @@ func (r *demoRetention) run(ctx context.Context) demoRetentionResult {
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:
+ if 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)
}
+ if res.err != nil {
+ r.logf("adopt: demo build retention kept every build it could not prove unused: %v (backlog %d)", res.err, res.backlog)
+ }
r.saveStatus(res)
return res
}
@@ -472,36 +689,42 @@ func (r *demoRetention) saveStatus(res demoRetentionResult) {
}
// 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.
+// through release.WithBeforeStage before a new output is staged: for a
+// demo app, every staged output of that app that nothing pins (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.
//
-// path is the VersionPath about to be written. A path that is not a demo
-// app's (<ver>/<demo account>/tmp-demo-<name> of a demo route) is left to
-// stage.
+// path is the VersionPath about to be written, in either layout
+// (<ver>/<account>/<app>, or the ops account's <ver>/<app>). A path that is
+// not the demo account's tmp-demo- app is left to stage. One that is, on a
+// box that cannot bound it (the demo account is the ops account, or the
+// name is not a demo name), is refused.
func (r *demoRetention) beforeStage(ctx context.Context, path string) error {
if r == nil || !r.box.BoxMode() {
return nil
}
- rel, err := filepath.Rel(filepath.Join(r.optDir, "versions"), path)
- parts := strings.Split(rel, string(filepath.Separator))
- if err != nil || len(parts) != 3 || !release.ValidVersion(parts[0]) {
+ ver, k, ok := r.outputAt(path)
+ if !ok || k.acct != r.box.Account || !strings.HasPrefix(k.app, demo.AppPrefix) {
return nil
}
- ver, k := parts[0], demoAppKey{parts[1], parts[2]}
- if release.VersionPath(r.optDir, k.acct, ver, k.app) != filepath.Clean(path) || !r.demoAppListed(k) {
- return nil
+ if _, err := r.demoAccount(); err != nil {
+ return fmt.Errorf("demo build cleanup: %w", err)
+ }
+ if !validDemoName(k.app) {
+ return fmt.Errorf("demo build cleanup: %q is not a demo app name, so its build is not staged", k.app)
}
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)
+ outs, inc, err := r.selection(ctx, k.app, ver, true)
if err != nil {
return fmt.Errorf("demo build cleanup: %w", err)
}
+ if inc != nil && inc.Covers(k.acct, k.app) {
+ return fmt.Errorf("demo build cleanup: %s: %w", k.app, inc)
+ }
for _, o := range outs {
- if o.keep {
+ if o.pinned {
continue
}
if err := r.removeOutput(o); err != nil {
@@ -512,30 +735,34 @@ func (r *demoRetention) beforeStage(ctx context.Context, path string) error {
return nil
}
-// demoAppListed: a demo route runs k. A registry that does not list
-// counts as listed, so the cleanup's own read refuses the stage.
-func (r *demoRetention) demoAppListed(k demoAppKey) bool {
- if k.acct != r.box.Account || !strings.HasPrefix(k.app, demo.AppPrefix) {
- return false
- }
- if r.reg == nil {
- return true
- }
- routes, err := r.reg.List()
+// outputAt reads path as a canonical VersionPath in either layout: the
+// version, account and app it names.
+func (r *demoRetention) outputAt(path string) (string, demoAppKey, bool) {
+ rel, err := filepath.Rel(filepath.Join(r.optDir, "versions"), path)
if err != nil {
- return true
- }
- for _, rt := range routes {
- if got, ok := r.demoApp(rt); ok && got == k {
- return true
- }
+ return "", demoAppKey{}, false
}
- return false
+ parts := strings.Split(rel, string(filepath.Separator))
+ var k demoAppKey
+ switch len(parts) {
+ case 2:
+ k = demoAppKey{release.OpsAccount, parts[1]}
+ case 3:
+ k = demoAppKey{parts[1], parts[2]}
+ default:
+ return "", demoAppKey{}, false
+ }
+ ver := parts[0]
+ if !release.ValidVersion(ver) || release.VersionPath(r.optDir, k.acct, ver, k.app) != filepath.Clean(path) {
+ return "", demoAppKey{}, false
+ }
+ return ver, k, true
}
-// 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).
+// demoAdoptions is the demo account's tmp-demo- routes' adopted versions by
+// host, read before a pass so afterPass can tell whether it adopted one.
+// It decides only whether retention runs, never what it removes. 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
@@ -546,13 +773,36 @@ func (r *demoRetention) demoAdoptions() map[string]string {
}
out := map[string]string{}
for _, rt := range routes {
- if _, ok := r.demoApp(rt); ok {
+ if release.RouteAccount(rt) == r.box.Account && strings.HasPrefix(rt.App, demo.AppPrefix) {
out[rt.Host] = rt.Version
}
}
return out
}
+// adoptPassRetention is the demo build retention a root adopt pass runs,
+// from its mode flags and whether it took the adopt pass lock: none on a
+// -config-only or -restart-only pass, which adopts nothing; locked only
+// when the lock was taken (without it retention deletes nothing and a demo
+// stage is refused); hourly (retention runs even when the pass adopted no
+// demo version) unless -stage-only. build makes the retention for a lock
+// state.
+func adoptPassRetention(configOnly, restartOnly, stageOnly bool, lockErr error, build func(locked bool) *demoRetention) (*demoRetention, bool) {
+ if configOnly || restartOnly {
+ return nil, false
+ }
+ return build(lockErr == nil), !stageOnly
+}
+
+// adoptPassAround is runAdoptUnderRootRelease's release pass inside the
+// demo build retention its mode and lock allow (adoptPassRetention).
+func adoptPassAround(ctx context.Context, configOnly, restartOnly, stageOnly bool, lockErr error, reg routeLister, rootPins release.PinSource, pass func(stage release.PassOption) error) func() error {
+ r, hourly := adoptPassRetention(configOnly, restartOnly, stageOnly, lockErr, func(locked bool) *demoRetention {
+ return productionDemoRetention(reg, rootPins, locked)
+ })
+ return r.around(ctx, hourly, pass)
+}
+
// 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.
diff --git a/internal/host/demoretention_linux_test.go b/internal/host/demoretention_linux_test.go
index 1bbb40206..93750f074 100644
--- a/internal/host/demoretention_linux_test.go
+++ b/internal/host/demoretention_linux_test.go
@@ -162,3 +162,90 @@ func TestDemoRetentionConcurrentAdoptionIsSerialized(t *testing.T) {
t.Fatal("the second pass did not run")
}
}
+
+// A sibling app's root generation reserves the tree that holds the demo's
+// output (<ver>/<account>, its Tree): retention keeps every output inside
+// it, as generationWriteCheck refuses writes there (Astra round 1 P1-1).
+// The reservation is a real one in root's ledger, read through the
+// production source.
+func TestDemoRetentionKeepsOutputsInsideAReservedTree(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)
+ if err := release.StageArtifact(b.opt, "shop", demoVer(1), "blog", []byte("blog build")); err != nil {
+ t.Fatal(err)
+ }
+
+ held := permit.reservation.Binding
+ held.Attempt, held.Invocation = "blog-worker", "blog-worker"
+ held.Binding.Account, held.Binding.App, held.Version = "shop", "blog", demoVer(1)
+ held.Path = release.VersionPath(b.opt, "shop", demoVer(1), "blog")
+ 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)
+ }
+ got := b.outputs("shop", app)
+ if !slices.Contains(got, demoVer(1)) {
+ t.Fatalf("the demo output inside the reserved tree was removed: %v", got)
+ }
+ if slices.Contains(got, demoVer(2)) {
+ t.Fatalf("v2, outside every reserved tree, survived: %v", got)
+ }
+}
+
+// A pin on any directory above an output keeps it, whether the pin and the
+// output are spelled through the store's own path or its real path.
+func TestDemoRetentionPinnedByAnAncestorUnderEitherSpelling(t *testing.T) {
+ real := t.TempDir()
+ opt := filepath.Join(t.TempDir(), "opt")
+ if err := os.Symlink(real, opt); err != nil {
+ t.Fatal(err)
+ }
+ app := demoAppName("red")
+ if err := os.MkdirAll(filepath.Join(real, "versions", demoVer(1), "shop"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(release.VersionPath(real, "shop", demoVer(1), app), []byte("build"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ o := demoOutput{demoAppKey: demoAppKey{"shop", app}, version: demoVer(1)}
+ for _, c := range []struct {
+ pin string
+ want bool
+ }{
+ {filepath.Join(opt, "versions", demoVer(1), "shop"), true},
+ {filepath.Join(opt, "versions", demoVer(1)), true},
+ {filepath.Join(real, "versions", demoVer(1), "shop"), true},
+ {filepath.Join(real, "versions", demoVer(1)), true},
+ {filepath.Join(opt, "versions", demoVer(1), "shop", "blog"), false},
+ {filepath.Join(opt, "versions", demoVer(2), "shop"), false},
+ {filepath.Join(opt, "versions", demoVer(1), "sho"), false},
+ } {
+ if got := pinned([]string{c.pin}, opt, o); got != c.want {
+ t.Errorf("pin %s: pinned = %v, want %v", c.pin, got, c.want)
+ }
+ }
+}
diff --git a/internal/host/demoretention_test.go b/internal/host/demoretention_test.go
index 974bc0219..1f92abfc9 100644
--- a/internal/host/demoretention_test.go
+++ b/internal/host/demoretention_test.go
@@ -3,6 +3,8 @@ package host
import (
"context"
"crypto/ed25519"
+ "crypto/sha256"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -11,6 +13,7 @@ import (
"runtime"
"slices"
"sort"
+ "strings"
"testing"
"time"
@@ -66,14 +69,26 @@ func (b *retentionBox) retention(locked bool) *demoRetention {
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 }
+// demoPublicNames gives each test demo the public name the console would
+// (demo.ValidPublicName): retention only ever selects those.
+var demoPublicNames = map[string]string{"red": "amber-acorn-01", "blue": "azure-apple-02"}
+
+func demoHost(name string) string { return demoPublicNames[name] + "." + retentionDemo.Domain }
+func demoAppName(name string) string { return demo.AppPrefix + demoPublicNames[name] }
+
+// demoRow is the registry row the console's placement writes for a demo:
+// a complete, valid descriptor (demo.Config.ValidateBinding).
+func (b *retentionBox) demoRow(name string, hibernate bool) registry.Route {
+ id := sha256.Sum256([]byte(name))
+ return 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: base64.RawURLEncoding.EncodeToString(id[:16]), DemoHost: demoHost(name), DemoLifetime: "24h",
+ DemoExpiresAt: b.clock.Add(24 * time.Hour).Unix()}
+}
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 {
+ if err := b.reg.Upsert(b.demoRow(name, hibernate)); err != nil {
b.t.Fatal(err)
}
}
@@ -489,14 +504,7 @@ func TestDemoRetentionBacklogAcrossFailedRuns(t *testing.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)
- }
+ b.adoptedAt("red", 4, 3, 4)
start := b.clock
b.retention(false).run(context.Background())
if s := b.status(); s.Backlog != 2 || !s.BacklogSince.Equal(start) {
@@ -541,7 +549,7 @@ func TestDemoRetentionFailedOutputsDoNotAccumulate(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- pins, err := b.retention(true).pinSet(context.Background(), routes, true)
+ pins, _, err := b.retention(true).pinSet(context.Background(), routes, true)
if err != nil {
t.Fatal(err)
}
@@ -584,3 +592,289 @@ func TestDemoRetentionLeavesNonDemoBoxesAndAppsAlone(t *testing.T) {
t.Fatalf("a non-demo box wrote the record: %v", err)
}
}
+
+// adoptedAt stages builds 1..staged of name's app and leaves the demo at
+// live (adopted through its live link, the row naming live and prev), as
+// a box would after those updates: the builds below prev are beyond the
+// bound, and those above live were never adopted.
+func (b *retentionBox) adoptedAt(name string, staged, prev, live int) {
+ b.t.Helper()
+ app := demoAppName(name)
+ for i := 1; i <= staged; i++ {
+ if err := release.StageArtifact(b.opt, retentionDemo.Account, demoVer(i), app, []byte("build "+demoVer(i))); err != nil {
+ b.t.Fatal(err)
+ }
+ }
+ if err := b.reg.SetVersions(demoHost(name), demoVer(live), demoVer(prev)); err != nil {
+ b.t.Fatal(err)
+ }
+ for _, v := range []int{prev, live} {
+ if err := release.PointLive(context.Background(), nil, b.opt, demoHost(name), retentionDemo.Account, demoVer(v), app); err != nil {
+ b.t.Fatal(err)
+ }
+ }
+}
+
+// forgedLister is the registry with rows the service could write: a forged
+// row replaces the real row of its host, or is added. Retention must read
+// them as protection only.
+type forgedLister struct {
+ reg routeLister
+ rows []registry.Route
+}
+
+func (f forgedLister) List() ([]registry.Route, error) {
+ rows, err := f.reg.List()
+ added := slices.Clone(f.rows)
+ for i, rt := range rows {
+ for j, forged := range added {
+ if forged.Host == rt.Host {
+ rows[i] = forged
+ added = slices.Delete(added, j, j+1)
+ break
+ }
+ }
+ }
+ return append(rows, added...), err
+}
+
+// Registry rows are service-owned, so they may only add protection (Astra
+// round 1 P1-2). What makes an output eligible is root's: the box's demo
+// account from host.env and a tmp-demo- name it lists in its own store.
+// A malformed descriptor, a second row running the app as something other
+// than a demo, and a name that climbs out of the store select nothing.
+func TestDemoRetentionRegistryRowsOnlyAddProtection(t *testing.T) {
+ cases := []struct {
+ name string
+ forge func(b *retentionBox) []registry.Route
+ kept bool
+ }{
+ {"valid demo row", func(b *retentionBox) []registry.Route { return nil }, false},
+ {"malformed descriptor", func(b *retentionBox) []registry.Route {
+ rt := b.route("red")
+ rt.DemoID = "not-a-demo-id"
+ return []registry.Route{rt}
+ }, true},
+ {"conflicting non-demo row", func(b *retentionBox) []registry.Route {
+ rt := b.demoRow("red", true)
+ rt.Host, rt.Socket = "shop.example.org", provision.NestedSocket("shop.example.org")
+ rt.DemoID, rt.DemoHost, rt.DemoLifetime, rt.DemoExpiresAt = "", "", "", 0
+ return []registry.Route{rt}
+ }, true},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.adoptedAt("red", 4, 3, 4)
+ if rows := c.forge(b); rows != nil {
+ b.lister = forgedLister{reg: b.reg, rows: rows}
+ }
+ res := b.retention(true).run(context.Background())
+ got := b.outputs("shop", demoAppName("red"))
+ if c.kept && len(got) != 4 {
+ t.Fatalf("a registry row made builds eligible: store %v (%+v)", got, res)
+ }
+ if !c.kept && !sameSet(got, []string{demoVer(3), demoVer(4)}) {
+ t.Fatalf("control: store %v, want v3 and v4 (%+v)", got, res)
+ }
+ })
+ }
+}
+
+// A demo-marked row whose app climbs out of the version store makes root
+// neither read nor count nor remove anything outside it: names come from
+// root's listing of its own store, validated before any use.
+func TestDemoRetentionTraversalNameReachesNothingOutsideTheStore(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.adoptedAt("red", 4, 3, 4)
+ outside := filepath.Join(b.opt, "outside")
+ if err := os.WriteFile(outside, []byte("not a build"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ rt := b.demoRow("red", true)
+ rt.Host, rt.DemoHost = "climb."+retentionDemo.Domain, "climb."+retentionDemo.Domain
+ rt.App = demo.AppPrefix + "x/../../../../outside"
+ rt.Version = demoVer(99)
+ b.lister = forgedLister{reg: b.reg, rows: []registry.Route{rt}}
+ r := b.retention(true)
+ var removed []string
+ r.onRemove = func(p string) { removed = append(removed, p) }
+ res := r.run(context.Background())
+ if _, err := os.Stat(outside); err != nil {
+ t.Fatalf("the file outside the store: %v", err)
+ }
+ for _, p := range removed {
+ if rel, err := filepath.Rel(filepath.Join(b.opt, "versions"), p); err != nil || strings.HasPrefix(rel, "..") {
+ t.Fatalf("a removal outside the store: %s", p)
+ }
+ }
+ if res.err != nil || res.outputs != 2 {
+ t.Fatalf("retention counted or tried something outside the store: %+v", res)
+ }
+ if got := b.outputs("shop", demoAppName("red")); !sameSet(got, []string{demoVer(3), demoVer(4)}) {
+ t.Fatalf("store %v", got)
+ }
+}
+
+// The ops account keeps the pre-accounts layout (<ver>/<app>), shared with
+// every ops app, and the console never places demos there. A demo box
+// configured with it refuses loudly: every demo stage is refused and the
+// retention record says why. Nothing is skipped silently.
+func TestDemoRetentionRefusesADemoAccountOnTheOpsLayout(t *testing.T) {
+ b := newRetentionBox(t, "")
+ app := demoAppName("red")
+ rt := b.demoRow("red", true)
+ rt.Account = release.OpsAccount
+ if err := b.reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ b.ship(release.OpsAccount, app, demoVer(1))
+ r := b.retention(true)
+ r.box.Account = release.OpsAccount
+ b.pass(r, false)
+ if v := b.route("red").Version; v != "" {
+ t.Fatalf("a demo build was staged on the ops layout: route at %q", v)
+ }
+ err := r.beforeStage(context.Background(), release.VersionPath(b.opt, release.OpsAccount, demoVer(2), app))
+ if err == nil || !strings.Contains(err.Error(), "ops account") {
+ t.Fatalf("beforeStage = %v, want a refusal naming the ops account", err)
+ }
+ res := r.run(context.Background())
+ if res.err == nil || !strings.Contains(b.status().Reason, "ops account") {
+ t.Fatalf("retention did not refuse: %+v, record %+v", res, b.status())
+ }
+}
+
+// A box upgraded with failed outputs already piled up: retention keeps the
+// pins and the newest output never adopted, and removes the older pending
+// ones under the lock. Pending names it cannot order are kept and counted
+// as backlog.
+func TestDemoRetentionPreExistingPendingOutputs(t *testing.T) {
+ t.Run("ordered", func(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.adoptedAt("red", 6, 2, 3)
+ res := b.retention(true).run(context.Background())
+ if got := b.outputs("shop", demoAppName("red")); !sameSet(got, []string{demoVer(2), demoVer(3), demoVer(6)}) {
+ t.Fatalf("store %v, want the pins v2 and v3 and the newest pending v6 (%+v)", got, res)
+ }
+ if s := b.status(); s.Backlog != 0 || s.Outputs != 3 {
+ t.Fatalf("record %+v", s)
+ }
+ })
+ t.Run("unordered", func(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.adoptedAt("red", 3, 2, 3)
+ for _, v := range []string{"v8-custom", "v9-custom"} {
+ if err := release.StageArtifact(b.opt, "shop", v, demoAppName("red"), []byte("build")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ b.retention(true).run(context.Background())
+ if got := b.outputs("shop", demoAppName("red")); !sameSet(got, []string{demoVer(2), demoVer(3), "v8-custom", "v9-custom"}) {
+ t.Fatalf("store %v", got)
+ }
+ if s := b.status(); s.Backlog != 1 || s.BacklogSince.IsZero() {
+ t.Fatalf("record %+v, want one pending output reported beyond the bound", s)
+ }
+ })
+}
+
+// BoxPins reports another app's unreadable settings references with the
+// pins it did read (IncompleteRefsError). Retention keeps those pins and
+// holds only the apps the error covers: another app's bad column does not
+// stop the demo's retention; the demo's own stops its retention and
+// refuses its next stage.
+func TestDemoRetentionIncompleteReferencesStopOnlyTheirApp(t *testing.T) {
+ manual, err := json.Marshal(release.UpdateSettings{Updates: release.UpdatesManual})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Run("another app", func(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.addDemo("blue", true)
+ b.adoptedAt("red", 4, 3, 4)
+ if err := b.reg.Upsert(registry.Route{Host: "blog.example.org", Kind: "instance", Account: "other", App: "blog", Channel: "edge", Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ for _, host := range []string{"blog.example.org", demoHost("blue")} {
+ if err := b.reg.SetUpdateSettings(host, string(manual)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ res := b.retention(true).run(context.Background())
+ if got := b.outputs("shop", demoAppName("red")); !sameSet(got, []string{demoVer(3), demoVer(4)}) {
+ t.Fatalf("another app's references stopped the demo's retention: store %v (%+v)", got, res)
+ }
+ })
+ t.Run("its own", func(t *testing.T) {
+ b := newRetentionBox(t, "")
+ b.addDemo("red", true)
+ b.adoptedAt("red", 4, 3, 4)
+ if err := b.reg.SetUpdateSettings(demoHost("red"), string(manual)); err != nil {
+ t.Fatal(err)
+ }
+ r := b.retention(true)
+ res := r.run(context.Background())
+ if got := b.outputs("shop", demoAppName("red")); len(got) != 4 {
+ t.Fatalf("the demo's own unread references deleted builds: %v", got)
+ }
+ if s := b.status(); res.err == nil || s.Backlog != 2 || s.Reason == "" {
+ t.Fatalf("result %+v, record %+v", res, s)
+ }
+ if err := r.beforeStage(context.Background(), release.VersionPath(b.opt, "shop", demoVer(5), demoAppName("red"))); err == nil {
+ t.Fatal("the demo's next stage was not refused")
+ }
+ })
+}
+
+// The composition runAdoptUnderRootRelease uses: no retention on the narrow
+// passes, locked only when the pass lock was taken, hourly unless
+// -stage-only.
+func TestAdoptPassRetentionFollowsTheModeAndTheLock(t *testing.T) {
+ b := newRetentionBox(t, "")
+ built := 0
+ build := func(locked bool) *demoRetention { built++; return b.retention(locked) }
+ lockErr := errors.New("lock file unavailable")
+ for _, c := range []struct {
+ name string
+ configOnly, restartOnly, stage bool
+ lockErr error
+ wantNil, wantLocked, wantHourly bool
+ }{
+ {name: "normal", wantLocked: true, wantHourly: true},
+ {name: "stage-only", stage: true, wantLocked: true},
+ {name: "lock failure", lockErr: lockErr, wantHourly: true},
+ {name: "config-only", configOnly: true, wantNil: true},
+ {name: "restart-only", restartOnly: true, wantNil: true},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ built = 0
+ r, hourly := adoptPassRetention(c.configOnly, c.restartOnly, c.stage, c.lockErr, build)
+ if c.wantNil {
+ if r != nil || built != 0 {
+ t.Fatalf("a narrow pass built retention: %v (%d)", r, built)
+ }
+ return
+ }
+ if r == nil || r.locked != c.wantLocked || hourly != c.wantHourly {
+ t.Fatalf("retention %+v hourly %v", r, hourly)
+ }
+ })
+ }
+ // Without the lock it deletes nothing and refuses a demo stage.
+ b.addDemo("red", true)
+ b.adoptedAt("red", 4, 3, 4)
+ r, _ := adoptPassRetention(false, false, false, lockErr, build)
+ r.run(context.Background())
+ if got := b.outputs("shop", demoAppName("red")); len(got) != 4 {
+ t.Fatalf("retention without the lock deleted: %v", got)
+ }
+ if err := r.beforeStage(context.Background(), release.VersionPath(b.opt, "shop", demoVer(5), demoAppName("red"))); err == nil {
+ t.Fatal("a stage without the lock was not refused")
+ }
+}