Merge thin-v1-slice4b round-1 fixes (56a623b) into thin-v1-slice4c
Ask output bounds, ask termination proof, ReportAnswer retry and the git_show range.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+513
−32
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/SLICE4B-PROGRESS.md+29 −0internal/headless/ask_test.go+5 −0internal/headless/env_test.go+17 −0internal/runner/thin/ask.go+150 −19internal/runner/thin/ask_review_test.go+252 −0internal/runner/thin/ask_test.go+3 −3internal/runner/thin/engineer.go+8 −1internal/runner/thin/state.go+10 −0internal/runner/thin/step.go+38 −8
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 0713734e..ed988b1f 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -37,7 +37,7 @@ time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced se |
| time internal/tryequipo 30s Release starter-set controller K3 records CI runs of 10.8s and 13.1s; 30s retains the guide integration checks with headroom on the shared runner. |
| size internal/runner/thin 8200 - Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| time internal/thintest 30s Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. |
| -time internal/runner/thin 30s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. |
| +time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom. |
| time internal/headless 240s Thin v1 headless suite: real instance, runner and bubblewrap per scenario (spec 7, under two minutes). Slice 4 adds the review and checks scenarios (4_review with its fix rounds, branch move and merge; 4_checks_honest); loaded CI measured 170s on 2026-11-07. Slice 4b adds 4b_ask (about 12s); loaded CI measured 182.9s. 240s keeps 30 percent headroom. |
| perf GET /api/v1/turns/{id} skip Thin v1 person API: bearer-only JSON for devices, not a browser screen. |
| perf GET /api/v1/events skip Thin v1 person event stream (Server-Sent Events), long-lived by design; not a screen. |
diff --git a/docs/superpowers/plans/SLICE4B-PROGRESS.md b/docs/superpowers/plans/SLICE4B-PROGRESS.md| index 2a72c8a7..c9f4e42c 100644 |
| --- a/docs/superpowers/plans/SLICE4B-PROGRESS.md |
| +++ b/docs/superpowers/plans/SLICE4B-PROGRESS.md |
| @@ -147,6 +147,35 @@ Conventions and scripts as in `SLICE1-PROGRESS.md` to `SLICE4-PROGRESS.md`. |
| index-pack failure, and a stall) hung before the fix; after it they |
| end in 0.2 s and at the 3 s test deadline, leaving no process. |
| +11. Astra round 1 on slice 4b (REQUEST CHANGES, three Important, one |
| + Minor), each with a test that failed first: |
| + 1. Git output in the answering session is bounded while read: at |
| + most MaxDiffBytes is read, then git's process group is stopped and |
| + reaped and the answer is cut (`TestAnswerGitOutputBoundedWhileRead`: |
| + a 16 MiB patch and commit allocated 80 MiB before, under 4 MiB now). |
| + 2. A question is complete only once its namespace's exit is verified: |
| + the run records the namespace against the question's own attempt |
| + (`asks.ns_id`, not the steps table); an unverified exit holds the |
| + answer (`pending`, the report kept in `asks.final`), listed in |
| + sync, released by the probe at start and on every sync once |
| + verified; a restart holds a running question whose namespace is |
| + unproven (`TestAskHeldUntilTerminationVerified` failed and stalled, |
| + `TestRecoverAsksHoldsUnprovenNamespaces`; headless `4b_ask` checks |
| + the namespace is recorded, a mutation routing it to the steps |
| + table fails it). |
| + 3. A question is marked started durably before its provider runs and |
| + is never picked again; its result stays in memory and its final |
| + write is retried with backoff, never the provider |
| + (`TestAskReportPersistedWithoutRerun`, three injected write |
| + failures: the provider ran once and the answer was sent). |
| + 4. Minor: `git_show` takes only base..candidate, as `git_log` shows |
| + (`TestAnswerGitShowKeepsToTheChange`: the base and older history |
| + are refused). |
| + Mutations: the retry loop (killed), the held release (killed), the |
| + namespace hook (killed in headless); the started filter alone |
| + survives behind the retry loop (defence in depth). Time budget |
| + `internal/runner/thin` 45s. |
| + |
| ## Decisions |
| - Sessions are kept as transcripts, like the coordinator's; the tree |
diff --git a/internal/headless/ask_test.go b/internal/headless/ask_test.go| index b7a241d7..412ba1cf 100644 |
| --- a/internal/headless/ask_test.go |
| +++ b/internal/headless/ask_test.go |
| @@ -88,6 +88,11 @@ func scenarioAsk(t *testing.T, env *Env) { |
| if !strings.HasPrefix(q1.Answer, "From my session: "+eng.Summary) || !strings.Contains(q1.Answer, "The change: +") || !strings.Contains(q1.Answer, "the panes") || !strings.Contains(q1.Answer, "README.md starts: ") { |
| t.Fatalf("engineering answer %q (its step said %q)", q1.Answer, eng.Summary) |
| } |
| + // The question's own namespace is recorded against it, for the proof |
| + // of its exit. |
| + if ns := env.AskNamespace(t, q1.ID); ns == "" { |
| + t.Fatal("no namespace recorded for the question") |
| + } |
| if c1.FirstText == 0 || c1.FirstActivity == 0 { |
| t.Fatalf("the answer did not stream: %+v", c1) |
| } |
diff --git a/internal/headless/env_test.go b/internal/headless/env_test.go| index 6e9eac9d..fe5875e3 100644 |
| --- a/internal/headless/env_test.go |
| +++ b/internal/headless/env_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "crypto/rand" |
| "crypto/sha256" |
| + "database/sql" |
| "encoding/hex" |
| "encoding/json" |
| "io" |
| @@ -25,6 +26,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/thintest" |
| "amadan.net/oficina/equipo/internal/toolproxy" |
| "amadan.net/rastrillo/rastrillo/budget" |
| + _ "modernc.org/sqlite" |
| ) |
| // TestMain also serves as the namespace helper, the fake claude and the |
| @@ -90,6 +92,9 @@ type Env struct { |
| // KeptSessions counts the step sessions the runner keeps on disk |
| // (local only). |
| KeptSessions func(t *testing.T) int |
| + // AskNamespace is the containment namespace the runner recorded for |
| + // a question's attempt (local only). |
| + AskNamespace func(t *testing.T, question string) string |
| turns *int |
| } |
| @@ -288,6 +293,18 @@ func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) { |
| r.start(t) |
| }, |
| ForgePath: forge.path, |
| + AskNamespace: func(t *testing.T, question string) string { |
| + d, err := sql.Open("sqlite", "file:"+filepath.Join(state, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + var ns string |
| + if err := d.QueryRow("SELECT ns_id FROM asks WHERE question_id=?", question).Scan(&ns); err != nil { |
| + t.Fatal(err) |
| + } |
| + return ns |
| + }, |
| KeptSessions: func(t *testing.T) int { |
| dirs, _ := filepath.Glob(filepath.Join(thin.SessionRoot(cfg), "*", "steps", "*")) |
| return len(dirs) |
diff --git a/internal/runner/thin/ask.go b/internal/runner/thin/ask.go| index 4c8f1222..b5460fd1 100644 |
| --- a/internal/runner/thin/ask.go |
| +++ b/internal/runner/thin/ask.go |
| @@ -7,7 +7,6 @@ import ( |
| "errors" |
| "io" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "regexp" |
| "slices" |
| @@ -195,7 +194,7 @@ func (s *State) nextAsk(ctx context.Context) (askRow, bool, error) { |
| var a askRow |
| var body string |
| var cancel int |
| - err := s.db.QueryRowContext(ctx, "SELECT body, cancel, created_at FROM asks WHERE state=? ORDER BY created_at, question_id LIMIT 1", runRunning).Scan(&body, &cancel, &a.Created) |
| + err := s.db.QueryRowContext(ctx, "SELECT body, cancel, created_at FROM asks WHERE state=? AND started=0 ORDER BY created_at, question_id LIMIT 1", runRunning).Scan(&body, &cancel, &a.Created) |
| if errors.Is(err, sql.ErrNoRows) { |
| return a, false, nil |
| } |
| @@ -212,6 +211,87 @@ func (s *State) askCancelled(ctx context.Context, a askRow) bool { |
| return cancel == 1 |
| } |
| +// startAsk marks an attempt started, durably, before its provider runs: |
| +// a started attempt is never picked again; only recovery ends it. |
| +func (s *State) startAsk(ctx context.Context, a askRow) error { |
| + res, err := s.db.ExecContext(ctx, "UPDATE asks SET started=1 WHERE question_id=? AND attempt=? AND state=? AND started=0", a.QuestionID, a.Attempt, runRunning) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n != 1 { |
| + return errors.New("question attempt not runnable") |
| + } |
| + return nil |
| +} |
| + |
| +// FinishAsk records an attempt's final report: sent now when its |
| +// namespace's exit is verified, else held (pending) with the report, so |
| +// a probe that verifies the exit sends it later. Either way the attempt |
| +// leaves the queue. |
| +func (s *State) FinishAsk(ctx context.Context, a askRow, rep wire.AnswerReport, terminated bool) error { |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + if s.fault != nil { |
| + if err := s.fault("finish_ask"); err != nil { |
| + return err |
| + } |
| + } |
| + if !terminated { |
| + raw, _ := json.Marshal(rep) |
| + _, err := t.Exec("UPDATE asks SET state=?, final=? WHERE question_id=? AND attempt=? AND state=?", runPending, string(raw), a.QuestionID, a.Attempt, runRunning) |
| + return err |
| + } |
| + res, err := t.Exec("UPDATE asks SET state=? WHERE question_id=? AND attempt=? AND state=?", runReported, a.QuestionID, a.Attempt, runRunning) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n != 1 { |
| + return nil |
| + } |
| + return s.enqueue(t, wire.FrameAnswer, "", rep) |
| + }) |
| +} |
| + |
| +// heldAsk is an attempt whose answer waits for its namespace's proof. |
| +type heldAsk struct { |
| + question, ns, final string |
| + attempt int64 |
| +} |
| + |
| +func (s *State) heldAsks(ctx context.Context) ([]heldAsk, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT question_id, attempt, ns_id, final FROM asks WHERE state=?", runPending) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []heldAsk |
| + for rows.Next() { |
| + var h heldAsk |
| + if err = rows.Scan(&h.question, &h.attempt, &h.ns, &h.final); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, h) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// releaseAsk sends a held answer once its namespace's exit is verified. |
| +func (s *State) releaseAsk(ctx context.Context, h heldAsk) error { |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + res, err := t.Exec("UPDATE asks SET state=? WHERE question_id=? AND attempt=? AND state=?", runReported, h.question, h.attempt, runPending) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n != 1 { |
| + return nil |
| + } |
| + var rep wire.AnswerReport |
| + if err := json.Unmarshal([]byte(h.final), &rep); err != nil { |
| + return err |
| + } |
| + return s.enqueue(t, wire.FrameAnswer, "", rep) |
| + }) |
| +} |
| + |
| // ReportAnswer queues an answer report; a final one ends the attempt here |
| // in the same transaction. |
| func (s *State) ReportAnswer(ctx context.Context, a askRow, rep wire.AnswerReport) error { |
| @@ -244,7 +324,7 @@ func answerAcked(t *sql.Tx, body string) error { |
| // syncAsks lists the question attempts this runner holds. |
| func (s *State) syncAsks(ctx context.Context) ([]wire.AskRun, error) { |
| - rows, err := s.db.QueryContext(ctx, "SELECT question_id, attempt, state FROM asks WHERE state IN (?,?) ORDER BY created_at", runRunning, runReported) |
| + rows, err := s.db.QueryContext(ctx, "SELECT question_id, attempt, state FROM asks WHERE state IN (?,?,?) ORDER BY created_at", runRunning, runReported, runPending) |
| if err != nil { |
| return nil, err |
| } |
| @@ -262,17 +342,18 @@ func (s *State) syncAsks(ctx context.Context) ([]wire.AskRun, error) { |
| // RecoverAsks ends the questions a previous process left running: their |
| // namespaces died with it. A question is never run twice. |
| -func (s *State) RecoverAsks(ctx context.Context) error { |
| +func (s *State) RecoverAsks(ctx context.Context, verify func(context.Context, string) bool) error { |
| var all []askRow |
| - rows, err := s.db.QueryContext(ctx, "SELECT body, cancel FROM asks WHERE state=?", runRunning) |
| + ns := map[string]string{} |
| + rows, err := s.db.QueryContext(ctx, "SELECT body, cancel, ns_id FROM asks WHERE state=?", runRunning) |
| if err != nil { |
| return err |
| } |
| for rows.Next() { |
| var a askRow |
| - var body string |
| + var body, id string |
| var cancel int |
| - if err = rows.Scan(&body, &cancel); err != nil { |
| + if err = rows.Scan(&body, &cancel, &id); err != nil { |
| rows.Close() |
| return err |
| } |
| @@ -282,6 +363,7 @@ func (s *State) RecoverAsks(ctx context.Context) error { |
| } |
| a.Cancel = cancel == 1 |
| all = append(all, a) |
| + ns[a.QuestionID] = id |
| } |
| rows.Close() |
| for _, a := range all { |
| @@ -289,16 +371,33 @@ func (s *State) RecoverAsks(ctx context.Context) error { |
| if a.Cancel { |
| rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| } |
| - if err := s.ReportAnswer(ctx, a, rep); err != nil { |
| + // Its namespace died with the old process; until that exit is |
| + // verified the question stays held. |
| + proven := ns[a.QuestionID] == "" || verify == nil || verify(ctx, ns[a.QuestionID]) |
| + if err := s.FinishAsk(ctx, a, rep, proven); err != nil { |
| return err |
| } |
| } |
| return nil |
| } |
| +// askResult is how a question attempt ended: its final report, and |
| +// whether its namespace's exit was verified (true when none started). |
| +type askResult struct { |
| + Report wire.AnswerReport |
| + Terminated bool |
| +} |
| + |
| // AskFunc answers one question attempt; progress sends the running |
| -// report. The returned report is final. |
| -type AskFunc func(ctx context.Context, a askRow, progress func(wire.AnswerReport)) wire.AnswerReport |
| +// report. |
| +type AskFunc func(ctx context.Context, a askRow, progress func(wire.AnswerReport)) askResult |
| + |
| +// setAskNamespace records the containment namespace a question attempt |
| +// runs in, so its exit can be verified again later. |
| +func (s *State) setAskNamespace(ctx context.Context, a askRow, id string) error { |
| + _, err := s.db.ExecContext(ctx, "UPDATE asks SET ns_id=? WHERE question_id=? AND attempt=?", id, a.QuestionID, a.Attempt) |
| + return err |
| +} |
| // --- Keeping a step's session --- |
| @@ -393,20 +492,36 @@ var hexRef = regexp.MustCompile(`^[0-9a-f]{7,64}$`) |
| // answerGit runs one read-only git tool on the tree's private repository. |
| func answerGit(ctx context.Context, git, gitDir, base, candidate, name string, args json.RawMessage) (string, bool) { |
| + // run reads at most MaxDiffBytes of git's output; past that git is |
| + // stopped (its process group) and reaped, and the answer is cut. |
| run := func(argv ...string) (string, error) { |
| - cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + gitDir, "-c", "core.quotePath=false"}, argv...)...) |
| + cctx, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + cmd := groupCommand(cctx, git, append([]string{"--git-dir=" + gitDir, "-c", "core.quotePath=false"}, argv...)...) |
| env := workspace.GitEnvironment() |
| env["HOME"] = "/nonexistent" |
| for k, v := range env { |
| cmd.Env = append(cmd.Env, k+"="+v) |
| } |
| cmd.Stderr = io.Discard |
| - out, err := cmd.Output() |
| - s := strings.ToValidUTF8(string(out), "?") |
| - if len(s) > wire.MaxDiffBytes { |
| - s = s[:wire.MaxDiffBytes] + "\n[cut; read the files in /workspace]" |
| + pipe, err := cmd.StdoutPipe() |
| + if err != nil { |
| + return "", err |
| } |
| - return s, err |
| + if err = cmd.Start(); err != nil { |
| + return "", err |
| + } |
| + out, _ := io.ReadAll(io.LimitReader(pipe, wire.MaxDiffBytes+1)) |
| + cut := len(out) > wire.MaxDiffBytes |
| + if cut { |
| + cancel() |
| + pipe.Close() |
| + } |
| + err = cmd.Wait() |
| + if cut { |
| + return strings.ToValidUTF8(string(out[:wire.MaxDiffBytes]), "?") + "\n[cut; read the files in /workspace]", nil |
| + } |
| + return strings.ToValidUTF8(string(out), "?"), err |
| } |
| span := candidate |
| if base != "" { |
| @@ -454,10 +569,16 @@ func answerGit(ctx context.Context, git, gitDir, base, candidate, name string, a |
| return "git_show takes a commit hash from git_log.", true |
| } |
| c := strings.TrimSpace(in.Commit) |
| - // Only commits of this change's history, never another ref. |
| + // Only commits git_log shows (base..candidate), never another ref |
| + // or the history before the change. |
| if _, err := run("merge-base", "--is-ancestor", c+"^{commit}", candidate); err != nil { |
| return "That commit is not part of this change.", true |
| } |
| + if base != "" { |
| + if _, err := run("merge-base", "--is-ancestor", c+"^{commit}", base); err == nil { |
| + return "That commit is not part of this change.", true |
| + } |
| + } |
| out, err := run("show", "--no-color", "--no-ext-diff", "--no-textconv", "--format=%h %an%n%n%B", c+"^{commit}") |
| if err != nil { |
| return "That commit is not available.", true |
| @@ -548,7 +669,15 @@ func answerActivity(raw []byte) (kind, tool string, ok bool) { |
| } |
| // ask answers one question from the step's own session. |
| -func (e *Engineer) ask(ctx context.Context, a askRow, progress func(wire.AnswerReport)) wire.AnswerReport { |
| +func (e *Engineer) ask(ctx context.Context, a askRow, progress func(wire.AnswerReport)) askResult { |
| + terminated := true |
| + rep := e.answer(ctx, a, progress, &terminated) |
| + return askResult{Report: rep, Terminated: terminated} |
| +} |
| + |
| +// answer runs the question; terminated is false only when its |
| +// namespace started and its exit was not verified. |
| +func (e *Engineer) answer(ctx context.Context, a askRow, progress func(wire.AnswerReport), terminated *bool) wire.AnswerReport { |
| received := time.Now() |
| rep := wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} |
| fail := func(reason string) wire.AnswerReport { |
| @@ -619,7 +748,9 @@ func (e *Engineer) ask(ctx context.Context, a askRow, progress func(wire.AnswerR |
| if limit <= 0 { |
| limit = maxAnswer |
| } |
| - res := e.run(ctx, r, tree, specialistRun{action: "answer", binding: bs[i], tools: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: claude.ReadPermission, call: call, prompt: e.askPrompt(a), resume: kept.SessionID, keep: kept.Dir, stream: stream, limit: limit, noLog: true}) |
| + res := e.run(ctx, r, tree, specialistRun{action: "answer", binding: bs[i], tools: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: claude.ReadPermission, call: call, prompt: e.askPrompt(a), resume: kept.SessionID, keep: kept.Dir, stream: stream, limit: limit, noLog: true, |
| + record: func(ctx context.Context, id string) error { return e.O.State.setAskNamespace(ctx, a, id) }}) |
| + *terminated = res.terminated |
| if res.kept > 0 { |
| e.log("kept sessions", e.O.State.touchKept(context.WithoutCancel(ctx), kept, res.kept)) |
| } |
diff --git a/internal/runner/thin/ask_review_test.go b/internal/runner/thin/ask_review_test.go| new file mode 100644 |
| index 00000000..558c5bd9 |
| --- /dev/null |
| +++ b/internal/runner/thin/ask_review_test.go |
| @@ -0,0 +1,252 @@ |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Astra 4b round 1, finding 1: an answering session's git output is |
| +// bounded while it is read; a huge patch never lands in runner memory, |
| +// and git is stopped and reaped once the bound is reached. |
| +func TestAnswerGitOutputBoundedWhileRead(t *testing.T) { |
| + if testing.Short() { |
| + t.Skip("writes 16 MiB") |
| + } |
| + root := t.TempDir() |
| + work := filepath.Join(root, "work") |
| + gitT(t, root, "init", "-q", "-b", "main", work) |
| + os.WriteFile(filepath.Join(work, "a.txt"), []byte("a\n"), 0644) |
| + gitT(t, work, "add", "-A") |
| + gitT(t, work, "commit", "-qm", "base") |
| + base := gitT(t, work, "rev-parse", "HEAD") |
| + var big bytes.Buffer |
| + raw := make([]byte, 48<<17) |
| + rand.Read(raw) |
| + for i := 0; i < len(raw); i += 48 { |
| + big.WriteString(strconv.Quote(string(raw[i:i+48])) + "\n") |
| + } |
| + os.WriteFile(filepath.Join(work, "big.txt"), big.Bytes(), 0644) |
| + big.Reset() |
| + raw = nil |
| + gitT(t, work, "add", "-A") |
| + gitT(t, work, "commit", "-qm", "big") |
| + cand := gitT(t, work, "rev-parse", "HEAD") |
| + gitDir := filepath.Join(work, ".git") |
| + for _, c := range []struct{ name, args string }{{"git_diff", `{}`}, {"git_show", `{"commit":"` + cand + `"}`}} { |
| + runtime.GC() |
| + var a, b runtime.MemStats |
| + runtime.ReadMemStats(&a) |
| + out, bad := answerGit(context.Background(), "/usr/bin/git", gitDir, base, cand, c.name, json.RawMessage(c.args)) |
| + runtime.ReadMemStats(&b) |
| + if bad || len(out) > wire.MaxDiffBytes+200 || !strings.Contains(out, "[cut;") { |
| + t.Fatalf("%s: %d bytes, error %v", c.name, len(out), bad) |
| + } |
| + if grew := b.TotalAlloc - a.TotalAlloc; grew > 4<<20 { |
| + t.Fatalf("%s allocated %d MiB reading git's output", c.name, grew>>20) |
| + } |
| + } |
| +} |
| + |
| +// Astra 4b round 1, minor: git_show takes only commits git_log shows, |
| +// base..candidate: not the base, nor anything before it. |
| +func TestAnswerGitShowKeepsToTheChange(t *testing.T) { |
| + root := t.TempDir() |
| + work := filepath.Join(root, "work") |
| + gitT(t, root, "init", "-q", "-b", "main", work) |
| + os.WriteFile(filepath.Join(work, "a.txt"), []byte("first\n"), 0644) |
| + gitT(t, work, "add", "-A") |
| + gitT(t, work, "commit", "-qm", "older history") |
| + older := gitT(t, work, "rev-parse", "HEAD") |
| + os.WriteFile(filepath.Join(work, "a.txt"), []byte("second\n"), 0644) |
| + gitT(t, work, "commit", "-qam", "the base") |
| + base := gitT(t, work, "rev-parse", "HEAD") |
| + os.WriteFile(filepath.Join(work, "a.txt"), []byte("third\n"), 0644) |
| + gitT(t, work, "commit", "-qam", "the change") |
| + cand := gitT(t, work, "rev-parse", "HEAD") |
| + gd := filepath.Join(work, ".git") |
| + if out, bad := answerGit(context.Background(), "/usr/bin/git", gd, base, cand, "git_show", json.RawMessage(`{"commit":"`+cand+`"}`)); bad || !strings.Contains(out, "the change") { |
| + t.Fatalf("the change itself: %q", out) |
| + } |
| + for _, c := range []string{base, older} { |
| + if out, bad := answerGit(context.Background(), "/usr/bin/git", gd, base, cand, "git_show", json.RawMessage(`{"commit":"`+c+`"}`)); !bad { |
| + t.Fatalf("git_show answered outside base..candidate: %q", out) |
| + } |
| + } |
| +} |
| + |
| +func outboxAnswers(t *testing.T, s *State) map[string]wire.AnswerReport { |
| + t.Helper() |
| + frames, _, err := s.Unacked(context.Background(), 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out := map[string]wire.AnswerReport{} |
| + for _, f := range frames { |
| + if f.Type == wire.FrameAnswer { |
| + var r wire.AnswerReport |
| + json.Unmarshal(f.Data, &r) |
| + if wire.QuestionTerminal(r.State) { |
| + out[r.QuestionID] = r |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// runAsk runs the engine until the question leaves the running state. |
| +func runAsk(t *testing.T, s *State, e *StepEngine, q string) { |
| + t.Helper() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + if err := e.Start(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.AcceptAsk(context.Background(), "c-"+q, wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: q, Attempt: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e.Wake() |
| + deadline := time.Now().Add(10 * time.Second) |
| + for { |
| + var state string |
| + s.db.QueryRow("SELECT state FROM asks WHERE question_id=?", q).Scan(&state) |
| + if state != runRunning { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("the question did not end") |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + cancel() |
| + e.Wait() |
| +} |
| + |
| +// Astra 4b round 1, finding 2: a question is complete only once its |
| +// namespace's exit is verified. Until then (the exit failed or stalled) |
| +// its answer is held, recorded against the question's own namespace, |
| +// and survives a restart; the verified exit releases it, once. |
| +func TestAskHeldUntilTerminationVerified(t *testing.T) { |
| + for _, how := range []string{"failed", "stalled"} { |
| + t.Run(how, func(t *testing.T) { |
| + ctx := context.Background() |
| + dir := t.TempDir() |
| + s, err := OpenState(ctx, dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var verified atomic.Bool |
| + e := &StepEngine{State: s, Notify: func() {}, Verify: func(_ context.Context, ns string) bool { return ns == "ns-q1" && verified.Load() }, |
| + Ask: func(ctx context.Context, a askRow, _ func(wire.AnswerReport)) askResult { |
| + // The run recorded its namespace, then its exit was not |
| + // verified (Wait failed, or it outlived the limit). |
| + if err := s.setAskNamespace(ctx, a, "ns-q1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "An answer."}, Terminated: false} |
| + }} |
| + runAsk(t, s, e, "q1") |
| + if got := outboxAnswers(t, s); len(got) != 0 { |
| + t.Fatalf("answered before the exit was verified: %+v", got) |
| + } |
| + if runs, _ := s.syncAsks(ctx); len(runs) != 1 || runs[0].QuestionID != "q1" { |
| + t.Fatalf("a held question is not listed in sync: %+v", runs) |
| + } |
| + // A restart keeps holding it, and never runs it again. |
| + s.Close() |
| + if s, err = OpenState(ctx, dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + ran := 0 |
| + e2 := &StepEngine{State: s, Notify: func() {}, Verify: e.Verify, Ask: func(context.Context, askRow, func(wire.AnswerReport)) askResult { ran++; return askResult{} }} |
| + cctx, cancel := context.WithCancel(ctx) |
| + if err := e2.Start(cctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := outboxAnswers(t, s); len(got) != 0 { |
| + t.Fatalf("released at restart without proof: %+v", got) |
| + } |
| + verified.Store(true) |
| + e2.Probe(ctx) |
| + e2.Probe(ctx) |
| + cancel() |
| + e2.Wait() |
| + got := outboxAnswers(t, s) |
| + if ran != 0 || len(got) != 1 || got["q1"].State != wire.QuestionAnswered || got["q1"].Text != "An answer." { |
| + t.Fatalf("after the verified exit: ran %d, reports %+v", ran, got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A running question a previous process left with a namespace whose exit |
| +// is unproven is held, not reported, until a probe verifies it. |
| +func TestRecoverAsksHoldsUnprovenNamespaces(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + a := askRow{AskCommand: wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q1", Attempt: 1}} |
| + if err := s.AcceptAsk(ctx, "c1", a.AskCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.setAskNamespace(ctx, a, "ns-gone") |
| + ok := false |
| + e := &StepEngine{State: s, Notify: func() {}, Verify: func(context.Context, string) bool { return ok }} |
| + if err := s.RecoverAsks(ctx, e.Verify); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := outboxAnswers(t, s); len(got) != 0 { |
| + t.Fatalf("reported without proof: %+v", got) |
| + } |
| + ok = true |
| + e.Probe(ctx) |
| + if got := outboxAnswers(t, s); got["q1"].Reason != "runner_restarted" { |
| + t.Fatalf("after proof: %+v", got) |
| + } |
| +} |
| + |
| +// Astra 4b round 1, finding 3: if the final report cannot be saved the |
| +// answer is kept and saved again; the provider runs exactly once. |
| +func TestAskReportPersistedWithoutRerun(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + var fails atomic.Int32 |
| + fails.Store(3) |
| + s.fault = func(op string) error { |
| + if op == "finish_ask" && fails.Add(-1) >= 0 { |
| + return errors.New("injected: database busy") |
| + } |
| + return nil |
| + } |
| + var runs atomic.Int32 |
| + e := &StepEngine{State: s, Notify: func() {}, Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) askResult { |
| + runs.Add(1) |
| + return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "Once."}, Terminated: true} |
| + }} |
| + runAsk(t, s, e, "q1") |
| + if n := runs.Load(); n != 1 { |
| + t.Fatalf("the provider ran %d times", n) |
| + } |
| + if got := outboxAnswers(t, s); got["q1"].Text != "Once." { |
| + t.Fatalf("the answer was lost: %+v", got) |
| + } |
| +} |
diff --git a/internal/runner/thin/ask_test.go b/internal/runner/thin/ask_test.go| index a03dd08b..56f59893 100644 |
| --- a/internal/runner/thin/ask_test.go |
| +++ b/internal/runner/thin/ask_test.go |
| @@ -193,14 +193,14 @@ func TestAskQueuesWithSteps(t *testing.T) { |
| stepping = false |
| mu.Unlock() |
| return wire.StepReport{State: wire.StepDone, Termination: true} |
| - }, Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) wire.AnswerReport { |
| + }, Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) askResult { |
| mu.Lock() |
| defer mu.Unlock() |
| if stepping { |
| t.Error("a question ran beside a step") |
| } |
| order = append(order, a.QuestionID) |
| - return wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "ok"} |
| + return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "ok"}, Terminated: true} |
| }} |
| cctx, cancel := context.WithCancel(ctx) |
| defer cancel() |
| @@ -271,7 +271,7 @@ func TestRecoverAsks(t *testing.T) { |
| if err := s.AcceptAsk(ctx, "c1", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q_1", Attempt: 1}); err != nil { |
| t.Fatal(err) |
| } |
| - if err := s.RecoverAsks(ctx); err != nil { |
| + if err := s.RecoverAsks(ctx, nil); err != nil { |
| t.Fatal(err) |
| } |
| if _, ok, _ := s.nextAsk(ctx); ok { |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index f06a5d3f..e8e4af72 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -399,6 +399,9 @@ type specialistRun struct { |
| stream *answerStream |
| limit time.Duration |
| noLog bool |
| + // record keeps the namespace the run started in, against its own |
| + // attempt (a step's, or a question's); nil records the step's. |
| + record func(ctx context.Context, nsID string) error |
| } |
| // stepResult is how the specialist's process ended. session is the |
| @@ -476,7 +479,11 @@ func (e *Engineer) run(ctx context.Context, r stepRow, tree workspace.TaskTree, |
| e.log("step start", err) |
| return stepResult{reason: "policy_rejected", terminated: true} |
| } |
| - if err := e.O.State.setStepNamespace(context.WithoutCancel(ctx), r, proc.ID()); err != nil { |
| + record := spec.record |
| + if record == nil { |
| + record = func(ctx context.Context, id string) error { return e.O.State.setStepNamespace(ctx, r, id) } |
| + } |
| + if err := record(context.WithoutCancel(ctx), proc.ID()); err != nil { |
| e.log("step namespace", err) |
| } |
| // exited carries Wait's verdict: nil only when the containment |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index 3559731c..8d3825ab 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -32,6 +32,8 @@ const ( |
| type State struct { |
| db *sql.DB |
| prefix string |
| + // fault, in tests, fails the named write ("finish_ask") on demand. |
| + fault func(op string) error |
| } |
| const schema = ` |
| @@ -64,6 +66,14 @@ func OpenState(ctx context.Context, dir string) (*State, error) { |
| return nil, err |
| } |
| } |
| + // Added in slice 4b review: a question's namespace, its held final |
| + // report, and whether its provider started. |
| + for _, col := range []string{"ns_id TEXT NOT NULL DEFAULT ''", "final TEXT NOT NULL DEFAULT ''", "started INTEGER NOT NULL DEFAULT 0"} { |
| + if _, err = d.ExecContext(ctx, "ALTER TABLE asks ADD COLUMN "+col); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + d.Close() |
| + return nil, err |
| + } |
| + } |
| // Added in slice 3 review: a step's namespace and the ending it |
| // reported while its termination is still to be proven. |
| // Added in slice 4 review: the task branch head last reported. |
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go| index a871dbde..ad1c0103 100644 |
| --- a/internal/runner/thin/step.go |
| +++ b/internal/runner/thin/step.go |
| @@ -330,12 +330,25 @@ func (e *StepEngine) Probe(ctx context.Context) { |
| if e.Verify == nil { |
| return |
| } |
| + sent := false |
| + // Questions held for their namespace's proof are released once it is |
| + // verified. |
| + held, err := e.State.heldAsks(ctx) |
| + if err != nil { |
| + e.log("ask probe", err) |
| + } |
| + for _, h := range held { |
| + if h.ns != "" && !e.Verify(ctx, h.ns) { |
| + continue |
| + } |
| + e.log("ask probe", e.State.releaseAsk(ctx, h)) |
| + sent = true |
| + } |
| pending, err := e.State.pendingSteps(ctx) |
| if err != nil { |
| e.log("step probe", err) |
| return |
| } |
| - sent := false |
| for _, p := range pending { |
| if !e.Verify(ctx, p.ns) { |
| continue |
| @@ -353,7 +366,7 @@ func (e *StepEngine) Start(ctx context.Context) error { |
| if err := e.State.RecoverSteps(ctx, e.Verify); err != nil { |
| return err |
| } |
| - if err := e.State.RecoverAsks(ctx); err != nil { |
| + if err := e.State.RecoverAsks(ctx, e.Verify); err != nil { |
| return err |
| } |
| e.Probe(ctx) |
| @@ -479,21 +492,38 @@ func (e *StepEngine) askOne(ctx context.Context, a askRow) { |
| if e.State.askCancelled(ctx, a) { |
| cancel() |
| } |
| - rep := e.Ask(actx, a, func(p wire.AnswerReport) { |
| + // Started, durably, before the provider runs: never run twice. |
| + if err := e.State.startAsk(ctx, a); err != nil { |
| + e.log("ask start", err) |
| + return |
| + } |
| + res := e.Ask(actx, a, func(p wire.AnswerReport) { |
| p.State = wire.QuestionRunning |
| report(p) |
| }) |
| - if ctx.Err() != nil { |
| - // Shutting down: the next start ends it (runner_restarted). |
| - return |
| - } |
| + rep := res.Report |
| if actx.Err() != nil && rep.State != wire.QuestionAnswered { |
| rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" |
| } |
| if !wire.QuestionTerminal(rep.State) { |
| rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" |
| } |
| - report(rep) |
| + // The result is kept in memory until it is saved: a failed write is |
| + // tried again, never the provider. Shutting down before then, the |
| + // next start ends the attempt (runner_restarted). |
| + for i := 0; ; i++ { |
| + err := e.State.FinishAsk(context.WithoutCancel(ctx), a, rep, res.Terminated) |
| + if err == nil { |
| + break |
| + } |
| + e.log("answer report", err) |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-time.After(min(time.Duration(i+1)*100*time.Millisecond, 5*time.Second)): |
| + } |
| + } |
| + e.Notify() |
| } |
| func (e *StepEngine) runOne(ctx context.Context, r stepRow) { |