oficina / equipo Public

hosted: a block deadline refuses (99) and stops nothing

Coordinator ruling 2026-12-03, after Astra's p34-r5 findings 20 to 22:
past --max a block journals DEADLINE, exits 99, and stops, unlocks and
reconciles nothing and asks for no recovery; the command runs on in its
unit. Removed the process-group stopper and its proof, the inherited
deadline, the stale-lock force-unlock, the post-deadline reconcile and
the TF-START lines, with their tests and fake knobs. tf.go is back to
its text before K12. unit start --max and reboot --not-after stay.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d77b505d8b0e31ccd9ab3b1bf221621ab779f23f parent 793514b
14 files changed, +192 −898
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +36 −0
  • infra/hosted/README.md +7 −12
  • internal/hostedops/fake_test.go +0 −8
  • internal/hostedops/kit34cut_test.go +92 −0
  • internal/hostedops/kit34r3_test.go +0 −89
  • internal/hostedops/kit34r4_test.go +0 −273
  • internal/hostedops/kit34r5_test.go +0 −75
  • internal/hostedops/ops.go +2 −11
  • internal/hostedops/ops_test.go +0 −13
  • internal/hostedops/proc_other.go +0 −36
  • internal/hostedops/proc_unix.go +0 −75
  • internal/hostedops/stop.go +51 −213
  • internal/hostedops/tf.go +3 −92

CI failed — run details

CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/hosted-runners-2: Type  Size Avail | ext4   96G   84G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type  Size Avail | ext4   96G   84G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: image pulled in 9.8s
ci-box: claude: fetched and verified in 9.9s
ci-box: codex: fetched and verified in 3.4s
ci-box: codex-code-mode-host: fetched and verified in 1.3s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
ci-box: tofu: fetched and verified in 1.5s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: pi: installed and verified in 7.2s
ci-box: opencode: installed and verified in 2.2s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.6s
ci-box: clone deepened in 5.4s
ci-box: file times set from content: 4065 files, 303 directories
ci-box: ready in 25.2s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
--- FAIL: TestReleaseCopyReviewed (0.09s)
    task_pages_test.go:236: COPY REVIEW REQUIRED: copy-status.py verify found copy pending review or stale bookkeeping
FAIL
rastrillo-budget/v1 ran 89ms
FAIL	amadan.net/oficina/equipo/internal/equipotest	0.241s
FAIL
make: *** [Makefile:324: copy-release-check] Error 1

amadan: step copy failed: exit status 2

amadan: job failed at step copy — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 34eba813..2b5d6a39 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 8362 - 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); after cap K12 and K13 (block deadlines with process groups, reboot --not-after); scoped review K14 to K17 (synchronous group stop, own stale lock release, safety kept, touched roots; own locks released after a killed plan); measured 8362.
+size internal/hostedops 7991 - 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); after cap K12 and K13 (block deadlines with process groups, reboot --not-after); scoped review K14 to K17 (synchronous group stop, own stale lock release, safety kept, touched roots; own locks released after a killed plan), then cut: a block deadline only refuses (99), K14 to K17 removed; measured 7991.
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index e7b09e4d..14d1536f 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -4104,3 +4104,39 @@ Green: the three plan-parse tests, `make budget`, `bash -n` on all 32 `sh` block
`run.env`. Stub run: teardown in order (eight blocks, 8.7 at 195m); 8.1 past its deadline, a
FINDING, then 8.2 on; 8.3a past it twice, `escalate`, exit 99; 8.4.1 past it, `escalate` with no
retry, exit 99; verify-gone's tag index unreadable, a FINDING, then the stop, exit 99.
+
+### Task 34 kit, cut: a block deadline refuses (coordinator ruling 2026-12-03, after Astra p34-r5)
+
+No AWS call. Tests kill only the PID their command recorded.
+
+`ops block ID [--teardown] --max D`: past D the block journals `DEADLINE block=ID max=D: refused;
+nothing stopped; waiting for Paul` and exits 99. It stops nothing (the command runs on in its unit;
+the unit's runtime cap is systemd's backstop), unlocks nothing, reconciles nothing and requests no
+recovery. Before D the command's own exit decides, as without `--max` (0 is 0, 99 is 99 with
+recovery, an `--optional` block's 1 is 1). `unit start --max` and `controller reboot --not-after`
+stay.
+
+Removed, with their tests and fake knobs: the process-group runner and its group-gone proof
+(`proc_unix.go`, `proc_other.go`: `runGroup`, `groupEnd`, `signalGroup`, `termCmd`), the inherited
+deadline (`EQUIPO_HOSTED_OPS_DEADLINE` in `Main`), `BlockKillGrace`, `GroupKillWait`,
+`TofuStopGrace`, `DeadlineReconcile`, `Deps.groupGrace/groupKillWait`; the post-deadline reconcile
+(`blockDeadline`, `yesNo`, `touchedRoots`, `reconcileAfterKill`); the lock handling
+(`releaseOwnLock`, `forceUnlockOwn`, `LockInfo`, `LockError`, `parseLock`, `lockWho`, `tofuError`,
+tofu's stderr capture); the `TF-START` lines. `tf.go` is again byte-identical to before K12 (tofu runs
+under `exec.CommandContext` as it did). Tests removed: `kit34r4_test.go`, `kit34r5_test.go`,
+`TestBlockDeadlineKillsAndReconciles` and `TestTofuGetsTheInheritedDeadline`; `fake_test.go` and the
+fake tofu in `ops_test.go` are back to their pre-K12 text. `internal/hostedops` measures 7991 lines.
+
+Tests: `kit34cut_test.go` (unix: `TestBlockDeadlineRefuses`, both `--teardown` and a spend-gated
+block, a real `sh` that records its PID and sleeps: 99, the DEADLINE line, the command still alive
+(not a zombie), no RECOVERY, SAFE-STOP, TF-RECONCILED, FORCE-UNLOCK or UNIT line and no provider call
+but the estimate's; `TestBlockMaxBeforeTheDeadline`). Red first: `kit34cut_test.go:58 ops block 8.3
+--teardown --max 300ms ... = 1, want 99`.
+
+Mutation checks (`-run 'TestBlockDeadlineRefuses|TestBlockMaxBeforeTheDeadline'`), each restored:
+- **C1** the deadline ignored (wait for the command): FAILED `:58 ... = 0, want 99`.
+- **C2** the command given a context that ends at the deadline (stopped): FAILED `:60 [--teardown]: no
+ DEADLINE refusal` (the killed command's exit won the race).
+- **C3** recovery requested at the deadline: FAILED `:67 [--teardown]: the deadline did more than refuse (RECOVERY)`.
+- **C4** the deadline made 1: FAILED `:58 ... = 1, want 99`.
+- **C5** no DEADLINE line: FAILED `:60 [--teardown]: no DEADLINE refusal`.
diff --git a/infra/hosted/README.md b/infra/hosted/README.md
index a3e54025..13f66754 100644
--- a/infra/hosted/README.md
+++ b/infra/hosted/README.md
@@ -187,7 +187,7 @@ safety refusal, so it branches on the exit code, not on "non-zero".
| --- | --- | --- | --- |
| `equipo-hosted-ops` | 0 | done | |
| `equipo-hosted-ops` | 1 | ordinary: a fallback may retry or skip | usage; a failed read (status, a VM scan still incomplete at `--max`, the tag index, the inventory); `tofu` apply or destroy failing after `plan-check.py` accepted the plan (`tf reconcile ROOT` next); a connector create refused, `FAILED` or not `ACTIVE` in time; a connector delete not done while the connector is still recorded; a controller reboot not seen down and back within `--max`; a reservation the estimate cannot admit; `wait object` past `--max`; a bucket create or object put the provider refused; a Litestream restore that could not be read; `unit start` refusing; `unit status` unable to read |
-| `equipo-hosted-ops` | 99 | safety refusal: a hard stop, section S follows | the guard (account, caller, region); a `plan-check.py` refusal; ownership and ledger (a name collision, another account's ARN, an unresolved intent blocking teardown, another run's directory); the spend gate (`--stop` reached, a reservation asked at the stop, an estimate that does not compute, a create inside a teardown block); a live VM neither the controller's nor a recorded launch; an image not proved clear; fence, terminate, unfence, and reboot while fenced; `verify-gone`; settings or checksums not reading back; a secret where none may be; a failed `assert`; a failed unit (`unit wait`); an expired human wait; safe-stop with problems; connector interfaces not proved gone once the connector is deleted |
+| `equipo-hosted-ops` | 99 | safety refusal: a hard stop, section S follows | the guard (account, caller, region); a `plan-check.py` refusal; ownership and ledger (a name collision, another account's ARN, an unresolved intent blocking teardown, another run's directory); the spend gate (`--stop` reached, a reservation asked at the stop, an estimate that does not compute, a create inside a teardown block); a live VM neither the controller's nor a recorded launch; an image not proved clear; fence, terminate, unfence, and reboot while fenced; `verify-gone`; settings or checksums not reading back; a secret where none may be; a failed `assert`; a failed unit (`unit wait`); an expired human wait; a block past its `--max` (refused: nothing stopped, and here no section S); safe-stop with problems; connector interfaces not proved gone once the connector is deleted |
| `equipo-hosted-image` | 4 | safety refusal | a guard: caller, account, region, prefix, an image `-ledger` does not record |
| `equipo-hosted-image` | 1, 2, 5, 6 | ordinary | other, an AWS call failed, a wait ran out, a failed state |
| `equipo-hosted-image` | 3 | usage | |
@@ -206,17 +206,12 @@ teardown the recovery unit starts by itself once a safe stop has finished
unless a guard failure caused the stop, the file changed since the arm,
or it already ran once. `ops continuation disarm` withdraws it.
-`ops block ID [--teardown] --max D -- CMD` gives CMD a deadline. Past it
-the whole process group is stopped before anything else: TERM, up to 90 s
-for it to go (more than tofu's own 60 s), then KILL and up to 30 s more.
-The block journals `DEADLINE`; a group not proved gone, or the command's
-own 99, is a stop. Otherwise it reconciles the roots it touched
-(`TF-START` since its start), releasing with `force-unlock` only a state
-lock its own killed tofu left (this user@host, created inside the block's
-window; `FORCE-UNLOCK`), stops on any safety error, and exits 1 for the
-plan's retry. Worst case, a deadline adds 18 min 30 s (2 min 30 s for the
-group, 15 min for the reconcile, 60 s for its last tofu), and 35 min 45 s
-more when it ends in a stop and asks for recovery. `ops unit
+`ops block ID [--teardown] --max D -- CMD` gives CMD a deadline, as a
+refusal and nothing more. Past D the block journals `DEADLINE block=ID
+max=D: refused; nothing stopped; waiting for Paul` and exits 99. It stops
+nothing (the command runs on in its unit, whose runtime cap is systemd's
+backstop), unlocks nothing, reconciles nothing and asks for no recovery.
+Before D, the command's own exit decides as without `--max`. `ops unit
start BLOCK --max D` sets the unit's `RuntimeMaxSec`. `ops controller
reboot --not-after T` sends nothing after T (`REBOOT-LATE`, 1) and
journals `REBOOT-SENT at=` when the provider accepted the reboot.
diff --git a/internal/hostedops/fake_test.go b/internal/hostedops/fake_test.go
index b7117667..8685c59c 100644
--- a/internal/hostedops/fake_test.go
+++ b/internal/hostedops/fake_test.go
@@ -284,14 +284,6 @@ func (f *fakeCloud) HeadObject(_ context.Context, b, o, k string) (string, error
return base64.StdEncoding.EncodeToString(s[:]), nil
}
func (f *fakeCloud) GetObject(_ context.Context, b, o, k string) ([]byte, error) {
- if strings.HasSuffix(k, ".tflock") { // the state lock object: the fake tofu's lock.json, if any
- f.rec("GetObject %s/%s", b, k)
- raw, err := os.ReadFile(filepath.Join(os.Getenv("FAKE_TOFU"), "lock.json"))
- if err != nil {
- return nil, ErrNotFound
- }
- return raw, nil
- }
f.mu.Lock()
defer f.mu.Unlock()
body, ok := f.objects[b+"/"+k]
diff --git a/internal/hostedops/kit34cut_test.go b/internal/hostedops/kit34cut_test.go
new file mode 100644
index 00000000..a2bb42ff
--- /dev/null
+++ b/internal/hostedops/kit34cut_test.go
@@ -0,0 +1,92 @@
+//go:build unix
+
+package hostedops
+
+import (
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+// The deadline path cut to a refusal (coordinator ruling 2026-12-03,
+// kit-cut-brief.md, after p34-r5 findings 20 to 22): at a block's --max
+// the block journals DEADLINE and exits 99. It stops nothing, unlocks
+// nothing, reconciles nothing and asks for no recovery; the command runs
+// on in its unit.
+
+// livePID writes a command that records its PID and sleeps; the test
+// kills that PID, and only it, when it ends.
+func livePID(t *testing.T) (argv []string, pid func() int) {
+ f := filepath.Join(t.TempDir(), "child.pid")
+ read := func() int {
+ b, err := os.ReadFile(f)
+ if err != nil {
+ return 0
+ }
+ n, _ := strconv.Atoi(strings.TrimSpace(string(b)))
+ return n
+ }
+ t.Cleanup(func() {
+ if n := read(); n > 1 {
+ _ = syscall.Kill(n, syscall.SIGKILL)
+ }
+ })
+ return []string{"sh", "-c", `echo $$ > "` + f + `"; exec sleep 120`}, read
+}
+
+func alive(pid int) bool {
+ if pid <= 1 || syscall.Kill(pid, 0) != nil {
+ return false
+ }
+ b, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
+ if err != nil {
+ return false
+ }
+ s := string(b)
+ i := strings.LastIndex(s, ")")
+ return i > 0 && len(s) > i+2 && s[i+2] != 'Z'
+}
+
+func TestBlockDeadlineRefuses(t *testing.T) {
+ for _, mode := range [][]string{{"--teardown"}, {"--stop", "40"}} {
+ r := newRig(t, "TF-APPLY network start destroy-network")
+ argv, pid := livePID(t)
+ args := append(append([]string{"block", "8.3"}, mode...), "--max", "300ms", "--")
+ r.want(ExitStop, append(args, argv...)...)
+ if !r.has("DEADLINE", "block=8.3 max=300ms: refused; nothing stopped; waiting for Paul") {
+ t.Fatalf("%v: no DEADLINE refusal:\n%s", mode, journalText(r))
+ }
+ if !alive(pid()) {
+ t.Fatalf("%v: the command (pid %d) was stopped", mode, pid())
+ }
+ for _, verb := range []string{"RECOVERY", "SAFE-STOP", "TF-RECONCILED", "FORCE-UNLOCK", "UNIT"} {
+ if r.has(verb, "") {
+ t.Fatalf("%v: the deadline did more than refuse (%s):\n%s", mode, verb, journalText(r))
+ }
+ }
+ for _, c := range r.cloud.log() {
+ if !strings.HasPrefix(c, "ListVMs") {
+ t.Fatalf("%v: the deadline made a provider call: %s", mode, c)
+ }
+ }
+ }
+}
+
+// Before the deadline, the command's own exit decides, as without --max:
+// 0 is 0; 99 is 99 (and asks for recovery); an --optional block's 1 is 1.
+func TestBlockMaxBeforeTheDeadline(t *testing.T) {
+ r := newRig(t)
+ r.want(0, "block", "8.4", "--teardown", "--max", "1m", "--", "true")
+ r.want(ExitStop, "block", "8.5", "--teardown", "--max", "1m", "--", "sh", "-c", "exit 99")
+ if !r.has("SAFE-STOP", "start") {
+ t.Fatal("a command's 99 did not ask for recovery")
+ }
+ r = newRig(t)
+ r.want(ExitFail, "block", "8.6", "--teardown", "--optional", "--max", "1m", "--", "sh", "-c", "exit 1")
+ if r.has("DEADLINE", "") {
+ t.Fatal("a command that ended in time journalled DEADLINE")
+ }
+}
diff --git a/internal/hostedops/kit34r3_test.go b/internal/hostedops/kit34r3_test.go
index 2864d660..fbb2ad74 100644
--- a/internal/hostedops/kit34r3_test.go
+++ b/internal/hostedops/kit34r3_test.go
@@ -1,13 +1,7 @@
-//go:build unix
-
package hostedops
import (
- "os"
- "path/filepath"
- "strconv"
"strings"
- "syscall"
"testing"
"time"
@@ -17,89 +11,6 @@ import (
// After-cap kit fixes from the dev drill plan's review round 3 (p34-r3.md
// findings 1 and 10), rulings K12 and K13.
-// gone reports whether the process pid no longer runs (within 3 s).
-func gone(pid int) bool {
- for i := 0; i < 60; i++ {
- if err := syscall.Kill(pid, 0); err == syscall.ESRCH {
- return true
- }
- time.Sleep(50 * time.Millisecond)
- }
- return false
-}
-
-// K12: a block's --max kills its whole process group at the deadline,
-// journals DEADLINE, reconciles every root whose apply did not finish (so
-// what state holds is recorded) and exits 1, never 99, asking for no
-// recovery.
-func TestBlockDeadlineKillsAndReconciles(t *testing.T) {
- r, fake := tfRig(t,
- "REC tf network/module.network.aws_vpc.vm id=vpc-0vm type=aws_vpc source=state",
- "INTENT tf network/module.network.aws_iam_role.connector_operator - type=aws_iam_role name=equipo-hosted-connector-operator",
- "TF-APPLY network start destroy-network")
- os.WriteFile(filepath.Join(fake, "stall-apply"), nil, 0o600)
- os.WriteFile(filepath.Join(fake, "plan-network-refresh.json"), []byte(`{"planned_values":{"root_module":{"child_modules":[{"resources":[
-{"address":"module.network.aws_vpc.vm","type":"aws_vpc","values":{"id":"vpc-0vm"}},
-{"address":"module.network.aws_iam_role.connector_operator","type":"aws_iam_role","values":{"id":"equipo-hosted-connector-operator","arn":"arn:aws:iam::149757027610:role/equipo-hosted-connector-operator","name":"equipo-hosted-connector-operator"}}]}]}}}`), 0o600)
- start := time.Now()
- touch := `printf '2026-12-01T10:00:00.000Z\tTF-START network destroy-network\n2026-12-01T10:00:00.000Z\tTF-APPLY network start destroy-network\n' >> ` + filepath.Join(r.dir, JournalFile) + `; `
- r.want(ExitFail, "block", "8.3", "--teardown", "--max", "500ms", "--", "sh", "-c", touch+`"$FAKE_TOFU/tofu" -chdir=x apply x.tfplan`)
- if d := time.Since(start); d > 30*time.Second {
- t.Fatalf("the block ran %v past a 2s deadline", d)
- }
- raw, _ := os.ReadFile(filepath.Join(fake, "sleep.pid"))
- pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
- if err != nil || !gone(pid) {
- t.Fatalf("the stalled grandchild %q survived the deadline (%v)", raw, err)
- }
- if !r.has("DEADLINE", "block=8.3 max=500ms") {
- t.Fatalf("no DEADLINE line:\n%s", journalText(r))
- }
- if !strings.Contains(calls(t, fake), "-refresh-only") || !r.has("TF-RECONCILED", "network") {
- t.Fatalf("no reconcile after the deadline:\n%s\n%s", calls(t, fake), journalText(r))
- }
- l := r.ledger()
- if l.RecValue("tf", "network/module.network.aws_vpc.vm") == "" || l.Deleted["tf network/module.network.aws_vpc.vm"] {
- t.Fatal("a resource state still holds is not recorded present")
- }
- if l.RecValue("tf", "network/module.network.aws_iam_role.connector_operator") == "" || len(l.Open("tf")) != 0 {
- t.Fatalf("the reconcile did not record what state holds: open %d", len(l.Open("tf")))
- }
- if r.has("SAFE-STOP", "") || r.has("RECOVERY", "") {
- t.Fatal("a deadline asked for recovery")
- }
- // A block that ends in time is untouched by --max.
- r = newRig(t)
- r.want(0, "block", "8.4", "--max", "1m", "--", "true")
- if r.has("DEADLINE", "") {
- t.Fatal("a block that ended in time journalled DEADLINE")
- }
- r.want(ExitFail, "block", "8.5", "--max", "25h", "--", "true")
-}
-
-// K12: ops gives tofu the deadline it inherits (EQUIPO_HOSTED_OPS_DEADLINE)
-// through its context: a stalled apply is stopped there, an ordinary 1.
-func TestTofuGetsTheInheritedDeadline(t *testing.T) {
- r, fake := tfRig(t)
- os.WriteFile(filepath.Join(fake, "stall-apply"), nil, 0o600)
- t.Cleanup(func() { // tofu alone is stopped here; its stray sleep is the test's to end
- if raw, err := os.ReadFile(filepath.Join(fake, "sleep.pid")); err == nil {
- if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil {
- _ = syscall.Kill(pid, syscall.SIGKILL)
- }
- }
- })
- t.Setenv(DeadlineEnv, strconv.FormatInt(time.Now().Add(time.Second).UnixNano(), 10))
- start := time.Now()
- r.want(ExitFail, "tf", "network", "network")
- if d := time.Since(start); d > 30*time.Second {
- t.Fatalf("tofu ran %v past the inherited deadline", d)
- }
- if !r.has("FINDING", "apply of network failed") {
- t.Fatalf("the stopped apply is not a FINDING:\n%s", journalText(r))
- }
-}
-
// K12: unit start --max sets the unit's RuntimeMaxSec.
func TestUnitStartMax(t *testing.T) {
r := newRig(t)
diff --git a/internal/hostedops/kit34r4_test.go b/internal/hostedops/kit34r4_test.go
deleted file mode 100644
index edce6b3e..00000000
--- a/internal/hostedops/kit34r4_test.go
+++ /dev/null
@@ -1,273 +0,0 @@
-//go:build unix
-
-package hostedops
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "syscall"
- "testing"
- "time"
-)
-
-// Fixes from the scoped review of the after-cap change (p34-r4.md
-// findings 16 to 19), rulings K14 to K17.
-
-// pidGone reports whether pid has ended: no such process, or a zombie
-// waiting for its reaper.
-func pidGone(pid int) bool {
- if err := syscall.Kill(pid, 0); err == syscall.ESRCH {
- return true
- }
- b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
- if err != nil {
- return true
- }
- s := string(b)
- i := strings.LastIndex(s, ")")
- return i > 0 && len(s) > i+2 && s[i+2] == 'Z'
-}
-
-// recordedPIDs reads the PIDs a test's command wrote, one file each, and
-// kills only those at cleanup (house rule: never by pattern or user).
-func recordedPIDs(t *testing.T, files ...string) func() []int {
- read := func() []int {
- var pids []int
- for _, f := range files {
- if b, err := os.ReadFile(f); err == nil {
- if pid, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && pid > 1 {
- pids = append(pids, pid)
- }
- }
- }
- return pids
- }
- t.Cleanup(func() {
- for _, pid := range read() {
- _ = syscall.Kill(pid, syscall.SIGKILL)
- }
- })
- return read
-}
-
-// stubborn is a command whose grandchild ignores TERM and outlives the
-// direct child, which ends on TERM. Each writes its PID.
-func stubborn(dir string) []string {
- return []string{"sh", "-c", `echo $$ > "` + dir + `/leader.pid"; (trap "" TERM; exec sleep 120) & echo $! > "` + dir + `/grand.pid"; sleep 120`}
-}
-
-// K14: at a block's deadline the whole group is stopped before anything
-// else: TERM, a wait for the group to go, KILL when a member ignores TERM,
-// and a wait until the group is gone. Only then the block returns (1).
-func TestDeadlineStopsTheGroupSynchronously(t *testing.T) {
- r := newRig(t)
- d := t.TempDir()
- pids := recordedPIDs(t, filepath.Join(d, "leader.pid"), filepath.Join(d, "grand.pid"))
- r.deps.groupGrace, r.deps.groupKillWait = 300*time.Millisecond, 5*time.Second
- r.want(ExitFail, "block", "8.4", "--teardown", "--max", "300ms", "--", stubborn(d)[0], stubborn(d)[1], stubborn(d)[2])
- got := pids()
- if len(got) != 2 {
- t.Fatalf("the command did not record its PIDs: %v", got)
- }
- for _, pid := range got { // checked at once: the block returned only after the group was gone
- if !pidGone(pid) {
- t.Fatalf("pid %d still runs after the block returned", pid)
- }
- }
- if !r.has("DEADLINE", "block=8.4") || !r.has("DEADLINE", "kill=yes gone=yes") {
- t.Fatalf("the DEADLINE line does not say the group was killed and is gone:\n%s", journalText(r))
- }
- if BlockKillGrace < TofuStopGrace+30*time.Second {
- t.Fatalf("BlockKillGrace %v does not exceed tofu's own grace %v by 30 s", BlockKillGrace, TofuStopGrace)
- }
-}
-
-// K14: a group that cannot be proved gone is a stop (99), with no
-// reconcile: the run cannot claim its processes stopped.
-func TestDeadlineGroupNotProvedGoneStops(t *testing.T) {
- r, fake := tfRig(t)
- d := t.TempDir()
- recordedPIDs(t, filepath.Join(d, "leader.pid"), filepath.Join(d, "grand.pid"))
- r.deps.groupGrace, r.deps.groupKillWait = 200*time.Millisecond, 300*time.Millisecond
- saved := signalGroup
- signalGroup = func(pgid int, sig syscall.Signal) error {
- if sig == 0 {
- return nil // every probe says a member is still there
- }
- return saved(pgid, sig)
- }
- t.Cleanup(func() { signalGroup = saved })
- cmd := stubborn(d)
- cmd[2] = `printf '2026-12-01T10:00:00.000Z\tTF-START network network\n' >> ` + filepath.Join(r.dir, JournalFile) + `; ` + cmd[2]
- r.want(ExitStop, append([]string{"block", "8.4", "--teardown", "--max", "300ms", "--"}, cmd...)...)
- if !r.has("DEADLINE", "gone=no") || !r.has("ABORT", "not proved gone") {
- t.Fatalf("no record that the group was not proved gone:\n%s", journalText(r))
- }
- if strings.Contains(calls(t, fake), "-refresh-only") {
- t.Fatal("a reconcile ran while the group was not proved gone")
- }
-}
-
-// lockText is OpenTofu's lock error for who, created at.
-func lockText(id, who string, at time.Time) string {
- return "Error: Error acquiring the state lock\n\nError message: operation error S3: PutObject, https response error StatusCode: 412\nLock Info:\n" +
- " ID: " + id + "\n Path: equipo-hosted-tfstate-149757027610/prod/network.tfstate\n Operation: OperationTypeApply\n" +
- " Who: " + who + "\n Version: 1.12.5\n Created: " + at.UTC().Format("2006-01-02 15:04:05.999999999 -0700 MST") + "\n Info:\n"
-}
-
-// K15: after the group is proved gone, a state lock this block's killed
-// tofu left (this user@host, created inside the block's window) is
-// released with force-unlock, journalled, and the reconcile goes on; any
-// other lock is a stop, never released.
-func TestDeadlineReleasesOnlyOurStaleLock(t *testing.T) {
- who := lockWho()
- for name, c := range map[string]struct {
- who string
- at func(start time.Time) time.Time
- exit int
- released bool
- }{
- "ours": {who, func(s time.Time) time.Time { return s.Add(10 * time.Millisecond) }, ExitFail, true},
- "another who": {"someone@elsewhere", func(s time.Time) time.Time { return s.Add(10 * time.Millisecond) }, ExitStop, false},
- "before the block": {who, func(s time.Time) time.Time { return s.Add(-time.Hour) }, ExitStop, false},
- "after the deadline": {who, func(s time.Time) time.Time { return s.Add(time.Hour) }, ExitStop, false},
- } {
- r, fake := tfRig(t)
- lock := filepath.Join(fake, "lock")
- r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int {
- r.journal("TF-START network destroy-network", "TF-APPLY network start destroy-network")
- os.WriteFile(lock, []byte(lockText("lock-0abc", c.who, c.at(time.Now()))), 0o600)
- <-ctx.Done()
- return 143
- }
- if got := r.ops("block", "8.3", "--teardown", "--max", "50ms", "--", "x"); got != c.exit {
- t.Errorf("%s: block = %d, want %d:\n%s", name, got, c.exit, r.out.String())
- continue
- }
- unlocked := strings.Contains(calls(t, fake), "force-unlock -force lock-0abc")
- if unlocked != c.released || r.has("FORCE-UNLOCK", "network") != c.released {
- t.Errorf("%s: force-unlock ran %t, journalled %t; want %t\n%s", name, unlocked, r.has("FORCE-UNLOCK", ""), c.released, journalText(r))
- }
- if c.released && (!r.has("FORCE-UNLOCK", "id=lock-0abc who="+who) || !r.has("TF-RECONCILED", "network")) {
- t.Errorf("%s: the release or the reconcile after it is not journalled:\n%s", name, journalText(r))
- }
- }
-}
-
-// withServices gives a tfRig the services root too, so reconciling it
-// would reach tofu.
-func withServices(r *rig) {
- root := filepath.Join(r.dir, "repo", "infra", "hosted", "envs", "prod", "services")
- os.MkdirAll(root, 0o700)
- os.WriteFile(filepath.Join(root, "main.tf"), []byte("terraform {\n backend \"s3\" {}\n}\n"), 0o600)
-}
-
-// K16: a child's 99 stays 99 when its deadline passed too; in the
-// reconcile after a deadline, a safety error stops at once (99, the next
-// root untouched) and only ordinary tofu failures become FINDINGs.
-func TestDeadlineKeepsSafetyRefusals(t *testing.T) {
- waitThen := func(code int) func(ctxT, []string, []string, wT, wT) int {
- return func(ctx ctxT, _ []string, _ []string, _, _ wT) int {
- <-ctx.Done()
- return code
- }
- }
- r := newRig(t)
- r.deps.Exec = waitThen(ExitStop)
- r.want(ExitStop, "block", "8.3", "--teardown", "--max", "50ms", "--", "x")
-
- touch := func(r *rig, extra ...string) {
- r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int {
- r.journal(append([]string{"TF-START network destroy-network", "TF-APPLY network start destroy-network", "TF-START services destroy-services", "TF-APPLY services start destroy-services"}, extra...)...)
- <-ctx.Done()
- return 143
- }
- }
- for name, setup := range map[string]func(r *rig, fake string){
- "ownership": func(r *rig, fake string) {
- r.cloud.headBucket = func(string) error { return stopf("the state bucket is owned by another account") }
- },
- "malformed state": func(r *rig, fake string) {
- os.WriteFile(filepath.Join(fake, "plan-network-refresh.json"), []byte("not json"), 0o600)
- },
- "unresolved intents": func(r *rig, fake string) {
- r.journal("INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc")
- r.cloud.lookup = func(LookupKey) (LookupResult, error) { return LookupResult{}, nil }
- },
- } {
- r, fake := tfRig(t)
- withServices(r)
- setup(r, fake)
- touch(r)
- if got := r.ops("block", "8.3", "--teardown", "--max", "50ms", "--", "x"); got != ExitStop {
- t.Errorf("%s: block = %d, want 99:\n%s", name, got, r.out.String())
- }
- // Between the DEADLINE and the block's ABORT no other root is
- // touched (the recovery after it may reconcile roots left applying).
- in := false
- for _, e := range r.ledger().Entries {
- switch {
- case e.Verb == "DEADLINE":
- in = true
- case e.Verb == "ABORT" && strings.HasPrefix(e.Text, "block 8.3"):
- in = false
- case in && e.Verb == "TF-START" && e.Field(0) == "services":
- t.Errorf("%s: the next root was reconciled after a safety error", name)
- }
- }
- _ = fake
- }
- // The ledger not reading is a stop.
- r, _ = tfRig(t)
- r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int {
- f, _ := os.OpenFile(filepath.Join(r.dir, JournalFile), os.O_APPEND|os.O_WRONLY, 0o600)
- f.WriteString("a line with no tab\n")
- f.Close()
- <-ctx.Done()
- return 143
- }
- r.want(ExitStop, "block", "8.3", "--teardown", "--max", "50ms", "--", "x")
- // An ordinary tofu failure is a FINDING, the next root is still reconciled, exit 1.
- r, fake := tfRig(t)
- withServices(r)
- os.WriteFile(filepath.Join(fake, "fail-refresh"), nil, 0o600)
- touch(r)
- r.want(ExitFail, "block", "8.3", "--teardown", "--max", "50ms", "--", "x")
- if !r.has("FINDING", "tf reconcile network") || !strings.Contains(calls(t, fake), "envs/prod/services") {
- t.Fatalf("an ordinary reconcile failure: want a FINDING and the next root reconciled:\n%s", journalText(r))
- }
-}
-
-// K17: the reconcile after a deadline covers only the roots this block
-// touched (TF-START since its BLOCK start), not every root left applying
-// by earlier work.
-func TestDeadlineReconcilesOnlyTouchedRoots(t *testing.T) {
- r, fake := tfRig(t, "TF-APPLY services start destroy-services", "TF-START services destroy-services")
- withServices(r)
- r.deps.Exec = func(ctx ctxT, _ []string, _ []string, _, _ wT) int {
- r.journal("TF-START network destroy-network", "TF-APPLY network start destroy-network")
- <-ctx.Done()
- return 143
- }
- r.want(ExitFail, "block", "8.3", "--teardown", "--max", "50ms", "--", "x")
- log := calls(t, fake)
- if !strings.Contains(log, "envs/prod/network plan -refresh-only") || strings.Contains(log, "envs/prod/services") {
- t.Fatalf("reconciled the wrong roots:\n%s", log)
- }
- // ops tf and tf reconcile journal TF-START before their tofu work.
- r, _ = tfRig(t)
- r.want(0, "tf", "network", "network")
- r.want(0, "tf", "reconcile", "network")
- n := 0
- for _, e := range r.ledger().Entries {
- if e.Verb == "TF-START" && e.Field(0) == "network" {
- n++
- }
- }
- if n != 2 {
- t.Fatalf("%d TF-START lines for network, want 2:\n%s", n, journalText(r))
- }
-}
diff --git a/internal/hostedops/kit34r5_test.go b/internal/hostedops/kit34r5_test.go
deleted file mode 100644
index ac63f85f..00000000
--- a/internal/hostedops/kit34r5_test.go
+++ /dev/null
@@ -1,75 +0,0 @@
-//go:build unix
-
-package hostedops
-
-import (
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-// K15 extended (the coordinator, after the scoped review): a block
-// killed while tofu plans (a destroy's plan phase) leaves its own state
-// lock; at the deadline every root the block touched has its lock read,
-// and one this block provably left is released, though the root was not
-// applying; only roots the block was applying are reconciled.
-
-// planKillRig runs a block whose command journals TF-START for network
-// and runs the fake tofu's plan, which takes a lock for who and stalls.
-func planKillRig(t *testing.T, who string) (*rig, string, []string) {
- r, fake := tfRig(t)
- t.Setenv("FAKE_WHO", who)
- os.WriteFile(filepath.Join(fake, "stall-plan"), nil, 0o600)
- recordedPIDs(t, filepath.Join(fake, "sleep.pid"))
- r.deps.groupGrace, r.deps.groupKillWait = 300*1e6, 5*1e9
- dir := filepath.Join(r.dir, "repo", "infra", "hosted", "envs", "prod", "network")
- cmd := `printf '2026-12-01T10:00:00.000Z\tTF-START network destroy-network\n' >> ` + filepath.Join(r.dir, JournalFile) +
- `; "$FAKE_TOFU/tofu" -chdir=` + dir + ` plan -destroy -out=` + filepath.Join(fake, "x.tfplan")
- return r, fake, []string{"block", "8.3b", "--teardown", "--max", "500ms", "--", "sh", "-c", cmd}
-}
-
-func TestDeadlineInPlanReleasesOwnLock(t *testing.T) {
- r, fake, block := planKillRig(t, lockWho())
- r.want(ExitFail, block...)
- log := calls(t, fake)
- if !r.has("FORCE-UNLOCK", "network id=lock-0plan who="+lockWho()) || !strings.Contains(log, "force-unlock -force lock-0plan") {
- t.Fatalf("our own lock from a killed plan was not released:\n%s\n%s", log, journalText(r))
- }
- if strings.Contains(log, "-refresh-only") {
- t.Fatal("a root that was only planning was reconciled")
- }
- if r.cloud.index("GetObject equipo-hosted-tfstate-149757027610/prod/network.tfstate.tflock") < 0 {
- t.Fatalf("the lock object was not read: %v", r.cloud.log())
- }
- r.want(0, "tf", "network", "destroy-network") // the retry
-}
-
-func TestDeadlineInPlanKeepsAnotherLock(t *testing.T) {
- r, fake, block := planKillRig(t, "someone@elsewhere")
- r.want(ExitStop, block...)
- if strings.Contains(calls(t, fake), "force-unlock") || r.has("FORCE-UNLOCK", "") {
- t.Fatal("another Who's lock was released")
- }
- if !r.has("ABORT", "not released") {
- t.Fatalf("no record of the lock kept:\n%s", journalText(r))
- }
-}
-
-// A root counts as touched from the first tofu command: TF-START comes
-// before init, so an init that fails still marks it.
-func TestTouchedFromInit(t *testing.T) {
- r, fake := tfRig(t)
- os.WriteFile(filepath.Join(fake, "fail-init"), nil, 0o600)
- r.want(ExitFail, "tf", "network", "destroy-network")
- r.want(ExitFail, "tf", "reconcile", "network")
- n := 0
- for _, e := range r.ledger().Entries {
- if e.Verb == "TF-START" && e.Field(0) == "network" {
- n++
- }
- }
- if n != 2 {
- t.Fatalf("%d TF-START lines with init failing, want 2:\n%s", n, journalText(r))
- }
-}
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go
index 9c346271..11a7a46c 100644
--- a/internal/hostedops/ops.go
+++ b/internal/hostedops/ops.go
@@ -29,7 +29,8 @@
// a bucket or object not reading back as set (settings, checksum)
// a secret where none may be (journal, report, bundle, variables)
// named assertions that do not hold (assert), a failed unit (unit
-// wait), an expired human wait, safe-stop with problems
+// wait), an expired human wait, a block past its --max (refused,
+// nothing stopped, no recovery), safe-stop with problems
// 1 usage errors; a read that failed (status, a VM scan still
// incomplete at its bound, the tag index, the inventory); a tofu
// plan, apply or destroy that failed after plan-check accepted it
@@ -67,7 +68,6 @@ import (
"path/filepath"
"regexp"
"sort"
- "strconv"
"strings"
"time"
)
@@ -146,9 +146,6 @@ type Deps struct {
SelfUnit func() string
Stdout io.Writer
Stderr io.Writer
- // groupGrace and groupKillWait replace BlockKillGrace and GroupKillWait
- // in tests.
- groupGrace, groupKillWait time.Duration
// noSync: tests skip the journal's fsync (it is the only reason they
// are slow); production always syncs.
noSync bool
@@ -370,12 +367,6 @@ func lookup(args []string) (string, command, []string, bool) {
// Main runs one invocation and returns its exit code.
func Main(ctx context.Context, args []string, d Deps) int {
- // A block's deadline, inherited (K12): every call, and tofu, ends by it.
- if n, err := strconv.ParseInt(os.Getenv(DeadlineEnv), 10, 64); err == nil && n > 0 {
- var cancel context.CancelFunc
- ctx, cancel = context.WithDeadline(ctx, time.Unix(0, n))
- defer cancel()
- }
o := &Ops{Deps: d, ctx: ctx}
if o.Stdout == nil {
o.Stdout = os.Stdout
diff --git a/internal/hostedops/ops_test.go b/internal/hostedops/ops_test.go
index 0d1e41bc..ff9c25cc 100644
--- a/internal/hostedops/ops_test.go
+++ b/internal/hostedops/ops_test.go
@@ -210,19 +210,6 @@ case " $* " in
*" show -json -no-color "*) cat "$FAKE_TOFU/state.json";;
*" output -json "*) echo '{"vm_vpc_id":{"value":"vpc-0vm"}}';;
esac
-case " $* " in
- *" init "*) [ -f "$FAKE_TOFU/fail-init" ] && exit 1;;
- *" force-unlock -force "*) rm -f "$FAKE_TOFU/lock" "$FAKE_TOFU/lock.json";;
- *" plan "*) if [ -f "$FAKE_TOFU/lock" ]; then cat "$FAKE_TOFU/lock" >&2; exit 1; fi
- case " $* " in *" -refresh-only "*) [ -f "$FAKE_TOFU/fail-refresh" ] && exit 1;; esac
- if [ -f "$FAKE_TOFU/stall-plan" ]; then
- printf '{"ID":"lock-0plan","Operation":"OperationTypePlan","Info":"","Who":"%s","Version":"1.12.5","Created":"%s","Path":"x"}' "$FAKE_WHO" "$(date -u +%Y-%m-%dT%H:%M:%S.%NZ)" > "$FAKE_TOFU/lock.json"
- printf 'Error: Error acquiring the state lock\nLock Info:\n ID: lock-0plan\n Operation: OperationTypePlan\n Who: %s\n Created: %s\n' "$FAKE_WHO" "$(date -u '+%Y-%m-%d %H:%M:%S.%N +0000 UTC')" > "$FAKE_TOFU/lock"
- rm -f "$FAKE_TOFU/stall-plan"
- sleep 120 >/dev/null 2>&1 & echo $! > "$FAKE_TOFU/sleep.pid"; wait
- fi;;
-esac
-case " $* " in *" apply "*) if [ -f "$FAKE_TOFU/stall-apply" ]; then sleep 120 >/dev/null 2>&1 & echo $! > "$FAKE_TOFU/sleep.pid"; wait; fi;; esac
case " $* " in *" apply "*) [ -f "$FAKE_TOFU/fail-apply" ] && exit 1;; esac
exit 0
`
diff --git a/internal/hostedops/proc_other.go b/internal/hostedops/proc_other.go
deleted file mode 100644
index a652929d..00000000
--- a/internal/hostedops/proc_other.go
+++ /dev/null
@@ -1,36 +0,0 @@
-//go:build !unix
-
-package hostedops
-
-import (
- "context"
- "os/exec"
- "time"
-)
-
-type groupEnd struct{ stopped, killed, gone bool }
-
-// runGroup: no process groups here (the run kit runs on Linux); the
-// command is killed when ctx ends, and counts as gone once it is reaped.
-func runGroup(ctx context.Context, cmd *exec.Cmd, grace, killWait time.Duration) (groupEnd, error) {
- if err := cmd.Start(); err != nil {
- return groupEnd{gone: true}, err
- }
- done := make(chan error, 1)
- go func() { done <- cmd.Wait() }()
- select {
- case err := <-done:
- return groupEnd{gone: true}, err
- case <-ctx.Done():
- }
- _ = cmd.Process.Kill()
- select {
- case err := <-done:
- return groupEnd{stopped: true, killed: true, gone: true}, err
- case <-time.After(killWait):
- return groupEnd{stopped: true, killed: true}, nil
- }
-}
-
-// termCmd: the context's end kills the command.
-func termCmd(cmd *exec.Cmd, grace time.Duration) { cmd.WaitDelay = grace }
diff --git a/internal/hostedops/proc_unix.go b/internal/hostedops/proc_unix.go
deleted file mode 100644
index a251307d..00000000
--- a/internal/hostedops/proc_unix.go
+++ /dev/null
@@ -1,75 +0,0 @@
-//go:build unix
-
-package hostedops
-
-import (
- "context"
- "os/exec"
- "syscall"
- "time"
-)
-
-// signalGroup signals a process group; tests replace it.
-var signalGroup = func(pgid int, sig syscall.Signal) error { return syscall.Kill(-pgid, sig) }
-
-// groupEnd is how a command's process group ended.
-type groupEnd struct {
- stopped bool // its context ended first: the group was told to stop
- killed bool // a member outlived TERM by grace: the group got KILL
- gone bool // the group was proved gone (or never needed stopping)
-}
-
-// runGroup runs cmd as the leader of its own process group (K14,
-// p34-r4 finding 16). If it ends first, that is its result. If ctx ends
-// first, the group is stopped synchronously: TERM, then a wait (probing
-// the group every 100 ms) of up to grace for it to go; then KILL and a
-// wait of up to killWait. gone says whether it was proved gone; nothing
-// is left scheduled. Descendants that left the group (setsid) are not
-// covered.
-func runGroup(ctx context.Context, cmd *exec.Cmd, grace, killWait time.Duration) (groupEnd, error) {
- cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
- if err := cmd.Start(); err != nil {
- return groupEnd{gone: true}, err
- }
- pgid := cmd.Process.Pid
- done := make(chan error, 1)
- go func() { done <- cmd.Wait() }() // reaps the leader, so a dead leader is not counted alive
- select {
- case err := <-done:
- return groupEnd{gone: true}, err
- case <-ctx.Done():
- }
- end := groupEnd{stopped: true}
- waitGone := func(d time.Duration) bool {
- until := time.Now().Add(d)
- for {
- if err := signalGroup(pgid, 0); err == syscall.ESRCH {
- return true
- }
- if time.Now().After(until) {
- return false
- }
- time.Sleep(100 * time.Millisecond)
- }
- }
- _ = signalGroup(pgid, syscall.SIGTERM)
- if end.gone = waitGone(grace); !end.gone {
- end.killed = true
- _ = signalGroup(pgid, syscall.SIGKILL)
- end.gone = waitGone(killWait)
- }
- var err error
- select {
- case err = <-done:
- case <-time.After(killWait): // pipes still held: the group is not gone
- end.gone = false
- }
- return end, err
-}
-
-// termCmd stops cmd with TERM when its context ends (tofu then stops
-// cleanly and releases its state lock), and kills it after grace.
-func termCmd(cmd *exec.Cmd, grace time.Duration) {
- cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }
- cmd.WaitDelay = grace
-}
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go
index f09fd24b..c63f1c63 100644
--- a/internal/hostedops/stop.go
+++ b/internal/hostedops/stop.go
@@ -2,7 +2,6 @@ package hostedops
import (
"context"
- "encoding/json"
"errors"
"flag"
"io"
@@ -10,15 +9,10 @@ import (
"os"
"os/exec"
"slices"
- "strconv"
"strings"
"time"
)
-// DeadlineEnv carries a block's deadline (Unix nanoseconds) to its
-// command; ops takes it as its context's deadline (K12).
-const DeadlineEnv = "EQUIPO_HOSTED_OPS_DEADLINE"
-
// TeardownEnv names the teardown block a command runs in: block
// --teardown sets it in its command's environment.
const TeardownEnv = "EQUIPO_HOSTED_OPS_TEARDOWN"
@@ -48,12 +42,18 @@ func (o *Ops) refuseInTeardown(what string) error {
// compared; teardown is the safe direction, and waiting costs money. Its
// command runs with EQUIPO_HOSTED_OPS_TEARDOWN set, and every command that
// creates or admits spend refuses inside it (refuseInTeardown).
+//
+// --max D is the command's deadline, a refusal and nothing more
+// (coordinator ruling 2026-12-03, after p34-r5): past D the block journals
+// DEADLINE and exits 99. It stops nothing (the command runs on in its
+// unit), unlocks nothing, reconciles nothing and asks for no recovery.
+// The command's own exit before D decides as without --max.
func cmdBlock(o *Ops, args []string) error {
fs := flag.NewFlagSet("block", flag.ContinueOnError)
stop := fs.Float64("stop", DefaultStop, "the run's own spend stop")
optional := fs.Bool("optional", false, "a non-zero exit other than 99 is not a hard stop")
teardown := fs.Bool("teardown", false, "a teardown block: the guard and the ledger's ownership, no spend gate; nothing in it may create")
- maxD := fs.Duration("max", 0, "the command's deadline: past it its process group is killed, roots reconciled, exit 1")
+ maxD := fs.Duration("max", 0, "the command's deadline: past it the block refuses (99) and stops nothing")
pos, err := parseFlags(fs, args)
stopSet := false
fs.Visit(func(f *flag.Flag) { stopSet = stopSet || f.Name == "stop" })
@@ -106,22 +106,18 @@ func cmdBlock(o *Ops, args []string) error {
return hard("the estimate $" + ftoa(e.Total) + " reaches the stop $" + ftoa(*stop))
}
}
- ctx, cancel := o.ctx, context.CancelFunc(func() {})
- began := time.Now()
- if *maxD > 0 {
- ctx, cancel = context.WithTimeout(o.ctx, *maxD)
- }
- code, end := o.execBlock(ctx, argv, id, *teardown)
- expired := ctx.Err() == context.DeadlineExceeded
- cancel()
- _ = o.jw("BLOCK", "%s exit=%d", id, code)
+ code, expired := o.execBlock(argv, id, *teardown, *maxD)
if expired {
- err := o.blockDeadline(id, *maxD, code, end, began)
- if IsStop(err) {
- return hard(err.Error())
- }
- return err
+ // The refusal (coordinator ruling 2026-12-03, after p34-r5): the
+ // block stops nothing, unlocks nothing, reconciles nothing and asks
+ // for no recovery (it would reconcile next to a possibly live
+ // writer). The command runs on in its unit, whose runtime cap is
+ // systemd's backstop; the run waits for Paul.
+ _ = o.jw("DEADLINE", "block=%s max=%s: refused; nothing stopped; waiting for Paul", id, *maxD)
+ o.out("block %s passed its %s deadline: refused (99); its command still runs; nothing was stopped; waiting for Paul", id, *maxD)
+ return stopf("block %s passed its %s deadline: refused; nothing stopped; waiting for Paul", id, *maxD)
}
+ _ = o.jw("BLOCK", "%s exit=%d", id, code)
switch {
case code == 0:
return nil
@@ -133,213 +129,55 @@ func cmdBlock(o *Ops, args []string) error {
return &exitError{code: code, msg: "block " + id + " exited " + itoa(code)}
}
-func (o *Ops) execBlock(ctx context.Context, argv []string, id string, teardown bool) (int, groupEnd) {
+func (o *Ops) execBlock(argv []string, id string, teardown bool, maxD time.Duration) (code int, expired bool) {
env := append(os.Environ(), "EQUIPO_HOSTED_OPS_BLOCK="+id)
if teardown {
env = append(env, TeardownEnv+"="+id)
}
- if d, ok := ctx.Deadline(); ok {
- env = append(env, DeadlineEnv+"="+strconv.FormatInt(d.UnixNano(), 10))
- }
- if o.Exec != nil { // a test's command: no process group to stop
- return o.Exec(ctx, argv, env, o.Stdout, o.Stderr), groupEnd{stopped: ctx.Err() != nil, gone: true}
+ done := make(chan int, 1)
+ if o.Exec != nil {
+ go func() { done <- o.Exec(o.ctx, argv, env, o.Stdout, o.Stderr) }()
+ } else if err := startChild(o.ctx, argv, env, o.Stdout, o.Stderr, done); err != nil {
+ return ExitFail, false
}
- grace, killWait := BlockKillGrace, GroupKillWait
- if o.groupGrace > 0 {
- grace = o.groupGrace
+ var past <-chan time.Time
+ if maxD > 0 {
+ t := time.NewTimer(maxD)
+ defer t.Stop()
+ past = t.C
}
- if o.groupKillWait > 0 {
- killWait = o.groupKillWait
+ select {
+ case code := <-done:
+ return code, false
+ case <-past:
+ return 0, true // the command is left running
}
- return runChild(ctx, argv, env, o.Stdout, o.Stderr, grace, killWait)
}
-// Block deadlines (K12, p34-r3 finding 1; K14 to K17, p34-r4).
-const (
- MaxBlock = 24 * time.Hour // --max's ceiling
- BlockKillGrace = 90 * time.Second // TERM to KILL for a block's process group: above tofu's own grace
- GroupKillWait = 30 * time.Second // after KILL, the longest wait for the group to be gone
- TofuStopGrace = 60 * time.Second // TERM to KILL for tofu
- DeadlineReconcile = 15 * time.Minute // the reconcile after a deadline, all roots together
-)
+// MaxBlock is block --max's ceiling (and unit start --max's).
+const MaxBlock = 24 * time.Hour
-// blockDeadline is a block past its --max. runChild has already stopped
-// its process group, synchronously (K14). In order:
-// - DEADLINE is journalled with how the group ended;
-// - the command's own 99 stays 99 (K16);
-// - a group not proved gone is a stop: the run cannot claim its
-// processes stopped, and nothing is reconciled (K14);
-// - each root this block touched (a TF-START line since its BLOCK
-// start; K17) is reconciled under a fresh context, so what state holds
-// is recorded. A state lock the killed tofu left is released only when
-// it is provably this block's (K15). A safety error stops at once (99,
-// no further root); an ordinary tofu failure is a FINDING (K16);
-// - exit 1: the plan may retry within its budget.
-//
-// A stop error returned here goes through the block's hard path.
-func (o *Ops) blockDeadline(id string, maxD time.Duration, code int, end groupEnd, began time.Time) error {
- deadline := began.Add(maxD)
- _ = o.jw("DEADLINE", "block=%s max=%s exit=%d term=%s kill=%s gone=%s", id, maxD, code, yesNo(end.stopped), yesNo(end.killed), yesNo(end.gone))
- o.out("block %s passed its %s deadline", id, maxD)
- if code == ExitStop {
- return stopf("exit 99 (its %s deadline passed too)", maxD)
- }
- if !end.gone {
- return stopf("past its %s deadline its process group was not proved gone; nothing reconciled", maxD)
- }
- outer := o.ctx
- ctx, cancel := context.WithTimeout(context.WithoutCancel(outer), DeadlineReconcile)
- o.ctx = ctx
- defer func() { cancel(); o.ctx = outer }()
- l, err := o.ledger()
- if err != nil {
- return stopf("after its deadline the ledger does not read: %v", err)
- }
- touched, applying := touchedRoots(l, id)
- for _, root := range touched { // a lock this block's killed tofu left, at any phase
- err := o.releaseOwnLock(root, began, deadline)
- switch {
- case err == nil:
- case IsStop(err):
- return stopf("after its deadline, the state lock of %s: %v", root, err)
- default:
- if ferr := o.finding("block %s: after its deadline, the state lock of %s: %v", id, root, err); ferr != nil {
- return ferr
- }
- }
+// startChild starts argv and sends its exit code on done when it ends.
+// Only ops's own context ending (ops told to stop) kills it.
+func startChild(ctx context.Context, argv, env []string, stdout, stderr io.Writer, done chan<- int) error {
+ cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
+ cmd.Env, cmd.Stdout, cmd.Stderr, cmd.Stdin = env, stdout, stderr, nil
+ if err := cmd.Start(); err != nil {
+ return err
}
- for _, root := range applying {
- err := o.reconcileAfterKill(root, began, deadline)
+ go func() {
+ err := cmd.Wait()
+ var x *exec.ExitError
switch {
case err == nil:
- case IsStop(err):
- return stopf("after its deadline, tf reconcile %s: %v", root, err)
+ done <- 0
+ case errors.As(err, &x) && x.ExitCode() >= 0:
+ done <- x.ExitCode()
default:
- if ferr := o.finding("block %s: after its deadline, tf reconcile %s: %v", id, root, err); ferr != nil {
- return ferr
- }
- }
- }
- return failf("block %s passed its %s deadline: its process group was stopped and proved gone, and the roots it touched reconciled; a retry is the plan's", id, maxD)
-}
-
-func yesNo(b bool) string {
- if b {
- return "yes"
- }
- return "no"
-}
-
-// touchedRoots are, since block id's last BLOCK start line and in roots
-// order, the roots with a TF-START line (any tofu work, init on), and of
-// those the ones this block was applying: a TF-APPLY start with no later
-// TF-APPLY done (K15, K17).
-func touchedRoots(l *Ledger, id string) (touched, applying []string) {
- start := 0
- for _, e := range l.Entries {
- if e.Verb == "BLOCK" && e.Field(0) == id && e.Field(1) == "start" {
- start = e.Line
+ done <- ExitFail
}
- }
- seen, apply := map[string]bool{}, map[string]bool{}
- for _, e := range l.Entries {
- switch {
- case e.Line <= start:
- case e.Verb == "TF-START":
- seen[e.Field(0)] = true
- case e.Verb == "TF-APPLY":
- apply[e.Field(0)] = e.Field(1) == "start"
- }
- }
- for _, r := range roots {
- if seen[r] {
- touched = append(touched, r)
- }
- if seen[r] && apply[r] {
- applying = append(applying, r)
- }
- }
- return touched, applying
-}
-
-// releaseOwnLock reads root's state lock object (the S3 lockfile beside
-// the state, KEY.tflock) directly: none, nothing to do; one, released only
-// when this block's killed tofu provably left it (forceUnlockOwn), else a
-// stop. A read that fails is ordinary.
-func (o *Ops) releaseOwnLock(root string, began, deadline time.Time) error {
- key := o.env() + "/" + root + ".tfstate.tflock"
- raw, err := o.cloud.GetObject(o.ctx, o.stateBucket(), o.Account, key)
- switch {
- case errors.Is(err, ErrNotFound):
- return nil
- case err != nil:
- return failf("the lock object %s did not read: %v", key, err)
- }
- var in struct {
- ID, Operation, Who string
- Created time.Time
- }
- if err := json.Unmarshal(raw, &in); err != nil || in.ID == "" || in.Who == "" || in.Created.IsZero() {
- _ = o.jw("ABORT", "the lock object %s does not read as a lock (%v)", key, err)
- return stopf("the lock object %s does not read as a lock (%v)", key, err)
- }
- return o.forceUnlockOwn(root, LockInfo{ID: in.ID, Who: in.Who, Operation: in.Operation, Created: in.Created}, began, deadline)
-}
-
-// forceUnlockOwn releases lock in on root only when this block's killed
-// tofu provably left it: Who is this user@host and Created lies between
-// the block's start and its deadline (the caller has proved the group
-// gone). Anything else is a stop; locking is never bypassed.
-func (o *Ops) forceUnlockOwn(root string, in LockInfo, began, deadline time.Time) error {
- if in.Who != lockWho() || !in.Created.After(began) || !in.Created.Before(deadline) {
- _ = o.jw("ABORT", "state lock on %s not released: id=%s who=%s operation=%s created=%s (this block: %s, %s to %s)", root, in.ID, in.Who, in.Operation,
- in.Created.UTC().Format(time.RFC3339Nano), lockWho(), began.UTC().Format(time.RFC3339Nano), deadline.UTC().Format(time.RFC3339Nano))
- return stopf("the state of %s is locked by %s since %s, not provably by this block's killed tofu; not released", root, in.Who, in.Created.UTC().Format(time.RFC3339))
- }
- dir := o.rootDir(root)
- if err := o.tofuInit(root, dir); err != nil {
- return err
- }
- if _, err := o.tofu("-chdir="+dir, "force-unlock", "-force", in.ID); err != nil {
- return stopf("force-unlock of %s (%s) failed: %v", root, in.ID, err)
- }
- return o.jw("FORCE-UNLOCK", "%s id=%s who=%s operation=%s created=%s", root, in.ID, in.Who, in.Operation, in.Created.UTC().Format(time.RFC3339Nano))
-}
-
-// reconcileAfterKill is tf reconcile ROOT after a block's group was
-// proved gone. A state lock (K15, p34-r4 finding 17) is released with
-// force-unlock only when this block's killed tofu provably left it: Who is
-// this user@host and Created lies between the block's start and its
-// deadline. Then the reconcile runs once more. Any other lock, or a lock
-// still there, is a stop: locking is never bypassed.
-func (o *Ops) reconcileAfterKill(root string, began, deadline time.Time) error {
- err := o.tfReconcile(root)
- var le *LockError
- if !errors.As(err, &le) {
- return err
- }
- if err := o.forceUnlockOwn(root, le.Info, began, deadline); err != nil {
- return err
- }
- err = o.tfReconcile(root)
- if errors.As(err, &le) {
- return stopf("the state of %s is still locked after force-unlock: %v", root, err)
- }
- return err
-}
-
-func runChild(ctx context.Context, argv, env []string, stdout, stderr io.Writer, grace, killWait time.Duration) (int, groupEnd) {
- cmd := exec.Command(argv[0], argv[1:]...)
- cmd.Env, cmd.Stdout, cmd.Stderr, cmd.Stdin = env, stdout, stderr, nil
- end, err := runGroup(ctx, cmd, grace, killWait)
- var x *exec.ExitError
- switch {
- case err == nil:
- return 0, end
- case errors.As(err, &x) && x.ExitCode() >= 0:
- return x.ExitCode(), end
- }
- return ExitFail, end
+ }()
+ return nil
}
// SafeStopBound bounds one safe stop, whatever the invocation's context.
diff --git a/internal/hostedops/tf.go b/internal/hostedops/tf.go
index 0bcf8a58..ba8cb5cd 100644
--- a/internal/hostedops/tf.go
+++ b/internal/hostedops/tf.go
@@ -7,16 +7,13 @@ import (
"encoding/json"
"errors"
"fmt"
- "io"
"os"
"os/exec"
- "os/user"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
- "time"
)
// ops tf ROOT PHASE (account plan, "Rules for every block"): the state
@@ -125,12 +122,11 @@ func (o *Ops) tofuEnv(k Keys) []string {
// tofu runs one tofu command and returns its stdout.
func (o *Ops) tofu(args ...string) ([]byte, error) {
cmd := exec.CommandContext(o.ctx, o.Tofu, args...)
- termCmd(cmd, TofuStopGrace) // the context's deadline (a block's --max) stops tofu cleanly first
cmd.Env = o.tofuEnv(o.cloud.Keys())
- var out, errOut bytes.Buffer
- cmd.Stdout, cmd.Stderr = &out, io.MultiWriter(o.Stderr, &errOut)
+ var out bytes.Buffer
+ cmd.Stdout, cmd.Stderr = &out, o.Stderr
if err := cmd.Run(); err != nil {
- return out.Bytes(), &tofuError{err: fmt.Errorf("tofu %s: %w", args[1], err), stderr: errOut.String()}
+ return out.Bytes(), fmt.Errorf("tofu %s: %w", args[1], err)
}
return out.Bytes(), nil
}
@@ -260,12 +256,6 @@ func cmdTf(o *Ops, args []string) error {
return failf("no %s: run tfvars first", vars)
}
dir := o.rootDir(root)
- // TF-START: this root's tofu work begins, from init on (a lock may be
- // taken). A block's deadline reads the lock of every root it touched
- // (K15) and reconciles those it was applying (K17).
- if err := o.jw("TF-START", "%s %s", root, phase); err != nil {
- return err
- }
if err := o.tofuInit(root, dir); err != nil {
return err
}
@@ -522,9 +512,6 @@ func (o *Ops) tfReconcile(root string) error {
if _, err := o.open(); err != nil {
return err
}
- if err := o.jw("TF-START", "%s reconcile", root); err != nil {
- return err
- }
dir := o.rootDir(root)
if err := o.tofuInit(root, dir); err != nil {
return err
@@ -535,12 +522,6 @@ func (o *Ops) tfReconcile(root string) error {
return failf("%v", err)
}
if _, err := o.tofu("-chdir="+dir, "plan", "-refresh-only", "-input=false", "-no-color", "-out="+planFile, "-var-file="+vars, "-var=run="+o.Run); err != nil {
- var te *tofuError
- if errors.As(err, &te) {
- if in, ok := parseLock(te.stderr); ok {
- return &LockError{Root: root, Info: in, Err: err}
- }
- }
return failf("%v", err)
}
js, err := o.tofu("-chdir="+dir, "show", "-json", "-no-color", planFile)
@@ -1099,73 +1080,3 @@ func (o *Ops) adoptPending(root, dir, vars string) error {
// verified VPC deletion proves it gone. A gateway, an Elastic IP or an
// instance can outlive or leave a VPC, and is not here (after-cap fix 2).
var containedTypes = []string{"aws_subnet", "aws_route_table", "aws_security_group", "aws_network_acl"}
-
-// LockInfo is OpenTofu's description of a state lock.
-type LockInfo struct {
- ID, Who, Operation string
- Created time.Time
-}
-
-// LockError is a tofu call that failed on a state lock. It is an ordinary
-// failure (1) wherever nothing handles it; after a block's deadline,
-// reconcileAfterKill decides (K15).
-type LockError struct {
- Root string
- Info LockInfo
- Err error
-}
-
-func (e *LockError) Error() string {
- return fmt.Sprintf("the state of %s is locked: ID %s, Who %s, Operation %s, Created %s (%v)", e.Root, e.Info.ID, e.Info.Who,
- e.Info.Operation, e.Info.Created.UTC().Format(time.RFC3339Nano), e.Err)
-}
-
-var lockField = regexp.MustCompile(`(?m)^\s*(ID|Who|Operation|Created):\s*(.*?)\s*$`)
-
-// parseLock reads the Lock Info block of tofu's "Error acquiring the
-// state lock"; ok only with an ID, a Who and a Created that parses.
-func parseLock(stderr string) (LockInfo, bool) {
- if !strings.Contains(stderr, "Error acquiring the state lock") {
- return LockInfo{}, false
- }
- var in LockInfo
- var created string
- for _, m := range lockField.FindAllStringSubmatch(stderr, -1) {
- switch m[1] {
- case "ID":
- in.ID = m[2]
- case "Who":
- in.Who = m[2]
- case "Operation":
- in.Operation = m[2]
- case "Created":
- created = m[2]
- }
- }
- t, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", created)
- if err != nil || in.ID == "" || in.Who == "" || strings.ContainsAny(in.ID, " \t") {
- return LockInfo{}, false
- }
- in.Created = t
- return in, true
-}
-
-// lockWho is the Who OpenTofu writes into a lock this process's tofu
-// takes: the user's name, "@", the host name (its statemgr.NewLockInfo).
-func lockWho() string {
- name := ""
- if u, err := user.Current(); err == nil {
- name = u.Username
- }
- host, _ := os.Hostname()
- return name + "@" + host
-}
-
-// tofuError is a failed tofu call, with what it wrote to stderr.
-type tofuError struct {
- err error
- stderr string
-}
-
-func (e *tofuError) Error() string { return e.err.Error() }
-func (e *tofuError) Unwrap() error { return e.err }