hosted: ops teardown continuation, settle --ended-at, bucket resume
The run kit's side of Astra's plan review r2, rulings K9 to K11: - continuation arm FILE --max D: after a safe stop the recovery unit starts FILE as h<env>-<RUN>-teardown (RuntimeMaxSec D, 5 min stop), unless a guard failure caused it, the file changed, it was disarmed or it already ran. Every guard refusal is journalled ABORT guard:. - vms settle --step --ended-at: the step's real end; the bound counts from it; refused in the future or before the step could start. - bucket empty and delete take a recorded bucket read gone as done.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+582
−23
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+62 −0infra/hosted/README.md+8 −1internal/hostedops/buckets.go+46 −2internal/hostedops/continuation.go+162 −0internal/hostedops/fake_test.go+6 −1internal/hostedops/kit34r2_test.go+224 −0internal/hostedops/ops.go+7 −1internal/hostedops/stop.go+8 −2internal/hostedops/units.go+17 −7internal/hostedops/vms.go+41 −8
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index edc738af..e458901a 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -88,4 +88,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin, |
| # and the same bounded cardView as the snapshot; no list scan or new route. |
| perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen. |
| size internal/hostedctl 6079 10017 Hosted controller core and its lifecycle simulation; split planned for slice 1b; slice 2: egress snapshot, admission, deadlines, healthz; measured 6079/10017. |
| -size internal/hostedops 7654 - Hosted slice 2 Task 33: equipo-hosted-ops, one journal and one Ops shared by every run kit subcommand, so one package; dev drill run-kit fixes 2 and 5 to 7 (fence record, reboot waits, scan retry, S.1 argv); Task 34 kit K1 to K8 (teardown blocks, exit classes, tag cross-check, VM accounting and step settle, unit status and retries, finding); measured 7654. |
| +size internal/hostedops 7915 - Hosted slice 2 Task 33: equipo-hosted-ops, one journal and one Ops shared by every run kit subcommand, so one package; dev drill run-kit fixes 2 and 5 to 7 (fence record, reboot waits, scan retry, S.1 argv); Task 34 kit K1 to K8 (teardown blocks, exit classes, tag cross-check, VM accounting and step settle, unit status and retries, finding); round 2 K9 to K11 (recovery-to-teardown continuation, settle --ended-at, resumable bucket teardown); measured 7915. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index d1e26070..932f2f38 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -3796,3 +3796,65 @@ Mutation checks, each restored: |
| one run with H11, each failing its own case. |
| - **H14** `fresh_suite` making its own run id: `test_fresh_runs_and_green_record` FAILED, the |
| `HOSTED-SUITE-START` run differing from `EQUIPO_STAGING_RUN_ID`. |
| + |
| +### Task 34 kit, round 2 (Astra's plan review r2, rulings K9 to K11, 2026-12-02) |
| + |
| +No AWS call of any kind. Brief `kit-p34-r2-brief.md`, findings `p34-r2.md`. |
| + |
| +- **K9** `ops continuation arm FILE --max D` (FILE under the run directory, not group or other |
| + writable, D at most 24h) journals `CONTINUATION armed path= sha256= max=`; `ops continuation |
| + disarm` withdraws it. After its safe stop the recovery unit starts FILE as |
| + `h<env>-<RUN>-teardown` (`/bin/bash FILE`, env -i allowlist, RuntimeMaxSec D, TimeoutStopSec |
| + 5 min), journalled `CONTINUATION started`, unless: an `ABORT guard:` line since the arm, the |
| + recovery's own credential check failed, the file is gone or its SHA-256 changed, disarmed, or |
| + already started once; each `CONTINUATION not run: WHY`. `open()` now journals every guard refusal |
| + as `ABORT guard:` (account or region of another run, the opener's answer differing). S.0 spares the |
| + continuation unit, and `busy()` lets blocks start inside it. The `Systemd` interface's `Start` |
| + takes a runtime bound (`RuntimeMaxSec`). |
| +- **K10** `vms settle --step ID --ended-at RFC3339`: the given time becomes `STEP-END ... given=yes` |
| + and the bound counts from it; refused (1) in the future, before the image was recorded or before |
| + the image's last `STEP-SETTLED`, without `--step`, or differing from a step's existing end. |
| +- **K11** `bucket empty` and `bucket delete`: a recorded bucket (ops's or OpenTofu's) a direct read |
| + shows absent is done, its record journalled `DELETED ... read-gone`, and later calls skip it; |
| + another owner is 99, a failed read 1. |
| + |
| +Tests: `internal/hostedops/kit34r2_test.go` (`TestContinuationRunsAfterSafeStop`, |
| +`TestContinuationRefusals`, `TestContinuationArmChecks`, `TestSettleStepEndedAt`, |
| +`TestBucketTeardownResumable`, `TestRound2InvocationsParse`). Red first (the `Start` signature and |
| +`ContinuationStopTimeout` only, so failures are assertions): `kit34r2_test.go:42: ops continuation arm |
| +... = 1, want 0`, `:85` and `:117` the same, `:129: ops vms settle --step s1 ... --ended-at ... = 1, |
| +want 0`, `:170: ops bucket empty ... = 1, want 0`, `:215: ops continuation arm: usage: unknown command`. |
| +Green: `./internal/hostedops/...`, `./cmd/equipo-hosted-ops`, `./internal/isolatedjob/awsjob/opsaws`, |
| +`./cmd/equipo-hosted-image` (plan parse tests against plan rev 2 included). |
| + |
| +Mutation checks, each restored and green again (`go test ./internal/hostedops -count=1 -run <test>`): |
| +- **K9a** recovery never continues: `TestContinuationRunsAfterSafeStop` FAILED `:48 the continuation |
| + did not start: started [hprod-r1-recovery.service]`. |
| +- **K9b** guard lines ignored: `TestContinuationRefusals` FAILED `guard failure journalled: the |
| + continuation started`. |
| +- **K9c** the recovery's credential check ignored: first SURVIVED (a refused guard is also |
| + journalled `ABORT guard:`); the test gained an ordinary credential failure (expired session), |
| + then FAILED `recovery's credentials expired: the continuation started`. |
| +- **K9d** SHA-256 not checked: FAILED `tampered: the continuation started`. |
| +- **K9e** disarm ignored: FAILED `disarmed: the continuation started`. |
| +- **K9f** a second start allowed: first SURVIVED (startUnit refuses the reused name, and its message |
| + also says "already started"); the assertion now asks for "not run: already started once", then |
| + FAILED `:67 the second recovery did not say why`. |
| +- **K9g** S.0 stops the continuation: FAILED `:64 second recovery: ... stopped [hprod-r1-teardown.service]`. |
| +- **K9h** a guard failure before the arm counted: FAILED `:100 a guard failure before the arm held |
| + the continuation back`. |
| +- **K9i** no runtime bound: FAILED `:55 bounds: runtime 0s, stop timeout 5m0s`. |
| +- **K9j** a file outside the run directory armed: `TestContinuationArmChecks` FAILED `:109 ... = 0, want 1`. |
| +- **K9k** a group-writable file armed: FAILED `:112 ... = 0, want 1`. |
| +- **K9l** the continuation counted busy: `TestContinuationRunsAfterSafeStop` FAILED `:71 ops unit |
| + start 8.2 -- bash x = 1, want 0`. |
| +- **K10a** the given end ignored: `TestSettleStepEndedAt` FAILED `:131 STEP-END does not carry the given end`. |
| +- **K10b** a future end accepted: FAILED `:145 ... --ended-at 2026-12-01T10:01:00Z ... = 0, want 1`. |
| +- **K10c** an end before the image accepted: FAILED `:145 ... --ended-at 2026-12-01T09:00:00Z ... = 99, want 1`. |
| +- **K10d** the previous step's settlement ignored: FAILED `:150 ops vms settle --step s5 ... = 0, want 1`. |
| +- **K10e** another end on a re-run accepted: FAILED `:154 ... --step s6 ... = 99, want 1`. |
| +- **K11a** an absent bucket not accepted: `TestBucketTeardownResumable` FAILED `:170 ops bucket empty ... = 1, want 0`. |
| +- **K11b** not journalled: FAILED `:175 ops-recorded empty: the bucket's state is confirmed, want absent`. |
| +- **K11c** another owner accepted: FAILED `:184 ... = 0, want 99`. |
| +- **K11d** OpenTofu's record not marked: FAILED `:175 tf-recorded empty: the bucket's state is |
| + confirmed, want absent`. |
diff --git a/infra/hosted/README.md b/infra/hosted/README.md| index f9fbff70..47ff99ea 100644 |
| --- a/infra/hosted/README.md |
| +++ b/infra/hosted/README.md |
| @@ -197,7 +197,14 @@ ledger's ownership run, the spend gate does not, and every command that |
| creates or admits spend refuses inside it (99). Teardown commands (`tf |
| ROOT destroy-*`, `controller terminate`, `unfence`, `bucket empty` and |
| `delete`, `connector delete`, `img delete`, `verify-gone`, `vms settle`) |
| -never look at spend. |
| +never look at spend, and `bucket empty` and `delete`, like `img delete |
| +-ledger`, take a recorded bucket a direct read shows gone as done. |
| + |
| +`ops continuation arm FILE --max D`, before any human wait, arms the |
| +teardown the recovery unit starts by itself once a safe stop has finished |
| +(unit `h<env>-<RUN>-teardown`, at most D, then stopped within 5 minutes), |
| +unless a guard failure caused the stop, the file changed since the arm, |
| +or it already ran once. `ops continuation disarm` withdraws it. |
| ## Checks |
diff --git a/internal/hostedops/buckets.go b/internal/hostedops/buckets.go| index 48ea75eb..16995d95 100644 |
| --- a/internal/hostedops/buckets.go |
| +++ b/internal/hostedops/buckets.go |
| @@ -176,6 +176,44 @@ func (o *Ops) haveBucket(name string) (bool, error) { |
| } |
| } |
| +// ownedOrGone is bucket empty's and delete's owner check, resumable (K11, |
| +// p34-r2 finding 13): a recorded bucket a direct read shows absent is gone |
| +// (true), its record journalled DELETED read-gone, so a teardown replayed |
| +// after a partial destroy goes on. The expected owner must be this run's |
| +// account and a bucket of another owner stays a stop (99); a read that |
| +// fails is 1. |
| +func (o *Ops) ownedOrGone(name, owner string) (bool, error) { |
| + if owner == "" { |
| + owner = o.Account |
| + } |
| + if owner != o.Account { |
| + return false, stopf("--expected-owner %s is not this run's account %s", owner, o.Account) |
| + } |
| + err := o.cloud.HeadBucket(o.ctx, name, owner) |
| + switch { |
| + case errors.Is(err, ErrNotFound): |
| + case err != nil: |
| + return false, o.checkOwner(name, owner) // the owner check's own classes: 99 another owner, 1 a failed read |
| + default: |
| + return false, o.jw("OWNER", "%s %s", name, owner) |
| + } |
| + l, err := o.ledger() |
| + if err != nil { |
| + return false, err |
| + } |
| + for _, r := range l.Recs { |
| + if (r.Kind == "s3-bucket" && r.Name == name) || (r.Kind == "tf" && r.Attr("type") == "aws_s3_bucket" && r.Attr("id") == name) { |
| + if !l.Deleted[r.Kind+" "+r.Value] { |
| + if err := o.jw("DELETED", "%s %s read-gone", r.Kind, r.Value); err != nil { |
| + return false, err |
| + } |
| + } |
| + } |
| + } |
| + o.out("bucket %s is already gone (a direct read)", name) |
| + return true, nil |
| +} |
| + |
| // emptyBucket deletes every version and delete marker, page by page, then |
| // lists again until a listing is empty. It returns how many it deleted. |
| func (o *Ops) emptyBucket(name string) (int, error) { |
| @@ -219,10 +257,13 @@ func cmdBucketEmpty(o *Ops, args []string) error { |
| if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *b.name == "" { |
| return usagef("bucket empty --name N [--expected-owner A]") |
| } |
| + if *b.owner != "" && *b.owner != o.Account { |
| + return stopf("--expected-owner %s is not this run's account %s", *b.owner, o.Account) |
| + } |
| if ok, err := o.haveBucket(*b.name); !ok || err != nil { |
| return err |
| } |
| - if err := o.checkOwner(*b.name, *b.owner); err != nil { |
| + if gone, err := o.ownedOrGone(*b.name, *b.owner); gone || err != nil { |
| return err |
| } |
| n, err := o.emptyBucket(*b.name) |
| @@ -239,10 +280,13 @@ func cmdBucketDelete(o *Ops, args []string) error { |
| if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *b.name == "" { |
| return usagef("bucket delete --name N [--expected-owner A]") |
| } |
| + if *b.owner != "" && *b.owner != o.Account { |
| + return stopf("--expected-owner %s is not this run's account %s", *b.owner, o.Account) |
| + } |
| if ok, err := o.haveBucket(*b.name); !ok || err != nil { |
| return err |
| } |
| - if err := o.checkOwner(*b.name, *b.owner); err != nil { |
| + if gone, err := o.ownedOrGone(*b.name, *b.owner); gone || err != nil { |
| return err |
| } |
| p, err := o.cloud.ListVersions(o.ctx, *b.name, o.Account, "", "") |
diff --git a/internal/hostedops/continuation.go b/internal/hostedops/continuation.go| new file mode 100644 |
| index 00000000..fc1c6452 |
| --- /dev/null |
| +++ b/internal/hostedops/continuation.go |
| @@ -0,0 +1,162 @@ |
| +package hostedops |
| + |
| +import ( |
| + "flag" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// The recovery-to-teardown continuation (Task 34 kit, K9; p34-r2 finding |
| +// 1). Armed before any human wait, it is a teardown script the plan wrote |
| +// from its section 8: the recovery unit, once its safe stop has finished, |
| +// starts it unattended as its own journalled unit, h<env>-<RUN>-teardown, |
| +// bounded by the --max it was armed with (RuntimeMaxSec) and |
| +// ContinuationStopTimeout. It is not started when the safe stop's cause |
| +// was a guard failure (an "ABORT guard:" line journalled since the arm, or |
| +// the recovery's own credentials refused), when the file is gone or no |
| +// longer has the SHA-256 it was armed with, when it was disarmed, or when |
| +// it already started once: each journalled "CONTINUATION not run: WHY". |
| + |
| +// ContinuationBlock names the continuation's unit. |
| +const ContinuationBlock = "teardown" |
| + |
| +// MaxContinuation bounds --max. |
| +const MaxContinuation = 24 * time.Hour |
| + |
| +// continuation is the run's continuation as the journal records it. |
| +type continuation struct { |
| + armed bool |
| + path, sum string |
| + max time.Duration |
| + armLine int |
| + started bool |
| + everArmed bool |
| + startedAny bool |
| +} |
| + |
| +func continuationOf(l *Ledger) continuation { |
| + var c continuation |
| + for _, e := range l.Entries { |
| + if e.Verb != "CONTINUATION" { |
| + continue |
| + } |
| + switch e.Field(0) { |
| + case "armed": |
| + max, _ := time.ParseDuration(e.Attr("max")) |
| + c = continuation{armed: true, path: e.Attr("path"), sum: e.Attr("sha256"), max: max, armLine: e.Line, |
| + everArmed: true, startedAny: c.startedAny} |
| + case "disarmed": |
| + c.armed = false |
| + case "started": |
| + c.started, c.startedAny = true, true |
| + } |
| + } |
| + return c |
| +} |
| + |
| +func cmdContinuationArm(o *Ops, args []string) error { |
| + fs := flag.NewFlagSet("continuation arm", flag.ContinueOnError) |
| + maxD := fs.Duration("max", 0, "the continuation unit's longest run (RuntimeMaxSec)") |
| + pos, err := parseFlags(fs, args) |
| + if err != nil || len(pos) != 1 || *maxD <= 0 || *maxD > MaxContinuation { |
| + return usagef("continuation arm FILE --max D (D at most %s)", MaxContinuation) |
| + } |
| + l, err := o.ledger() |
| + if err != nil { |
| + return err |
| + } |
| + if continuationOf(l).startedAny { |
| + return failf("a continuation already started in this run; it runs once") |
| + } |
| + file, err := filepath.Abs(pos[0]) |
| + if err != nil { |
| + return failf("%v", err) |
| + } |
| + dir, err := filepath.Abs(o.Dir) |
| + if err != nil { |
| + return failf("%v", err) |
| + } |
| + if !strings.HasPrefix(file, dir+string(filepath.Separator)) { |
| + return failf("%s is not under the run directory %s", file, dir) |
| + } |
| + if strings.ContainsAny(file, " \t\n\"'\\$") { |
| + return failf("the continuation's path has characters a systemd command line could misread") |
| + } |
| + st, err := os.Stat(file) |
| + if err != nil || !st.Mode().IsRegular() { |
| + return failf("%s is not a file (%v)", file, err) |
| + } |
| + if st.Mode().Perm()&0o022 != 0 { |
| + return failf("%s is writable by group or others", file) |
| + } |
| + sum, err := fileHash(file) |
| + if err != nil { |
| + return failf("%v", err) |
| + } |
| + if err := o.jw("CONTINUATION", "armed path=%s sha256=%s max=%s", file, sum, *maxD); err != nil { |
| + return err |
| + } |
| + o.out("continuation armed: %s (sha256 %s), at most %s, after any safe stop but a guard failure", file, sum, *maxD) |
| + return nil |
| +} |
| + |
| +func cmdContinuationDisarm(o *Ops, args []string) error { |
| + if len(args) != 0 { |
| + return usagef("continuation disarm") |
| + } |
| + l, err := o.ledger() |
| + if err != nil { |
| + return err |
| + } |
| + if !continuationOf(l).armed { |
| + return failf("no continuation is armed") |
| + } |
| + o.out("continuation disarmed") |
| + return o.jw("CONTINUATION", "disarmed") |
| +} |
| + |
| +// continueTeardown is the recovery unit's last step, after its safe stop. |
| +// credsOK is whether the safe stop's own credential check passed. |
| +func (o *Ops) continueTeardown(credsOK bool) { |
| + l, err := o.ledger() |
| + if err != nil { |
| + return |
| + } |
| + c := continuationOf(l) |
| + notRun := func(why string) { _ = o.jw("CONTINUATION", "not run: %s", why); o.out("continuation not run: %s", why) } |
| + switch { |
| + case !c.armed: |
| + return |
| + case c.started: |
| + notRun("already started once (" + o.unitName(ContinuationBlock) + ")") |
| + return |
| + case !credsOK: |
| + notRun("the safe stop's credential check failed (a guard failure)") |
| + return |
| + } |
| + for _, e := range l.Entries { |
| + if e.Line > c.armLine && e.Verb == "ABORT" && strings.HasPrefix(e.Text, "guard:") { |
| + notRun("a guard failure was journalled since the arm (line " + itoa(e.Line) + ")") |
| + return |
| + } |
| + } |
| + if sum, err := fileHash(c.path); err != nil || sum != c.sum { |
| + notRun("the file " + c.path + " no longer has sha256 " + c.sum + " (" + sum + ", " + errText(err) + ")") |
| + return |
| + } |
| + if err := o.startUnitBounded(ContinuationBlock, []string{"/bin/bash", c.path}, ContinuationStopTimeout, c.max, false); err != nil { |
| + notRun("its unit did not start: " + err.Error()) |
| + return |
| + } |
| + _ = o.jw("CONTINUATION", "started unit=%s max=%s stop-timeout=%s", o.unitName(ContinuationBlock), c.max, ContinuationStopTimeout) |
| + o.out("continuation started: %s runs %s, at most %s", o.unitName(ContinuationBlock), c.path, c.max) |
| +} |
| + |
| +func errText(err error) string { |
| + if err == nil { |
| + return "read" |
| + } |
| + return err.Error() |
| +} |
diff --git a/internal/hostedops/fake_test.go b/internal/hostedops/fake_test.go| index edca84cc..8685c59c 100644 |
| --- a/internal/hostedops/fake_test.go |
| +++ b/internal/hostedops/fake_test.go |
| @@ -372,6 +372,7 @@ type fakeSystemd struct { |
| argv map[string][]string |
| status map[string]string // unit -> its status file |
| timeouts map[string]time.Duration |
| + runtimes map[string]time.Duration // RuntimeMaxSec per unit |
| run func(unit string, argv []string) (int, bool) |
| override func(unit string) (string, bool) // a forced State answer |
| } |
| @@ -395,7 +396,7 @@ func unitEnv(argv []string, invocation string) (env, prog []string) { |
| return env, argv[i:] |
| } |
| -func (s *fakeSystemd) Start(unit, wd, out, status, ep string, stopTimeout time.Duration, argv []string) error { |
| +func (s *fakeSystemd) Start(unit, wd, out, status, ep string, stopTimeout, runtimeMax time.Duration, argv []string) error { |
| s.mu.Lock() |
| run := s.run |
| defer func() { |
| @@ -419,6 +420,10 @@ func (s *fakeSystemd) Start(unit, wd, out, status, ep string, stopTimeout time.D |
| s.timeouts = map[string]time.Duration{} |
| } |
| s.timeouts[unit] = stopTimeout |
| + if s.runtimes == nil { |
| + s.runtimes = map[string]time.Duration{} |
| + } |
| + s.runtimes[unit] = runtimeMax |
| s.states[unit] = "running" |
| if s.argv == nil { |
| s.argv, s.status = map[string][]string{}, map[string]string{} |
diff --git a/internal/hostedops/kit34r2_test.go b/internal/hostedops/kit34r2_test.go| new file mode 100644 |
| index 00000000..3b46b3cb |
| --- /dev/null |
| +++ b/internal/hostedops/kit34r2_test.go |
| @@ -0,0 +1,224 @@ |
| +package hostedops |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The run kit's changes for the dev drill plan's review round 2 |
| +// (p34-r2.md), the coordinator's rulings K9 to K11 (kit-p34-r2-brief.md). |
| + |
| +const teardownUnit = "hprod-r1-teardown.service" |
| + |
| +// contRig is a run with a teardown script written under its directory. |
| +func contRig(t *testing.T, lines ...string) (*rig, string) { |
| + r := newRig(t, append([]string{"REC microvm-image " + image1}, lines...)...) |
| + os.MkdirAll(filepath.Join(r.dir, "blocks"), 0o700) |
| + f := filepath.Join(r.dir, "blocks", "teardown.sh") |
| + os.WriteFile(f, []byte("set -euo pipefail\nops unit stop --all\n"), 0o600) |
| + return r, f |
| +} |
| + |
| +func (r *rig) started(unit string) int { |
| + n := 0 |
| + for _, u := range r.systemd.started { |
| + if u == unit { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// K9: an armed continuation runs, unattended, as its own journalled unit |
| +// once a safe stop has finished, with the bound it was armed with. |
| +func TestContinuationRunsAfterSafeStop(t *testing.T) { |
| + r, f := contRig(t) |
| + r.want(0, "continuation", "arm", f, "--max", "9h") |
| + if !r.has("CONTINUATION", "armed path="+f) || !r.has("CONTINUATION", "max=9h0m0s") { |
| + t.Fatalf("not armed:\n%s", journalText(r)) |
| + } |
| + r.ops("safe-stop") |
| + if r.started(teardownUnit) != 1 || !r.has("UNIT", teardownUnit) || !r.has("CONTINUATION", "started unit="+teardownUnit) { |
| + t.Fatalf("the continuation did not start: started %v\n%s", r.systemd.started, journalText(r)) |
| + } |
| + argv := r.systemd.argv[teardownUnit] |
| + if !slices.Equal(argv[len(argv)-2:], []string{"/bin/bash", f}) { |
| + t.Fatalf("the continuation runs %v", argv) |
| + } |
| + if r.systemd.runtimes[teardownUnit] != 9*time.Hour || r.systemd.timeouts[teardownUnit] != ContinuationStopTimeout { |
| + t.Fatalf("bounds: runtime %v, stop timeout %v", r.systemd.runtimes[teardownUnit], r.systemd.timeouts[teardownUnit]) |
| + } |
| + if i, j := slices.Index(r.systemd.started, "hprod-r1-recovery.service"), slices.Index(r.systemd.started, teardownUnit); i < 0 || j < i || !r.has("SAFE-STOP", "end") { |
| + t.Fatalf("the continuation did not follow the safe stop: %v\n%s", r.systemd.started, journalText(r)) |
| + } |
| + |
| + // A second recovery spares the running teardown and starts no second one. |
| + r.ops("safe-stop") |
| + if r.started(teardownUnit) != 1 || slices.Contains(r.systemd.stopped, teardownUnit) { |
| + t.Fatalf("second recovery: started %v, stopped %v", r.systemd.started, r.systemd.stopped) |
| + } |
| + if !r.has("CONTINUATION", "not run: already started once") { |
| + t.Fatalf("the second recovery did not say why:\n%s", journalText(r)) |
| + } |
| + // Inside the continuation, a block's unit may start: the continuation is not "busy". |
| + r.deps.SelfUnit = func() string { return teardownUnit } |
| + r.want(0, "unit", "start", "8.2", "--", "bash", "x") |
| +} |
| + |
| +// K9: no continuation after a guard failure (journalled after the arm, or |
| +// the recovery's own credentials refused), a tampered file, or a disarm. |
| +func TestContinuationRefusals(t *testing.T) { |
| + for name, setup := range map[string]func(r *rig, f string){ |
| + "guard failure journalled": func(r *rig, f string) { r.journal("ABORT guard: the caller is arn:aws:iam::149757027610:user/other") }, |
| + "recovery's guard refused": func(r *rig, f string) { r.opener.refuse = stopf("the credentials are in account 640012953448") }, |
| + "recovery's credentials expired": func(r *rig, f string) { |
| + r.opener.refuse = errors.New("the exported credentials expire at 2026-12-01T10:01:00Z, too soon to start") |
| + }, |
| + "tampered": func(r *rig, f string) { os.WriteFile(f, []byte("aws s3 rb --force s3://anything\n"), 0o600) }, |
| + "removed": func(r *rig, f string) { os.Remove(f) }, |
| + "disarmed": func(r *rig, f string) { r.want(0, "continuation", "disarm") }, |
| + } { |
| + r, f := contRig(t) |
| + r.want(0, "continuation", "arm", f, "--max", "9h") |
| + setup(r, f) |
| + r.ops("safe-stop") |
| + if r.started(teardownUnit) != 0 { |
| + t.Errorf("%s: the continuation started", name) |
| + } |
| + if name != "disarmed" && !r.has("CONTINUATION", "not run") { |
| + t.Errorf("%s: no journalled reason:\n%s", name, journalText(r)) |
| + } |
| + } |
| + // A guard failure before the arm is the operator's business, not this one's. |
| + r, f := contRig(t, "ABORT guard: an old refusal") |
| + r.want(0, "continuation", "arm", f, "--max", "9h") |
| + r.ops("safe-stop") |
| + if r.started(teardownUnit) != 1 { |
| + t.Fatalf("a guard failure before the arm held the continuation back:\n%s", journalText(r)) |
| + } |
| +} |
| + |
| +// K9: arm refuses what it cannot run safely. |
| +func TestContinuationArmChecks(t *testing.T) { |
| + r, f := contRig(t) |
| + outside := filepath.Join(t.TempDir(), "teardown.sh") |
| + os.WriteFile(outside, []byte("true\n"), 0o600) |
| + r.want(ExitFail, "continuation", "arm", outside, "--max", "9h") |
| + r.want(ExitFail, "continuation", "arm", filepath.Join(r.dir, "blocks", "none.sh"), "--max", "9h") |
| + os.Chmod(f, 0o666) |
| + r.want(ExitFail, "continuation", "arm", f, "--max", "9h") |
| + os.Chmod(f, 0o600) |
| + r.want(ExitFail, "continuation", "arm", f) |
| + r.want(ExitFail, "continuation", "arm", f, "--max", "25h") |
| + r.want(ExitFail, "continuation", "disarm") // nothing armed |
| + r.want(0, "continuation", "arm", f, "--max", "9h") |
| + r.ops("safe-stop") |
| + r.want(ExitFail, "continuation", "arm", f, "--max", "9h") // one continuation per run |
| +} |
| + |
| +// K10: settle --step --ended-at takes the step's end from the caller, and |
| +// the bound counts from it; a time in the future, or before the step could |
| +// have started, is refused. |
| +func TestSettleStepEndedAt(t *testing.T) { |
| + r := settleRig(t, nil) |
| + r.clock.Sleep(context.Background(), 5*time.Minute) |
| + ended := t0.Add(2 * time.Minute) |
| + r.want(0, "vms", "settle", "--step", "s1", "--image", image1, "--ended-at", ended.Format(time.RFC3339), "--max", "10m") |
| + if !r.has("STEP-END", "s1 image="+image1+" at="+itoa(int(ended.Unix()))) || !r.has("STEP-END", "given=yes") { |
| + t.Fatalf("STEP-END does not carry the given end:\n%s", journalText(r)) |
| + } |
| + // The bound counts from the given end: live throughout, it stops ~1 min after invocation. |
| + r = settleRig(t, []string{"microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x"}) |
| + r.clock.Sleep(context.Background(), 9*time.Minute) |
| + start := r.clock.Now() |
| + r.want(ExitStop, "vms", "settle", "--step", "s2", "--image", image1, "--ended-at", t0.Format(time.RFC3339), "--max", "10m") |
| + if d := r.clock.Now().Sub(start); d > time.Minute+ScanGap { |
| + t.Fatalf("the bound did not count from the given end: settled for %v", d) |
| + } |
| + // Refused: in the future; before the image was recorded; before the |
| + // previous step settled; not RFC 3339; without --step; another end on a re-run. |
| + r = settleRig(t, nil) |
| + for _, at := range []string{t0.Add(time.Minute).Format(time.RFC3339), t0.Add(-time.Hour).Format(time.RFC3339), "yesterday"} { |
| + r.want(ExitFail, "vms", "settle", "--step", "s3", "--image", image1, "--ended-at", at, "--max", "10m") |
| + } |
| + r.want(ExitFail, "vms", "settle", "--image", image1, "--ended-at", t0.Format(time.RFC3339), "--max", "10m") |
| + r.want(0, "vms", "settle", "--step", "s4", "--image", image1, "--max", "10m") |
| + r.clock.Sleep(context.Background(), 5*time.Minute) |
| + r.want(ExitFail, "vms", "settle", "--step", "s5", "--image", image1, "--ended-at", t0.Format(time.RFC3339), "--max", "10m") |
| + r = settleRig(t, []string{"microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x", "microvm-x"}) |
| + r.clock.Sleep(context.Background(), time.Minute) |
| + r.want(ExitStop, "vms", "settle", "--step", "s6", "--image", image1, "--ended-at", t0.Format(time.RFC3339), "--max", "2m") |
| + r.want(ExitFail, "vms", "settle", "--step", "s6", "--image", image1, "--ended-at", t0.Add(30*time.Second).Format(time.RFC3339), "--max", "2m") |
| +} |
| + |
| +// K11: bucket empty and delete are resumable: a recorded bucket a direct |
| +// read shows gone is success, journalled; ownership still stops. |
| +func TestBucketTeardownResumable(t *testing.T) { |
| + const name = "equipo-hosted-config-" + ProdAccount |
| + arn := "arn:aws:s3:::" + name |
| + tfRec := "REC tf config/module.config.aws_s3_bucket.config id=" + name + " type=aws_s3_bucket source=state rname=" + name |
| + for label, lines := range map[string][]string{ |
| + "ops-recorded": {"INTENT s3-bucket " + name, "OWNER " + name + " " + ProdAccount, "REC s3-bucket " + arn + " name=" + name}, |
| + "tf-recorded": {"INTENT tf config/module.config.aws_s3_bucket.config - type=aws_s3_bucket name=" + name, tfRec}, |
| + } { |
| + for _, verb := range []string{"empty", "delete"} { |
| + r := newRig(t, lines...) |
| + r.cloud.headBucket = func(string) error { return ErrNotFound } |
| + r.want(0, "bucket", verb, "--name", name, "--expected-owner", ProdAccount) |
| + if r.cloud.count("ListVersions")+r.cloud.count("DeleteBucket") != 0 || !r.has("DELETED", "read-gone") { |
| + t.Errorf("%s %s of a bucket already gone: calls %v\n%s", label, verb, r.cloud.log(), journalText(r)) |
| + } |
| + if st := bucketState(r.ledger(), name); st != StateAbsent { |
| + t.Errorf("%s %s: the bucket's state is %s, want absent", label, verb, st) |
| + } |
| + r.want(0, "bucket", verb, "--name", name, "--expected-owner", ProdAccount) // and again |
| + } |
| + } |
| + // Another owner is still a stop; a read that fails is 1; a bucket there is emptied. |
| + lines := []string{"INTENT s3-bucket " + name, "OWNER " + name + " " + ProdAccount, "REC s3-bucket " + arn + " name=" + name} |
| + r := newRig(t, lines...) |
| + r.cloud.headBucket = func(string) error { return stopf("bucket %s is owned by another account", name) } |
| + r.want(ExitStop, "bucket", "empty", "--name", name, "--expected-owner", ProdAccount) |
| + r = newRig(t, lines...) |
| + r.cloud.headBucket = func(string) error { return errors.New("SlowDown") } |
| + r.want(ExitFail, "bucket", "empty", "--name", name, "--expected-owner", ProdAccount) |
| + if r.has("DELETED", "") { |
| + t.Fatal("an unreadable bucket was recorded deleted") |
| + } |
| + r = newRig(t, lines...) |
| + r.want(0, "bucket", "empty", "--name", name, "--expected-owner", ProdAccount) |
| + if r.cloud.count("ListVersions") == 0 || r.has("DELETED", "") { |
| + t.Fatal("a bucket that is there was not emptied, or was recorded deleted") |
| + } |
| + r.want(ExitStop, "bucket", "empty", "--name", name, "--expected-owner", "640012953448") |
| +} |
| + |
| +// The new forms through the plan-parse machinery. |
| +func TestRound2InvocationsParse(t *testing.T) { |
| + plan := "```sh\n" + strings.Join([]string{ |
| + `ops continuation arm "$P/blocks/teardown.sh" --max 10h`, |
| + `ops continuation disarm`, |
| + `ops vms settle --step hosted-pass --image arn:aws:lambda:eu-west-1:149757027610:microvm-image:equipo-hosted-prod-r1 --ended-at 2026-12-01T09:59:00Z --max 10m`, |
| + }, "\n") + "\n```\nProse: `ops continuation arm`, `ops continuation`.\n" |
| + invs := planInvocations(plan) |
| + if len(invs) != 5 { |
| + t.Fatalf("%d invocations: %q", len(invs), invs) |
| + } |
| + for _, inv := range invs { |
| + r := newRig(t, "REC microvm-image "+image1) |
| + r.ops(inv...) |
| + out := r.out.String() |
| + if strings.Contains(out, "unknown command") || !bare(inv) && strings.Contains(out, "usage:") { |
| + t.Errorf("ops %s: %s", strings.Join(inv, " "), out) |
| + } |
| + } |
| + if u := usageText(); !strings.Contains(u, "continuation arm FILE --max D") || !strings.Contains(u, "--ended-at RFC3339") { |
| + t.Fatalf("the usage does not name the new forms:\n%s", u) |
| + } |
| +} |
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go| index 617662e8..2cc3831c 100644 |
| --- a/internal/hostedops/ops.go |
| +++ b/internal/hostedops/ops.go |
| @@ -160,6 +160,8 @@ type Ops struct { |
| j *Journal |
| cloud Cloud |
| ctx context.Context |
| + // stopCredsOK: the safe stop's own credential check passed (K9). |
| + stopCredsOK bool |
| } |
| var ( |
| @@ -250,6 +252,7 @@ func (o *Ops) open() (Cloud, error) { |
| } |
| for _, e := range l.Entries { |
| if e.Verb == "GUARD" && (e.Attr("account") != o.Account || e.Attr("region") != o.Region) { |
| + _ = o.jw("ABORT", "guard: this run was opened for account %s in %s; refusing %s in %s", e.Attr("account"), e.Attr("region"), o.Account, o.Region) |
| return nil, stopf("this run was opened for account %s in %s; refusing %s in %s", e.Attr("account"), e.Attr("region"), o.Account, o.Region) |
| } |
| } |
| @@ -263,6 +266,7 @@ func (o *Ops) open() (Cloud, error) { |
| } |
| id := c.Identity() |
| if id.Account != o.Account || id.Region != o.Region { // the opener's own answer, checked again here |
| + _ = o.jw("ABORT", "guard: the opener returned account %s in %s, not %s in %s", id.Account, id.Region, o.Account, o.Region) |
| return nil, stopf("the opener returned account %s in %s, not %s in %s", id.Account, id.Region, o.Account, o.Region) |
| } |
| if bound != "" && id.ARN != bound { |
| @@ -300,7 +304,7 @@ func init() { |
| "ledger show": {false, cmdLedgerShow, ""}, |
| "object put": {true, cmdObjectPut, "--bucket B --key K --file F [--expected-owner A]"}, |
| "vms scan": {true, cmdVMsScan, "--image ARN [--max D] [controller flags]: 99 on a live VM neither the controller's nor a recorded launch"}, |
| - "vms settle": {true, cmdVMsSettle, "--image ARN [--terminate | --step ID] --max D"}, |
| + "vms settle": {true, cmdVMsSettle, "--image ARN [--terminate | --step ID [--ended-at RFC3339]] --max D"}, |
| "vms reconcile": {true, cmdVMsReconcile, ""}, |
| "vms adopt": {false, cmdVMsAdopt, "[controller flags]"}, |
| "tfvars": {false, cmdTfvars, "--out F ... | --add-image FILE --add-connector"}, |
| @@ -313,6 +317,8 @@ func init() { |
| "block": {false, cmdBlock, "ID [--stop USD | --teardown] [--optional] -- CMD..."}, |
| "unit start": {false, cmdUnitStart, "BLOCK[.retry1|.retry2] -- CMD..."}, |
| "unit wait": {false, cmdUnitWait, "BLOCK --max D"}, |
| + "continuation arm": {false, cmdContinuationArm, "FILE --max D: after any safe stop but a guard failure, the recovery unit runs FILE (sha256 checked) as h<env>-<RUN>-teardown"}, |
| + "continuation disarm": {false, cmdContinuationDisarm, ""}, |
| "unit status": {false, cmdUnitStatus, "BLOCK: the unit's state and result as JSON; never stops or recovers"}, |
| "finding": {false, cmdFinding, "TEXT...: journal a FINDING line"}, |
| "unit stop": {false, cmdUnitStop, "BLOCK | --all"}, |
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go| index 50d0da74..d29543d2 100644 |
| --- a/internal/hostedops/stop.go |
| +++ b/internal/hostedops/stop.go |
| @@ -139,6 +139,9 @@ const SafeStopBound = 30 * time.Minute |
| // RecoveryBlock names the one recovery unit, h<env>-<RUN>-recovery. |
| const RecoveryBlock = "recovery" |
| +// ContinuationStopTimeout is the continuation unit's TimeoutStopSec. |
| +const ContinuationStopTimeout = 5 * time.Minute |
| + |
| // cmdSafeStop asks for recovery (N1): one dedicated unit runs section S's |
| // steps, outside every block and watchdog unit, and every requester (an |
| // operator, a failed block, a watchdog) waits for it. --recovery is that |
| @@ -189,7 +192,7 @@ func (o *Ops) requestRecovery() error { |
| st, _ := os.ReadFile(o.path("units", RecoveryBlock+".status")) |
| status := strings.TrimSpace(string(st)) |
| if status == "0" { |
| - o.out("recovery done; the run waits for Paul") |
| + o.out("recovery done; the run waits for Paul, or for the armed continuation") |
| return nil |
| } |
| return stopf("recovery ended with status %s; waiting for Paul", status) |
| @@ -217,7 +220,9 @@ func (o *Ops) recover() error { |
| return o.jw("RECOVERY", "already owned; standing aside") |
| } |
| defer release() |
| - return o.safeStop() |
| + err = o.safeStop() |
| + o.continueTeardown(o.stopCredsOK) |
| + return err |
| } |
| // safeStop is section S. It never checks spend. Local steps first (S.0, |
| @@ -248,6 +253,7 @@ func (o *Ops) safeStop() error { |
| cloudOK = false |
| note("credentials", err) |
| } |
| + o.stopCredsOK = cloudOK |
| if cloudOK { |
| fenceErr := o.fence() |
| note("S.2 fence", fenceErr) |
diff --git a/internal/hostedops/units.go b/internal/hostedops/units.go| index 8a055dd4..460eafae 100644 |
| --- a/internal/hostedops/units.go |
| +++ b/internal/hostedops/units.go |
| @@ -27,8 +27,9 @@ import ( |
| // Systemd is the user manager. |
| type Systemd interface { |
| // Start runs argv as unit, output appended to out, its exit status |
| - // written to status by exitpost (ExecStopPost). |
| - Start(unit, workdir, out, status, exitpost string, stopTimeout time.Duration, argv []string) error |
| + // written to status by exitpost (ExecStopPost). A runtimeMax above |
| + // zero is the unit's RuntimeMaxSec: systemd stops it then. |
| + Start(unit, workdir, out, status, exitpost string, stopTimeout, runtimeMax time.Duration, argv []string) error |
| // State is running, done or unresolved (R44's unit_state). |
| State(unit string) string |
| // Stop stops unit (TERM, KILL after 45 s) and waits for done. |
| @@ -67,7 +68,7 @@ func (o *Ops) unitName(block string) string { return o.unitPrefix() + block + ". |
| func (o *Ops) busy(l *Ledger, except string) []string { |
| var b []string |
| for _, u := range l.Units { |
| - if u == except || strings.HasPrefix(u, o.unitPrefix()+"wait-") || u == o.unitName("probe") { |
| + if u == except || strings.HasPrefix(u, o.unitPrefix()+"wait-") || u == o.unitName("probe") || u == o.unitName(ContinuationBlock) { |
| continue |
| } |
| if s := o.Systemd.State(u); s != "done" { |
| @@ -197,6 +198,11 @@ func cmdUnitStatus(o *Ops, args []string) error { |
| // unit for block, under /usr/bin/env -i with the allowlist and the unit's |
| // own name (EQUIPO_HOSTED_OPS_UNIT, so a safe-stop inside it can spare it). |
| func (o *Ops) startUnit(block string, argv []string, stopTimeout time.Duration, again bool) error { |
| + return o.startUnitBounded(block, argv, stopTimeout, 0, again) |
| +} |
| + |
| +// startUnitBounded is startUnit with a runtime bound (RuntimeMaxSec; 0 none). |
| +func (o *Ops) startUnitBounded(block string, argv []string, stopTimeout, runtimeMax time.Duration, again bool) error { |
| if strings.ContainsAny(o.Dir, " \t\n\"'\\$") { |
| return failf("the run directory has characters a systemd command line could misread") |
| } |
| @@ -234,7 +240,7 @@ func (o *Ops) startUnit(block string, argv []string, stopTimeout time.Duration, |
| if err := writeFileAtomic(o.path("units", block+".start"), []byte(strconv.FormatInt(o.Clock.Now().Unix(), 10)+"\n"), 0o600); err != nil { |
| return failf("%v", err) |
| } |
| - if err := o.Systemd.Start(u, o.Dir, o.path("units", block+".out"), o.path("units", block+".status"), ep, stopTimeout, full); err != nil { |
| + if err := o.Systemd.Start(u, o.Dir, o.path("units", block+".out"), o.path("units", block+".status"), ep, stopTimeout, runtimeMax, full); err != nil { |
| return failf("systemd-run could not start %s: %v", u, err) |
| } |
| return nil |
| @@ -333,7 +339,7 @@ func (o *Ops) stopUnits(only string) error { |
| if only != "" && u != only { |
| continue |
| } |
| - if u == own || (only == "" && u == o.unitName(RecoveryBlock)) { // never the recovery unit, nor this process's own (N1) |
| + if u == own || (only == "" && (u == o.unitName(RecoveryBlock) || u == o.unitName(ContinuationBlock))) { // never the recovery unit or the continuation (K9), nor this process's own (N1) |
| if err := o.jw("UNIT-SPARED", "%s: this process runs in it", u); err != nil { |
| return err |
| } |
| @@ -393,13 +399,17 @@ func sc(args ...string) (string, error) { |
| return out.String(), err |
| } |
| -func (realSystemd) Start(unit, workdir, out, status, exitpost string, stopTimeout time.Duration, argv []string) error { |
| +func (realSystemd) Start(unit, workdir, out, status, exitpost string, stopTimeout, runtimeMax time.Duration, argv []string) error { |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| args := []string{"--user", "--quiet", "--collect", "--expand-environment=no", "--unit=" + unit, |
| "-p", "KillMode=control-group", "-p", fmt.Sprintf("TimeoutStopSec=%d", int(stopTimeout.Seconds())), "-p", "WorkingDirectory=" + workdir, |
| "-p", "StandardInput=null", "-p", "StandardOutput=append:" + out, "-p", "StandardError=append:" + out, |
| - "-p", "ExecStopPost=" + exitpost + " " + status, "--"} |
| + "-p", "ExecStopPost=" + exitpost + " " + status} |
| + if runtimeMax > 0 { |
| + args = append(args, "-p", fmt.Sprintf("RuntimeMaxSec=%d", int(runtimeMax.Seconds()))) |
| + } |
| + args = append(args, "--") |
| cmd := exec.CommandContext(ctx, "systemd-run", append(args, argv...)...) |
| var e bytes.Buffer |
| cmd.Stderr = &e |
diff --git a/internal/hostedops/vms.go b/internal/hostedops/vms.go| index e9636a1c..f5def743 100644 |
| --- a/internal/hostedops/vms.go |
| +++ b/internal/hostedops/vms.go |
| @@ -341,9 +341,15 @@ func cmdVMsSettle(o *Ops, args []string) error { |
| image := imageFlag(fs) |
| terminate := fs.Bool("terminate", false, "terminate every target and live VM first") |
| step := fs.String("step", "", "prove the VMs of this plan step ended, within --max of the step's end") |
| + endedAt := fs.String("ended-at", "", "with --step: when the step ended (RFC 3339), not now") |
| maxD := fs.Duration("max", defaultSettle, "the bound") |
| - if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || (*step != "" && (*terminate || !blockPattern.MatchString(*step))) { |
| - return usagef("vms settle --image ARN [--terminate | --step ID] --max D") |
| + var ended time.Time |
| + pos, err := parseFlags(fs, args) |
| + if err == nil && *endedAt != "" { |
| + ended, err = time.Parse(time.RFC3339, *endedAt) |
| + } |
| + if err != nil || len(pos) != 0 || (*step != "" && (*terminate || !blockPattern.MatchString(*step))) || (*endedAt != "" && *step == "") { |
| + return usagef("vms settle --image ARN [--terminate | --step ID [--ended-at RFC3339]] --max D") |
| } |
| if *maxD <= 0 || *maxD > MaxSettle { |
| return failf("--max must be positive and at most %s", MaxSettle) |
| @@ -356,7 +362,7 @@ func cmdVMsSettle(o *Ops, args []string) error { |
| return err |
| } |
| if *step != "" { |
| - return o.settleStep(l, *step, *image, *maxD) |
| + return o.settleStep(l, *step, *image, *maxD, ended) |
| } |
| return o.settleImage(*image, *terminate, *maxD) |
| } |
| @@ -371,28 +377,55 @@ func cmdVMsSettle(o *Ops, args []string) error { |
| // Proved: STEP-SETTLED STEP image= vms= ended= after=. Not proved by the |
| // bound: 99, hard stop 3 (a VM live 10 minutes after its step ended). A |
| // step already settled is refused (1). |
| -func (o *Ops) settleStep(l *Ledger, step, image string, maxD time.Duration) error { |
| +// |
| +// given (--ended-at; K10, p34-r2 finding 4) is the step's real end when the |
| +// caller learned it late (the suite reports after collecting evidence): it |
| +// becomes the STEP-END and the bound counts from it. It is refused (1) when |
| +// it is in the future, or before the step could have started: before the |
| +// image was recorded, or before the image's last STEP-SETTLED. A re-run |
| +// keeps the first STEP-END; another end then is refused. |
| +func (o *Ops) settleStep(l *Ledger, step, image string, maxD time.Duration, given time.Time) error { |
| var ended time.Time |
| - var since int // the line after the image's last STEP-SETTLED |
| + var since int // the line after the image's last STEP-SETTLED |
| + var earliest time.Time // the step cannot have started before this |
| for _, e := range l.Entries { |
| switch { |
| + case e.Verb == "REC" && e.Field(0) == "microvm-image" && e.Field(1) == image && earliest.IsZero(): |
| + earliest = e.At |
| case e.Verb == "STEP-SETTLED" && e.Attr("image") == image: |
| if e.Field(0) == step { |
| return failf("step %s was already settled", step) |
| } |
| - since = e.Line |
| + since, earliest = e.Line, e.At |
| case e.Verb == "STEP-END" && e.Field(0) == step && ended.IsZero(): |
| if sec, err := strconv.ParseInt(e.Attr("at"), 10, 64); err == nil { |
| ended = time.Unix(sec, 0) |
| } |
| } |
| } |
| + switch { |
| + case !given.IsZero() && !ended.IsZero() && !given.Equal(ended): |
| + return failf("step %s already ended at %s; --ended-at %s is another end", step, ended.UTC().Format(time.RFC3339), given.UTC().Format(time.RFC3339)) |
| + case !given.IsZero() && given.After(o.Clock.Now()): |
| + return failf("--ended-at %s is in the future", given.UTC().Format(time.RFC3339)) |
| + case !given.IsZero() && given.Before(earliest.Truncate(time.Second)): |
| + return failf("--ended-at %s is before step %s could have started (%s)", given.UTC().Format(time.RFC3339), step, earliest.UTC().Format(time.RFC3339)) |
| + } |
| if ended.IsZero() { |
| - ended = o.Clock.Now() |
| - if err := o.jw("STEP-END", "%s image=%s at=%d max=%s", step, image, ended.Unix(), maxD); err != nil { |
| + ended, how := o.Clock.Now(), "" |
| + if !given.IsZero() { |
| + ended, how = given, " given=yes" |
| + } |
| + if err := o.jw("STEP-END", "%s image=%s at=%d max=%s%s", step, image, ended.Unix(), maxD, how); err != nil { |
| return err |
| } |
| + return o.settleStepFrom(l, step, image, maxD, ended, since) |
| } |
| + return o.settleStepFrom(l, step, image, maxD, ended, since) |
| +} |
| + |
| +// settleStepFrom proves the step's VMs ended within maxD of ended. |
| +func (o *Ops) settleStepFrom(l *Ledger, step, image string, maxD time.Duration, ended time.Time, since int) error { |
| var vms []string |
| for _, e := range l.Entries { |
| if e.Verb == "VM" && e.Line > since && (e.Attr("image") == "" || e.Attr("image") == image) && !slices.Contains(vms, e.Field(0)) { |