carlos / platform Public

grouproll: journal failures are sticky; a failed session row cancels it

A row written but not fsynced may be on disk, so a later row could repeat
its seq and fork the chain. Journal.Add now keeps the first write or fsync
failure and returns it for every later row, writing nothing. When the
session-opened row fails, call cuts the request, cancels every session it
opened, returns the failure, and refuses any further provider request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a1f932f2690bc9eb5d8d17e4ac9236b4944b95b6 parent 726d942
4 files changed, +159 −7
  • internal/grouproll/engine.go +45 −5
  • internal/grouproll/engine_test.go +53 −0
  • internal/grouproll/journal.go +12 −2
  • internal/grouproll/journal_test.go +49 −0

Intent

Human

<task-notification> <task-id>b9uuw4tkp</task-id> <tool-use-id>toolu_016J9dfC9xVaeivX9hgCBuv9</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/b9uuw4tkp.output</output-file> <status>completed</status> <summary>Background command "Ledger; wait for Astra branch review" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a9a91ead675b546b9</task-id> <tool-use-id>toolu_01J3ef2rmwnkJTek9Cqh8Bwt</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a9a91ead675b546b9.output</output-file> <status>completed</status> <summary>Agent "Fable branch review round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The report is written to `/home/paulca/.cache/group-roll-go/BRANCH-FABLE-R1.md`; that one copy needed a write outside the sandbox, because the sandbox mounts that directory read-only. The worktree is untouched and my scratch files are removed. The same text follows. # Branch review: `group-roll-verb`, round 1 (Fable) Commit 726d942f7e29655ba56ce18ec0ad1432362056fa against merge-base ef8371cb. Independent of the Astra review; I did not read it. **What I did.** Read the spec (rev 3.1) and all production code in `internal/grouproll`, `internal/grouprollaws`, `internal/release/systemlookup.go`, `system_group*.go` and the `system_roles.go` change, side by side with `scripts/region-group-roll.py` and `region-group-probe.py` at `origin/held-floor-sha-map` (e17a74d3). Sampled the tests (deciders, mutations, depart simulation audits, V10/V11 tests). **What I ran.** Builds for linux, darwin/arm64 and windows/amd64, and `go vet` on the two new packages: clean. Focused tests, all passing: `internal/grouproll` (`TestClassifyGolden|TestTerminateGolden|TestRequiredMutations|TestDepartMutations|TestSeededDepartSimulation|TestRemoteCommand|TestParityLedgerComplete|TestDepart*`), all of `internal/grouprollaws`, and the pointer tests in `internal/release`. I did not run the full suites, and nothing here was checked against live AWS. ## P1 None. ## P2 ### P2-1. V11: an answered restore is sent again when the next read is below N - **Area:** check item 1, the replace watch's capacity restore. - **Problem:** Spec §7 V11 says "only an unanswered restore is retried". `restoreCapacity` never looks at the restore's response row. It resends whenever no `desired-restored` (or `minimum-restored`) row exists and the value reads below N. That row is written only when a later describe shows N. - **Evidence:** `internal/grouproll/depart.go:1048-1075` (the `st.value &lt; n` branch at 1064-1068 sends without checking for a response); caller at `depart.go:973-979` (`continue` with no sleep); the code comment at `depart.go:967-972` says "unsent, unanswered or lost". `TestDepartUnansweredRestoreRecovers` (`depart_test.go:1534`) covers a lost answer and a never-sent restore, not an answered one. - **Failure scenario:** `desired` is raised to N and AWS answers (response row journaled). The run is cut before the next snapshot (Ctrl-C, a failed target read, a journal error). Before the operator resumes, someone lowers desired to N-1. Resume finds no `desired-restored` row, reads N-1 and raises desired again. That launches capacity an outside reduction removed, which is what V11 exists to stop. The same holds within one run if the reduction lands between the answer and the next describe. The window is narrow and the raise stays inside the adapter's H4 guard (`group.go:484-502`), so this is not unsafe termination; it is the V11 mechanism not matching its row. - **Fix:** either 1. honour the row: when the journal holds a response for the latest `desired` (or `minimum`) restore intent and the value reads below N, stop with `desired_changed` (failed) instead of resending; or 2. keep the observation-based rule (it tolerates a stale describe) and correct V11's sentence to "a restore not yet observed at N is retried". Either way add a test for answered-then-reduced-before-observed. - **Fault family:** H4 capacity, raising capacity the tool already restored. ### P2-2. The runbook still sends operators to the superseded script, and the §11 step 5 switch is written nowhere an operator reads - **Area:** rollout, the first of the two round-3 fixes the brief asks this review to check. - **Problem:** The code side of the switch holds: the tools cannot share state (V4). But the branch ships no operator text for the switch, and its operator docs contradict each other. - **Evidence:** - `docs/region-ha-runbook.md:58` and `:76-81` still say to run `region-group-roll.py` as root on the operator host. - `scripts/region-group-roll.py:2-8` (added on this branch) says do not use it for live rolls. - `docs/site/cli.md:3180` says the verb "replaces `scripts/region-group-roll.py`" with no switch step. - Spec §11 step 5 (`…group-roll-verb-design.md:500-511`): the root check that `active.json` and `provider-divergence.json` are absent, the rename to `&lt;hash&gt;.retired-&lt;date&gt;`, deleting the script config. - Plan Task 13 Step 2 (`…2026-11-09-group-roll-verb.md:216`): the runbook page; not on the branch. - **Failure scenario:** After the release an operator follows the runbook and runs the script, with the V10 and V11 defects its own header names. Or an operator runs the Go verb on a group whose script directory holds `provider-divergence.json`; the Go verb cannot see it, and nothing they read told them to check. The only mechanical backstop is that preflight refuses until the controller places `provider-observation.json` in the new group directory (`engine.go:876-882`). That gates the switch but does not prompt the divergence check. - **Fix:** before the release that ships the verb, through copy review: update the runbook section to the Go verb (operator account, the 0700 state directory that must already exist, placing the observation file) and add the step 5 switch as a written card or runbook step. If Paul wants the runbook held for the retirement branch, at least add the switch step and the "do not use the script" line to the runbook now. - **Fault family:** two tools on one group, divergence block lost across a tool switch. ## P3 (follow-up list) 1. **Misleading alert after a failed-drain return.** `finishReturn` writes `done`, removes the active file, then returns the `drain_failed` refusal (`roll.go:1440-1449`). The return loop treats that as an operation error (`roll.go:1300-1310`, `1323-1329`), classify answers `resumable api`, and `stopDecision` (`roll.go:591-600`) journals an `alert` row after `done` and prints "ALERT: An AWS response is unavailable or invalid" before the real refusal. The script does the same, so this is parity, but the line is wrong for the operator. Return the refusal straight out of the loop once the script is retired. 2. **The depart simulation's finished-drain audit reads only the engine's own journal.** `sim_test.go:992-996` checks the `drained` and `pre-action-checked` rows. The fence and edge audits also read the fake's real state (`:1003`, `:1005`), and there is no mutant or negative control for the drain audit (`mutation_test.go:119-148`). Add a check against the fake agent's drain state and a mutant such as "accept a report whose result is not ok". 3. **A session whose StartSession answer lacks a token or stream URL is left open.** `session.go:318-324` reports the id, then returns `Uncertain(api)` without `Timeout`, so the engine does not call `CancelSession`. No command runs without the plugin attached; the session idles out. Cancel it in place. 4. **`ActiveID` re-reads and re-hashes every journal in the group directory** (`state.go:253-300`), and it runs on each `activeHere`. Parity with the script; it grows with history. Cache per process or skip journals that are already closed. 5. **The caller identity is journaled at start only** (`roll.go:111-117`, `depart.go:65-69`, `probe.go:52-57`). `resume`, `return` and `cancel-drain` neither journal nor compare the current caller. The spec asks only for the start row; a `caller` row per verb run would make the record complete. 6. **Witness note, not a defect.** The adapter treats an omitted collection as malformed (`group.go:145-153`, `:289`, `:321`, `:362`). That is the right fail-closed rule, and `TestMissingCollectionsAreNeverAbsence` pins it. It depends on AWS sending an explicit empty list for "no reservations" and "no activities"; the dev witnesses should include one `close-lost` on an expired instance id to confirm. ## What I checked and found sound 1. **Termination and capacity (H4, H5).** - `Terminate` is reached only through `stopAndTerminate` (`depart.go:726-761`). Each pass, including a watch retry, proves the edge stopped (MainPID 0 and inactive or failed, then the fence re-read, `depart.go:651-678`), runs the second lock sweep, and only then makes the call. - `stopSent()` can be true only after a `pre-action-checked` pass in the same journal, and a `drain-failed` row routes to the return before the loop (`depart.go:175-177`). - The adapter's `Terminate` requires a fresh describe showing raw `Standby` and `desired == minimum`, and sends `ShouldDecrementDesiredCapacity=false` (`group.go:583-612`). - Desired is lowered only by `Park`, behind the engine's `enter` guard (`engine.go:187-192`). It is raised only in `restoreCapacity` for a replace, after `terminate-checked`, behind the adapter guard. - V10 fails the probe on any change to the admitted replacement (`depart.go:1014-1018`). 2. **The r2 cut.** `Unpark` has one caller, the return's `exit`. It runs only after `returnReadiness` passed `refuseWhileMoving` in the same loop (`roll.go:1344-1391`); unknown or malformed drain status stops `drain-moving`. The 5 s freshness check is in `call`. 3. **Decision parity.** `Classify` and `TerminateDecision` match the script branch for branch. The golden fixtures go through a phase table that `TestMapPhaseMatchesCoreCopy` ties to `MapPhase`. The executors (resume, return, rollback, mutation, depart, watch, cancel-drain, abandon, close-lost, probe) match the script apart from V1-V11. Seams are unexported fields or package variables set only from tests; the zero value is production. 4. **Credentials and transport.** - The environment is rebuilt from the allow-list before `signal.NotifyContext` and before any SDK load (`system_group.go:274-286`). - `checkProfileIdentity` walks the whole `Source` chain and refuses everything but static keys, SSO, and assume-role with a session name, over the same file lists the loader gets (the typed `LoadSharedConfigOptions` option, `config.go:114-117`, `212-216`). - Endpoints are cleared on the config and on every client. Retries are 1. - The token goes only into the child's environment (`session.go:331-332`); argv holds the variable name. - The process group is killed before the leader is reaped on every early return (`pty_unix.go:108-117`, `143`). - The body bound is a deserialize middleware in the loaded config, so credential clients get it (`TestAssumeRoleAnswersAreBounded` passes). 5. **The floor.** The strict tool read runs first, then `GetSystemPointer` over the same bytes. A grant is refused before the signature. Every channel is read. Zero or two versions refuse. A non-`vX.Y.Z` version refuses. Every doubt lands in `errs` and refuses `floor_error`, never `dr4` (`floor.go:148-155`). `ha_take` counts only as int64 1. 6. **State and journal.** `O_NOFOLLOW`, 0600, owner and single-link checks on every file. 0700 group directory and ancestor walk. Hash chain with a canonical re-encode on read. `flock` non-blocking. `status` is lock-free and read-only. The script's file names are never read. 7. **The CLI.** Refusal order is Windows, root, box, then flags. No console import. Flags only. `--config` required. 8. **Census.** `runSystemGroup` refuses euid 0 before any read, including the `host.env` Lstat (`system_group.go:254-262`). The new packages have no `init` that reads files or the environment. No existing function in `internal/release` or elsewhere changed; `system_roles.go` only adds registry nodes. Root on a box is not made to read, run or follow anything new. I approve the 24 units and the four re-pinned envelopes on that basis. ## Verdict **READY AFTER FIXES**: no P1. P2-1 and P2-2 are fixed without another round.</result> <usage><subagent_tokens>400102</subagent_tokens><tool_uses>58</tool_uses><duration_ms>990446</duration_ms></usage> </task-notification>

diff --git a/internal/grouproll/engine.go b/internal/grouproll/engine.go
index ba3aa2113..3093c4148 100644
--- a/internal/grouproll/engine.go
+++ b/internal/grouproll/engine.go
@@ -41,7 +41,10 @@ type Engine struct {
header Row
lastResponseAt time.Time
- memberEdges map[string]map[string]any
+ // journalErr is the journal failure that ended this engine's writes:
+ // set when a session-opened row fails, after which call sends nothing.
+ journalErr error
+ memberEdges map[string]map[string]any
// ConfigPath is the --config path, named in the cancel-drain
// instructions an operator is given.
@@ -183,6 +186,11 @@ func (e *Engine) call(ctx context.Context, op string, args map[string]any, fresh
if e.probe && !probeOps[op] {
return nil, refuse("probe_read_only")
}
+ // After a journal failure no request is sent: nothing it did could be
+ // recorded.
+ if e.journalErr != nil {
+ return nil, e.journalErr
+ }
// H4: only this transaction's member may enter Standby, with decrement.
if op == "enter" {
iid, _ := e.header["iid"].(string)
@@ -211,11 +219,24 @@ func (e *Engine) call(ctx context.Context, op string, args map[string]any, fresh
intentSeq = intent["seq"]
}
lastSession := ""
+ // The observer journals each id as its session opens. When that row
+ // fails, the journal is unusable (its failures are sticky), so the
+ // request is cut at once, every session it opened is cancelled before
+ // any other work, and the call returns the journal's failure.
+ reqCtx, cut := context.WithCancel(ctx)
+ defer cut()
+ var observerErr error
+ var opened []string
onSession := func(id string) {
lastSession = id
- // The script's observer journals the id as the session opens; a
- // journal failure here surfaces at the response or error row.
- e.event("session-opened", map[string]any{"session_id": id, "intent": intentSeq})
+ opened = append(opened, id)
+ if observerErr != nil {
+ return
+ }
+ if _, err := e.event("session-opened", map[string]any{"session_id": id, "intent": intentSeq}); err != nil {
+ observerErr = err
+ cut()
+ }
}
sessionID := func() any {
if op != "session" || lastSession == "" {
@@ -235,8 +256,13 @@ func (e *Engine) call(ctx context.Context, op string, args map[string]any, fresh
}
}
dispatched = true
- return request(ctx, onSession)
+ return request(reqCtx, onSession)
}()
+ if observerErr != nil {
+ e.journalErr = observerErr
+ e.cancelUnjournaled(ctx, opened)
+ return nil, observerErr
+ }
if err != nil {
details := map[string]any{}
var u Uncertain
@@ -279,6 +305,20 @@ func (e *Engine) call(ctx context.Context, op string, args map[string]any, fresh
return result, nil
}
+// cancelUnjournaled ends the sessions a request opened after its journal
+// failed. No row can record them, so the calls go straight to the box
+// adapter, on a context the operator's Ctrl-C does not cut.
+func (e *Engine) cancelUnjournaled(ctx context.Context, ids []string) {
+ for _, id := range ids {
+ c, done := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
+ err := e.b.CancelSession(c, id)
+ done()
+ if err != nil {
+ e.say("ALERT", Text("session_cleanup"))
+ }
+ }
+}
+
// reasonOf is the script's str(exc) for the error row.
func reasonOf(err error) string {
var r Refusal
diff --git a/internal/grouproll/engine_test.go b/internal/grouproll/engine_test.go
index fcb776cc8..8dcb5da2c 100644
--- a/internal/grouproll/engine_test.go
+++ b/internal/grouproll/engine_test.go
@@ -509,3 +509,56 @@ func TestCallH4(t *testing.T) {
t.Fatalf("calls = %v", h.f.ops())
}
}
+
+// Astra P1-1: a session-opened row whose fsync fails ends the run. The
+// journal's failure is sticky, the session is cancelled at once (with no
+// row: none can be written), the roll returns record, no other provider
+// request follows, and the saved journal still loads: the failed row
+// reached the file, nothing came after it, so the chain is whole.
+func TestSessionJournalFailureCancelsAndStops(t *testing.T) {
+ h := newHarness(t, 2)
+ h.f.sessions = func(iid, verb string) []string { return []string{"s-" + verb} }
+ armed, failed := false, false
+ h.beforeEvent = func(kind string, _ map[string]any) {
+ if kind == "session-opened" && !failed {
+ armed = true
+ }
+ }
+ h.state.fsync = func(*os.File) error {
+ if armed {
+ armed, failed = false, true
+ return os.ErrInvalid
+ }
+ return nil
+ }
+ mark := -1
+ h.f.before = func(op string, _ map[string]any) error {
+ if failed && mark < 0 {
+ mark = len(h.f.calls) - 1
+ }
+ return nil
+ }
+ err := h.runRoll()
+ if refusalKey(err) != "record" {
+ t.Fatalf("roll = %v, want record", err)
+ }
+ if !failed {
+ t.Fatal("no session-opened row failed")
+ }
+ if mark < 0 {
+ t.Fatalf("no request after the failed row; the session was not cancelled: %v", h.f.ops())
+ }
+ after := h.f.calls[mark:]
+ if len(after) != 1 || after[0].Op != "terminate_session" || after[0].Args["session_id"] != "s-status" {
+ t.Fatalf("calls after the failed row = %v, want one terminate_session of s-status", after)
+ }
+ tx := h.onlyTx()
+ j, lerr := h.state.Load(tx, true)
+ if lerr != nil {
+ t.Fatalf("the saved journal does not load: %v", lerr)
+ }
+ defer j.Close()
+ if last := j.Rows()[len(j.Rows())-1]; last["kind"] != "session-opened" {
+ t.Fatalf("last saved row = %v, want the unsynced session-opened", last)
+ }
+}
diff --git a/internal/grouproll/journal.go b/internal/grouproll/journal.go
index d1e21e28d..957e4f344 100644
--- a/internal/grouproll/journal.go
+++ b/internal/grouproll/journal.go
@@ -58,6 +58,11 @@ type Journal struct {
rows []Row
// fsync replaces the row fsync when set (the State's test seam).
fsync func(f *os.File) error
+ // failed is the first write or fsync failure. It is sticky: a row
+ // that was written but not fsynced may or may not be on disk, so the
+ // journal's next seq and previous hash are unknown, and any later row
+ // could fork the chain. Every later Add returns it and writes nothing.
+ failed error
}
// encodeRow is the canonical format 2 encoding: object keys sorted, no
@@ -402,6 +407,9 @@ func (j *Journal) Close() error {
// written and fsynced before it returns (script Journal.add). The first row
// must be "begin" and gets "format": 2.
func (j *Journal) Add(kind string, fields map[string]any) (Row, error) {
+ if j.failed != nil {
+ return nil, j.failed
+ }
if j.readonly || j.file == nil {
return nil, refuse("record")
}
@@ -440,14 +448,16 @@ func (j *Journal) Add(kind string, fields map[string]any) (Row, error) {
return nil, refuse("record")
}
if _, err := j.file.Write(append(line, '\n')); err != nil {
- return nil, refuse("record")
+ j.failed = refuse("record")
+ return nil, j.failed
}
sync := (*os.File).Sync
if j.fsync != nil {
sync = j.fsync
}
if err := sync(j.file); err != nil {
- return nil, refuse("record")
+ j.failed = refuse("record")
+ return nil, j.failed
}
j.rows = append(j.rows, Row(normal))
return Row(normal), nil
diff --git a/internal/grouproll/journal_test.go b/internal/grouproll/journal_test.go
index 652f8d1cc..2cbfc448d 100644
--- a/internal/grouproll/journal_test.go
+++ b/internal/grouproll/journal_test.go
@@ -7,6 +7,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "errors"
"math"
"os"
"path/filepath"
@@ -329,3 +330,51 @@ func TestJournalLargeRow(t *testing.T) {
t.Fatal("large row did not round-trip")
}
}
+
+// A write or fsync failure is sticky: the failed row may be on disk, so a
+// later row could repeat its seq and previous hash and fork the chain.
+// Every later Add returns the first failure and writes no byte, and the
+// saved file still loads (the unsynced row present or not).
+func TestJournalFailureIsSticky(t *testing.T) {
+ j, path := newJournal(t)
+ begin, intent := goldenRows()
+ if _, err := j.Add("begin", begin); err != nil {
+ t.Fatal(err)
+ }
+ fail := true
+ j.fsync = func(f *os.File) error {
+ if fail {
+ fail = false
+ return os.ErrInvalid
+ }
+ return f.Sync()
+ }
+ _, first := j.Add("intent", intent)
+ var r Refusal
+ if !errors.As(first, &r) || r.Key != "record" {
+ t.Fatalf("first failure = %v, want record", first)
+ }
+ size := func() int64 {
+ fi, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fi.Size()
+ }
+ before := size()
+ if _, err := j.Add("response", map[string]any{"op": "describe"}); !errors.As(err, &r) || r.Key != "record" {
+ t.Fatalf("later Add = %v, want the first failure %v", err, first)
+ }
+ if size() != before || len(j.Rows()) != 1 {
+ t.Fatalf("a row was written after the failure: %d -> %d bytes, %d rows", before, size(), len(j.Rows()))
+ }
+ j.Close()
+ saved, err := openJournal(path, currentOwner(), false, true)
+ if err != nil {
+ t.Fatalf("the saved journal does not load: %v", err)
+ }
+ defer saved.Close()
+ if n := len(saved.Rows()); n != 2 {
+ t.Fatalf("saved rows = %d, want begin and the unsynced intent", n)
+ }
+}