oficina / equipo Public

equipo: Task 21 review 1, prove abandoned intents and keep the deadline

An abandoned intent with no VM ref is never-launched evidence only past
launch-by plus the job's lifetime plus 2 minutes: a lost launch reply
may have made a VM the intent never linked. The job keeps its lifetime
and the first time its VM was seen running (migration 0126 in place),
so the enrolment deadline survives restarts and controller outages.
Admission takes the placing transaction's step attempt (Retry), attempt
IDs are provider-valid (hj-), and a retry names a stop-proven
predecessor. Tests: the real controller with a lost launch reply,
unlinked VMs and admission records in the simulation, Retry, the
replacement runner, the cancelled task and a VM learned while stopping.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b58bdd980f611f956608d7d7c0150fcda53b3490 parent cb81f75
13 files changed, +560 −117
  • .rastrillo/budgets.txt +2 −2
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +47 −0
  • internal/equipo/chat/hosted_jobs.go +40 −17
  • internal/equipo/chat/hosted_jobs_test.go +13 −5
  • internal/equipo/chat/hosted_limits_test.go +19 −9
  • internal/equipo/chat/hosted_place_test.go +115 −0
  • internal/equipo/chat/hosted_run.go +25 −4
  • internal/equipo/hostedrun/controller_test.go +167 −0
  • internal/equipo/hostedrun/dispatcher.go +22 −37
  • internal/equipo/hostedrun/dispatcher_test.go +64 −21
  • internal/equipo/hostedrun/sim_test.go +44 −20
  • internal/equipo/migrations/0126_hosted_jobs.sql +1 −1
  • internal/equipo/migrations/schema.sql +1 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 8d0e14f6..2850b570 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -13,7 +13,7 @@ size internal/equipo/team 9396 - Coordinator period accounting, fenced delivery
perf GET /* skip Unknown private paths render 404; this fallback contains no screens.
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-time internal/equipo/hostedrun 45s Hosted slice 2 Task 21: TestDispatcherSimulation runs 200 seeds of the real chat store (SQLite) and dispatcher against a fake controller, about 35 s of CPU in parallel subtests; measured 8 to 10 s on a 16 CPU docs-t1 under load 4; 45s covers a loaded 4 CPU runner.
+time internal/equipo/hostedrun 60s Hosted slice 2 Task 21: TestDispatcherSimulation runs 200 seeds of the real chat store (SQLite) and dispatcher against a fake controller, with unlinked VMs that run to their 90-minute lifetime since review round 1, and one test drives the real controller over TLS for 90 simulated minutes; about 35 s of CPU in parallel subtests; measured 14 s on a 16 CPU docs-t1 under load 2.4; 60s covers a loaded 4 CPU runner.
size internal/equipo 24867 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. Task 17: work.reason.deps_conflict, deps_new_module, deps_missing, deps_too_large and token_renewal_failed (pending); 24741. Task 18: the owner setting "Run checks in a hosted VM" (config flag, routes, section, handler, four pending keys); 24825. Its review round 1: chatMe reports a roster denial as chat.ErrForbidden too (chatDenied); 24837. Task 21: the hosted dispatcher started only with EQUIPO_HOSTED_RUNNERS=1, execution on and a controller configured (EQUIPO_HOSTED_* config, RevokeRunner wiring), and the work.reason words for hosted_enrol_timeout, hosted_vm_lost and hosted_unavailable (pending); 24867.
size internal/wire 9899 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), abilities, 36 lookups, 37 Mac Engineering, 38 Design, unproven and probe detail codes, 39 hosted runners (hosted.go: placement, hosted_pack and deps transfer limits, enrolment types); measured 9848. Task 15 opened TransferHeader.Valid to hosted_pack (inbound, base then candidate) and added ReasonPackIncomplete; 9860. Its review round 1 registered it in StepReasons; 9862. Task 17: the hosted worker's reasons (deps_conflict, deps_new_module, deps_missing, deps_too_large, token_renewal_failed) registered in StepReasons, and TransferHeader.Valid opened to deps with the hosted_pack rules (the worker accepts the bundle; Task 23 sends it); 9884. Task 21: ReasonHostedEnrolTimeout, ReasonHostedVMLost and ReasonHostedUnavailable, registered in StepReasons; 9899.
@@ -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 46665 20804 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.
+size internal/equipo/chat 46709 20937 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.
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 5c798f36..0972396d 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1631,3 +1631,50 @@ Mutations (an exact-string replace from a script under `mktemp -d`, one at a tim
`TestHostedSweepStopsRemovedPerson` (chat, matched by the brief's regex) was added for 303 and 304: with the roster unreadable the sweep fails and the job stays pending; with the person made inactive the job stops `person_removed`.
Not mutation-checked: the cancelled-task branch of `hostedStepAgain`, and `HostedLaunched` recording a VM on a job already stopping. No targeted test reaches them; the simulation reaches the second only by chance.
+
+### Task 21 review round 1 (t21-r1.md: changes requested; coordinator rulings)
+
+1. **Critical, corrected ruling: an abandoned intent is not never-launched evidence until the VM's lifetime has run out.** A launch whose reply was lost may have made a VM the intent never linked. The provider ends that VM at the launch's maximum duration, which is the job's lifetime. So:
+ - `HostedNeverLaunched.holds` takes `abandoned` only when observed at or after `LaunchBy + Lifetime + 2m`; `absent` (the signed 404) keeps `LaunchBy + 2m`.
+ - The job keeps its lifetime: a new `lifetime` column, added in place to unreleased migration 0126 and to `schema.sql`. Placement sets it to `HostedChecksLifetime`; the launch's `MaxLifetimeMS` comes from it.
+ - The dispatcher asks for abandoned evidence only after that time. Until then it keeps calling `Stop`, so the controller's proof ends the job once the unlinked VM is gone.
+ - `HostedReplaces` returns an error for a predecessor holding neither stop proof nor evidence that holds. It names the predecessor whenever its proof is a stop proof.
+ - The integration test also found that `hj_` attempt IDs are refused by the controller (`400 invalid`): attempt IDs are the provider's client token, letters, digits and '-' only. Jobs are now `hj-` IDs.
+2. **The enrolment window is kept on the job.** A new `running_seen_at` column (0126 in place) is set once by `HostedRunning` the first time `Admission` reports the VM running. `watch` checks the deadline from the job row before asking `Admission`, so neither a restart nor a controller outage extends it. The process memory for it is removed.
+3. **Retry.** `hostedJobSpec.Attempt` is the step attempt the placing transaction holds. A person's Retry and a replacement increment it before the step is saved. `newHostedJob` refuses one below the stored attempt and records it.
+4. **Simulation.**
+ - Its fake controller now models launches whose reply was lost after the VM was made. Such a VM is unlinked: the intent has no ref until a replay links it. Stopping abandons it, it runs on until its lifetime or a death, and proof comes only once it is gone. The provider's lifetime limit applies to every VM. "At most one live VM per step" counts unlinked VMs.
+ - The certification claim is gone; Task 24's report acceptance owns that. After every pass the simulation instead checks each job's recorded admission: taken at a time the controller answered for that attempt, never after now or before the previous record, valid only if the certificate was valid then, and naming the job's launch and VM.
+ - Tick cap 180 minutes.
+5. **Throttle staying `launching`.** Accepted by ruling; the dispatcher's comment says so.
+
+New tests:
+- chat: `TestHostedRetryAfterSettled` (the public `RetryStep` after a hosted job settled: job and step both at attempt 2 at once, a sweep leaves the job alone, and the new VM's runner is granted attempt 2), `TestHostedReplacementRunnerAuthorized` (after a VM death the retry's runner is granted the same attempt and the dead VM's runner is refused), `TestHostedCancelledTaskEndsStep`, `TestHostedLaunchedWhileStopping`. `TestEndNeedsProofNeverLaunched` and `TestDelayedLaunchReadmitted` were updated for the corrected abandoned rule.
+- hostedrun: `TestDispatcherLostLaunchReply` (the real controller over TLS with the `isolatedjob` fake injecting `FaultLostReply` on launch, run for 120 simulated minutes), `TestEnrolTimeoutAcrossRestart`, `TestEnrolTimeoutAdmissionOutage`.
+
+Red:
+- `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestEndNeedsProofNeverLaunched|TestDelayedLaunchReadmitted' -count=1`: `hosted_jobs_test.go:297: abandoned at launch-by + 2m: <nil>, state failed` and `hosted_limits_test.go:239: failed on an abandoned intent within its lifetime: <nil>`.
+- `-run TestHostedRetryAfterSettled`: `hosted_place_test.go:557: after Retry: step attempt 2, jobs [... {... StepAttempt:1 ... State:pending ...}]`.
+- The other three chat tests passed at once; they are the guard tests for the branches round 1 left untested (mutations 311 and 312), plus the replacement-runner test the review asked for.
+- `go test ./internal/equipo/hostedrun -run 'TestDispatcherLostLaunchReply|TestEnrolTimeoutAcrossRestart|TestEnrolTimeoutAdmissionOutage' -count=1`:
+ - `controller_test.go:151: restarted just before the window closed: enrolling "", want stopping hosted_enrol_timeout`.
+ - `controller_test.go:165: window closed with the controller unreachable: enrolling ""`.
+ - `controller_test.go:96: the lost launch made no VM: map[]; ... controller answered 400 "invalid"` (the `hj_` IDs). With `hj-` IDs: `controller_test.go:111: job ended at 12:12:20 while its unlinked VM is live`.
+- `-run TestDispatcherSimulation` with unlinked VMs: `sim_test.go:111: seed 26: hj-6pwh... settled as never launched, but its VM vm-4 ran`.
+
+Green: the brief's command passes. The whole chat (30.2 s), hostedrun (14.1 s alone, 17.2 s beside other packages), hostedctl, hostedclient and wire packages pass, as do `./internal/equipo -run 'TestStepReasons|Copy|Config|TestHostedSetting|Migration|Schema'` and the thintest placement, Mac, sandbox, transfer and worker contracts. `make migration-check budget build vet`: exit 0 after raising chat to 46709/20937 and the hostedrun time record to 60s, each with its reason. gofmt and `git diff --check`: clean.
+
+Mutations (same method, a script under `mktemp -d`; each file restored from a copy and compared byte for byte: identical every time):
+- **305** abandoned evidence at launch-by + 2m in the store (the lifetime case removed from `holds`). `-run 'TestEndNeedsProofNeverLaunched|TestDelayedLaunchReadmitted'`: exit 1, `hosted_jobs_test.go:297: abandoned at launch-by + 2m: <nil>, state failed` and `hosted_limits_test.go:243: failed on an abandoned intent within its lifetime: <nil>`. Restored.
+- **306** the same in the dispatcher alone. `-run TestDispatcherLostLaunchReply`: exit 1, `controller_test.go:105: pass at 12:12:20: hosted job hj-...: chat: hosted job has no proof it ended` (the store refuses it). Restored.
+- **307** (the review's critical) both of 305 and 306. `-run 'TestDispatcherLostLaunchReply|TestDispatcherSimulation'`: exit 1, `controller_test.go:111: job ended at 12:12:20 while its unlinked VM is live` and `sim_test.go:111: seed 26: hj-... settled as never launched, but its VM vm-4 ran`. Restored.
+- **308** the first running sight not kept (`HostedRunning` not called). `-run TestEnrolTimeout`: exit 1, `controller_test.go:151: restarted just before the window closed: enrolling ""...`, `controller_test.go:165: ... enrolling ""`, and `TestEnrolTimeoutRetriesOnce` failing. Restored.
+- **309** the deadline checked only after a successful admission. `-run TestEnrolTimeoutAdmissionOutage`: exit 1, `controller_test.go:165: window closed with the controller unreachable: enrolling ""`. Restored.
+- **310** the job takes the stored step attempt. `-run TestHostedRetryAfterSettled`: exit 1, `hosted_place_test.go:557: after Retry: step attempt 2, jobs [... StepAttempt:1 ...]`. Restored.
+- **311** the cancelled-task branch skipped. `-run TestHostedCancelledTaskEndsStep`: exit 1, `hosted_place_test.go:599: cancelled task's step after its VM stopped: queued terminated false, task in_review, 2 jobs`. Restored.
+- **312** a VM named for a stopping job not recorded. `-run TestHostedLaunchedWhileStopping`: exit 1, `hosted_place_test.go:616: VM learned while stopping: stopping "" ""`. Restored.
+- **313** admission recorded a minute early. `-run TestDispatcherSimulation`: exit 1, `sim_test.go:112: seed 200: hj-... admission recorded at 2026-11-08 12:00:00 +0000 UTC, when the controller gave none`, and seeds 38, 45, 63. Restored.
+- **314** `hj_` attempt IDs. `-run TestDispatcherLostLaunchReply`: exit 1, `controller_test.go:96: the lost launch made no VM: map[]; ... controller answered 400 "invalid"`. Restored.
+- **315** a retry never names its stop-proven predecessor (`if false && p.Stop != nil`). `-run TestEnrolTimeoutRetriesOnce`: exit 1, `dispatcher_test.go:630: retry launches [... Replaces: ...], want one for hj-... replacing hj-...`. Restored.
+
+Not mutation-checked: `HostedReplaces`'s error for a predecessor with no proof. `newHostedJob` already refuses such a retry, so no path reaches it.
diff --git a/internal/equipo/chat/hosted_jobs.go b/internal/equipo/chat/hosted_jobs.go
index b1296d1f..9766572b 100644
--- a/internal/equipo/chat/hosted_jobs.go
+++ b/internal/equipo/chat/hosted_jobs.go
@@ -61,7 +61,10 @@ type HostedJob struct {
Project string
Person string `gorm:"index:hosted_jobs_person,priority:1"`
Size isolatedjob.Size
- State string `gorm:"index:hosted_jobs_person,priority:2"`
+ // Lifetime is the VM's maximum lifetime the launch asks for: the
+ // provider ends any VM of the attempt by launch-by plus it.
+ Lifetime time.Duration
+ State string `gorm:"index:hosted_jobs_person,priority:2"`
// LaunchID, VMRef and Epoch are the controller's, from its launch view.
LaunchID string
VMRef string `gorm:"column:vm_ref"`
@@ -72,6 +75,10 @@ type HostedJob struct {
// launching until its reply or its return is recorded.
LaunchBy *time.Time
LaunchingSince *time.Time
+ // RunningSeenAt is when the dispatcher first saw the job's VM
+ // running while it waited to enrol: the enrolment window runs from it
+ // (HostedEnrolTimeout), across restarts and controller outages.
+ RunningSeenAt *time.Time
// Cert* is the controller's latest admission record for the VM.
CertDigest string
CertValid bool
@@ -206,8 +213,12 @@ const (
)
// 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.
+// must be observed to have no record of the attempt: it refuses or
+// abandons any launch after the launch-by, so nothing for the attempt can
+// start once this has passed. An abandoned intent needs the job's
+// lifetime more as well: a launch whose reply was lost may have made a VM
+// the intent never linked, which the provider ends at its lifetime
+// (Task 21 review ruling).
const HostedNeverLaunchedAfter = 2 * time.Minute
// HostedNeverLaunched is the controller's answer for an attempt, as the
@@ -224,14 +235,16 @@ type HostedNeverLaunched struct {
}
// 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.
+// and its launch-by; no record, observed at least HostedNeverLaunchedAfter
+// past the launch-by, or an abandoned intent with no VM, observed at
+// least j's lifetime and HostedNeverLaunchedAfter past it; 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 n.ControllerState == HostedControllerAbandoned && (j.Lifetime <= 0 || n.ObservedAt.Before(n.LaunchBy.Add(j.Lifetime+HostedNeverLaunchedAfter))):
case j.LaunchBy != nil && !j.LaunchBy.Equal(n.LaunchBy):
case j.LaunchingSince != nil:
case j.LaunchID != "", j.VMRef != "", j.RunnerID != "":
@@ -272,23 +285,28 @@ func (j HostedJob) provenErr() error {
return p.proofFor(j)
}
-// hostedJobSpec is what placement admits: the step (its task, project,
-// person and attempt are read from it), the VM size, the hold the limits
-// computed at At, and the proven job of the same step it retries.
+// hostedJobSpec is what placement admits: the step (its task, project
+// and person are read from it) at Attempt, the step's attempt as the
+// placing transaction holds it (a Retry or a replacement moves it on
+// before the step is saved; never below the stored one), the VM size and
+// lifetime, the hold the limits computed at At, and the proven job of the
+// same step it retries.
type hostedJobSpec struct {
- Step string
- Size isolatedjob.Size
- Hold HostedCharge
- RetryOf string
- At time.Time
+ Step string
+ Attempt int64
+ Size isolatedjob.Size
+ Lifetime time.Duration
+ Hold HostedCharge
+ RetryOf string
+ At time.Time
}
// newHostedJob records a pending job for a current member's step: at most
// one live job a step, a non-empty hold, a retry only of its own step's
// ended or failed job that holds proof. Audited in the transaction.
func (t *txn) newHostedJob(sp hostedJobSpec) (HostedJob, error) {
- if sp.Size.MemoryMiB() == 0 || sp.At.IsZero() || len(sp.Hold.Seconds) == 0 || len(sp.Hold.Micros) == 0 {
- return HostedJob{}, fmt.Errorf("%w: hosted job size, time or hold", ErrInvalid)
+ if sp.Size.MemoryMiB() == 0 || sp.At.IsZero() || len(sp.Hold.Seconds) == 0 || len(sp.Hold.Micros) == 0 || sp.Lifetime <= 0 || sp.Lifetime > hostedMaxLifetime {
+ return HostedJob{}, fmt.Errorf("%w: hosted job size, lifetime, time or hold", ErrInvalid)
}
hs, hm, err := sp.Hold.encode()
if err != nil {
@@ -305,6 +323,9 @@ func (t *txn) newHostedJob(sp hostedJobSpec) (HostedJob, error) {
if _, err := t.s.authority.Me(t.db, s.Person); err != nil {
return HostedJob{}, err
}
+ if sp.Attempt < 1 || sp.Attempt < s.Attempt {
+ return HostedJob{}, fmt.Errorf("%w: hosted job for attempt %d of %s at %d", ErrInvalid, sp.Attempt, s.ID, s.Attempt)
+ }
var live int64
if err := t.db.Model(&HostedJob{}).Where("step_id = ? AND state NOT IN ?", s.ID, []string{HostedJobEnded, HostedJobFailed}).Count(&live).Error; err != nil {
return HostedJob{}, err
@@ -313,7 +334,9 @@ func (t *txn) newHostedJob(sp hostedJobSpec) (HostedJob, error) {
return HostedJob{}, ErrHostedJobLive
}
at := sp.At.UTC()
- j := HostedJob{AttemptID: newID("hj_"), StepID: s.ID, StepAttempt: s.Attempt, TaskID: k.ID, Project: k.ProjectID, Person: s.Person, Size: sp.Size,
+ // Attempt IDs are the provider's client tokens: letters, digits and
+ // '-' only.
+ j := HostedJob{AttemptID: newID("hj-"), StepID: s.ID, StepAttempt: sp.Attempt, TaskID: k.ID, Project: k.ProjectID, Person: s.Person, Size: sp.Size, Lifetime: sp.Lifetime,
State: HostedJobPending, AdmittedAt: &at, HoldSecondsJSON: hs, HoldMicrosJSON: hm, RetryOf: sp.RetryOf, Revision: 1}
if sp.RetryOf != "" {
var prior HostedJob
diff --git a/internal/equipo/chat/hosted_jobs_test.go b/internal/equipo/chat/hosted_jobs_test.go
index 76b330eb..4e43c1e0 100644
--- a/internal/equipo/chat/hosted_jobs_test.go
+++ b/internal/equipo/chat/hosted_jobs_test.go
@@ -61,7 +61,7 @@ func (r *hkRig) newJob(step, retryOf string) (HostedJob, error) {
var j HostedJob
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})
+ j, err = t.newHostedJob(hostedJobSpec{Step: step, Attempt: 2, Size: isolatedjob.SizeSmall, Lifetime: HostedChecksLifetime, Hold: hostedHold(), RetryOf: retryOf, At: r.now})
return err
})
return j, err
@@ -247,10 +247,13 @@ func TestEndNeedsProof(t *testing.T) {
}
// 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.
+// when it is the controller's signed observation for the attempt, and no
+// launch call of the job is in flight: no record at all, made at least 2
+// minutes after the job's launch-by; or an abandoned intent with no VM,
+// made at least the job's lifetime plus 2 minutes after it (a launch
+// whose reply was lost may have made a VM no record links, and the
+// provider ends it at its lifetime; Task 21 review ruling). Anything else
+// needs stop proof.
func TestEndNeedsProofNeverLaunched(t *testing.T) {
r, _ := hostedRig(t)
r.hostedStep("st1")
@@ -291,6 +294,11 @@ func TestEndNeedsProofNeverLaunched(t *testing.T) {
refused("no evidence at all", HostedEndProof{ObservedAt: r.now})
abandoned := neverLaunched(j.AttemptID)
abandoned.NeverLaunched.ControllerState = HostedControllerAbandoned
+ refused("abandoned at launch-by + 2m", abandoned)
+ late := hostedLaunchBy.Add(HostedChecksLifetime + 2*time.Minute)
+ abandoned.NeverLaunched.ObservedAt, abandoned.ObservedAt = late.Add(-time.Second), late.Add(-time.Second)
+ refused("abandoned a second before launch-by + lifetime + 2m", abandoned)
+ abandoned.NeverLaunched.ObservedAt, abandoned.ObservedAt = late, late
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)
diff --git a/internal/equipo/chat/hosted_limits_test.go b/internal/equipo/chat/hosted_limits_test.go
index 4be58eb0..47eac378 100644
--- a/internal/equipo/chat/hosted_limits_test.go
+++ b/internal/equipo/chat/hosted_limits_test.go
@@ -35,7 +35,7 @@ func (r *hkRig) admit(step string, size isolatedjob.Size, now time.Time, retryOf
if err != nil {
return err
}
- j, err = t.newHostedJob(hostedJobSpec{Step: step, Size: size, Hold: hold, RetryOf: retryOf, At: now})
+ j, err = t.newHostedJob(hostedJobSpec{Step: step, Attempt: 2, Size: size, Lifetime: HostedChecksLifetime, Hold: hold, RetryOf: retryOf, At: now})
return err
})
return j, reason, err
@@ -165,7 +165,7 @@ func TestLimitsRace(t *testing.T) {
if err != nil {
return err
}
- _, err = t.newHostedJob(hostedJobSpec{Step: step, Size: isolatedjob.SizeLarge, Hold: hold, At: r.now})
+ _, err = t.newHostedJob(hostedJobSpec{Step: step, Attempt: 2, Size: isolatedjob.SizeLarge, Lifetime: HostedChecksLifetime, Hold: hold, At: r.now})
results[i] = "admitted"
return err
})
@@ -210,7 +210,8 @@ func TestHoldSpansMidnight(t *testing.T) {
// TestDelayedLaunchReadmitted: a job admitted at 23:55 and not launched by
// 00:05 is failed, and its step is admitted again against the new day only
-// once the controller shows the intent abandoned and the job settles.
+// once the controller shows it has no record of the attempt (an abandoned
+// intent counts only past the job's lifetime too) and the job settles.
func TestDelayedLaunchReadmitted(t *testing.T) {
r, _ := hostedRig(t)
r.setLimits(HostedLimits{Running: 1, DailySeconds: 6000 + 420, MonthlyMicros: DefaultHostedLimits.MonthlyMicros})
@@ -228,13 +229,22 @@ func TestDelayedLaunchReadmitted(t *testing.T) {
if _, reason, err := r.admit("st-a", isolatedjob.SizeLarge, at(9, 0, 6), j.AttemptID); reason != "running" || err != nil {
t.Fatalf("readmitted while stopping: %q %v", reason, err)
}
- abandoned := func(when time.Time) HostedEndProof {
- return HostedEndProof{NeverLaunched: &HostedNeverLaunched{AttemptID: j.AttemptID, ObservedAt: when, LaunchBy: launchBy, ControllerState: HostedControllerAbandoned, Signed: true}, ObservedAt: when}
+ evidence := func(state string, when time.Time) HostedEndProof {
+ return HostedEndProof{NeverLaunched: &HostedNeverLaunched{AttemptID: j.AttemptID, ObservedAt: when, LaunchBy: launchBy, ControllerState: state, Signed: true}, ObservedAt: when}
}
- if err := r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobFailed, abandoned(at(9, 0, 6))) }); !errors.Is(err, ErrHostedNoProof) {
+ if err := r.hosted(func(t *txn) error {
+ return t.hostedEnd(j.AttemptID, HostedJobFailed, evidence(HostedControllerAbsent, at(9, 0, 6)))
+ }); !errors.Is(err, ErrHostedNoProof) {
t.Fatalf("failed before launch-by plus 2 minutes: %v", err)
}
- r.must(r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobFailed, abandoned(at(9, 0, 7))) }))
+ if err := r.hosted(func(t *txn) error {
+ return t.hostedEnd(j.AttemptID, HostedJobFailed, evidence(HostedControllerAbandoned, at(9, 0, 7)))
+ }); !errors.Is(err, ErrHostedNoProof) {
+ t.Fatalf("failed on an abandoned intent within its lifetime: %v", err)
+ }
+ r.must(r.hosted(func(t *txn) error {
+ return t.hostedEnd(j.AttemptID, HostedJobFailed, evidence(HostedControllerAbsent, at(9, 0, 7)))
+ }))
// Failed but not settled: the whole hold still counts on both days.
if _, reason, err := r.admit("st-a", isolatedjob.SizeLarge, at(9, 0, 8), j.AttemptID); reason != "daily" || err != nil {
t.Fatalf("readmitted before settling: %q %v", reason, err)
@@ -419,7 +429,7 @@ func TestOwnerRaisesLimit(t *testing.T) {
if err != nil {
return err
}
- _, err = t.newHostedJob(hostedJobSpec{Step: step, Size: isolatedjob.SizeLarge, Hold: hold, At: r.now})
+ _, err = t.newHostedJob(hostedJobSpec{Step: step, Attempt: 2, Size: isolatedjob.SizeLarge, Lifetime: HostedChecksLifetime, Hold: hold, At: r.now})
reason = "admitted"
return err
}))
@@ -510,7 +520,7 @@ func TestOwnerRaisesLimitRevoked(t *testing.T) {
if err != nil {
return err
}
- _, err = t.newHostedJob(hostedJobSpec{Step: step, Size: isolatedjob.SizeLarge, Hold: hold, At: r.now})
+ _, err = t.newHostedJob(hostedJobSpec{Step: step, Attempt: 2, Size: isolatedjob.SizeLarge, Lifetime: HostedChecksLifetime, Hold: hold, At: r.now})
return err
})
return reason, err
diff --git a/internal/equipo/chat/hosted_place_test.go b/internal/equipo/chat/hosted_place_test.go
index 3d92a07e..d41c4f0a 100644
--- a/internal/equipo/chat/hosted_place_test.go
+++ b/internal/equipo/chat/hosted_place_test.go
@@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
+ "errors"
"strings"
"testing"
"time"
@@ -512,3 +513,117 @@ func TestHostedSweepStopsRemovedPerson(t *testing.T) {
t.Fatalf("person removed: job %s %q, want stopping", j.State, j.StopReason)
}
}
+
+// hostedOnVM places s1 of tkp on job VM vm enrolled as runner, and
+// returns the job.
+func (r *hkRig) hostedOnVM(vm, runner string) HostedJob {
+ r.t.Helper()
+ jobs := r.jobsOf("s1")
+ a := jobs[len(jobs)-1].AttemptID
+ r.launched(a, vm)
+ r.enrol(a, runner, wire.ProtocolHostedRunners)
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.place()
+ if s := r.step("s1"); s.RunnerID != runner {
+ r.t.Fatalf("s1 on %q, want %s", s.RunnerID, runner)
+ }
+ return r.job(a)
+}
+
+func hostedLease(runner string) Lease {
+ return Lease{Runner: RunnerPrincipal{RunnerID: runner, Person: hkOwner}, Generation: 1, Process: "p", Protocol: wire.ProtocolHostedRunners, Role: wire.RoleWorker}
+}
+
+// TestHostedRetryAfterSettled: the person's Retry of a hosted step whose
+// jobs have settled admits a job for the step's new attempt, in the same
+// transaction: the job and the step name the same attempt at once, the
+// sweep leaves it alone, and its runner is authorized for that attempt.
+func TestHostedRetryAfterSettled(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ first := r.hostedOnVM("vm-1", "H1")
+ r.exec("UPDATE chat_steps SET state = ?, reason = 'checks_timeout', terminated = 1, finished_at = ? WHERE id = 's1'", wire.StepFailed, r.now)
+ r.must(r.s.HostedSweep(r.ctx))
+ r.must(r.s.HostedStopped(r.ctx, first.AttemptID, hostedwire.StopProof{AttemptID: first.AttemptID, VMRef: "vm-1", State: isolatedjob.StateStopped}, r.now))
+ if j := r.job(first.AttemptID); j.State != HostedJobEnded || j.SettledAt == nil {
+ t.Fatalf("first job after its step failed: %s settled %v", j.State, j.SettledAt)
+ }
+ attempt, err := r.s.RetryStep(r.ctx, hkOwner, "tkp", "s1")
+ if err != nil || attempt != 2 {
+ t.Fatalf("Retry: %d %v", attempt, err)
+ }
+ jobs := r.jobsOf("s1")
+ if s := r.step("s1"); len(jobs) != 2 || jobs[1].StepAttempt != s.Attempt || s.Attempt != 2 || jobs[1].State != HostedJobPending || jobs[1].RetryOf != "" {
+ t.Fatalf("after Retry: step attempt %d, jobs %+v", s.Attempt, jobs)
+ }
+ r.must(r.s.HostedSweep(r.ctx))
+ if j := r.job(jobs[1].AttemptID); j.State != HostedJobPending {
+ t.Fatalf("the retry's job after a sweep: %s %q", j.State, j.StopReason)
+ }
+ r.hostedOnVM("vm-2", "H2")
+ if got, err := r.s.Authorize(r.ctx, hostedLease("H2"), "s1", 2, "", "", ""); err != nil || got != "" {
+ t.Fatalf("H2 authorizing attempt 2: %q %v, want granted", got, err)
+ }
+}
+
+// TestHostedReplacementRunnerAuthorized: after a VM dies mid-step its
+// attempt is placed again under the same attempt; the retry's runner is
+// authorized for it and the dead VM's runner is not.
+func TestHostedReplacementRunnerAuthorized(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ first := r.hostedOnVM("vm-1", "H1")
+ if got, err := r.s.Authorize(r.ctx, hostedLease("H1"), "s1", 1, "", "", ""); err != nil || got != "" {
+ t.Fatalf("H1 authorizing: %q %v", got, err)
+ }
+ r.stopped(first.AttemptID, wire.ReasonHostedVMLost)
+ r.hostedOnVM("vm-2", "H2")
+ if got, err := r.s.Authorize(r.ctx, hostedLease("H2"), "s1", 1, "", "", ""); err != nil || got != "" {
+ t.Fatalf("H2 authorizing the replaced attempt: %q %v, want granted", got, err)
+ }
+ if got, err := r.s.Authorize(r.ctx, hostedLease("H1"), "s1", 1, "", "", ""); err != nil || got != "withdrawn" {
+ t.Fatalf("the dead VM's H1 authorizing: %q %v, want withdrawn", got, err)
+ }
+}
+
+// TestHostedCancelledTaskEndsStep: a cancelled task's step on a VM ends
+// cancelled once the VM is proven stopped; nothing is placed again.
+func TestHostedCancelledTaskEndsStep(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.hostedOnVM("vm-1", "H1")
+ r.exec("UPDATE chat_tasks SET cancel_requested = 1 WHERE id = 'tkp'")
+ r.stopped(j.AttemptID, wire.ReasonHostedVMLost)
+ s, k := r.step("s1"), r.load("tkp")
+ if s.State != wire.StepCancelled || !s.Terminated || k.Stage != wire.StageCancelled || len(r.jobsOf("s1")) != 1 {
+ t.Fatalf("cancelled task's step after its VM stopped: %s terminated %t, task %s, %d jobs", s.State, s.Terminated, k.Stage, len(r.jobsOf("s1")))
+ }
+}
+
+// TestHostedLaunchedWhileStopping: a VM the controller names for a job
+// that is already stopping is recorded: never-launched evidence no longer
+// ends the job, nor does another VM's proof; that VM's proof does.
+func TestHostedLaunchedWhileStopping(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ a := r.jobsOf("s1")[0].AttemptID
+ by := r.job(a).AdmittedAt.Add(HostedLaunchWindow)
+ r.must(r.s.HostedLaunching(r.ctx, a, hostedCode, by.Add(HostedLaunchWindow), by))
+ r.must(r.s.HostedLaunchReturned(r.ctx, a))
+ r.must(r.s.HostedFailed(r.ctx, a, wire.ReasonHostedUnavailable))
+ r.must(r.s.HostedLaunched(r.ctx, a, hostedwire.JobView{AttemptID: a, LaunchID: "launch-7", State: "running", VMRef: "vm-7"}))
+ if j := r.job(a); j.State != HostedJobStopping || j.VMRef != "vm-7" || j.LaunchID != "launch-7" {
+ t.Fatalf("VM learned while stopping: %s %q %q", j.State, j.VMRef, j.LaunchID)
+ }
+ at := by.Add(HostedNeverLaunchedAfter)
+ if err := r.s.HostedNeverLaunched(r.ctx, a, HostedNeverLaunched{AttemptID: a, ObservedAt: at, LaunchBy: by, ControllerState: HostedControllerAbsent, Signed: true}); !errors.Is(err, ErrHostedNoProof) {
+ t.Fatalf("never-launched evidence for a job with a VM: %v", err)
+ }
+ if err := r.s.HostedStopped(r.ctx, a, hostedwire.StopProof{AttemptID: a, VMRef: "vm-8", State: isolatedjob.StateStopped}, at); !errors.Is(err, ErrHostedNoProof) {
+ t.Fatalf("another VM's proof: %v", err)
+ }
+ r.must(r.s.HostedStopped(r.ctx, a, hostedwire.StopProof{AttemptID: a, VMRef: "vm-7", State: isolatedjob.StateStopped}, at))
+ if j := r.job(a); j.State != HostedJobFailed || j.SettledAt == nil {
+ t.Fatalf("after its VM's proof: %s", j.State)
+ }
+}
diff --git a/internal/equipo/chat/hosted_run.go b/internal/equipo/chat/hosted_run.go
index d8835117..feb09c30 100644
--- a/internal/equipo/chat/hosted_run.go
+++ b/internal/equipo/chat/hosted_run.go
@@ -172,7 +172,7 @@ func (t *txn) placeHosted(k *taskRecord, s *stepRecord, primary string, needs []
if err != nil {
return false, false, err
}
- if _, err := t.newHostedJob(hostedJobSpec{Step: s.ID, Size: HostedChecksSize, Hold: hold, RetryOf: retryOf, At: now}); err != nil {
+ if _, err := t.newHostedJob(hostedJobSpec{Step: s.ID, Attempt: s.Attempt, Size: HostedChecksSize, Lifetime: HostedChecksLifetime, Hold: hold, RetryOf: retryOf, At: now}); err != nil {
return false, false, err
}
return wait(wire.PlacementHosted, "")
@@ -344,6 +344,20 @@ func (s *Store) HostedAdmitted(ctx context.Context, attempt string, a hostedwire
})
}
+// HostedRunning records when the dispatcher first saw an enrolling job's
+// VM running (at, on the instance's clock); a later observation changes
+// nothing. The enrolment window runs from it.
+func (s *Store) HostedRunning(ctx context.Context, attempt string, at time.Time) error {
+ return s.tx(ctx, func(t *txn) error {
+ res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND state = ? AND running_seen_at IS NULL", attempt, HostedJobEnrolling).
+ Updates(map[string]any{"running_seen_at": at.UTC(), "revision": gorm.Expr("revision + 1")})
+ if res.Error != nil || res.RowsAffected == 0 {
+ return res.Error
+ }
+ return t.s.authority.Audit(t.db, "system", "hosted.job", attempt+":running_seen")
+ })
+}
+
// HostedFailed stops a live job for reason (the dispatcher's
// wire.ReasonHosted* failures): it moves to stopping, and ends failed
// once its proof arrives. A job already stopping or ended is left as it
@@ -380,8 +394,9 @@ func (s *Store) HostedNeverLaunched(ctx context.Context, attempt string, n Hoste
// HostedReplaces is what a job's launch names as the attempt it replaces:
// its predecessor (retry_of) when that one ended with the controller's
// stop proof, which the controller holds too; "" for a first job, or one
-// whose predecessor never launched (the controller holds no proof for an
-// attempt it never ran, and would refuse the launch).
+// whose predecessor ended with never-launched evidence that holds (the
+// controller holds no proof for an attempt it never ran, and would refuse
+// the launch). A predecessor with neither is an error: the launch waits.
func (s *Store) HostedReplaces(ctx context.Context, attempt string) (string, error) {
var out string
err := s.read(ctx, func(tx *gorm.DB) error {
@@ -393,7 +408,13 @@ func (s *Store) HostedReplaces(ctx context.Context, attempt string) (string, err
return err
}
var p HostedEndProof
- if prior.proven() && json.Unmarshal([]byte(prior.StopProofJSON), &p) == nil && p.Stop != nil {
+ if err := prior.provenErr(); err != nil {
+ return err
+ }
+ if err := json.Unmarshal([]byte(prior.StopProofJSON), &p); err != nil {
+ return err
+ }
+ if p.Stop != nil {
out = prior.AttemptID
}
return nil
diff --git a/internal/equipo/hostedrun/controller_test.go b/internal/equipo/hostedrun/controller_test.go
new file mode 100644
index 00000000..592df97f
--- /dev/null
+++ b/internal/equipo/hostedrun/controller_test.go
@@ -0,0 +1,167 @@
+package hostedrun
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/json"
+ "net/netip"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/hostedclient"
+ "amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+type nopAlerter struct{}
+
+func (nopAlerter) Alert(context.Context, hostedctl.Alert) error { return nil }
+
+// TestDispatcherLostLaunchReply: the real controller over the provider
+// fake, which makes the VM but loses its launch reply, so the intent
+// holds no VM ref. The step ends, the stop abandons the intent, and the
+// unlinked VM runs on to its lifetime: the job stays stopping, with its
+// hold, past launch-by + 2 minutes, and ends only once the controller
+// proves no VM is left. At no time is the job ended while a VM of its
+// attempt is live.
+func TestDispatcherLostLaunchReply(t *testing.T) {
+ r := newRig(t, nil)
+ ctx := context.Background()
+ clk := isolatedjobtest.NewFakeClock(r.now)
+ store, err := hostedctl.Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), clk)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+ fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: ctlcerttest.Set(ctlcerttest.Cert(image, "equipo.example.com")),
+ ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey(), ProviderNamespace: "test",
+ ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
+ Manifest: ctlegress.Manifest{
+ Services: map[string]hostedwire.Service{"instance": {Host: "equipo.example.com", Port: 443, Class: hostedwire.ServiceInstance}},
+ Proxies: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8443")},
+ ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8444")},
+ ProxyCAPin: strings.Repeat("ab", 32),
+ }},
+ hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := c.RunAudit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ instKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
+ ctlKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize))
+ h, err := c.Handler(hostedctl.HandlerConfig{
+ Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{"inst-1": {Public: instKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}},
+ Signing: ctlKey, Wall: time.Now})
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := serveTLS(t, h)
+ t.Setenv(hostedclient.FlagEnv, "1")
+ cl, err := hostedclient.New(hostedclient.Config{BaseURL: srv.URL, KeyID: "inst-1", Key: instKey, ControllerKey: ctlKey.Public().(ed25519.PublicKey), HTTP: srv.Client()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.disp.Client = cl
+ step := func(d time.Duration) {
+ t.Helper()
+ r.now = r.now.Add(d)
+ clk.AdvanceMono(d)
+ clk.SetWall(r.now)
+ r.online(primary)
+ fake.Tick()
+ _ = c.Refresh(ctx)
+ if err := r.disp.Pass(ctx); err != nil {
+ t.Fatalf("pass at %s: %v", r.now.Format(time.TimeOnly), err)
+ }
+ }
+ r.checks("s1", "tk1")
+ step(Every)
+ j := r.jobs("s1")[0]
+ fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultLostReply)
+ step(Every)
+ if fake.LiveByAttempt()[j.AttemptID] != 1 {
+ t.Fatalf("the lost launch made no VM: %v; job %s; log %s", fake.LiveByAttempt(), r.job(j.AttemptID).State, r.logs)
+ }
+ if got := r.job(j.AttemptID); got.State != chat.HostedJobLaunching || got.VMRef != "" || got.LaunchingSince != nil {
+ t.Fatalf("after the lost reply: %s %q in flight %v", got.State, got.VMRef, got.LaunchingSince)
+ }
+ r.exec("UPDATE chat_steps SET state = ?, checks = ? WHERE id = 's1'", wire.StepDone, wire.ChecksPassed)
+ by := j.AdmittedAt.Add(chat.HostedLaunchWindow)
+ sawLive := false
+ for i := 0; i < 240; i++ {
+ step(30 * time.Second)
+ got := r.job(j.AttemptID)
+ live := fake.LiveByAttempt()[j.AttemptID] > 0
+ sawLive = sawLive || live && r.now.After(by.Add(chat.HostedNeverLaunchedAfter+time.Minute))
+ if !got.Live() {
+ if live {
+ t.Fatalf("job %s at %s while its unlinked VM is live", got.State, r.now.Format(time.TimeOnly))
+ }
+ var p chat.HostedEndProof
+ r.must(json.Unmarshal([]byte(got.StopProofJSON), &p))
+ if got.SettledAt == nil || !sawLive {
+ t.Fatalf("ended %s settled %v; the VM was live past launch-by + 2m: %t", got.State, got.SettledAt, sawLive)
+ }
+ return
+ }
+ if got.SettledAt != nil || got.HoldSecondsJSON == "" {
+ t.Fatalf("a live job lost its hold: %+v", got)
+ }
+ }
+ t.Fatalf("job never ended: %s", r.job(j.AttemptID).State)
+}
+
+// enrolling runs passes until the dispatcher has seen s1's job's VM
+// running, and returns the job.
+func (r *rig) enrolling() chat.HostedJob {
+ r.t.Helper()
+ r.checks("s1", "tk1")
+ r.passes(Every)
+ a := r.jobs("s1")[0].AttemptID
+ r.until(time.Minute, "the VM running", func() bool { v := r.ctl.vm(a); return v != nil && v.state == ctlRunning })
+ return r.job(a)
+}
+
+// TestEnrolTimeoutAcrossRestart: the enrolment window runs from when the
+// VM was first seen running, kept on the job: an instance restart just
+// before it closes does not open a new one.
+func TestEnrolTimeoutAcrossRestart(t *testing.T) {
+ r := newRig(t, nil)
+ j := r.enrolling()
+ r.passes(chat.HostedEnrolTimeout - Every)
+ if got := r.job(j.AttemptID); got.State != chat.HostedJobEnrolling {
+ t.Fatalf("within the window: %s", got.State)
+ }
+ r.restart()
+ r.passes(2 * Every)
+ if got := r.job(j.AttemptID); got.Live() && (got.State != chat.HostedJobStopping || got.StopReason != wire.ReasonHostedEnrolTimeout) {
+ t.Fatalf("restarted just before the window closed: %s %q, want stopping hosted_enrol_timeout", got.State, got.StopReason)
+ }
+}
+
+// TestEnrolTimeoutAdmissionOutage: a VM not enrolled when its window
+// closes is failed even while the controller cannot be reached.
+func TestEnrolTimeoutAdmissionOutage(t *testing.T) {
+ r := newRig(t, nil)
+ j := r.enrolling()
+ r.ctl.mu.Lock()
+ r.ctl.down = true
+ r.ctl.mu.Unlock()
+ r.passes(chat.HostedEnrolTimeout + Every)
+ if got := r.job(j.AttemptID); got.State != chat.HostedJobStopping || got.StopReason != wire.ReasonHostedEnrolTimeout {
+ t.Fatalf("window closed with the controller unreachable: %s %q", got.State, got.StopReason)
+ }
+}
diff --git a/internal/equipo/hostedrun/dispatcher.go b/internal/equipo/hostedrun/dispatcher.go
index 88365e89..2d7a9238 100644
--- a/internal/equipo/hostedrun/dispatcher.go
+++ b/internal/equipo/hostedrun/dispatcher.go
@@ -86,10 +86,6 @@ type Dispatcher struct {
// reply was lost is sent again unchanged (the controller takes the
// same request again). The store keeps only their hashes.
codes map[string]string
- // running is when this process first saw each enrolling job's VM
- // running: its enrolment window (chat.HostedEnrolTimeout) runs from
- // then.
- running map[string]time.Time
// waits are the launch and intent backoffs.
waits map[string]backoff
}
@@ -222,7 +218,10 @@ func (d *Dispatcher) job(ctx context.Context, j chat.HostedJob) error {
case v.State == ctlAbandoned:
return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedUnavailable)
}
- // Waiting: the controller launches it when the provider allows.
+ // Waiting: the controller launches it when the provider allows. The
+ // job stays launching meanwhile, not pending (Task 21 review
+ // ruling): the controller holds an intent that may still launch,
+ // so it ends only with proof.
d.later(j.AttemptID, now)
return nil
case chat.HostedJobEnrolling, chat.HostedJobEnrolled:
@@ -250,7 +249,7 @@ func (d *Dispatcher) launch(ctx context.Context, j chat.HostedJob, by time.Time)
return errors.Join(err, d.Store.HostedLaunchReturned(ctx, j.AttemptID))
}
q := hostedwire.LaunchRequest{AttemptID: j.AttemptID, TaskID: j.TaskID, Account: d.Account, Replaces: replaces, Image: d.Image,
- Size: j.Size, MaxLifetimeMS: chat.HostedChecksLifetime.Milliseconds(), InstanceCode: code,
+ Size: j.Size, MaxLifetimeMS: j.Lifetime.Milliseconds(), InstanceCode: code,
Person: j.Person, Purpose: hostedwire.PurposeChecks, LaunchByUnixMS: by.UnixMilli()}
v, err := d.Client.Launch(ctx, q)
if err == nil && v.VMRef.Valid() {
@@ -269,11 +268,15 @@ func (d *Dispatcher) launch(ctx context.Context, j chat.HostedJob, by time.Time)
// watch refreshes an enrolling or enrolled job's admission record and
// records it, with the time the question was asked (never later than the
-// controller's check). A VM the controller reports gone fails the job; an
-// enrolling VM running for chat.HostedEnrolTimeout without enrolling is
-// stopped.
+// controller's check). A VM the controller reports gone fails the job. An
+// enrolling VM first seen running chat.HostedEnrolTimeout ago (kept on
+// the job, so a restart or a controller outage does not extend it) is
+// stopped, whether or not this refresh succeeds.
func (d *Dispatcher) watch(ctx context.Context, j chat.HostedJob) error {
asked := d.now()
+ if j.State == chat.HostedJobEnrolling && j.RunningSeenAt != nil && !asked.Before(j.RunningSeenAt.Add(chat.HostedEnrolTimeout)) {
+ return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedEnrolTimeout)
+ }
a, err := d.Client.Admission(ctx, j.AttemptID)
if err != nil {
d.log().Warn("hosted_admission_failed", "attempt", j.AttemptID, "err", err)
@@ -286,21 +289,8 @@ func (d *Dispatcher) watch(ctx context.Context, j chat.HostedJob) error {
case ctlAbandoned, ctlStopping, ctlStopped:
return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedVMLost)
case ctlRunning:
- if j.State != chat.HostedJobEnrolling {
- return nil
- }
- d.mu.Lock()
- first, seen := d.running[j.AttemptID]
- if !seen {
- first = asked
- if d.running == nil {
- d.running = map[string]time.Time{}
- }
- d.running[j.AttemptID] = first
- }
- d.mu.Unlock()
- if asked.Sub(first) >= chat.HostedEnrolTimeout {
- return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedEnrolTimeout)
+ if j.State == chat.HostedJobEnrolling && j.RunningSeenAt == nil {
+ return d.Store.HostedRunning(ctx, j.AttemptID, asked)
}
}
return nil
@@ -325,11 +315,13 @@ func (d *Dispatcher) stop(ctx context.Context, j chat.HostedJob) error {
}
// neverLaunched ends a stopping job that has no launch on record with the
-// controller's own word, read at least chat.HostedNeverLaunchedAfter past
-// its launch-by (the controller launches nothing after it): a signed
-// not-found (hostedclient.ErrAbsent), or its intent abandoned with no VM.
-// A refusal or a transport error is never evidence. A VM the answer names
-// is recorded, and its stop proof is waited for instead.
+// controller's own word: a signed not-found (hostedclient.ErrAbsent) read
+// at least chat.HostedNeverLaunchedAfter past its launch-by (the
+// controller launches nothing after it), or its intent abandoned with no
+// VM read at least the job's lifetime more past it (a lost launch reply
+// may have made a VM the intent never linked; the provider ends it by
+// then). A refusal or a transport error is never evidence. A VM the
+// answer names is recorded, and its stop proof is waited for instead.
func (d *Dispatcher) neverLaunched(ctx context.Context, j chat.HostedJob) error {
by := launchBy(j)
observed := d.now()
@@ -350,7 +342,7 @@ func (d *Dispatcher) neverLaunched(ctx context.Context, j chat.HostedJob) error
return nil
case v.VMRef != "":
return d.Store.HostedLaunched(ctx, j.AttemptID, v)
- case v.State == ctlAbandoned:
+ case v.State == ctlAbandoned && !observed.Before(by.Add(j.Lifetime+chat.HostedNeverLaunchedAfter)):
state = chat.HostedControllerAbandoned
default:
return nil
@@ -406,13 +398,6 @@ func (d *Dispatcher) settled(attempt string) {
func (d *Dispatcher) forget(live map[string]bool) {
d.mu.Lock()
defer d.mu.Unlock()
- for _, m := range []map[string]time.Time{d.running} {
- for a := range m {
- if !live[a] {
- delete(m, a)
- }
- }
- }
for a := range d.codes {
if !live[a] {
delete(d.codes, a)
diff --git a/internal/equipo/hostedrun/dispatcher_test.go b/internal/equipo/hostedrun/dispatcher_test.go
index 5ff15e03..37407d74 100644
--- a/internal/equipo/hostedrun/dispatcher_test.go
+++ b/internal/equipo/hostedrun/dispatcher_test.go
@@ -309,29 +309,43 @@ type fakeVM struct {
proof *hostedwire.StopProof
proofAt time.Time
noEnrol bool
+ // unlinked: the provider made the VM but the launch reply was lost,
+ // so the intent holds no ref; replay links it, unless the intent was
+ // abandoned first. vmEnded: the VM is gone (stopped, died, or out of
+ // lifetime), proof or not.
+ unlinked bool
+ vmEnded bool
+ startedAt time.Time
}
func (v *fakeVM) view() hostedwire.JobView {
- return hostedwire.JobView{AttemptID: v.q.AttemptID, LaunchID: v.launchID, State: v.state, VMRef: v.ref}
+ w := hostedwire.JobView{AttemptID: v.q.AttemptID, LaunchID: v.launchID, State: v.state, VMRef: v.ref}
+ if v.unlinked {
+ w.VMRef = ""
+ }
+ return w
}
-// alive reports whether the VM may be running.
-func (v *fakeVM) alive() bool { return v.everVM && v.proof == nil }
+// alive reports whether the VM may be running, linked or not.
+func (v *fakeVM) alive() bool { return v.everVM && !v.vmEnded && v.proof == nil }
// fakeCtl is the controller as the dispatcher sees it: launch-by, the
// replaced attempt's proof, idempotent launches and signed not-found
// answers, with chance events from rng (lost replies, throttles, VM
// deaths). Each call happens in full; a lost reply only loses the answer.
type fakeCtl struct {
- mu sync.Mutex
- now func() time.Time
- rng *rand.Rand
- jobs map[string]*fakeVM
- n int
- lose float64
- throttle float64
- death float64
- noEnrol float64
+ mu sync.Mutex
+ now func() time.Time
+ rng *rand.Rand
+ jobs map[string]*fakeVM
+ n int
+ lose float64
+ throttle float64
+ death float64
+ noEnrol float64
+ unlinked float64
+ // admitted is when each attempt's admission was answered.
+ admitted map[string][]time.Time
certValid bool
// certs is when the certificate's validity changed, oldest first.
certs []certChange
@@ -365,13 +379,16 @@ func (f *fakeCtl) vm(attempt string) *fakeVM {
func (f *fakeCtl) start(v *fakeVM) {
f.n++
- v.ref, v.state, v.everVM = isolatedjob.Ref(fmt.Sprintf("vm-%d", f.n)), "starting", true
+ v.ref, v.state, v.everVM, v.startedAt = isolatedjob.Ref(fmt.Sprintf("vm-%d", f.n)), "starting", true, f.now()
v.noEnrol = f.chance(f.noEnrol)
}
func (f *fakeCtl) prove(v *fakeVM) {
- v.state = ctlStopped
+ v.state, v.vmEnded = ctlStopped, true
v.proof = &hostedwire.StopProof{AttemptID: v.q.AttemptID, VMRef: v.ref, State: isolatedjob.StateStopped}
+ if v.unlinked {
+ v.proof.VMRef = ""
+ }
v.proofAt = f.now()
}
@@ -381,11 +398,25 @@ func (f *fakeCtl) tick() {
f.mu.Lock()
defer f.mu.Unlock()
for _, v := range f.ordered() {
+ // The provider ends every VM at its lifetime, linked or not.
+ if v.alive() && f.now().Sub(v.startedAt) >= time.Duration(v.q.MaxLifetimeMS)*time.Millisecond {
+ v.vmEnded = true
+ if !v.unlinked {
+ f.prove(v)
+ }
+ }
+ if v.unlinked && v.alive() && v.state != ctlAbandoned && f.chance(f.death) {
+ v.vmEnded = true
+ }
switch v.state {
case "waiting":
- if f.now().UnixMilli() > v.q.LaunchByUnixMS || v.stopAsked {
+ switch {
+ case f.now().UnixMilli() > v.q.LaunchByUnixMS || v.stopAsked:
v.state = ctlAbandoned
- } else if !f.chance(f.throttle) {
+ case v.unlinked && !v.vmEnded && f.chance(0.5):
+ // Replay finds the VM its lost reply made.
+ v.unlinked, v.state = false, "starting"
+ case !v.everVM && !f.chance(f.throttle):
f.start(v)
}
case "starting":
@@ -399,7 +430,9 @@ func (f *fakeCtl) tick() {
f.prove(v)
}
case ctlAbandoned:
- if v.stopAsked && v.proof == nil {
+ // Proof only once a list shows no VM: an unlinked one is
+ // still running until it ends.
+ if v.stopAsked && v.proof == nil && (!v.everVM || v.vmEnded) {
v.proof = &hostedwire.StopProof{AttemptID: v.q.AttemptID, State: isolatedjob.StateStopped}
v.proofAt = f.now()
}
@@ -445,6 +478,12 @@ func (f *fakeCtl) Launch(_ context.Context, q hostedwire.LaunchRequest) (hostedw
}
v := &fakeVM{q: q, state: "waiting", launchID: fmt.Sprintf("launch-%d", len(f.jobs)+1)}
f.jobs[q.AttemptID] = v
+ if f.chance(f.unlinked) {
+ // The provider made it; its reply was lost.
+ f.start(v)
+ v.unlinked, v.state = true, "waiting"
+ return hostedwire.JobView{}, hostedclient.ErrProvider
+ }
if !f.chance(f.throttle) {
f.start(v)
}
@@ -489,7 +528,11 @@ func (f *fakeCtl) Admission(_ context.Context, attempt string) (hostedwire.Admis
if f.chance(f.lose) {
return hostedwire.AdmissionView{}, hostedclient.ErrTransport
}
- return hostedwire.AdmissionView{AttemptID: attempt, LaunchID: v.launchID, State: v.state, VMRef: v.ref, Image: v.q.Image,
+ if f.admitted == nil {
+ f.admitted = map[string][]time.Time{}
+ }
+ f.admitted[attempt] = append(f.admitted[attempt], f.now())
+ return hostedwire.AdmissionView{AttemptID: attempt, LaunchID: v.launchID, State: v.state, VMRef: v.view().VMRef, Image: v.q.Image,
CertDigest: "cert-1", CertValid: f.certValid, CheckedNS: f.now().UnixNano()}, nil
}
@@ -513,10 +556,10 @@ func (f *fakeCtl) Stop(_ context.Context, attempt, reason string) (hostedwire.St
}
return *v.proof, nil
}
- switch v.state {
- case "waiting":
+ switch {
+ case v.state == "waiting":
v.state = ctlAbandoned
- case "starting", ctlRunning:
+ case v.state == "starting" || v.state == ctlRunning:
v.state, v.stopTicks = ctlStopping, f.stopDelay
}
return hostedwire.StopProof{}, hostedclient.ErrStopPending
diff --git a/internal/equipo/hostedrun/sim_test.go b/internal/equipo/hostedrun/sim_test.go
index 5cf65bcf..e649b15b 100644
--- a/internal/equipo/hostedrun/sim_test.go
+++ b/internal/equipo/hostedrun/sim_test.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"math/rand"
+ "slices"
"testing"
"time"
@@ -20,21 +21,26 @@ const simSeeds = 200
const simEvery = 2 * Every
// TestDispatcherSimulation drives the real store and dispatcher against a
-// fake controller with lost replies, throttles, outages, VM deaths and
-// VMs that never enrol, with instance restarts (some mid-launch) and certificate
+// fake controller with lost replies, launches whose reply was lost after
+// the provider made the VM (unlinked until a replay finds it), throttles,
+// outages, VM deaths, VMs that never enrol and the provider's lifetime
+// limit, with instance restarts (some mid-launch) and certificate
// withdrawal, on a fake clock, one seed a run. Three checks steps of one
// person compete for two running jobs. After every pass:
//
-// - no step has more than one live VM;
+// - no step has more than one live VM, unlinked ones included;
// - the person never has more running jobs than the limit;
// - the held and settled charges never exceed the daily or monthly
// limit;
// - every settled job holds proof the controller would vouch for;
-// - a step's result counts as certified (the job's latest admission
-// valid and fresh) only when the certificate really was valid then.
+// - each job's recorded admission is one the controller gave: taken at
+// a time it answered for that attempt, never later than now or older
+// than the one before, valid only if the certificate was valid then,
+// and naming the job's own launch and VM.
//
-// Every step ends, and every job ends with proof and is settled. A
-// failure names its seed.
+// Whether a step's result counts as certified is Task 24's (report
+// acceptance); the simulation only ends steps. Every step ends, and every
+// job ends with proof and is settled. A failure names its seed.
func TestDispatcherSimulation(t *testing.T) {
for seed := int64(1); seed <= simSeeds; seed++ {
t.Run(fmt.Sprintf("seed-%d", seed), func(t *testing.T) {
@@ -48,7 +54,7 @@ func simulate(t *testing.T, seed int64) {
rng := rand.New(rand.NewSource(seed))
r := newRig(t, rng)
c := r.ctl
- c.lose, c.throttle, c.death, c.noEnrol = rng.Float64()*0.2, rng.Float64(), rng.Float64()*0.04, rng.Float64()*0.3
+ c.lose, c.throttle, c.death, c.noEnrol, c.unlinked = rng.Float64()*0.2, rng.Float64(), rng.Float64()*0.04, rng.Float64()*0.3, rng.Float64()*0.2
outage := 0
c.stopDelay = 1 + rng.Intn(4)
steps := []string{"s1", "s2", "s3"}
@@ -56,10 +62,11 @@ func simulate(t *testing.T, seed int64) {
r.checks(s, fmt.Sprintf("tk%d", i+1))
}
limits := chat.DefaultHostedLimits
+ checked := map[string]time.Time{}
runners := 0
for tick := 0; ; tick++ {
- if tick > 300 {
- t.Fatalf("seed %d: not settled after 100 minutes: %s", seed, r.summary(steps))
+ if tick > 540 {
+ t.Fatalf("seed %d: not settled after 180 minutes: %s", seed, r.summary(steps))
}
r.now = r.now.Add(simEvery)
r.online(primary)
@@ -98,19 +105,11 @@ func simulate(t *testing.T, seed int64) {
if s.RunnerID != j.RunnerID || s.State == wire.StepDone || v == nil || !v.alive() || rng.Float64() > 0.35 {
continue
}
- checks := wire.ChecksCannotRun
- if j.CertValid && j.CertCheckedAt != nil && r.now.Sub(*j.CertCheckedAt) <= 2*time.Minute {
- // Certified as Task 24 will read it: the record must not
- // overstate the certificate.
- if !c.validAt(*j.CertCheckedAt) || string(v.ref) != j.VMRef || v.launchID != j.LaunchID {
- t.Fatalf("seed %d: %s certified by %s with an admission (%v at %v) the controller did not give", seed, j.StepID, j.AttemptID, j.CertValid, j.CertCheckedAt)
- }
- checks = wire.ChecksPassed
- }
- r.exec("UPDATE chat_steps SET state = ?, checks = ? WHERE id = ?", wire.StepDone, checks, j.StepID)
+ r.exec("UPDATE chat_steps SET state = ?, checks = ? WHERE id = ?", wire.StepDone, wire.ChecksPassed, j.StepID)
}
}
r.invariants(seed, limits)
+ r.admissions(seed, checked)
done := len(r.liveJobs()) == 0
for _, s := range steps {
done = done && wire.StepTerminal(r.step(s).State)
@@ -222,6 +221,31 @@ func (r *rig) invariants(seed int64, limits chat.HostedLimits) {
}
}
+// admissions checks each job's recorded admission against the
+// controller's answers; checked is the last one seen for each job.
+func (r *rig) admissions(seed int64, checked map[string]time.Time) {
+ r.t.Helper()
+ var all []chat.HostedJob
+ r.must(r.d.G.Where("cert_checked_at IS NOT NULL").Find(&all).Error)
+ for _, j := range all {
+ at := j.CertCheckedAt.UTC()
+ if at.After(r.now) || at.Before(checked[j.AttemptID]) {
+ r.fail(seed, "%s admission at %v: now %v, the one before %v", j.AttemptID, at, r.now, checked[j.AttemptID])
+ }
+ checked[j.AttemptID] = at
+ r.ctl.mu.Lock()
+ answered := slices.ContainsFunc(r.ctl.admitted[j.AttemptID], at.Equal)
+ v := r.ctl.jobs[j.AttemptID]
+ r.ctl.mu.Unlock()
+ if !answered {
+ r.fail(seed, "%s admission recorded at %v, when the controller gave none", j.AttemptID, at)
+ }
+ if j.CertValid && (!r.ctl.validAt(at) || v == nil || string(v.ref) != j.VMRef || v.launchID != j.LaunchID) {
+ r.fail(seed, "%s admission valid at %v for VM %s, which the controller did not say", j.AttemptID, at, j.VMRef)
+ }
+ }
+}
+
// fail fails the run, naming its seed.
func (r *rig) fail(seed int64, format string, args ...any) {
r.t.Helper()
diff --git a/internal/equipo/migrations/0126_hosted_jobs.sql b/internal/equipo/migrations/0126_hosted_jobs.sql
index 783a5674..fc5dec71 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, 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));
+CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, lifetime integer, state text, launch_id text, vm_ref text, epoch integer, launch_by datetime, launching_since datetime, running_seen_at 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 ae93a386..79a26cf7 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, 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));
+CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, lifetime integer, state text, launch_id text, vm_ref text, epoch integer, launch_by datetime, launching_since datetime, running_seen_at 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';