oficina / equipo Public

equipo: Task 24 review 1, certification before any hosted checks end

stepReport now decides certification before any terminal transition
of a worker's checks step: done, failed, unasked cancelled, and the
early placement_refused and sandbox_unproven branches. A runner bound
to a hosted job that is not certified ends nothing and is not tainted.
Its job stops, and the step goes again once after the stop proof, then
ends cannot_run hosted_unavailable. The person's cancellation and an
ended task are taken as before.

Tests cover stale and withdrawn admissions with failed, cancelled and
done-then-failed, the person's cancellation, a different step, a
stopping job, and each admission identity substitution (mutations 354
to 366). The simulation also sends failed and cancelled reports and
reports from stopping jobs, and its invariant covers every ending.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 067e1099050c0f4368bc3550a95f151ec9a0b004 parent b2a8646
5 files changed, +335 −56
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +51 −0
  • internal/equipo/chat/hosted_results_test.go +195 −3
  • internal/equipo/chat/tasks.go +22 −20
  • internal/equipo/hostedrun/sim_test.go +66 −32
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 194eb7d2..adc2acf4 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -60,7 +60,7 @@ perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON
perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen.
perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen.
perf GET /api/v1/assistant/abilities skip Assistant person API: bearer-only JSON for Base's Settings line, not a browser screen.
-size internal/equipo/chat 47094 21522 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. Its review round 2: an admission record's current deadline is kept too (hostedAdmitted, for the dispatcher's refresh and the renewal's HostedRenewAdmit); 46932/20971. Round 3: HostedEnrolAdmit returns the job re-read after recording the admission, so the enrolment caps by its deadline; 46937/20971. Task 23: openHostedPack opens the deps bundle after the hosted pack (send_pack with Deps), the instance's chunk and byte checks per kind (wire.MaxChunks, wire.MaxBytes), deps_too_large for a bundle past its limit, and a hosted attempt's pack and bundle closed when its checks end; hosted_deps_test.go; 46957/21199. Task 24: hosted_results.go (hostedCertified, AdmissionFresh: a hosted worker's checks count as sandboxed and its base checks as trusted only through the job's fresh, valid admission record, never its hello; an uncertified hosted result is not kept, its job stops and the step goes again once; deps_new_module and deps_missing presented as needs_network), stepReport and acceptBaseChecks wired to it, the admission kept whole and the enrolment image (0129), and hosted_results_test.go; 47094/21522.
+size internal/equipo/chat 47096 21714 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. Its review round 2: an admission record's current deadline is kept too (hostedAdmitted, for the dispatcher's refresh and the renewal's HostedRenewAdmit); 46932/20971. Round 3: HostedEnrolAdmit returns the job re-read after recording the admission, so the enrolment caps by its deadline; 46937/20971. Task 23: openHostedPack opens the deps bundle after the hosted pack (send_pack with Deps), the instance's chunk and byte checks per kind (wire.MaxChunks, wire.MaxBytes), deps_too_large for a bundle past its limit, and a hosted attempt's pack and bundle closed when its checks end; hosted_deps_test.go; 46957/21199. Task 24: hosted_results.go (hostedCertified, AdmissionFresh: a hosted worker's checks count as sandboxed and its base checks as trusted only through the job's fresh, valid admission record, never its hello; an uncertified hosted result is not kept, its job stops and the step goes again once; deps_new_module and deps_missing presented as needs_network), stepReport and acceptBaseChecks wired to it, the admission kept whole and the enrolment image (0129), and hosted_results_test.go; 47094/21522. Task 24 review round 1: the certification decision moved before any terminal checks report from a worker (done, failed, unsolicited cancelled, the early failure branches), the person's cancellation kept, and tests for those, a wrong step, a stopping job and each admission identity substitution; 47096/21714.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index df34f14f..3981ae32 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1894,3 +1894,54 @@ Mutations. Each was an exact-string replace by a script under `~/.cache/t24`, on
- **353** (extra) the needs-network presentation removed. `… -run TestHostedCertifiedNewModuleNeedsNetwork`: exit 1, `hosted_results_test.go:203: task presents checks "cannot_run" reason "deps_new_module", want cannot_run needs_network` (and the same for `deps_missing`). Restored.
Budgets, each with its reason: `internal/equipo/chat` 46957/21199 → 47094/21522. `internal/equipo/mergegate` and `hostedrun` are unchanged and within budget.
+
+### Task 24 review round 1 (t24-r1.md: findings 1 and 2; finding 3 ruled in scope by the coordinator, left as it is)
+
+**Finding 1 (Important).** Certification ran only for `done`, so an uncertified hosted runner could end its step another way: `failed`, an unasked `cancelled`, or `failed` after a refused `done`. The step then ended, and Task 21's recovery never ran. Now the decision is made in `stepReport` before any terminal transition of a checks step reported by a worker. It sits right after the withdrawn-attempt block and ahead of the early `placement_refused` and `sandbox_unproven` branches, the `done` judgement and the failed/cancelled default. It applies when the step is not yet terminal and the report does not advance the attempt.
+- `certified := hostedCertified(...)` is computed once there. The `done` branch, the `BaseChecks` branch and `acceptBaseChecks` use it as before.
+- When it is false and the runner is bound to a hosted job, the report ends nothing. The job stops (`uncertified`) and the step goes again once after its stop proof.
+- The person's cancellation (`k.CancelRequested`) and a task already ended (`FinalStage`) are taken as before. An instance-withdrawn attempt goes through `withdrawnEnded` as before, because it returns earlier.
+
+**Finding 2 (Minor).** New report-path tests, each with its mutation below:
+- a different step ID, a step placed on the hosted runner other than its job's;
+- a stopping job: its VM reported lost, while its admission is still fresh and valid;
+- each admission identity substitution:
+ - through the store (`HostedAdmitted` with another launch, VM, epoch or certificate digest; the record is kept as not valid and the result refused);
+ - in the kept record itself, with `cert_valid` left set, so `hostedCertified`'s own guards decide: launch, VM, epoch, certificate digest, image, attempt, a record not running, a record not valid, and the job's column not valid.
+
+**Simulation.** Reports are now done (85%), failed (10%) or cancelled unasked (5%). A VM whose job is already stopping, with its step still on it and not ended, reports `done` again (30% a pass). The invariant now covers any ending: no step ends unless its job was `enrolled` with a valid, fresh admission held valid by the controller then, for the VM, launch and image it launched. Every refused report must leave the step not ended, keep nothing, taint nobody and leave the job stopping. Across seeds there must be certified reports and refusals of each kind: stale, withdrawn, failed or cancelled, and from a stopping job. One run gave 151 certified and 130 refused (5 stale, 38 withdrawn, 9 failed or cancelled, 87 from a stopping job).
+
+Red (tests written first, against `b2a8646b`): `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestHostedUncertifiedTerminalRetried|TestHostedCertifiedPersonCancelKept|TestHostedCertifiedWrongStep|TestHostedCertifiedStoppingJob|TestAdmissionIdentityNotCertified' -count=1`. All six `TestHostedUncertifiedTerminalRetried` cases failed on their assertions:
+- `stale/failed`, `withdrawn/failed`, `stale/done_then_failed`, `withdrawn/done_then_failed`: `hosted_results_test.go:371: VM 1 after failed: s1 failed sandbox "" … want nothing kept`;
+- `stale/cancelled` and `withdrawn/cancelled`: `… VM 1 after cancelled: s1 cancelled …`.
+The other tests passed against `b2a8646b`, because they guard decisions that already held: the person's cancellation, the wrong step, the stopping job, the identity checks. Mutations 355 to 366 are their failing evidence. The test helper `uncertified` now refuses any ended step, not only `done`.
+
+Green:
+- the new tests and all earlier Task 24 tests;
+- the whole `./internal/equipo/chat` (26.9 s) and `./internal/equipo/mergegate`;
+- `./internal/equipo/hostedrun` (20.4 s; the simulation alone 16 s);
+- `./internal/equipo -run 'Enrol|Renew|HostedCredential|Migration|Schema|Hosted'`.
+`make migration-check budget build vet`: exit 0. staticcheck v0.7.0 on chat and hostedrun, gofmt and `git diff --check`: clean.
+
+Mutations. A script under `~/.cache/t24r1` applied each exact-string replace and ran the named test. It then wrote the saved original back and checked it byte for byte.
+- **354** the decision for `done` only (`wire.StepTerminal(v.State)` → `v.State == wire.StepDone`). `CGO_ENABLED=0 go test ./internal/equipo/chat -run '^TestHostedUncertifiedTerminalRetried$' -count=1`: exit 1, `hosted_results_test.go:371: VM 1 after failed: s1 failed sandbox "" base checks "" "" checks "", want nothing kept` (and `after cancelled`). The simulation is a witness too: `… ./internal/equipo/hostedrun -run TestDispatcherSimulation`: exit 1, `sim_test.go:162: seed 30: s2 certified by hj-… with no valid admission` (that message now reads "ended failed by"). Restored.
+- **355** the person's cancellation not kept (`!k.CancelRequested &&` dropped). `… -run '^TestHostedCertifiedPersonCancelKept$'`: exit 1, `hosted_results_test.go:401: the person's cancellation: step queued, task in_review`. Restored.
+- **356** the step ID guard (`j.StepID != stepID` dropped). `… -run '^TestHostedCertifiedWrongStep$'`: exit 1, `hosted_results_test.go:419: another step's result: done sandbox "bubblewrap" base "aaaa…", want nothing kept`. Restored.
+- **357** the job state guard (`j.State != HostedJobEnrolled` dropped). `… -run '^TestHostedCertifiedStoppingJob$'`: exit 1, `hosted_results_test.go:435: a stopping job's result: done sandbox "bubblewrap" base "aaaa…" tainted false`. Restored. The simulation does not witness this guard: none of its stopping jobs has a fresh, valid admission while its VM is alive.
+- **358 to 365** each guard of the kept record, dropped one at a time; each run as `… -run '^TestAdmissionIdentityNotCertified$/^record$/^<name>$'`; each exits 1 with `hosted_results_test.go:494: <name>: s1 done sandbox "bubblewrap" base checks "passed" "aaaa…" checks "passed", want nothing kept`:
+
+ | Mutation | Guard dropped | Subtest `<name>` |
+ |---|---|---|
+ | 358 | launch | `launch` |
+ | 359 | VM | `vm` |
+ | 360 | epoch | `epoch` |
+ | 361 | certificate digest | `cert_digest` |
+ | 362 | image, in `hostedCertified` alone | `image` |
+ | 363 | the record's attempt | `attempt` |
+ | 364 | running | `not_running` |
+ | 365 | the record's `CertValid` | `record_not_valid` |
+
+ Each restored.
+- **366** the job column's `cert_valid` (`!j.CertValid` dropped). `… -run '^TestAdmissionIdentityNotCertified$/^record$/^column_not_valid$'`: exit 1, `hosted_results_test.go:503: column not valid: s1 done sandbox "bubblewrap" …, want nothing kept`. Restored.
+
+Budget: `internal/equipo/chat` 47094/21522 → 47096/21714, with its reason.
diff --git a/internal/equipo/chat/hosted_results_test.go b/internal/equipo/chat/hosted_results_test.go
index 08db3421..65a7632e 100644
--- a/internal/equipo/chat/hosted_results_test.go
+++ b/internal/equipo/chat/hosted_results_test.go
@@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
+ "fmt"
"strings"
"testing"
"time"
@@ -79,13 +80,13 @@ func (r *hkRig) tainted(runner string) bool {
return r.count("SELECT count(*) FROM runners WHERE id = ? AND tainted_at IS NOT NULL", runner) > 0
}
-// uncertified checks that a hosted runner's result did not count: s1 is
-// not done, nothing of the report was kept, the runner is not tainted,
+// uncertified checks that a hosted runner's result did not count: s1 has
+// not ended, nothing of the report was kept, the runner is not tainted,
// and its job is stopping for want of certification.
func (r *hkRig) uncertified(what, runner string, j HostedJob) {
r.t.Helper()
s := r.step("s1")
- if s.State == wire.StepDone || s.ChecksSandbox != "" || s.BaseChecks != "" || s.BaseChecksSHA != "" || s.Checks != "" {
+ if wire.StepTerminal(s.State) || s.ChecksSandbox != "" || s.BaseChecks != "" || s.BaseChecksSHA != "" || s.Checks != "" {
r.t.Fatalf("%s: s1 %s sandbox %q base checks %q %q checks %q, want nothing kept", what, s.State, s.ChecksSandbox, s.BaseChecks, s.BaseChecksSHA, s.Checks)
}
if r.tainted(runner) {
@@ -311,3 +312,194 @@ func TestHostedCertifiedKeepsLastAdmission(t *testing.T) {
t.Fatalf("job keeps admission %q (%v), image %q", j.AdmissionJSON, err, j.ImageDigest)
}
}
+
+// Task 24 review round 1.
+
+// spoil makes j's latest admission stale (the clock moves past
+// AdmissionFresh) or withdrawn (a fresh record with the certificate no
+// longer valid).
+func (r *hkRig) spoil(how string, j HostedJob, vm string) {
+ r.t.Helper()
+ switch how {
+ case "stale":
+ r.now = r.now.Add(AdmissionFresh + time.Second)
+ case "withdrawn":
+ r.now = r.now.Add(10 * time.Second)
+ r.must(r.s.HostedAdmitted(r.ctx, j.AttemptID, hrAdmission(j.AttemptID, vm, false), r.now))
+ default:
+ r.t.Fatalf("spoil %q", how)
+ }
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+}
+
+// terminal is a terminal checks report for s1 at attempt 1 that is not a
+// result: failed (its checks ran out of time) or cancelled, unasked.
+func terminal(state string) wire.StepReport {
+ reason := "checks_timeout"
+ if state == wire.StepCancelled {
+ reason = "cancelled"
+ }
+ return wire.StepReport{TaskID: "tkp", StepID: "s1", Attempt: 1, State: state, Reason: reason, Termination: true, BaseSHA: hpBase, CandidateSHA: hpCandidate}
+}
+
+// TestHostedUncertifiedTerminalRetried: with its admission stale or its
+// certificate withdrawn, a hosted runner cannot end its step any other
+// way either: a failed report, an unasked cancelled one, or a refused
+// done followed by failed all keep nothing, taint nobody and stop the
+// job; after its stop proof the step goes again once under the same
+// attempt, and when the retry's VM is no better the step ends cannot_run
+// hosted_unavailable.
+func TestHostedUncertifiedTerminalRetried(t *testing.T) {
+ for _, how := range []string{"stale", "withdrawn"} {
+ for _, tc := range []struct {
+ name string
+ reports []wire.StepReport
+ }{
+ {"failed", []wire.StepReport{terminal(wire.StepFailed)}},
+ {"cancelled", []wire.StepReport{terminal(wire.StepCancelled)}},
+ {"done then failed", []wire.StepReport{passedReport("s1", 1, wire.SandboxBubblewrap), terminal(wire.StepFailed)}},
+ } {
+ t.Run(how+"/"+tc.name, func(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ for i, vm := range []string{"vm-1", "vm-2"} {
+ runner := fmt.Sprintf("H%d", i+1)
+ j := r.certifiedOnVM(vm, runner)
+ r.spoil(how, j, vm)
+ for _, rep := range tc.reports {
+ r.reportAs(runner, rep)
+ r.uncertified(fmt.Sprintf("VM %d after %s", i+1, rep.State), runner, j)
+ }
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.must(r.s.HostedStopped(r.ctx, j.AttemptID, hostedwire.StopProof{AttemptID: j.AttemptID, VMRef: isolatedjob.Ref(vm), State: isolatedjob.StateStopped}, r.now))
+ jobs, s := r.jobsOf("s1"), r.step("s1")
+ if i == 0 && (len(jobs) != 2 || jobs[1].RetryOf != j.AttemptID || jobs[1].StepAttempt != 1 || s.State != wire.StepQueued || s.Attempt != 1) {
+ t.Fatalf("after the first VM's proof: step %s attempt %d, %d jobs", s.State, s.Attempt, len(jobs))
+ }
+ if i == 1 && (len(jobs) != 2 || s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != wire.ReasonHostedUnavailable) {
+ t.Fatalf("after the retry's proof: step %s %s %q, %d jobs; want cannot_run hosted_unavailable", s.State, s.Checks, s.Reason, len(jobs))
+ }
+ }
+ })
+ }
+ }
+}
+
+// TestHostedCertifiedPersonCancelKept: the person's cancellation of a
+// task whose checks run on a VM with a stale admission still ends: the
+// runner's cancelled report is taken.
+func TestHostedCertifiedPersonCancelKept(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.certifiedOnVM("vm-1", "H1")
+ r.spoil("stale", j, "vm-1")
+ if _, err := r.s.CancelTask(r.ctx, hkOwner, "tkp"); err != nil {
+ t.Fatal(err)
+ }
+ r.reportAs("H1", terminal(wire.StepCancelled))
+ if s, k := r.step("s1"), r.load("tkp"); s.State != wire.StepCancelled || k.Stage != wire.StageCancelled {
+ t.Fatalf("the person's cancellation: step %s, task %s", s.State, k.Stage)
+ }
+ if got := r.job(j.AttemptID); got.StopReason == hostedStopUncertified {
+ t.Fatalf("the person's cancellation stopped the job as %q", got.StopReason)
+ }
+}
+
+// TestHostedCertifiedWrongStep: a hosted runner that reports another
+// step it was somehow given, its own job's admission fresh and valid, is
+// not certified for it.
+func TestHostedCertifiedWrongStep(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.certifiedOnVM("vm-1", "H1")
+ st := stepRecord{ID: "s2", TaskID: "tkp", Idx: 3, Person: hkOwner, RunnerID: "H1", Specialist: wire.SpecialistChecks, State: wire.StepRunning, Attempt: 1, BaseSHA: hpBase, CandidateSHA: hpCandidate, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ r.must(r.s.db.G.Create(&st).Error)
+ r.reportAs("H1", passedReport("s2", 1, wire.SandboxBubblewrap))
+ if s := r.step("s2"); s.State == wire.StepDone || s.ChecksSandbox != "" || s.BaseChecksSHA != "" {
+ t.Fatalf("another step's result: %s sandbox %q base %q, want nothing kept", s.State, s.ChecksSandbox, s.BaseChecksSHA)
+ }
+ if got := r.job(j.AttemptID); got.State != HostedJobStopping || r.tainted("H1") {
+ t.Fatalf("job %s, runner tainted %t", got.State, r.tainted("H1"))
+ }
+}
+
+// TestHostedCertifiedStoppingJob: a job already stopping (its VM reported
+// lost) certifies nothing, even with a fresh valid admission.
+func TestHostedCertifiedStoppingJob(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.certifiedOnVM("vm-1", "H1")
+ r.must(r.s.HostedFailed(r.ctx, j.AttemptID, wire.ReasonHostedVMLost))
+ r.reportAs("H1", passedReport("s1", 1, wire.SandboxBubblewrap))
+ if s := r.step("s1"); wire.StepTerminal(s.State) || s.ChecksSandbox != "" || s.BaseChecksSHA != "" || r.tainted("H1") {
+ t.Fatalf("a stopping job's result: %s sandbox %q base %q tainted %t", s.State, s.ChecksSandbox, s.BaseChecksSHA, r.tainted("H1"))
+ }
+ if got := r.job(j.AttemptID); got.State != HostedJobStopping || got.StopReason != wire.ReasonHostedVMLost {
+ t.Fatalf("job %s %q, want stopping %s", got.State, got.StopReason, wire.ReasonHostedVMLost)
+ }
+}
+
+// TestAdmissionIdentityNotCertified: the latest admission names another
+// launch, VM, epoch or certificate than the job's. Through the store
+// (HostedAdmitted) such a record is kept as not valid; and should the
+// stored record differ while the job still says valid, hostedCertified
+// reads the record itself and refuses it. Each substitution, and a record
+// that is not running, for another attempt, or not valid while the job's
+// column says it is, is refused.
+func TestAdmissionIdentityNotCertified(t *testing.T) {
+ subs := []struct {
+ name string
+ edit func(*hostedwire.AdmissionView)
+ }{
+ {"launch", func(a *hostedwire.AdmissionView) { a.LaunchID = "launch-other" }},
+ {"vm", func(a *hostedwire.AdmissionView) { a.VMRef = "vm-other" }},
+ {"epoch", func(a *hostedwire.AdmissionView) { a.Epoch = 7 }},
+ {"cert digest", func(a *hostedwire.AdmissionView) { a.CertDigest = "cert-digest-other" }},
+ }
+ for _, sub := range subs {
+ t.Run("store/"+sub.name, func(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.certifiedOnVM("vm-1", "H1")
+ r.now = r.now.Add(10 * time.Second)
+ a := hrAdmission(j.AttemptID, "vm-1", true)
+ sub.edit(&a)
+ r.must(r.s.HostedAdmitted(r.ctx, j.AttemptID, a, r.now))
+ r.reportAs("H1", passedReport("s1", 1, wire.SandboxBubblewrap))
+ r.uncertified(sub.name, "H1", j)
+ })
+ }
+ more := append(subs, []struct {
+ name string
+ edit func(*hostedwire.AdmissionView)
+ }{
+ {"image", func(a *hostedwire.AdmissionView) {
+ a.Image = isolatedjob.ImageDigest("sha256:" + strings.Repeat("d", 64))
+ }},
+ {"attempt", func(a *hostedwire.AdmissionView) { a.AttemptID = "hj-other" }},
+ {"not running", func(a *hostedwire.AdmissionView) { a.State = "stopping" }},
+ {"record not valid", func(a *hostedwire.AdmissionView) { a.CertValid = false }},
+ }...)
+ for _, sub := range more {
+ t.Run("record/"+sub.name, func(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.certifiedOnVM("vm-1", "H1")
+ a := hrAdmission(j.AttemptID, "vm-1", true)
+ sub.edit(&a)
+ raw, err := json.Marshal(a)
+ r.must(err)
+ r.exec("UPDATE hosted_jobs SET admission_json = ?, cert_valid = 1 WHERE attempt_id = ?", string(raw), j.AttemptID)
+ r.reportAs("H1", passedReport("s1", 1, wire.SandboxBubblewrap))
+ r.uncertified(sub.name, "H1", j)
+ })
+ }
+ t.Run("record/column not valid", func(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.certifiedOnVM("vm-1", "H1")
+ r.exec("UPDATE hosted_jobs SET cert_valid = 0 WHERE attempt_id = ?", j.AttemptID)
+ r.reportAs("H1", passedReport("s1", 1, wire.SandboxBubblewrap))
+ r.uncertified("column not valid", "H1", j)
+ })
+}
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 5f238f13..f1b86fc4 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -1634,6 +1634,28 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
}
return t.withdrawnEnded(&k, &s)
}
+ // certified: a worker's checks ending (done, failed or cancelled),
+ // through the controller's fresh admission record for its hosted job
+ // alone (never its hello or its word). A hosted runner that is not
+ // certified ends nothing: its report is not kept, it is not tainted,
+ // its job stops and the step is placed again, once (hostedStepAgain).
+ // The person's cancellation, or a task already ended, is taken as
+ // before.
+ certified := false
+ if s.Specialist == wire.SpecialistChecks && role == wire.RoleWorker && wire.StepTerminal(v.State) && !wire.StepTerminal(s.State) && !advanced {
+ if certified, err = t.hostedCertified(l.Runner.RunnerID, s.ID, s.Attempt, t.now()); err != nil {
+ return err
+ }
+ if !certified && !k.CancelRequested && !wire.FinalStage(k.Stage) {
+ j, bound, err := t.hostedJobForRunner(l.Runner.RunnerID)
+ if err != nil {
+ return err
+ }
+ if bound {
+ return t.hostedUncertified(j)
+ }
+ }
+ }
if advanced && s.Specialist == wire.SpecialistEngineering && k.MakerSpecialistID != "" {
// A failover the runner made is a new Design attempt, counted
// here once (a replay is no longer an advance). At the autonomy
@@ -1863,26 +1885,6 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error {
if !ok {
return nil
}
- // certified: a hosted worker's result, through the
- // controller's fresh admission record for its job alone
- // (never its hello or its word). A hosted runner that is
- // not certified keeps nothing and is not tainted: its job
- // stops and the step is placed again, once.
- certified := false
- if s.Specialist == wire.SpecialistChecks && role == wire.RoleWorker {
- if certified, err = t.hostedCertified(l.Runner.RunnerID, s.ID, s.Attempt, now); err != nil {
- return err
- }
- if !certified {
- j, bound, err := t.hostedJobForRunner(l.Runner.RunnerID)
- if err != nil {
- return err
- }
- if bound {
- return t.hostedUncertified(j)
- }
- }
- }
s.Reason, s.Verdict, s.ReviewLabel, s.Checks, s.Gate, s.ExitCode = v.Reason, v.Verdict, v.ReviewLabel, v.Checks, v.Gate, v.ExitCode
if s.Specialist == wire.SpecialistChecks && (role == wire.RolePrimary || certified) && l.Protocol >= wire.ProtocolInjectionDefences {
switch v.BaseChecks {
diff --git a/internal/equipo/hostedrun/sim_test.go b/internal/equipo/hostedrun/sim_test.go
index def7c237..9e1a7a05 100644
--- a/internal/equipo/hostedrun/sim_test.go
+++ b/internal/equipo/hostedrun/sim_test.go
@@ -44,22 +44,26 @@ const simEvery = 2 * Every
// VMs enrol through the store's enrolment steps (Task 22: the code used,
// the controller's admission recorded and required), and a VM's runner
// reports its checks through the production report path (Store.Apply, so
-// stepReport), claiming bubblewrap and trusted base checks every time.
-// After every report (Task 24):
+// stepReport): mostly done, claiming bubblewrap and trusted base checks,
+// sometimes failed or cancelled unasked; a VM whose job is already
+// stopping sometimes reports done again. After every report (Task 24):
//
-// - no step is certified (kept as sandboxed, or with base checks) by a
-// VM whose admission was stale or invalid: the job's latest record,
-// read just before the report, was valid, asked for within
-// AdmissionFresh, at a time the controller held the certificate
-// valid, for the VM and image the controller launched;
-// - an uncertified report keeps nothing, taints no runner, and stops
-// its job (the step is placed again, once).
+// - no step ends (certified as sandboxed with base checks, or failed or
+// cancelled) by a VM whose job was not enrolled or whose admission was
+// stale or invalid: the job's latest record, read just before the
+// report, was valid, asked for within AdmissionFresh, at a time the
+// controller held the certificate valid, for the VM and image the
+// controller launched;
+// - a report that is not certified keeps nothing, ends nothing, taints
+// no runner, and leaves its job stopping (the step is placed again,
+// once).
//
// A VM's checks take 0 to 4 minutes, so some reports arrive while the
// controller is away (a stale admission) or after a withdrawal. Across all
-// seeds, reports are certified, refused on a stale admission and refused
-// on a withdrawn one. Every step ends, and every job ends with proof and
-// is settled. A failure names its seed.
+// seeds, reports are certified, refused on a stale admission, refused on a
+// withdrawn one, refused as failed or cancelled, and refused from a
+// stopping job. Every step ends, and every job ends with proof and is
+// settled. A failure names its seed.
func TestDispatcherSimulation(t *testing.T) {
var tally simTally
t.Run("seeds", func(t *testing.T) {
@@ -70,17 +74,19 @@ func TestDispatcherSimulation(t *testing.T) {
})
}
})
- got := fmt.Sprintf("reports: %d certified, %d not (%d on a stale admission, %d on a withdrawn one)", tally.certified.Load(), tally.uncertified.Load(), tally.stale.Load(), tally.withdrawn.Load())
- if tally.certified.Load() == 0 || tally.stale.Load() == 0 || tally.withdrawn.Load() == 0 {
+ got := fmt.Sprintf("reports: %d certified, %d not (%d on a stale admission, %d on a withdrawn one, %d failed or cancelled, %d from a stopping job)",
+ tally.certified.Load(), tally.uncertified.Load(), tally.stale.Load(), tally.withdrawn.Load(), tally.ended.Load(), tally.stopping.Load())
+ if tally.certified.Load() == 0 || tally.stale.Load() == 0 || tally.withdrawn.Load() == 0 || tally.ended.Load() == 0 || tally.stopping.Load() == 0 {
t.Fatalf("%s: the simulation must exercise each", got)
}
t.Log(got)
}
-// simTally counts, across seeds, the reports certified and not; stale
-// and withdrawn count the uncertified ones whose job's latest admission
-// was valid but older than AdmissionFresh, or not valid.
-type simTally struct{ certified, uncertified, stale, withdrawn atomic.Int64 }
+// simTally counts, across seeds, the reports certified and not. Of those
+// refused: stale and withdrawn count the ones whose job's latest admission
+// was valid but older than AdmissionFresh, or not valid; ended the failed
+// or cancelled ones; stopping the ones from a job already stopping.
+type simTally struct{ certified, uncertified, stale, withdrawn, ended, stopping atomic.Int64 }
func simulate(t *testing.T, seed int64, tally *simTally) {
rng := rand.New(rand.NewSource(seed))
@@ -147,7 +153,21 @@ func simulate(t *testing.T, seed int64, tally *simTally) {
if r.now.Before(reportAt[j.AttemptID]) {
continue
}
- r.checksReport(seed, j, tally)
+ state := wire.StepDone
+ if p := rng.Float64(); p < 0.1 {
+ state = wire.StepFailed
+ } else if p < 0.15 {
+ state = wire.StepCancelled
+ }
+ r.checksReport(seed, j, state, tally)
+ case chat.HostedJobStopping:
+ // A VM already being stopped may still report.
+ s := r.step(j.StepID)
+ v := c.vm(j.AttemptID)
+ if j.RunnerID == "" || s.RunnerID != j.RunnerID || wire.StepTerminal(s.State) || v == nil || !v.alive() || rng.Float64() > 0.3 {
+ continue
+ }
+ r.checksReport(seed, j, wire.StepDone, tally)
}
}
r.invariants(seed, limits)
@@ -218,21 +238,28 @@ func (r *rig) enrolVM(attempt, runner string) {
}
}
-// checksReport has j's runner report its step's checks passed in
-// bubblewrap with base checks passed, through Store.Apply, and checks
-// the result against the job's admission as it stood just before.
-func (r *rig) checksReport(seed int64, j chat.HostedJob, tally *simTally) {
+// checksReport has j's runner end its step as state through Store.Apply
+// (done: checks passed in bubblewrap with base checks passed; failed:
+// the checks ran out of time; cancelled, unasked), and checks the outcome
+// against the job as it stood just before.
+func (r *rig) checksReport(seed int64, j chat.HostedJob, state string, tally *simTally) {
r.t.Helper()
before := r.job(j.AttemptID)
s := r.step(j.StepID)
zero := 0
rep := wire.StepReport{TaskID: s.TaskID, StepID: j.StepID, Attempt: s.Attempt, State: wire.StepDone, Termination: true, BaseSHA: baseSHA, CandidateSHA: candidateSHA,
Checks: wire.ChecksPassed, Gate: "make ci", ExitCode: &zero, ChecksSandbox: wire.SandboxBubblewrap, BaseChecks: wire.ChecksPassed, BaseChecksSHA: baseSHA, Findings: []wire.Finding{}}
+ switch state {
+ case wire.StepFailed:
+ rep = wire.StepReport{TaskID: s.TaskID, StepID: j.StepID, Attempt: s.Attempt, State: state, Reason: "checks_timeout", Termination: true, BaseSHA: baseSHA, CandidateSHA: candidateSHA}
+ case wire.StepCancelled:
+ rep = wire.StepReport{TaskID: s.TaskID, StepID: j.StepID, Attempt: s.Attempt, State: state, Reason: "cancelled", Termination: true, BaseSHA: baseSHA, CandidateSHA: candidateSHA}
+ }
r.frames++
l := chat.Lease{Runner: chat.RunnerPrincipal{RunnerID: j.RunnerID, Person: owner}, Generation: 1, Process: "p", Protocol: wire.ProtocolHostedRunners, Role: wire.RoleWorker}
r.must(r.s.Apply(r.ctx, l, wire.Frame{ID: fmt.Sprintf("f%d", r.frames), Type: wire.FrameStep}, &rep))
after := r.step(j.StepID)
- if after.ChecksSandbox == wire.SandboxBubblewrap || after.BaseChecksSHA != "" {
+ if wire.StepTerminal(after.State) || after.ChecksSandbox != "" || after.BaseChecksSHA != "" {
tally.certified.Add(1)
at := before.CertCheckedAt
r.ctl.mu.Lock()
@@ -240,28 +267,35 @@ func (r *rig) checksReport(seed int64, j chat.HostedJob, tally *simTally) {
launched := v != nil && string(v.ref) == before.VMRef && v.launchID == before.LaunchID && string(v.q.Image) == before.ImageDigest
r.ctl.mu.Unlock()
switch {
- case after.State != wire.StepDone || after.ChecksSandbox != wire.SandboxBubblewrap || after.BaseChecksSHA != baseSHA:
- r.fail(seed, "%s certified in part: %+v", j.StepID, after)
+ case after.State != state || state == wire.StepDone && (after.ChecksSandbox != wire.SandboxBubblewrap || after.BaseChecksSHA != baseSHA):
+ r.fail(seed, "%s ended %s in part: %+v", j.StepID, state, after)
+ case before.State != chat.HostedJobEnrolled:
+ r.fail(seed, "%s ended %s by %s, whose job was %s", j.StepID, state, j.AttemptID, before.State)
case !before.CertValid || at == nil:
- r.fail(seed, "%s certified by %s with no valid admission", j.StepID, j.AttemptID)
+ r.fail(seed, "%s ended %s by %s with no valid admission", j.StepID, state, j.AttemptID)
case r.now.Sub(*at) > chat.AdmissionFresh || at.Sub(r.now) > chat.AdmissionFresh:
- r.fail(seed, "%s certified by %s on an admission from %v at %v", j.StepID, j.AttemptID, at, r.now)
+ r.fail(seed, "%s ended %s by %s on an admission from %v at %v", j.StepID, state, j.AttemptID, at, r.now)
case !r.ctl.validAt(*at):
- r.fail(seed, "%s certified by %s on an admission at %v, when the certificate was withdrawn", j.StepID, j.AttemptID, at)
+ r.fail(seed, "%s ended %s by %s on an admission at %v, when the certificate was withdrawn", j.StepID, state, j.AttemptID, at)
case !launched:
- r.fail(seed, "%s certified by %s on VM %s image %s, which the controller did not launch", j.StepID, j.AttemptID, before.VMRef, before.ImageDigest)
+ r.fail(seed, "%s ended %s by %s on VM %s image %s, which the controller did not launch", j.StepID, state, j.AttemptID, before.VMRef, before.ImageDigest)
}
return
}
tally.uncertified.Add(1)
+ if state != wire.StepDone {
+ tally.ended.Add(1)
+ }
switch {
+ case before.State == chat.HostedJobStopping:
+ tally.stopping.Add(1)
case !before.CertValid:
tally.withdrawn.Add(1)
case before.CertCheckedAt != nil && r.now.Sub(*before.CertCheckedAt) > chat.AdmissionFresh:
tally.stale.Add(1)
}
- if after.State == wire.StepDone || after.Checks != "" {
- r.fail(seed, "%s kept an uncertified result: %+v", j.StepID, after)
+ if wire.StepTerminal(after.State) || after.Checks != "" {
+ r.fail(seed, "%s kept an uncertified %s: %+v", j.StepID, state, after)
}
var tainted int64
r.must(r.d.G.Raw("SELECT count(*) FROM runners WHERE id = ? AND tainted_at IS NOT NULL", j.RunnerID).Scan(&tainted).Error)