equipo: Task 19 review 1, fenced never-launched evidence, audit in tx
Never-launched evidence is the controller's signed observation for the attempt (absent, or abandoned with no VM) made at least 2 minutes past the job's launch-by, with no launch call in flight (launching_since, added to 0126 beside launch_by; hostedLaunchReturned clears it) and no launch, VM or runner recorded; anything else needs stop proof. Settlement of unproven ended or failed records is refused and changes nothing. Audits are checked against the active transaction's own connection, and a failed audit rolls back moves and settlement.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+304
−43
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+29 −0internal/equipo/chat/hosted_jobs.go+88 −18internal/equipo/chat/hosted_jobs_test.go+184 −22internal/equipo/migrations/0126_hosted_jobs.sql+1 −1internal/equipo/migrations/schema.sql+1 −1
CI failed — run details
CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/hosted-runners-2: Type Size Avail | ext4 96G 84G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 84G
ci-box: bwrap: fetched and verified in 0.2s
ci-box: claude: fetched and verified in 1.4s
ci-box: codex: fetched and verified in 3.4s
ci-box: codex-code-mode-host: fetched and verified in 1.5s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.8s
ci-box: pi: installed and verified in 7.4s
ci-box: opencode: installed and verified in 2.3s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.6s
ci-box: clone deepened in 4.3s
ci-box: file times set from content: 3891 files, 271 directories
ci-box: ready in 17.8s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
--- FAIL: TestReleaseCopyReviewed (0.09s)
task_pages_test.go:236: COPY REVIEW REQUIRED: copy-status.py verify found copy pending review or stale bookkeeping
FAIL
rastrillo-budget/v1 ran 86ms
FAIL amadan.net/oficina/equipo/internal/equipotest 0.236s
FAIL
make: *** [Makefile:273: copy-release-check] Error 1
amadan: step copy failed: exit status 2
amadan: job failed at step copy — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 1c784575..b8c0ea64 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -59,7 +59,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 45658 19577 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. |
| +size internal/equipo/chat 45728 19739 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. |
| 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 cda2e533..5b80d13c 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1447,3 +1447,32 @@ Mutations (exact-string replace from a script under `mktemp -d`, one at a time, |
| - **242** the live index without its condition. `ON hosted_jobs(step_id) WHERE state <> 'ended' AND state <> 'failed';` became `ON hosted_jobs(step_id);`. Same command: exit 1, `hosted_jobs_test.go:450: constraint failed: UNIQUE constraint failed: hosted_jobs.step_id (2067)`. Restored. |
| Notes for Tasks 20 to 22: `failed` is reached only through `stopping` (any live state goes to stopping on a failure, then needs proof), so the dispatcher's `HostedFailed` should move the job to stopping with its reason and end it once proof or never-launched evidence arrives. `admitted_at` is the limit admission time (Task 20's settle start). The admission record columns (`cert_*`), `code_used_at` and `hosted_challenges` have no writers yet (Tasks 21 and 22). |
| + |
| +### Task 19 review round 1 (t19-r1.md: three findings fixed, by ruling for the first) |
| + |
| +1. **Never-launched evidence is a controller observation, fenced by the launch-by.** `HostedEndProof.NeverLaunched` is now `*HostedNeverLaunched{AttemptID, ObservedAt, LaunchBy, ControllerState, VMRef, Signed}`. `holds` accepts it only when: the response verified (`Signed`); it names the job's attempt; `ControllerState` is `absent` (no record) or `abandoned`, and `VMRef` is empty either way (a refusal, such as Get's `ErrForbidden`, is neither state); `LaunchBy` is set and `ObservedAt >= LaunchBy + HostedNeverLaunchedAfter` (2 minutes); `LaunchBy` equals the job's own `launch_by` when it has one; no launch call is in flight (`launching_since` is NULL); and the job records no launch ID, VM Ref or runner. Anything else needs controller stop proof. The basis: Task 3's controller refuses or abandons any launch after its launch-by, so nothing for the attempt can start once that has passed. Two columns were added to `hosted_jobs` in 0126 (not yet merged or released, so it was edited in place; `schema.sql` matches): `launch_by` and `launching_since`. `hostedLaunching(attempt, code, expires, launchBy)` sets both. `hostedEnrolling` clears `launching_since` when it records the reply. The new `hostedLaunchReturned(attempt)` clears it when the call returned without a view (an error or a lost reply). It makes no state change, raises the revision, is audited `<attempt>:launch_returned` in the transaction, and returns `ErrNotFound` for no job. A dispatcher that crashes mid-call leaves `launching_since` set, so that job needs stop proof. |
| +2. **Settlement refuses unproven terminal records.** `TestSettleIdempotentNeedsProof`: `ended` and `failed` rows set by hand with no proof, unreadable proof, another attempt's proof, or never-launched evidence observed too early. Each settlement is refused with `ErrHostedNoProof` and the row (usage, revision, `settled_at`), the audit log and the audit table are all unchanged. |
| +3. **Audit atomicity.** The rig's audit now checks that its handle is a `gorm.TxCommitter` and is the very connection of the transaction the test opened (`r.hosted`). It writes an `audit_probe` row there. `TestHostedJobAuditAtomic`: with a failing audit, a move to launching, the launch return, a move to stopping, a move to failed and a settlement each leave the job unchanged. With a working audit each writes one probe row. |
| + |
| +Red: `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestHostedJob|TestEndNeedsProof|TestOneLiveJob|TestSettleIdempotent|TestMigrationAdditive' -count=1`: build failed (`undefined: HostedNeverLaunched`, `undefined: HostedControllerAbsent`, too many arguments to `t.hostedLaunching`, `got.LaunchBy undefined`, `got.LaunchingSince undefined`). Findings 2 and 3 strengthen tests of code that was already correct; the mutations below are their assertion-level evidence. |
| + |
| +Green: the same command, ok (10 tests). The whole chat package once: ok (24.2 s). `./internal/equipo -run 'Migration|Schema'`: ok. `make migration-check budget build vet`: exit 0 (chat record 45728/19739, with the reason). gofmt and `git diff --check`: clean. |
| + |
| +Mutations (exact-string replace in `internal/equipo/chat/hosted_jobs.go` from a script under `mktemp -d`, one at a time, `CGO_ENABLED=0 go test ./internal/equipo/chat -run '<test>' -count=1`, restored from a copy and compared with `filecmp`: identical each time): |
| +- **243** unsigned accepted (`!n.Signed` dropped from `holds`). `-run TestEndNeedsProofNeverLaunched`: exit 1, `hosted_jobs_test.go:289: not signed: <nil>, state failed`. Restored. |
| +- **244** any attempt accepted (`n.AttemptID != j.AttemptID` dropped). Same: exit 1, `hosted_jobs_test.go:289: another attempt: <nil>, state failed`. Restored. |
| +- **245** a VM in the observation accepted (`n.VMRef != ""` dropped). Same: exit 1, `hosted_jobs_test.go:289: absent but with a VM: <nil>, state failed`. Restored. |
| +- **246** any controller state accepted (the `ControllerState` case deleted). Same: exit 1, `hosted_jobs_test.go:289: a refusal read as no record: <nil>, state failed`. Restored. |
| +- **247** no launch-by fence (`n.ObservedAt.Before(n.LaunchBy.Add(HostedNeverLaunchedAfter))` dropped). Same: exit 1, `hosted_jobs_test.go:289: observed before launch-by+2m: <nil>, state failed`. Restored. |
| +- **248** no launch-by needed (`n.LaunchBy.IsZero()` dropped). Same: exit 1, `hosted_jobs_test.go:307: evidence with no launch-by: <nil>`. Restored. |
| +- **249** the job's launch-by not compared (that case deleted). Same: exit 1, `hosted_jobs_test.go:289: another launch-by: <nil>, state failed`. Restored. |
| +- **250** a launch call in flight accepted (`case j.LaunchingSince != nil:` deleted). Same: exit 1, `hosted_jobs_test.go:268: a launch call in flight: <nil>, state failed`. Restored. |
| +- **251** a recorded launch accepted (the `j.LaunchID`/`j.VMRef`/`j.RunnerID` case deleted). `-run TestEndNeedsProof`: exit 1, `hosted_jobs_test.go:239: ended: hj_... with never launched, but it launched = <nil>, state ended`. Restored. |
| +- **252** the reply leaves the call in flight (`hostedEnrolling` kept `j.LaunchingSince`). `-run TestHostedJobLifecycle`: exit 1, `hosted_jobs_test.go:175: launch not recorded: {... State:enrolling ...}`. Restored. |
| +- **253** settlement without the proof check (the `j.provenErr()` block in `settleHostedJob`, the reviewer's `hosted_jobs.go:416`, deleted). `-run TestSettleIdempotentNeedsProof`: exit 1, `hosted_jobs_test.go:474: ended with no proof settled: <nil>`. Restored. |
| +- **254** move audit outside the transaction (`moveHostedJob`'s `Audit(t.db,` became `Audit(t.s.db.G,`). `-run TestHostedJobAuditAtomic`: exit 1, `hosted_jobs_test.go:505: audit outside the move's transaction`. Restored. |
| +- **255** settlement audit outside the transaction. Same command: exit 1, `hosted_jobs_test.go:527: audit outside the move's transaction`. Restored. |
| +- **256** launch-return audit outside the transaction. Same command: exit 1, `hosted_jobs_test.go:516: audit outside the move's transaction`. Restored. |
| +- **257** creation audit outside the transaction. `-run TestHostedJobLifecycle`: exit 1, `hosted_jobs_test.go:158: audit outside the move's transaction`. Restored. |
| + |
| +For Task 21: the dispatcher builds `HostedNeverLaunched` only from a verified controller answer: Get's not-found as `absent`, and an `abandoned` view with no VM Ref as `abandoned`. It never builds one from a refusal (`ErrForbidden`) or a transport error. It moves a job to launching before calling Launch and records `hostedLaunchReturned` (or the view) once the call returns. |
diff --git a/internal/equipo/chat/hosted_jobs.go b/internal/equipo/chat/hosted_jobs.go| index 7133c332..b8bcbfbc 100644 |
| --- a/internal/equipo/chat/hosted_jobs.go |
| +++ b/internal/equipo/chat/hosted_jobs.go |
| @@ -12,6 +12,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "gorm.io/gorm" |
| ) |
| // A hosted job's states (hosted runners spec §8, §10). pending to ended is |
| @@ -65,6 +66,12 @@ type HostedJob struct { |
| LaunchID string |
| VMRef string `gorm:"column:vm_ref"` |
| Epoch int64 |
| + // LaunchBy is the launch-by the job's launch request carries: the |
| + // controller refuses or abandons the launch after it. LaunchingSince |
| + // is set while a launch call may be in flight: from the move to |
| + // launching until its reply or its return is recorded. |
| + LaunchBy *time.Time |
| + LaunchingSince *time.Time |
| // Cert* is the controller's latest admission record for the VM. |
| CertDigest string |
| CertValid bool |
| @@ -182,27 +189,70 @@ func (c HostedCharge) encode() (seconds, micros string, err error) { |
| } |
| // HostedEndProof is what lets a job end: the controller's stop proof for |
| -// its attempt, or never-launched evidence (the controller's Get answered |
| -// not found for an intent it never dispatched). ObservedAt is when the |
| +// its attempt, or never-launched evidence. ObservedAt is when the |
| // instance received it, on the instance's clock. |
| type HostedEndProof struct { |
| Stop *hostedwire.StopProof `json:"stop,omitempty"` |
| - NeverLaunched bool `json:"never_launched,omitempty"` |
| + NeverLaunched *HostedNeverLaunched `json:"never_launched,omitempty"` |
| ObservedAt time.Time `json:"observed_at"` |
| } |
| +// The controller states never-launched evidence may name: no record of |
| +// the attempt, or an intent it abandoned before any VM. A refusal (such |
| +// as Get's ErrForbidden for an attempt it does not know) is neither. |
| +const ( |
| + HostedControllerAbsent = "absent" |
| + HostedControllerAbandoned = "abandoned" |
| +) |
| + |
| +// HostedNeverLaunchedAfter is how long past the launch-by the controller |
| +// must be observed: it refuses or abandons any launch after the |
| +// launch-by, so nothing for the attempt can start once this has passed. |
| +const HostedNeverLaunchedAfter = 2 * time.Minute |
| + |
| +// HostedNeverLaunched is the controller's answer for an attempt, as the |
| +// dispatcher observed it: ControllerState and VMRef from a response whose |
| +// signature verified (Signed), at ObservedAt, for a launch whose launch-by |
| +// was LaunchBy. |
| +type HostedNeverLaunched struct { |
| + AttemptID string `json:"attempt_id"` |
| + ObservedAt time.Time `json:"observed_at"` |
| + LaunchBy time.Time `json:"launch_by"` |
| + ControllerState string `json:"controller_state"` |
| + VMRef string `json:"vm_ref,omitempty"` |
| + Signed bool `json:"signed"` |
| +} |
| + |
| +// holds checks never-launched evidence against j: signed, for j's attempt |
| +// and its launch-by, observed at least HostedNeverLaunchedAfter past it, |
| +// no record or an abandoned intent with no VM; and on j's side no launch |
| +// call in flight and no launch, VM or runner recorded. |
| +func (n HostedNeverLaunched) holds(j HostedJob) bool { |
| + switch { |
| + case !n.Signed, n.AttemptID != j.AttemptID, n.VMRef != "": |
| + case n.ControllerState != HostedControllerAbsent && n.ControllerState != HostedControllerAbandoned: |
| + case n.LaunchBy.IsZero(), n.ObservedAt.Before(n.LaunchBy.Add(HostedNeverLaunchedAfter)): |
| + case j.LaunchBy != nil && !j.LaunchBy.Equal(n.LaunchBy): |
| + case j.LaunchingSince != nil: |
| + case j.LaunchID != "", j.VMRef != "", j.RunnerID != "": |
| + default: |
| + return true |
| + } |
| + return false |
| +} |
| + |
| // proofFor checks p against j: a terminal stop proof for j's attempt and, |
| -// once j has a VM, that VM; or never-launched evidence for a job the |
| -// controller never reported launching. Exactly one of the two. |
| +// once j has a VM, that VM; or never-launched evidence that holds for j. |
| +// Exactly one of the two. |
| func (p HostedEndProof) proofFor(j HostedJob) error { |
| switch { |
| case p.ObservedAt.IsZero(): |
| - case p.Stop != nil && !p.NeverLaunched: |
| + case p.Stop != nil && p.NeverLaunched == nil: |
| if p.Stop.AttemptID == j.AttemptID && p.Stop.State.Terminal() && (j.VMRef == "" || string(p.Stop.VMRef) == j.VMRef) { |
| return nil |
| } |
| - case p.Stop == nil && p.NeverLaunched: |
| - if j.LaunchID == "" && j.VMRef == "" && j.RunnerID == "" { |
| + case p.Stop == nil && p.NeverLaunched != nil: |
| + if p.NeverLaunched.holds(j) { |
| return nil |
| } |
| } |
| @@ -316,19 +366,39 @@ func (t *txn) moveHostedJob(attempt, to string, set func(*HostedJob) error, cols |
| return t.s.authority.Audit(t.db, "system", "hosted.job", attempt+":"+from+">"+to) |
| } |
| -// hostedLaunching records the instance code's hash before the launch is |
| -// asked for: code is the 32-byte base64url code the VM's payload carries. |
| -func (t *txn) hostedLaunching(attempt, code string, expires time.Time) error { |
| +// hostedLaunching records, before the launch is asked for, the instance |
| +// code's hash (code is the 32-byte base64url code the VM's payload |
| +// carries), the request's launch-by, and that a launch call may now be in |
| +// flight. |
| +func (t *txn) hostedLaunching(attempt, code string, expires, launchBy time.Time) error { |
| raw, err := base64.RawURLEncoding.Strict().DecodeString(code) |
| - if err != nil || len(raw) != 32 || expires.IsZero() { |
| - return fmt.Errorf("%w: instance code", ErrHostedTransition) |
| + if err != nil || len(raw) != 32 || expires.IsZero() || launchBy.IsZero() { |
| + return fmt.Errorf("%w: instance code or launch-by", ErrHostedTransition) |
| } |
| return t.moveHostedJob(attempt, HostedJobLaunching, func(j *HostedJob) error { |
| sum := sha256.Sum256([]byte(code)) |
| - e := expires.UTC() |
| - j.CodeHash, j.CodeExpiresAt = hex.EncodeToString(sum[:]), &e |
| + e, by, now := expires.UTC(), launchBy.UTC(), t.now().UTC() |
| + j.CodeHash, j.CodeExpiresAt, j.LaunchBy, j.LaunchingSince = hex.EncodeToString(sum[:]), &e, &by, &now |
| return nil |
| - }, "code_hash", "code_expires_at") |
| + }, "code_hash", "code_expires_at", "launch_by", "launching_since") |
| +} |
| + |
| +// hostedLaunchReturned records that the job's launch call returned |
| +// without a view (an error, a lost reply): no call is in flight. It |
| +// changes no state; it is audited in the transaction. |
| +func (t *txn) hostedLaunchReturned(attempt string) error { |
| + res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND launching_since IS NOT NULL", attempt).Updates(map[string]any{"launching_since": nil, "revision": gorm.Expr("revision + 1")}) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected == 0 { |
| + var n int64 |
| + if err := t.db.Model(&HostedJob{}).Where("attempt_id = ?", attempt).Count(&n).Error; err != nil || n == 1 { |
| + return err |
| + } |
| + return ErrNotFound |
| + } |
| + return t.s.authority.Audit(t.db, "system", "hosted.job", attempt+":launch_returned") |
| } |
| // hostedEnrolling records the controller's launch view: the VM now waits |
| @@ -338,9 +408,9 @@ func (t *txn) hostedEnrolling(attempt string, v hostedwire.JobView) error { |
| return fmt.Errorf("%w: launch view for %s", ErrHostedTransition, attempt) |
| } |
| return t.moveHostedJob(attempt, HostedJobEnrolling, func(j *HostedJob) error { |
| - j.LaunchID, j.VMRef, j.Epoch = v.LaunchID, string(v.VMRef), v.Epoch |
| + j.LaunchID, j.VMRef, j.Epoch, j.LaunchingSince = v.LaunchID, string(v.VMRef), v.Epoch, nil |
| return nil |
| - }, "launch_id", "vm_ref", "epoch") |
| + }, "launch_id", "vm_ref", "epoch", "launching_since") |
| } |
| // hostedEnrolled binds the job to the runner its VM enrolled as, once the |
diff --git a/internal/equipo/chat/hosted_jobs_test.go b/internal/equipo/chat/hosted_jobs_test.go| index 7c46460e..76b330eb 100644 |
| --- a/internal/equipo/chat/hosted_jobs_test.go |
| +++ b/internal/equipo/chat/hosted_jobs_test.go |
| @@ -4,7 +4,9 @@ import ( |
| "context" |
| "crypto/sha256" |
| "encoding/hex" |
| + "encoding/json" |
| "errors" |
| + "fmt" |
| "os" |
| "reflect" |
| "strings" |
| @@ -20,18 +22,28 @@ import ( |
| // hostedCode is a 32-byte instance code in unpadded base64url. |
| const hostedCode = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8" |
| -// hostedRig is a roster rig with task tkh in p1 and an audit log. |
| +// hostedLaunchBy is the launch-by the rig's launches carry. |
| +var hostedLaunchBy = time.Date(2026, 11, 8, 12, 10, 0, 0, time.UTC) |
| + |
| +// hostedPools is each rig's transaction in progress (r.hosted). |
| +var hostedPools = map[*hkRig]gorm.ConnPool{} |
| + |
| +// hostedRig is a roster rig with task tkh in p1 and an audit log. The |
| +// audit must come through the transaction r.hosted opened, and writes a |
| +// row (audit_probe) there. |
| func hostedRig(t *testing.T) (*hkRig, *[]string) { |
| r, _ := rosterRig(t) |
| r.task("tkh", "Hosted", hkOwner) |
| + r.exec("CREATE TABLE audit_probe (detail text)") |
| audits := new([]string) |
| r.s.authority.Audit = func(tx *gorm.DB, actor, kind, detail string) error { |
| - if tx == nil { |
| - t.Fatal("audit outside the transaction") |
| + if _, inTx := tx.Statement.ConnPool.(gorm.TxCommitter); !inTx || tx.Statement.ConnPool != hostedPools[r] { |
| + return errors.New("audit outside the move's transaction") |
| } |
| *audits = append(*audits, actor+" "+kind+" "+detail) |
| - return nil |
| + return tx.Exec("INSERT INTO audit_probe(detail) VALUES (?)", detail).Error |
| } |
| + t.Cleanup(func() { delete(hostedPools, r) }) |
| return r, audits |
| } |
| @@ -47,7 +59,7 @@ func hostedHold() HostedCharge { |
| func (r *hkRig) newJob(step, retryOf string) (HostedJob, error) { |
| var j HostedJob |
| - err := r.tx(func(t *txn) error { |
| + err := r.hosted(func(t *txn) error { |
| var err error |
| j, err = t.newHostedJob(hostedJobSpec{Step: step, Size: isolatedjob.SizeSmall, Hold: hostedHold(), RetryOf: retryOf, At: r.now}) |
| return err |
| @@ -62,7 +74,12 @@ func (r *hkRig) job(attempt string) HostedJob { |
| return j |
| } |
| -func (r *hkRig) hosted(fn func(t *txn) error) error { return r.tx(fn) } |
| +func (r *hkRig) hosted(fn func(t *txn) error) error { |
| + return r.tx(func(t *txn) error { |
| + hostedPools[r] = t.db.Statement.ConnPool |
| + return fn(t) |
| + }) |
| +} |
| func hostedView(attempt string) hostedwire.JobView { |
| return hostedwire.JobView{AttemptID: attempt, LaunchID: "launch-1", State: "running", VMRef: "vm-1", Epoch: 3} |
| @@ -72,13 +89,21 @@ func stopProof(attempt string) HostedEndProof { |
| return HostedEndProof{Stop: &hostedwire.StopProof{AttemptID: attempt, VMRef: "vm-1", State: isolatedjob.StateStopped, ObservedAt: 90 * time.Second}, ObservedAt: time.Date(2026, 11, 8, 12, 40, 0, 0, time.UTC)} |
| } |
| +// neverLaunched is valid never-launched evidence for attempt: the |
| +// controller's signed answer that it holds no record, observed 2 minutes |
| +// after the launch-by. |
| +func neverLaunched(attempt string) HostedEndProof { |
| + at := hostedLaunchBy.Add(2 * time.Minute) |
| + return HostedEndProof{NeverLaunched: &HostedNeverLaunched{AttemptID: attempt, ObservedAt: at, LaunchBy: hostedLaunchBy, ControllerState: HostedControllerAbsent, Signed: true}, ObservedAt: at} |
| +} |
| + |
| // moveTo makes the one move that reaches to, with valid inputs; the |
| // proof for ended or failed is never-launched evidence. |
| func (r *hkRig) moveTo(attempt, to string) error { |
| return r.hosted(func(t *txn) error { |
| switch to { |
| case HostedJobLaunching: |
| - return t.hostedLaunching(attempt, hostedCode, r.now.Add(2*time.Minute)) |
| + return t.hostedLaunching(attempt, hostedCode, r.now.Add(2*time.Minute), hostedLaunchBy) |
| case HostedJobEnrolling: |
| return t.hostedEnrolling(attempt, hostedView(attempt)) |
| case HostedJobEnrolled: |
| @@ -86,7 +111,7 @@ func (r *hkRig) moveTo(attempt, to string) error { |
| case HostedJobStopping: |
| return t.hostedStopping(attempt, "step_ended") |
| default: |
| - return t.hostedEnd(attempt, to, HostedEndProof{NeverLaunched: true, ObservedAt: r.now}) |
| + return t.hostedEnd(attempt, to, neverLaunched(attempt)) |
| } |
| }) |
| } |
| @@ -142,8 +167,11 @@ func TestHostedJobLifecycle(t *testing.T) { |
| if got := r.job(j.AttemptID); got.CodeHash != hex.EncodeToString(sum[:]) || got.CodeExpiresAt == nil || r.count("SELECT count(*) FROM hosted_jobs WHERE code_hash LIKE ?", "%"+hostedCode+"%") != 0 { |
| t.Fatalf("code kept as %q", got.CodeHash) |
| } |
| + if got := r.job(j.AttemptID); got.LaunchBy == nil || !got.LaunchBy.Equal(hostedLaunchBy) || got.LaunchingSince == nil { |
| + t.Fatalf("launch call not recorded: %+v", got) |
| + } |
| r.must(r.moveTo(j.AttemptID, HostedJobEnrolling)) |
| - if got := r.job(j.AttemptID); got.LaunchID != "launch-1" || got.VMRef != "vm-1" || got.Epoch != 3 { |
| + if got := r.job(j.AttemptID); got.LaunchID != "launch-1" || got.VMRef != "vm-1" || got.Epoch != 3 || got.LaunchingSince != nil { |
| t.Fatalf("launch not recorded: %+v", got) |
| } |
| if err := r.moveTo(j.AttemptID, HostedJobEnrolled); !errors.Is(err, ErrHostedTransition) { |
| @@ -196,10 +224,10 @@ func TestEndNeedsProof(t *testing.T) { |
| noTime := stopProof(j.AttemptID) |
| noTime.ObservedAt = time.Time{} |
| both := stopProof(j.AttemptID) |
| - both.NeverLaunched = true |
| + both.NeverLaunched = neverLaunched(j.AttemptID).NeverLaunched |
| for name, p := range map[string]HostedEndProof{ |
| "no evidence": {ObservedAt: r.now}, |
| - "never launched, but it launched": {NeverLaunched: true, ObservedAt: r.now}, |
| + "never launched, but it launched": neverLaunched(j.AttemptID), |
| "another attempt's proof": other, |
| "a live VM": running, |
| "another VM": wrongVM, |
| @@ -215,19 +243,76 @@ func TestEndNeedsProof(t *testing.T) { |
| if got := r.job(j.AttemptID); got.State != to || !got.proven() { |
| t.Fatalf("%s with proof: %+v", to, got) |
| } |
| - // A job the controller never reported launching ends on its |
| - // not-found answer. |
| - r.hostedStep("st2") |
| - k, err := r.newJob("st2", "") |
| - r.must(err) |
| - r.must(r.moveTo(k.AttemptID, HostedJobStopping)) |
| - r.must(r.hosted(func(t *txn) error { |
| - return t.hostedEnd(k.AttemptID, to, HostedEndProof{NeverLaunched: true, ObservedAt: r.now}) |
| - })) |
| - if got := r.job(k.AttemptID); got.State != to { |
| - t.Fatalf("never launched: %+v", got) |
| + } |
| +} |
| + |
| +// TestEndNeedsProofNeverLaunched: never-launched evidence ends a job only |
| +// when it is the controller's signed observation for the attempt, made |
| +// at least 2 minutes after the job's launch-by, that it holds no record |
| +// or an abandoned intent with no VM, and no launch call of the job is in |
| +// flight. Anything else needs stop proof. |
| +func TestEndNeedsProofNeverLaunched(t *testing.T) { |
| + r, _ := hostedRig(t) |
| + r.hostedStep("st1") |
| + j, err := r.newJob("st1", "") |
| + r.must(err) |
| + r.must(r.moveTo(j.AttemptID, HostedJobLaunching)) |
| + r.must(r.moveTo(j.AttemptID, HostedJobStopping)) |
| + refused := func(name string, p HostedEndProof) { |
| + t.Helper() |
| + err := r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobFailed, p) }) |
| + if got := r.job(j.AttemptID); !errors.Is(err, ErrHostedNoProof) || got.State != HostedJobStopping || got.StopProofJSON != "" { |
| + t.Fatalf("%s: %v, state %s", name, err, got.State) |
| } |
| } |
| + refused("a launch call in flight", neverLaunched(j.AttemptID)) |
| + r.must(r.hosted(func(t *txn) error { return t.hostedLaunchReturned(j.AttemptID) })) |
| + if got := r.job(j.AttemptID); got.LaunchingSince != nil || got.State != HostedJobStopping { |
| + t.Fatalf("launch return not recorded: %+v", got) |
| + } |
| + cases := map[string]func(*HostedNeverLaunched){ |
| + "missing observation": func(n *HostedNeverLaunched) { n.ObservedAt = time.Time{} }, |
| + "observed before launch-by+2m": func(n *HostedNeverLaunched) { n.ObservedAt = hostedLaunchBy.Add(2*time.Minute - time.Second) }, |
| + "abandoned but with a VM": func(n *HostedNeverLaunched) { n.ControllerState, n.VMRef = HostedControllerAbandoned, "vm-9" }, |
| + "absent but with a VM": func(n *HostedNeverLaunched) { n.VMRef = "vm-9" }, |
| + "not signed": func(n *HostedNeverLaunched) { n.Signed = false }, |
| + "a refusal read as no record": func(n *HostedNeverLaunched) { n.ControllerState = "forbidden" }, |
| + "another attempt": func(n *HostedNeverLaunched) { n.AttemptID = "hj_other" }, |
| + "another launch-by": func(n *HostedNeverLaunched) { |
| + n.LaunchBy, n.ObservedAt = hostedLaunchBy.Add(-time.Hour), hostedLaunchBy |
| + }, |
| + "no launch-by": func(n *HostedNeverLaunched) { n.LaunchBy = time.Time{} }, |
| + } |
| + for name, mutate := range cases { |
| + p := neverLaunched(j.AttemptID) |
| + mutate(p.NeverLaunched) |
| + refused(name, p) |
| + } |
| + refused("no evidence at all", HostedEndProof{ObservedAt: r.now}) |
| + abandoned := neverLaunched(j.AttemptID) |
| + abandoned.NeverLaunched.ControllerState = HostedControllerAbandoned |
| + r.must(r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobFailed, abandoned) })) |
| + if got := r.job(j.AttemptID); got.State != HostedJobFailed || !got.proven() { |
| + t.Fatalf("abandoned intent with no VM: %+v", got) |
| + } |
| + // A job that never left pending made no launch call; the evidence |
| + // still has to hold. |
| + r.hostedStep("st2") |
| + k, err := r.newJob("st2", "") |
| + r.must(err) |
| + r.must(r.moveTo(k.AttemptID, HostedJobStopping)) |
| + noBy := neverLaunched(k.AttemptID) |
| + noBy.NeverLaunched.LaunchBy = time.Time{} |
| + if err := r.hosted(func(t *txn) error { return t.hostedEnd(k.AttemptID, HostedJobEnded, noBy) }); !errors.Is(err, ErrHostedNoProof) { |
| + t.Fatalf("evidence with no launch-by: %v", err) |
| + } |
| + if err := r.hosted(func(t *txn) error { return t.hostedLaunchReturned("hj_none") }); !errors.Is(err, ErrNotFound) { |
| + t.Fatalf("launch return for no job: %v", err) |
| + } |
| + r.must(r.hosted(func(t *txn) error { return t.hostedEnd(k.AttemptID, HostedJobEnded, neverLaunched(k.AttemptID)) })) |
| + if got := r.job(k.AttemptID); got.State != HostedJobEnded { |
| + t.Fatalf("never launched: %+v", got) |
| + } |
| } |
| // TestOneLiveJobPerStep: a step has at most one live job, refused by the |
| @@ -368,6 +453,83 @@ func TestSettleIdempotent(t *testing.T) { |
| } |
| } |
| +// TestSettleIdempotentNeedsProof: an ended or failed record whose proof |
| +// is missing or does not hold (written outside the moves) does not |
| +// settle; nothing about it changes, its audit included. |
| +func TestSettleIdempotentNeedsProof(t *testing.T) { |
| + r, audits := hostedRig(t) |
| + used := HostedCharge{Seconds: map[string]int64{"2026-11-08": 600}, Micros: map[string]int64{"2026-11": 103_334}} |
| + launched := neverLaunched("x") |
| + launched.NeverLaunched.ObservedAt = hostedLaunchBy |
| + for i, state := range []string{HostedJobEnded, HostedJobFailed} { |
| + for name, proof := range map[string]string{"no proof": "", "unreadable proof": "{", "proof for another attempt": mustJSON(t, stopProof("hj_other")), "early never-launched evidence": mustJSON(t, launched)} { |
| + step := fmt.Sprintf("st-%d-%d", i, len(name)) |
| + r.hostedStep(step) |
| + j, err := r.newJob(step, "") |
| + r.must(err) |
| + r.exec("UPDATE hosted_jobs SET state = ?, stop_proof_json = ? WHERE attempt_id = ?", state, proof, j.AttemptID) |
| + before, n, probes := r.job(j.AttemptID), len(*audits), r.count("SELECT count(*) FROM audit_probe") |
| + err = r.hosted(func(t *txn) error { _, err := t.settleHostedJob(j.AttemptID, used, r.now); return err }) |
| + if after := r.job(j.AttemptID); !errors.Is(err, ErrHostedNoProof) || !reflect.DeepEqual(before, after) || len(*audits) != n || r.count("SELECT count(*) FROM audit_probe") != probes { |
| + t.Fatalf("%s with %s settled: %v\n%+v\n%+v", state, name, err, before, after) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func mustJSON(t *testing.T, v any) string { |
| + raw, err := json.Marshal(v) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(raw) |
| +} |
| + |
| +// TestHostedJobAuditAtomic: every move and the settlement audit through |
| +// the transaction that writes them (the rig's audit checks the handle), |
| +// and a failed audit rolls the move or the settlement back. |
| +func TestHostedJobAuditAtomic(t *testing.T) { |
| + r, audits := hostedRig(t) |
| + r.hostedStep("st1") |
| + j, err := r.newJob("st1", "") |
| + r.must(err) |
| + audit := r.s.authority.Audit |
| + failing := func(*gorm.DB, string, string, string) error { return errors.New("audit unavailable") } |
| + for _, to := range []string{HostedJobLaunching, HostedJobStopping, HostedJobFailed} { |
| + before, probes := r.job(j.AttemptID), r.count("SELECT count(*) FROM audit_probe") |
| + r.s.authority.Audit = failing |
| + if err := r.moveTo(j.AttemptID, to); err == nil || !reflect.DeepEqual(before, r.job(j.AttemptID)) { |
| + t.Fatalf("an unaudited move to %s was kept: %v", to, err) |
| + } |
| + r.s.authority.Audit = audit |
| + r.must(r.moveTo(j.AttemptID, to)) |
| + if r.count("SELECT count(*) FROM audit_probe") != probes+1 { |
| + t.Fatalf("the move to %s wrote no audit row in its transaction", to) |
| + } |
| + if to == HostedJobLaunching { |
| + before = r.job(j.AttemptID) |
| + r.s.authority.Audit = failing |
| + if err := r.hosted(func(t *txn) error { return t.hostedLaunchReturned(j.AttemptID) }); err == nil || !reflect.DeepEqual(before, r.job(j.AttemptID)) { |
| + t.Fatalf("an unaudited launch return was kept: %v", err) |
| + } |
| + r.s.authority.Audit = audit |
| + r.must(r.hosted(func(t *txn) error { return t.hostedLaunchReturned(j.AttemptID) })) |
| + } |
| + } |
| + used := HostedCharge{Seconds: map[string]int64{"2026-11-08": 600}} |
| + before := r.job(j.AttemptID) |
| + r.s.authority.Audit = failing |
| + if err := r.hosted(func(t *txn) error { _, err := t.settleHostedJob(j.AttemptID, used, r.now); return err }); err == nil || !reflect.DeepEqual(before, r.job(j.AttemptID)) { |
| + t.Fatalf("an unaudited settlement was kept: %v", err) |
| + } |
| + r.s.authority.Audit = audit |
| + n := len(*audits) |
| + r.must(r.hosted(func(t *txn) error { _, err := t.settleHostedJob(j.AttemptID, used, r.now); return err })) |
| + if len(*audits) != n+1 || r.job(j.AttemptID).SettledAt == nil { |
| + t.Fatalf("settlement not audited: %q", *audits) |
| + } |
| +} |
| + |
| // TestMigrationAdditive: from the hosted slice 2 migrations on, each one |
| // only adds. Every table, column and index before it is still there, |
| // unchanged, after it; 0126 adds exactly hosted_jobs and |
diff --git a/internal/equipo/migrations/0126_hosted_jobs.sql b/internal/equipo/migrations/0126_hosted_jobs.sql| index b35488af..783a5674 100644 |
| --- a/internal/equipo/migrations/0126_hosted_jobs.sql |
| +++ b/internal/equipo/migrations/0126_hosted_jobs.sql |
| @@ -3,7 +3,7 @@ |
| -- only; no existing row changes. The instance code and the challenge |
| -- nonce are kept as SHA-256 hashes, never as text. Holds and usage are |
| -- JSON: seconds per UTC day, USD micros per UTC month. |
| -CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, state text, launch_id text, vm_ref text, epoch integer, cert_digest text, cert_valid numeric, cert_checked_at datetime, code_hash text, code_expires_at datetime, code_used_at datetime, runner_id text, machine_public_key text, admitted_at datetime, enrolled_at datetime, ended_at datetime, hold_seconds_json text, hold_micros_json text, used_seconds_json text, used_micros_json text, settled_at datetime, stop_reason text, stop_proof_json text, retry_of text, retries integer, revision integer, PRIMARY KEY (attempt_id)); |
| +CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, state text, launch_id text, vm_ref text, epoch integer, launch_by datetime, launching_since datetime, cert_digest text, cert_valid numeric, cert_checked_at datetime, code_hash text, code_expires_at datetime, code_used_at datetime, runner_id text, machine_public_key text, admitted_at datetime, enrolled_at datetime, ended_at datetime, hold_seconds_json text, hold_micros_json text, used_seconds_json text, used_micros_json text, settled_at datetime, stop_reason text, stop_proof_json text, retry_of text, retries integer, revision integer, PRIMARY KEY (attempt_id)); |
| -- At most one live job a step; a runner is bound to one job; a code |
| -- names one job. |
| CREATE UNIQUE INDEX hosted_jobs_live_step ON hosted_jobs(step_id) WHERE state <> 'ended' AND state <> 'failed'; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index d9baa97c..e451eb7f 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -929,7 +929,7 @@ ALTER TABLE chat_projects ADD COLUMN hosted_checks_revision integer; |
| -- only; no existing row changes. The instance code and the challenge |
| -- nonce are kept as SHA-256 hashes, never as text. Holds and usage are |
| -- JSON: seconds per UTC day, USD micros per UTC month. |
| -CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, state text, launch_id text, vm_ref text, epoch integer, cert_digest text, cert_valid numeric, cert_checked_at datetime, code_hash text, code_expires_at datetime, code_used_at datetime, runner_id text, machine_public_key text, admitted_at datetime, enrolled_at datetime, ended_at datetime, hold_seconds_json text, hold_micros_json text, used_seconds_json text, used_micros_json text, settled_at datetime, stop_reason text, stop_proof_json text, retry_of text, retries integer, revision integer, PRIMARY KEY (attempt_id)); |
| +CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, state text, launch_id text, vm_ref text, epoch integer, launch_by datetime, launching_since datetime, cert_digest text, cert_valid numeric, cert_checked_at datetime, code_hash text, code_expires_at datetime, code_used_at datetime, runner_id text, machine_public_key text, admitted_at datetime, enrolled_at datetime, ended_at datetime, hold_seconds_json text, hold_micros_json text, used_seconds_json text, used_micros_json text, settled_at datetime, stop_reason text, stop_proof_json text, retry_of text, retries integer, revision integer, PRIMARY KEY (attempt_id)); |
| -- At most one live job a step; a runner is bound to one job; a code |
| -- names one job. |
| CREATE UNIQUE INDEX hosted_jobs_live_step ON hosted_jobs(step_id) WHERE state <> 'ended' AND state <> 'failed'; |