headless: hosted drill modes, checks-started barrier, bounded ends
Astra p34-r1 finding 10. hosted-slow takes a drill mode (plain, kill-proxy, stop-vm, withdraw-cert, controller-reboot) from EQUIPO_STAGING_HOSTED_MODE or suite's mode=<m>; each mode's expected result lines and job ends come from the chain test of the same fault, and the report records mode, expected and matched. The scenarios append HOSTED-START, HOSTED-TASK, HOSTED-BARRIER and HOSTED-END lines to a progress file the drill watches. The barrier is the checks step first running on a hosted runner, with that runner's job (attempt, VM, launch) from the database copy and a strike window. Every wait is bounded and each scenario ends with a status (ok, no_checks, no_vm, timed_out, missed_window); staging-thin.py always ends with HOSTED-SUITE status=ok|suite_failed|report_missing and keeps each run's report and progress apart under reports/.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+574
−47
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+34 −0internal/headless/hosted_fixture_test.go+117 −11internal/headless/hosted_test.go+282 −25scripts/staging-thin-test.py+50 −4scripts/staging-thin.py+90 −6
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 1fe53609..17dde392 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -75,7 +75,7 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only |
| perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen. |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally). |
| -size internal/headless - 14173 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files; restart wait; live site waits; card answer; scenario 7; Mac M9, mixed versions; 13400. Hosted slice 2: the dev drill's four hosted checks scenarios, their scratch project and its offline checks; 14173. |
| +size internal/headless - 14536 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files; restart wait; live site waits; card answer; scenario 7; Mac M9, mixed versions; 13400. Hosted slice 2: the dev drill's four hosted checks scenarios, their scratch project and its offline checks; drill modes, the checks-started barrier and bounded ends; 14536. |
| size internal/thintest - 42664 Protocol 31 to 38 contracts, Design end to end; hosted slice 2 Task 26: protocol 39 and 40 rows, older primaries' Research ends runner_update_needed; 42664. |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 0b42af39..261b038e 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -3564,3 +3564,37 @@ Mutation checks, each restored: |
| FAILED its `AssertionError` on the file name. |
| - **H6** the setting always saved at revision 0: `TestHostedSettingRoute` FAILED `saving the hosted |
| setting ...: 409 {}` on the second save. |
| + |
| +### Astra p34-r1 finding 10: barrier, modes, bounded ends, kept reports |
| + |
| +- **Barrier.** The scenarios watch for the first checks step to show `running` on a runner. A hosted |
| + VM's runner reports that only once the pack and bundle have arrived, straight before it checks the |
| + modules and starts the gate (`Worker.hosted`). The product has no signal for the gate's own start. |
| + On that signal the scenario reads the runner's hosted job (attempt, VM, launch) from the database |
| + copy, waiting up to 90 s. It then appends a `HOSTED-BARRIER` line to |
| + `EQUIPO_STAGING_HOSTED_PROGRESS`, with a strike window of 30 to 200 s after the barrier. |
| +- **Modes.** `EQUIPO_STAGING_HOSTED_MODE`, or `suite ... mode=<m>`, takes `plain`, `kill-proxy`, |
| + `stop-vm`, `withdraw-cert` or `controller-reboot`. Only `hosted-slow` takes a drill mode. |
| + `hostedExpected` holds each mode's expected result lines and job ends, taken from the chain test of |
| + the same fault. The report records `mode`, `expected` and `matched`. |
| +- **Ends.** Each scenario ends with `HOSTED-END status=ok|no_checks|no_vm|timed_out|missed_window`, |
| + bounded at 30 minutes to the barrier and 42 minutes to the end. Every `carlos db query` is bounded |
| + to 1 minute. `staging-thin.py` always ends with |
| + `HOSTED-SUITE status=ok|suite_failed|report_missing report=<kept|->`. |
| +- **Kept reports.** Each run is kept under `reports/` as `report-<scenarios>-<mode>-<n>.json` and |
| + `progress-<scenarios>-<mode>-<n>.log`. |
| + |
| +Green: `go test ./internal/headless -run '^(TestHosted.*|TestStaging)$'`, |
| +`-run '^TestHeadless$/^hosted'` (four skips), `go vet`, `scripts/staging-thin-test.py` (17), |
| +`make budget` (`internal/headless` 14536). |
| + |
| +Mutation checks, each restored: |
| +- **H7** `missed_window` without its `strike_after` test: `TestHostedStatus` FAILED `{mode:stop-vm |
| + ... want:missed_window}: ok, want missed_window`. |
| +- **H8** `matched` without the job ends: `TestHostedModes` FAILED `a retry after another fault |
| + matched stop-vm`. |
| +- **H9** `run_status` without `started`: the first version, run before the guard existed. |
| + `test_fresh_runs_and_green_record` FAILED, element 7 `status=report_missing` against |
| + `status=suite_failed`, for a refused mode. |
| +- **H10** a drill mode allowed on any scenario: `TestHostedGate` FAILED `a drill mode on a check: |
| + skip "" fail ""`. |
diff --git a/internal/headless/hosted_fixture_test.go b/internal/headless/hosted_fixture_test.go| index b780f774..293c8511 100644 |
| --- a/internal/headless/hosted_fixture_test.go |
| +++ b/internal/headless/hosted_fixture_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "regexp" |
| "slices" |
| "strings" |
| "testing" |
| @@ -53,25 +54,109 @@ func TestHostedScenariosRegistered(t *testing.T) { |
| func TestHostedGate(t *testing.T) { |
| for _, c := range []struct { |
| - live bool |
| - only, repo, cookie string |
| - skip, fail bool |
| - why string |
| + live bool |
| + name, only, repo, cookie string |
| + mode string |
| + skip, fail bool |
| + why string |
| }{ |
| - {false, "hosted-pass", "oficina/scratch", "/c", true, false, "a local run"}, |
| - {true, "", "oficina/scratch", "/c", true, false, "a whole staging run"}, |
| - {true, "hosted-fail", "oficina/scratch", "/c", true, false, "another scenario named"}, |
| - {true, "hosted-pass", "", "/c", false, true, "no scratch project"}, |
| - {true, "hosted-pass", "oficina/scratch", "", false, true, "no session"}, |
| - {true, "2_project,hosted-pass", "oficina/scratch", "/c", false, false, "named, with both"}, |
| + {false, "hosted-pass", "hosted-pass", "oficina/scratch", "/c", "plain", true, false, "a local run"}, |
| + {true, "hosted-pass", "", "oficina/scratch", "/c", "plain", true, false, "a whole staging run"}, |
| + {true, "hosted-pass", "hosted-fail", "oficina/scratch", "/c", "plain", true, false, "another scenario named"}, |
| + {true, "hosted-pass", "hosted-pass", "", "/c", "plain", false, true, "no scratch project"}, |
| + {true, "hosted-pass", "hosted-pass", "oficina/scratch", "", "plain", false, true, "no session"}, |
| + {true, "hosted-pass", "2_project,hosted-pass", "oficina/scratch", "/c", "plain", false, false, "named, with both"}, |
| + {true, "hosted-pass", "hosted-pass", "oficina/scratch", "/c", "stop-vm", false, true, "a drill mode on a check"}, |
| + {true, "hosted-slow", "hosted-slow", "oficina/scratch", "/c", "stop-vm", false, false, "a drill mode on the slow scenario"}, |
| + {true, "hosted-slow", "hosted-slow", "oficina/scratch", "/c", "reboot", false, true, "an unknown mode"}, |
| } { |
| - skip, fail := hostedGate(c.live, "hosted-pass", c.only, c.repo, c.cookie) |
| + skip, fail := hostedGate(c.live, c.name, c.only, c.repo, c.cookie, c.mode) |
| if (skip != "") != c.skip || (fail != "") != c.fail { |
| t.Errorf("%s: skip %q fail %q", c.why, skip, fail) |
| } |
| } |
| } |
| +// TestHostedModes: every scenario runs plain, hosted-slow runs every |
| +// drill mode, nothing else runs, and each expectation's results are lines |
| +// Line can write. |
| +func TestHostedModes(t *testing.T) { |
| + line := regexp.MustCompile(`^state=\S+ checks=\S+ reason=\S+ shown=\S+ sandbox=\S+ certified=(yes|no) base_checks=(trusted|none|other|unknown) jobs=([0-9]+|unknown)$`) |
| + for _, c := range hostedCases { |
| + for _, mode := range append(hostedModes, "", "reboot") { |
| + e, ok := hostedExpected(c.name, mode) |
| + if want := mode == "plain" || c.name == "hosted-slow" && slices.Contains(hostedModes, mode); ok != want { |
| + t.Errorf("%s under %q: expectation %v", c.name, mode, ok) |
| + } |
| + if !ok { |
| + continue |
| + } |
| + regexp.MustCompile(e.JobEnds) |
| + for _, r := range e.Results { |
| + if !line.MatchString(r) { |
| + t.Errorf("%s/%s expects %q, which no outcome writes", c.name, mode, r) |
| + } |
| + } |
| + } |
| + } |
| + e, _ := hostedExpected("hosted-slow", "stop-vm") |
| + base := strings.Repeat("b", 40) |
| + retried := hostedOutcome{State: "done", Checks: "passed", Sandbox: "bubblewrap", BaseSHA: base, Recorded: true, BaseChecksSHA: base, Jobs: 2, JobEnds: "failed:hosted_vm_lost,ended:step_ended"} |
| + if !e.matched(retried) { |
| + t.Fatalf("stop-vm's own outcome does not match: %s %s", retried.Line(), retried.JobEnds) |
| + } |
| + once := retried |
| + once.Jobs, once.JobEnds = 1, "ended:step_ended" |
| + if e.matched(once) { |
| + t.Fatal("a stop-vm run with no retry matched: the VM was never stopped") |
| + } |
| + otherFault := retried |
| + otherFault.JobEnds = "failed:hosted_unavailable,ended:step_ended" |
| + if e.matched(otherFault) { |
| + t.Fatal("a retry after another fault matched stop-vm") |
| + } |
| + unread := retried |
| + unread.Recorded = false |
| + if e.matched(unread) { |
| + t.Fatal("matched without the database copy's jobs") |
| + } |
| +} |
| + |
| +func TestHostedStatus(t *testing.T) { |
| + at := time.Date(2026, 12, 2, 10, 0, 0, 0, time.UTC) |
| + b := newBarrier(at, "s1", "r1") |
| + for _, c := range []struct { |
| + mode string |
| + checks, ended bool |
| + b *hostedBarrier |
| + endedAt time.Time |
| + want string |
| + }{ |
| + {"plain", false, false, nil, at, "no_checks"}, |
| + {"plain", true, false, nil, at, "no_vm"}, |
| + {"withdraw-cert", true, false, &b, at, "timed_out"}, |
| + {"plain", true, true, nil, at, "ok"}, |
| + {"stop-vm", true, true, nil, at, "missed_window"}, |
| + {"stop-vm", true, true, &b, at.Add(10 * time.Second), "missed_window"}, |
| + {"stop-vm", true, true, &b, at.Add(5 * time.Minute), "ok"}, |
| + } { |
| + if got := hostedStatus(c.mode, c.checks, c.ended, c.b, c.endedAt); got != c.want { |
| + t.Errorf("%+v: %s, want %s", c, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +func TestHostedBarrierLine(t *testing.T) { |
| + b := newBarrier(time.Date(2026, 12, 2, 10, 0, 0, 0, time.UTC), "s1", "r1") |
| + if got, want := b.Line("hosted-slow", "stop-vm", "tk1"), "HOSTED-BARRIER name=hosted-slow mode=stop-vm task=tk1 step=s1 runner=r1 attempt=unknown vm=unknown launch=unknown at=2026-12-02T10:00:00Z strike_after=2026-12-02T10:00:30Z strike_before=2026-12-02T10:03:20Z"; got != want { |
| + t.Fatalf("\n got %s\nwant %s", got, want) |
| + } |
| + b.Attempt, b.VM, b.Launch = "hj-1", "vm-1", "l-1" |
| + if got := b.Line("hosted-slow", "stop-vm", "tk1"); !strings.Contains(got, " attempt=hj-1 vm=vm-1 launch=l-1 ") { |
| + t.Fatalf("ids: %s", got) |
| + } |
| +} |
| + |
| func TestHostedResultLine(t *testing.T) { |
| base := strings.Repeat("b", 40) |
| for _, c := range []struct { |
| @@ -116,6 +201,7 @@ func TestHostedRecordQuery(t *testing.T) { |
| {"INSERT INTO hosted_jobs(attempt_id, step_id, step_attempt, task_id, state, stop_reason, admitted_at, revision) VALUES ('j2', 's1', 1, 'tk1', 'ended', '', ?, 1)", []any{now}}, |
| {"INSERT INTO hosted_jobs(attempt_id, step_id, step_attempt, task_id, state, stop_reason, admitted_at, revision) VALUES ('j1', 's1', 1, 'tk1', 'failed', 'uncertified', ?, 1)", []any{now.Add(-time.Minute)}}, |
| {"INSERT INTO hosted_jobs(attempt_id, step_id, step_attempt, task_id, state, admitted_at, revision) VALUES ('j3', 'other', 1, 'tk2', 'enrolled', ?, 1)", []any{now}}, |
| + {"INSERT INTO hosted_jobs(attempt_id, step_id, step_attempt, task_id, state, admitted_at, revision, runner_id, vm_ref, launch_id) VALUES ('hj-live', 's2', 1, 'tk3', 'enrolled', ?, 1, 'r_vm1', 'mvm-0abc', 'l-9')", []any{now}}, |
| } { |
| if _, err := inst.DB.Writer().Exec(q.sql, q.args...); err != nil { |
| t.Fatal(err) |
| @@ -140,6 +226,26 @@ func TestHostedRecordQuery(t *testing.T) { |
| if _, ok := hostedQuery(bad); ok { |
| t.Fatalf("step id %q put in the query", bad) |
| } |
| + if _, ok := hostedJobQuery("s2", bad); ok { |
| + t.Fatalf("runner id %q put in the query", bad) |
| + } |
| + } |
| + // The barrier's job: the one whose runner runs the step. |
| + jq, ok := hostedJobQuery("s2", "r_vm1") |
| + if !ok { |
| + t.Fatal("plain ids refused") |
| + } |
| + if err := inst.DB.Writer().QueryRow(jq).Scan(&row); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := newBarrier(now, "s2", "r_vm1") |
| + if m := hostedJobRow.FindStringSubmatch("result\n" + row + "\n"); m == nil || m[1] != "hj-live" || m[2] != "mvm-0abc" || m[3] != "l-9" || m[4] != "r_vm1" { |
| + t.Fatalf("job row %q: %v", row, m) |
| + } else { |
| + b.Attempt, b.VM, b.Launch = m[1], m[2], m[3] |
| + } |
| + if !strings.Contains(b.Line("hosted-slow", "plain", "tk3"), " attempt=hj-live vm=mvm-0abc launch=l-9 ") { |
| + t.Fatal(b.Line("hosted-slow", "plain", "tk3")) |
| } |
| } |
diff --git a/internal/headless/hosted_test.go b/internal/headless/hosted_test.go| index 4f549ea7..2d868240 100644 |
| --- a/internal/headless/hosted_test.go |
| +++ b/internal/headless/hosted_test.go |
| @@ -10,6 +10,7 @@ import ( |
| "os" |
| "os/exec" |
| "regexp" |
| + "slices" |
| "strconv" |
| "strings" |
| "testing" |
| @@ -25,13 +26,18 @@ import ( |
| // (EQUIPO_STAGING_HOSTED_PROJECT, a repository whose default branch is |
| // hostedFixture), turns on "Run checks on a hosted machine" for it through |
| // the owners' setting, and asks for one change. Each scenario waits for |
| -// the task's first checks step to end, records what it saw (Witness, so |
| -// the suite's report.json has it) and prints one HOSTED-RESULT line, then |
| -// cancels the task so no fix round or review starts another paid VM. |
| +// the task's first checks step to run on a hosted VM (the barrier, which |
| +// the drill strikes after) and then to end, records what it saw (Witness, |
| +// so the suite's report.json has it) and prints one HOSTED-RESULT line, |
| +// then cancels the task so no fix round or review starts another paid VM. |
| +// As it goes it appends HOSTED-START, HOSTED-TASK, HOSTED-BARRIER and |
| +// HOSTED-END lines to EQUIPO_STAGING_HOSTED_PROGRESS, which the drill |
| +// watches. EQUIPO_STAGING_HOSTED_MODE names the drill (hostedExpected). |
| // |
| -// The outcome is an observation, not an assertion: the drill compares it |
| -// with what it expects (ops fact), and its drills expect a step that does |
| -// not pass. A scenario fails only when it cannot get to a result. |
| +// The outcome is an observation, not an assertion: the report carries |
| +// what the mode expects and whether it matched, and the drill decides. |
| +// A scenario fails only when it gets no result (no_checks, no_vm, |
| +// timed_out), after recording what it has. Every wait is bounded. |
| // hostedRepoEnv names the scratch project's repository. |
| const hostedRepoEnv = "EQUIPO_STAGING_HOSTED_PROJECT" |
| @@ -109,6 +115,66 @@ var hostedCases = []hostedCase{ |
| map[string]string{"sleep.txt": "240\n"}}, |
| } |
| +// hostedModeEnv is the drill a hosted scenario runs under: plain (no |
| +// fault) or one the drill strikes while the checks run. Only hosted-slow |
| +// takes a drill mode. |
| +const hostedModeEnv = "EQUIPO_STAGING_HOSTED_MODE" |
| + |
| +var hostedModes = []string{"plain", "kill-proxy", "stop-vm", "withdraw-cert", "controller-reboot"} |
| + |
| +// The result lines the expectations name. |
| +const ( |
| + hostedPassed = "state=done checks=passed reason=- shown=- sandbox=bubblewrap certified=yes base_checks=trusted jobs=1" |
| + hostedRetried = "state=done checks=passed reason=- shown=- sandbox=bubblewrap certified=yes base_checks=trusted jobs=2" |
| +) |
| + |
| +// hostedExpect is what a scenario under a mode should end with: one of |
| +// Results, and its jobs' ends (state:stop_reason in admission order) |
| +// matching JobEnds. Each is the hostedtest chain test of the same fault. |
| +type hostedExpect struct { |
| + Results []string `json:"results"` |
| + JobEnds string `json:"job_ends"` |
| +} |
| + |
| +func hostedExpected(name, mode string) (hostedExpect, bool) { |
| + switch name + "/" + mode { |
| + case "hosted-pass/plain", "hosted-slow/plain": |
| + // TestChainHostedCheckPasses. |
| + return hostedExpect{[]string{hostedPassed}, `^ended:step_ended$`}, true |
| + case "hosted-fail/plain": |
| + // TestChainFailingCheck. |
| + return hostedExpect{[]string{"state=done checks=failed reason=- shown=- sandbox=bubblewrap certified=yes base_checks=none jobs=1"}, `^ended:step_ended$`}, true |
| + case "hosted-new-module/plain": |
| + // TestChainNewModule. |
| + return hostedExpect{[]string{"state=done checks=cannot_run reason=deps_new_module shown=needs_network sandbox=none certified=no base_checks=none jobs=1"}, `^ended:step_ended$`}, true |
| + case "hosted-slow/kill-proxy": |
| + // TestChainKillProxyMidStep: the runner fails over to the other |
| + // proxy; the same VM's result arrives, certified. |
| + return hostedExpect{[]string{hostedPassed}, `^ended:step_ended$`}, true |
| + case "hosted-slow/stop-vm": |
| + // TestChainStopVMMidStep: the job fails hosted_vm_lost, one retry |
| + // on a new VM passes. |
| + return hostedExpect{[]string{hostedRetried}, `^failed:hosted_vm_lost,ended:step_ended$`}, true |
| + case "hosted-slow/controller-reboot": |
| + // TestChainKillControllerMidStep: a reboot inside the feed's life |
| + // passes on the first VM; past it, the job fails |
| + // hosted_unavailable and one retry passes. |
| + return hostedExpect{[]string{hostedPassed, hostedRetried}, `^(ended:step_ended|failed:hosted_unavailable,ended:step_ended)$`}, true |
| + case "hosted-slow/withdraw-cert": |
| + // TestChainCertWithdrawnMidStep: the result is not kept, the job |
| + // fails uncertified (hosted_unavailable if the feed was lost), the |
| + // step is placed once more, nothing launches, and after the launch |
| + // window it ends not run. |
| + return hostedExpect{[]string{"state=done checks=cannot_run reason=hosted_unavailable shown=hosted_unavailable sandbox=none certified=no base_checks=none jobs=2"}, `^failed:(uncertified|hosted_unavailable),failed:[a-z_]+$`}, true |
| + } |
| + return hostedExpect{}, false |
| +} |
| + |
| +// matched reports whether o ended as e expects. |
| +func (e hostedExpect) matched(o hostedOutcome) bool { |
| + return o.Recorded && slices.Contains(e.Results, o.Line()) && regexp.MustCompile(e.JobEnds).MatchString(o.JobEnds) |
| +} |
| + |
| // hostedScenario reports whether name is a hosted scenario. |
| func hostedScenario(name string) bool { |
| _, ok := hostedCaseNamed(name) |
| @@ -132,10 +198,11 @@ func selected(only, name string) bool { |
| // hostedGate says why a hosted scenario does not run here (skip) or |
| // cannot (fail): only against staging, only when named (each launches |
| -// paid VMs, so a whole-suite run never starts one), and only with the |
| -// scratch project and the suite person's session. |
| -func hostedGate(live bool, name, only, repo, cookieFile string) (skip, fail string) { |
| - switch { |
| +// paid VMs, so a whole-suite run never starts one), only with the |
| +// scratch project and the suite person's session, and only under a mode |
| +// it has an expectation for (a drill mode is hosted-slow's alone). |
| +func hostedGate(live bool, name, only, repo, cookieFile, mode string) (skip, fail string) { |
| + switch _, known := hostedExpected(name, mode); { |
| case !live: |
| return "staging only: hosted checks need the controller and a hosted VM", "" |
| case only == "" || !selected(only, name): |
| @@ -144,10 +211,20 @@ func hostedGate(live bool, name, only, repo, cookieFile string) (skip, fail stri |
| return "", hostedRepoEnv + " is not set" |
| case cookieFile == "": |
| return "", "EQUIPO_STAGING_COOKIE_FILE is not set" |
| + case !known: |
| + return "", fmt.Sprintf("%s does not run under %s=%q (modes %v; drill modes are hosted-slow's)", name, hostedModeEnv, mode, hostedModes) |
| } |
| return "", "" |
| } |
| +// hostedMode is the mode from the environment; empty is plain. |
| +func hostedMode() string { |
| + if m := os.Getenv(hostedModeEnv); m != "" { |
| + return m |
| + } |
| + return "plain" |
| +} |
| + |
| // hostedOutcome is what a hosted scenario saw of its checks step: the |
| // step and the task's shown reason from the person API, and from the |
| // instance's database copy (Recorded) the base checks SHA, the step's |
| @@ -257,8 +334,8 @@ func hostedRecord(t *testing.T, step, state string) hostedOutcome { |
| var last hostedOutcome |
| deadline := time.Now().Add(5 * time.Minute) |
| for { |
| - out, err := exec.Command("/bin/sh", "-c", command+` "$1"`, "sh", q).CombinedOutput() |
| - got, o, ok := parseHostedRow(string(out)) |
| + out, err := dbQuery(command, q) |
| + got, o, ok := parseHostedRow(out) |
| if err == nil && ok && got == state { |
| last = o |
| if jobsSettled(o.JobEnds) { |
| @@ -266,7 +343,7 @@ func hostedRecord(t *testing.T, step, state string) hostedOutcome { |
| } |
| } |
| if time.Now().After(deadline) { |
| - t.Logf("hosted record: the database copy shows step %s as %q (want %s), jobs %q: %v %s", step, got, state, last.JobEnds, err, clipText(string(out), 300)) |
| + t.Logf("hosted record: the database copy shows step %s as %q (want %s), jobs %q: %v %s", step, got, state, last.JobEnds, err, clipText(out, 300)) |
| return last |
| } |
| time.Sleep(15 * time.Second) |
| @@ -386,18 +463,169 @@ func engineeringStopped(c *thintest.Conversation, task string) bool { |
| return wire.StepTerminal(st.State) && st.State != wire.StepDone |
| } |
| -// scenarioHosted is the hosted scenario name (hostedCases). |
| +// hostedProgress appends one line to the progress file the drill watches |
| +// while the suite runs (EQUIPO_STAGING_HOSTED_PROGRESS), and logs it. |
| +func hostedProgress(t *testing.T, format string, args ...any) { |
| + t.Helper() |
| + line := fmt.Sprintf(format, args...) |
| + t.Log(line) |
| + path := os.Getenv("EQUIPO_STAGING_HOSTED_PROGRESS") |
| + if path == "" { |
| + return |
| + } |
| + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) |
| + if err != nil { |
| + t.Logf("progress file: %v", err) |
| + return |
| + } |
| + defer f.Close() |
| + if _, err := fmt.Fprintln(f, line); err != nil { |
| + t.Logf("progress file: %v", err) |
| + } |
| +} |
| + |
| +func stamp(at time.Time) string { return at.UTC().Format(time.RFC3339) } |
| + |
| +// The drill's strike window after the barrier: go test builds the |
| +// package before TestSleep starts its 240 s, so a strike waits |
| +// hostedStrikeAfter, and lands by hostedStrikeBefore to leave the test |
| +// running when the fault arrives. |
| +const ( |
| + hostedStrikeAfter = 30 * time.Second |
| + hostedStrikeBefore = 200 * time.Second |
| +) |
| + |
| +// hostedBarrier is the checks-started barrier: when the checks step was |
| +// first seen running on a runner. A hosted VM's runner says running only |
| +// once the step's pack and dependency bundle have arrived, straight |
| +// before it checks the modules and starts the gate (Worker.hosted); no |
| +// signal marks the gate's own start. Attempt, VM and Launch are that |
| +// runner's hosted job, from the database copy ("" when it never showed). |
| +type hostedBarrier struct { |
| + At time.Time `json:"at"` |
| + Step string `json:"step"` |
| + Runner string `json:"runner"` |
| + Attempt string `json:"attempt"` |
| + VM string `json:"vm"` |
| + Launch string `json:"launch"` |
| + StrikeAfter time.Time `json:"strike_after"` |
| + StrikeBefore time.Time `json:"strike_before"` |
| +} |
| + |
| +func newBarrier(at time.Time, step, runner string) hostedBarrier { |
| + return hostedBarrier{At: at, Step: step, Runner: runner, StrikeAfter: at.Add(hostedStrikeAfter), StrikeBefore: at.Add(hostedStrikeBefore)} |
| +} |
| + |
| +// Line is the barrier as the progress file has it. |
| +func (b hostedBarrier) Line(name, mode, task string) string { |
| + unknown := func(s string) string { |
| + if s == "" { |
| + return "unknown" |
| + } |
| + return s |
| + } |
| + return fmt.Sprintf("HOSTED-BARRIER name=%s mode=%s task=%s step=%s runner=%s attempt=%s vm=%s launch=%s at=%s strike_after=%s strike_before=%s", |
| + name, mode, task, b.Step, b.Runner, unknown(b.Attempt), unknown(b.VM), unknown(b.Launch), stamp(b.At), stamp(b.StrikeAfter), stamp(b.StrikeBefore)) |
| +} |
| + |
| +var hostedJobRow = regexp.MustCompile(`(?m)^job=([A-Za-z0-9_.:-]+) vm=(\S*) launch=(\S*) runner=(\S*)\s*$`) |
| + |
| +// hostedJobQuery is the database copy's row for the hosted job whose |
| +// runner runs step. Only plain ids are ever put in it. |
| +func hostedJobQuery(step, runner string) (string, bool) { |
| + if !hostedStepID.MatchString(step) || !hostedStepID.MatchString(runner) { |
| + return "", false |
| + } |
| + return "SELECT 'job=' || attempt_id || ' vm=' || coalesce(vm_ref, '') || ' launch=' || coalesce(launch_id, '') || ' runner=' || coalesce(runner_id, '') FROM hosted_jobs WHERE step_id = '" + step + "' AND runner_id = '" + runner + "'", true |
| +} |
| + |
| +// dbQuery runs one SQL statement through EQUIPO_STAGING_DB_QUERY, bounded. |
| +func dbQuery(command, q string) (string, error) { |
| + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| + defer cancel() |
| + out, err := exec.CommandContext(ctx, "/bin/sh", "-c", command+` "$1"`, "sh", q).CombinedOutput() |
| + return string(out), err |
| +} |
| + |
| +// hostedJobOf reads the barrier's job from the database copy, waiting up |
| +// to 90 s for the copy to show it. |
| +func hostedJobOf(t *testing.T, b *hostedBarrier) { |
| + t.Helper() |
| + command := os.Getenv("EQUIPO_STAGING_DB_QUERY") |
| + q, ok := hostedJobQuery(b.Step, b.Runner) |
| + if command == "" || !ok { |
| + t.Logf("barrier job: not read (query command set %v, ids plain %v)", command != "", ok) |
| + return |
| + } |
| + deadline := time.Now().Add(90 * time.Second) |
| + for { |
| + out, err := dbQuery(command, q) |
| + if m := hostedJobRow.FindStringSubmatch(out); err == nil && m != nil { |
| + b.Attempt, b.VM, b.Launch = m[1], m[2], m[3] |
| + return |
| + } |
| + if time.Now().After(deadline) { |
| + t.Logf("barrier job: the database copy did not show it: %v %s", err, clipText(out, 300)) |
| + return |
| + } |
| + time.Sleep(10 * time.Second) |
| + } |
| +} |
| + |
| +// hostedStatus is how a hosted scenario ended (staging-thin.py adds |
| +// suite_failed and report_missing for the run as a whole): |
| +// |
| +// ok its checks step ended (a drill's after its window opened) |
| +// no_checks no checks step: Engineering stopped without a candidate |
| +// no_vm a checks step that no hosted VM ran within the bound |
| +// timed_out it ran on a VM and had not ended at the bound |
| +// missed_window a drill whose step ended with no barrier seen, or before strike_after |
| +func hostedStatus(mode string, haveChecks, ended bool, b *hostedBarrier, endedAt time.Time) string { |
| + switch { |
| + case !haveChecks: |
| + return "no_checks" |
| + case !ended && b == nil: |
| + return "no_vm" |
| + case !ended: |
| + return "timed_out" |
| + case mode != "plain" && (b == nil || endedAt.Before(b.StrikeAfter)): |
| + return "missed_window" |
| + } |
| + return "ok" |
| +} |
| + |
| +// The bounds: the barrier within 30 minutes of the ask (Engineering's |
| +// change, placement, enrolment within 2 minutes), the end within 42 |
| +// (a 240 s test, and in the drills a retry, or a 10-minute launch window |
| +// and 2 more for its never-launched proof), inside open's 50-minute |
| +// session. |
| +const ( |
| + hostedBarrierBound = 30 * time.Minute |
| + hostedEndBound = 42 * time.Minute |
| +) |
| + |
| +// scenarioHosted is the hosted scenario name (hostedCases), under the |
| +// mode hostedMode gives. |
| func scenarioHosted(name string) func(*testing.T, *Env) { |
| return func(t *testing.T, env *Env) { |
| c, _ := hostedCaseNamed(name) |
| + mode := hostedMode() |
| repo, cookieFile := os.Getenv(hostedRepoEnv), os.Getenv("EQUIPO_STAGING_COOKIE_FILE") |
| - skip, fail := hostedGate(env.Live, name, os.Getenv("EQUIPO_STAGING_SCENARIOS"), repo, cookieFile) |
| + skip, fail := hostedGate(env.Live, name, os.Getenv("EQUIPO_STAGING_SCENARIOS"), repo, cookieFile, mode) |
| if skip != "" { |
| t.Skip(skip) |
| } |
| + // From here every way out writes one HOSTED-END line; a failure |
| + // before the result is the suite's. |
| + task, status, line, matched := "-", "suite_failed", "-", "no" |
| + defer func() { |
| + hostedProgress(t, "HOSTED-END name=%s mode=%s task=%s status=%s matched=%s result=%s", name, mode, task, status, matched, line) |
| + }() |
| + hostedProgress(t, "HOSTED-START name=%s mode=%s at=%s", name, mode, stamp(time.Now())) |
| if fail != "" { |
| t.Fatal(fail) |
| } |
| + expect, _ := hostedExpected(name, mode) |
| raw, err := os.ReadFile(cookieFile) |
| if err != nil { |
| t.Fatalf("the suite person's session: %v", err) |
| @@ -415,12 +643,14 @@ func scenarioHosted(name string) func(*testing.T, *Env) { |
| start := time.Now() |
| sent := s.send(t, fmt.Sprintf(c.ask, repo)) |
| id := s.taskOf(t, sent.Turn.ID) |
| + task = id |
| + hostedProgress(t, "HOSTED-TASK name=%s mode=%s task=%s at=%s", name, mode, id, stamp(time.Now())) |
| hostedAt := -1.0 |
| var checks wire.Step |
| - // Engineering, enrolment within 2 minutes, a 240 s test, and in the |
| - // drills a retry or a 10-minute launch window, inside the session. |
| - // A step still running then is recorded as it stands, then fails. |
| - s.conv.Wait(40*time.Minute, func(c *thintest.Conversation) bool { |
| + var runningAt time.Time |
| + var runner string |
| + // Until the checks step runs on a VM (the barrier) or ends. |
| + s.conv.Wait(hostedBarrierBound, func(c *thintest.Conversation) bool { |
| st, ok := firstChecks(c, id) |
| if !ok { |
| return wire.FinalStage(c.Tasks[id].Stage) || engineeringStopped(c, id) |
| @@ -429,8 +659,29 @@ func scenarioHosted(name string) func(*testing.T, *Env) { |
| hostedAt = time.Since(start).Seconds() |
| } |
| checks = st |
| + if st.State == wire.StepRunning && st.RunnerID != "" && runningAt.IsZero() { |
| + runningAt, runner = time.Now(), st.RunnerID |
| + return true |
| + } |
| return wire.StepTerminal(st.State) || wire.FinalStage(c.Tasks[id].Stage) |
| }) |
| + var barrier *hostedBarrier |
| + if !runningAt.IsZero() { |
| + b := newBarrier(runningAt, checks.ID, runner) |
| + hostedJobOf(t, &b) |
| + barrier = &b |
| + hostedProgress(t, "%s", b.Line(name, mode, id)) |
| + // Until it ends. A step still running then is recorded as it |
| + // stands, then fails. |
| + s.conv.Wait(time.Until(start.Add(hostedEndBound)), func(c *thintest.Conversation) bool { |
| + st, ok := firstChecks(c, id) |
| + if ok { |
| + checks = st |
| + } |
| + return ok && wire.StepTerminal(st.State) || wire.FinalStage(c.Tasks[id].Stage) |
| + }) |
| + } |
| + endedAt := time.Now() |
| ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) |
| defer cancel() |
| k, err := env.Client.Task(ctx, id) |
| @@ -448,13 +699,18 @@ func scenarioHosted(name string) func(*testing.T, *Env) { |
| t.Logf("cancelling %s: %v", id, err) |
| } |
| } |
| + ended := checks.ID != "" && wire.StepTerminal(checks.State) |
| o := hostedOutcome{} |
| - if checks.ID != "" && wire.StepTerminal(checks.State) { |
| + if ended { |
| o = hostedRecord(t, checks.ID, checks.State) |
| } |
| o.State, o.Checks, o.Reason, o.Shown, o.Sandbox, o.BaseSHA = checks.State, checks.Checks, checks.Reason, k.ChecksReason, checks.ChecksSandbox, checks.BaseSHA |
| - line := o.Line() |
| - w := map[string]any{"result": line, "task": id, "stage": k.Stage, "step": checks.ID, "state": checks.State, "checks": checks.Checks, "reason": checks.Reason, |
| + line, status = o.Line(), hostedStatus(mode, checks.ID != "", ended, barrier, endedAt) |
| + if expect.matched(o) { |
| + matched = "yes" |
| + } |
| + w := map[string]any{"result": line, "mode": mode, "status": status, "barrier": barrier, "expected": expect, "matched": matched == "yes", |
| + "task": id, "stage": k.Stage, "step": checks.ID, "state": checks.State, "checks": checks.Checks, "reason": checks.Reason, |
| "checks_reason": k.ChecksReason, "checks_sandbox": checks.ChecksSandbox, "base_sha": checks.BaseSHA, "candidate_sha": checks.CandidateSHA, |
| "base_checks": checks.BaseChecks, "seconds": time.Since(start).Seconds(), "waiting_hosted_s": hostedAt} |
| if o.Recorded { |
| @@ -462,9 +718,10 @@ func scenarioHosted(name string) func(*testing.T, *Env) { |
| } |
| Witness[t.Name()] = w |
| fmt.Printf("HOSTED-RESULT %s %s\n", name, line) |
| - t.Logf("task %s (%s): %s", id, k.Stage, line) |
| - if checks.ID == "" || !wire.StepTerminal(checks.State) { |
| - t.Fatalf("no checks step ended: task %s %s", id, k.Stage) |
| + t.Logf("task %s (%s), %s, matched %s: %s", id, k.Stage, status, matched, line) |
| + switch status { |
| + case "no_checks", "no_vm", "timed_out": |
| + t.Fatalf("%s: task %s %s, checks step %q %s", status, id, k.Stage, checks.ID, checks.State) |
| } |
| } |
| } |
diff --git a/scripts/staging-thin-test.py b/scripts/staging-thin-test.py| index eecd28f4..3d22761b 100644 |
| --- a/scripts/staging-thin-test.py |
| +++ b/scripts/staging-thin-test.py |
| @@ -31,6 +31,7 @@ class SuiteTest(unittest.TestCase): |
| addresses, runs, cleaned, records, enrolled, retired = [], [], [], [], [], [] |
| fail = False |
| report_mode = "valid" |
| + modes = ['plain'] |
| def mail(address, path): |
| staging.private(path, 'cookie') |
| @@ -70,10 +71,16 @@ class SuiteTest(unittest.TestCase): |
| state = Path(running['EQUIPO_RUNNER_STATE_DIR']) |
| self.assertEqual((state / 'person').read_text(), addresses[-1]) |
| self.assertEqual(running['EQUIPO_RUNNER_CREATE_REPOS'], '0') |
| - if fail: |
| - raise RuntimeError('scenario failed') |
| + # The drill's mode and the progress file it watches, |
| + # started fresh for this run. |
| + self.assertEqual(env['EQUIPO_STAGING_HOSTED_MODE'], modes[-1]) |
| + self.assertEqual(env['EQUIPO_STAGING_HOSTED_PROGRESS'], str(root / 'hosted-progress.log')) |
| + self.assertEqual(Path(env['EQUIPO_STAGING_HOSTED_PROGRESS']).read_text().splitlines()[0].split(' at=')[0], |
| + f'HOSTED-SUITE-START scenarios={env["EQUIPO_STAGING_SCENARIOS"] or "all"} mode={modes[-1]}') |
| if report_mode != 'missing': |
| Path(env['EQUIPO_HEADLESS_REPORT']).write_text('{}' if report_mode == 'valid' else 'broken') |
| + if fail: |
| + raise RuntimeError('scenario failed') |
| return '' |
| def enrol(release, env, cookie): |
| @@ -95,20 +102,59 @@ class SuiteTest(unittest.TestCase): |
| patch.object(staging, 'record_running', side_effect=lambda: records.append(True)), \ |
| patch.dict(os.environ, {}, clear=False): |
| os.environ.pop('EQUIPO_STAGING_TURN_LIMIT', None) |
| + os.environ.pop('EQUIPO_STAGING_HOSTED_MODE', None) |
| os.environ['TMPDIR'] = str(root) |
| + ended = [] |
| + |
| + def last(): |
| + ended.append((root / 'hosted-progress.log').read_text().splitlines()[-1].split(' at=')[0]) |
| + |
| staging.suite() |
| + last() |
| staging.suite('2_project') |
| + last() |
| fail = True |
| with self.assertRaisesRegex(RuntimeError, 'scenario failed'): |
| staging.suite() |
| + last() |
| fail = False |
| report_mode = 'missing' |
| with self.assertRaises(FileNotFoundError): |
| staging.suite() |
| + last() |
| report_mode = 'broken' |
| with self.assertRaises(json.JSONDecodeError): |
| staging.suite() |
| - self.assertEqual(len(set(addresses)), 5) |
| + last() |
| + report_mode = 'valid' |
| + modes.append('stop-vm') |
| + staging.suite('hosted-slow', 'stop-vm') |
| + last() |
| + os.environ['EQUIPO_STAGING_HOSTED_MODE'] = 'stop-vm' |
| + staging.suite('hosted-slow') |
| + last() |
| + # An unknown mode starts no suite person, and still ends |
| + # with a status line. |
| + with self.assertRaisesRegex(ValueError, 'is not one of'): |
| + staging.suite('hosted-slow', 'reboot') |
| + last() |
| + kept = root / 'reports' |
| + self.assertEqual(ended, [ |
| + f'HOSTED-SUITE status=ok report={kept}/report-all-plain-1.json', |
| + f'HOSTED-SUITE status=ok report={kept}/report-2_project-plain-1.json', |
| + f'HOSTED-SUITE status=suite_failed report={kept}/report-all-plain-2.json', |
| + 'HOSTED-SUITE status=report_missing report=-', |
| + f'HOSTED-SUITE status=report_missing report={kept}/report-all-plain-4.json', |
| + f'HOSTED-SUITE status=ok report={kept}/report-hosted-slow-stop-vm-1.json', |
| + f'HOSTED-SUITE status=ok report={kept}/report-hosted-slow-stop-vm-2.json', |
| + 'HOSTED-SUITE status=suite_failed report=-']) |
| + # Each run's report and progress kept apart, private. |
| + self.assertEqual(sorted(p.name for p in kept.iterdir() if p.name.startswith('progress-')), |
| + ['progress-2_project-plain-1.log', 'progress-all-plain-1.log', 'progress-all-plain-2.log', 'progress-all-plain-3.log', |
| + 'progress-all-plain-4.log', 'progress-hosted-slow-reboot-1.log', 'progress-hosted-slow-stop-vm-1.log', 'progress-hosted-slow-stop-vm-2.log']) |
| + self.assertTrue(all(p.stat().st_mode & 0o777 == 0o600 for p in kept.iterdir())) |
| + self.assertIn('status=ok', (kept / 'progress-hosted-slow-stop-vm-1.log').read_text().splitlines()[-1]) |
| + self.assertEqual(len(set(addresses)), 7) |
| self.assertTrue(all(a.startswith('suite-') and a.endswith('@equipo-staging.invalid') for a in addresses)) |
| self.assertEqual(enrolled, addresses) |
| self.assertEqual(cleaned, addresses) |
| @@ -119,7 +165,7 @@ class SuiteTest(unittest.TestCase): |
| self.assertEqual(len(records), 1) |
| self.assertEqual(bindings.read_text(), original) |
| self.assertEqual(service.read_text(), original_service) |
| - self.assertEqual(len({e['EQUIPO_STAGING_RUN_ID'] for e in runs}), 5) |
| + self.assertEqual(len({e['EQUIPO_STAGING_RUN_ID'] for e in runs}), 7) |
| self.assertFalse(list(root.glob('equipo-suite-*'))) |
| def test_cleanup_only_this_person_and_continues_after_failure(self): |
diff --git a/scripts/staging-thin.py b/scripts/staging-thin.py| index 3a3a93ad..66309a0f 100755 |
| --- a/scripts/staging-thin.py |
| +++ b/scripts/staging-thin.py |
| @@ -7,7 +7,7 @@ unit on this machine with the real Claude CLI, and run the headless suite. |
| scripts/staging-thin.py deploy # env + carlos deploy --swap hold, wait for the version |
| scripts/staging-thin.py signin # owner and suite sign-in by logged mail, suite device bearer |
| scripts/staging-thin.py runner # both runner units: config, enrolment, start |
| - scripts/staging-thin.py suite [scenario,...] |
| + scripts/staging-thin.py suite [scenario,...] [mode=<hosted drill>] |
| scripts/staging-thin.py stop # stop both staging runner units |
| scripts/staging-thin.py cleanup-suite-runners # one-off: remove stale suite people and their runners |
| @@ -684,12 +684,83 @@ def fresh_suite(): |
| run(['systemctl', '--user', 'start', SUITE_UNIT]) |
| -def suite(only=''): |
| - with fresh_suite() as (run_id, token, cookie): |
| - suite_run(only, run_id, token, cookie) |
| +# The hosted drills a hosted scenario runs under (hosted_test.go's |
| +# hostedExpected): plain, or the fault the drill strikes with. |
| +HOSTED_MODES = ('plain', 'kill-proxy', 'stop-vm', 'withdraw-cert', 'controller-reboot') |
| -def suite_run(only, run_id, token, cookie): |
| +def stamp(): |
| + return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) |
| + |
| + |
| +def append(path, line): |
| + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) |
| + with os.fdopen(fd, 'a') as f: |
| + f.write(line + '\n') |
| + |
| + |
| +def run_status(report, started, failed): |
| + """How a suite run ended: suite_failed when it never started the |
| + scenarios (a refused mode, a failed sign-in) or failed with a report, |
| + report_missing when their report is missing or malformed, else ok.""" |
| + if not started: |
| + return 'suite_failed' |
| + try: |
| + json.loads(report.read_text()) |
| + except (OSError, ValueError): |
| + return 'report_missing' |
| + return 'suite_failed' if failed else 'ok' |
| + |
| + |
| +def keep_run(only, mode, report): |
| + """Each run's report and progress, kept apart under reports/: |
| + report-<scenarios>-<mode>-<n>.json and progress-<scenarios>-<mode>-<n>.log, |
| + n the next free number for those scenarios and mode. Returns the |
| + report's path (None when there was none) and the progress copy's.""" |
| + kept = ROOT / 'reports' |
| + kept.mkdir(parents=True, exist_ok=True, mode=0o700) |
| + label = re.sub(r'[^A-Za-z0-9_+-]', '_', (only or 'all').replace(',', '+')) |
| + pattern = re.compile(r'(?:report|progress)-' + re.escape(label) + '-' + re.escape(mode) + r'-(\d+)\.(?:json|log)') |
| + n = 1 + max([int(m.group(1)) for p in kept.iterdir() if (m := pattern.fullmatch(p.name))], default=0) |
| + path = None |
| + if report.exists(): |
| + path = kept / f'report-{label}-{mode}-{n}.json' |
| + private(path, report.read_text()) |
| + return path, kept / f'progress-{label}-{mode}-{n}.log' |
| + |
| + |
| +def suite(only='', mode=''): |
| + """The headless suite as a fresh suite person. mode is the hosted |
| + drill (mode=<m> after the scenarios, or EQUIPO_STAGING_HOSTED_MODE; |
| + plain by default). Every run writes hosted-progress.log as it goes, |
| + which a drill watches: HOSTED-SUITE-START, the hosted scenarios' own |
| + lines, then always one HOSTED-SUITE status=<ok|suite_failed|report_missing> |
| + report=<the kept report or -> line; the report and the progress are |
| + kept per run (keep_run).""" |
| + mode = mode or os.environ.get('EQUIPO_STAGING_HOSTED_MODE') or 'plain' |
| + report, progress = ROOT / 'report.json', ROOT / 'hosted-progress.log' |
| + report.unlink(missing_ok=True) |
| + known = mode in HOSTED_MODES |
| + if not known: |
| + mode = re.sub(r'[^A-Za-z0-9_-]', '_', mode)[:40] or 'unknown' |
| + private(progress, f'HOSTED-SUITE-START scenarios={only or "all"} mode={mode} at={stamp()}\n') |
| + started, failed = False, True |
| + try: |
| + if not known: |
| + raise ValueError(f'mode {mode!r} is not one of {", ".join(HOSTED_MODES)}') |
| + with fresh_suite() as (run_id, token, cookie): |
| + started = True |
| + suite_run(only, run_id, token, cookie, mode, progress) |
| + failed = False |
| + finally: |
| + status = run_status(report, started, failed) |
| + kept, kept_progress = keep_run(only, mode, report) |
| + append(progress, f'HOSTED-SUITE status={status} report={kept or "-"} at={stamp()}') |
| + private(kept_progress, progress.read_text()) |
| + print(f'suite {status}; report {kept or "missing"}; progress {kept_progress}', flush=True) |
| + |
| + |
| +def suite_run(only, run_id, token, cookie, mode='plain', progress=None): |
| restart = f'carlos restart --app {APP} --account {ACCOUNT} --console {CONSOLE}' |
| env = dict(os.environ, CGO_ENABLED='0', EQUIPO_STAGING_ORIGIN=ORIGIN, EQUIPO_STAGING_TOKEN=token, |
| # The hosted scenarios: the suite person's session (a 0600 |
| @@ -698,6 +769,10 @@ def suite_run(only, run_id, token, cookie): |
| # The scratch project is EQUIPO_STAGING_HOSTED_PROJECT. |
| EQUIPO_STAGING_COOKIE_FILE=str(cookie), |
| EQUIPO_STAGING_DB_QUERY=shlex.join(['carlos', 'db', 'query', '--app', APP, '--account', ACCOUNT, '--console', CONSOLE, '--sql']), |
| + # The drill the hosted scenarios run under, and the |
| + # progress file they append to as they go. |
| + EQUIPO_STAGING_HOSTED_MODE=mode, |
| + EQUIPO_STAGING_HOSTED_PROGRESS=str(progress or ''), |
| EQUIPO_STAGING_RUNNER_START=f'systemctl --user start {SUITE_UNIT}', |
| EQUIPO_STAGING_RUNNER_STOP=f'systemctl --user stop {SUITE_UNIT}', |
| EQUIPO_STAGING_RUNNER_RESTART=f'systemctl --user restart {SUITE_UNIT}', |
| @@ -833,6 +908,15 @@ def release(): |
| deploy(home) |
| +def suite_mode(args): |
| + """suite's optional mode=<m> argument; anything else is refused.""" |
| + if not args: |
| + return '' |
| + if len(args) != 1 or not args[0].startswith('mode='): |
| + raise ValueError('suite takes [scenario,...] [mode=<m>]') |
| + return args[0][len('mode='):] |
| + |
| + |
| def main(): |
| if len(sys.argv) < 2: |
| print(__doc__) |
| @@ -846,7 +930,7 @@ def main(): |
| try: |
| {'build': build, 'release': release, 'deploy': deploy, 'signin': signin, 'runner': runner, 'stop': stop, |
| 'cleanup-suite-runners': cleanup_suite_runners, |
| - 'suite': lambda: suite(sys.argv[2] if len(sys.argv) > 2 else '')}[step]() |
| + 'suite': lambda: suite(sys.argv[2] if len(sys.argv) > 2 else '', suite_mode(sys.argv[3:]))}[step]() |
| return 0 |
| except Exception as error: |
| print(f'FAIL {step}: {redact(str(error))}', file=sys.stderr, flush=True) |