oficina / equipo Public

equipo: place checks on hosted VMs and see each VM to its end

Hosted slice 2, Task 21. place puts a checks step of a project with the
hosted setting on a hosted VM before today's early return: a live job
first, one retry after proof, Mac needs on today's path, a primary at
protocol 39 online, then admission against the person's limits. A bound
runner fits and is authorized only for its job's step and attempt; a
hosted step is never withdrawn; the hosted pack goes at dispatch.

internal/equipo/hostedrun's dispatcher launches pending jobs outside any
transaction, refreshes admission each pass, stops a VM not enrolled two
minutes after running, fails a job past its launch-by, and stops each VM
until proof, then the store settles it, revokes its runner and moves its
step on. Never-launched evidence comes only from a signed 404 absent,
which the controller now answers for an attempt it has no record of.
It runs only with EQUIPO_HOSTED_RUNNERS=1 and a controller configured.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 938a8a3a6b096ed2620ae10e6c7f0e66fb607ef1 parent 197d9d6
28 files changed, +3,071 −77
  • .rastrillo/budgets.txt +5 −4
  • docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json +21 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +3 −0
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +83 −0
  • internal/equipo/app.go +19 −0
  • internal/equipo/chat/hosted_jobs.go +16 −4
  • internal/equipo/chat/hosted_place_test.go +514 −0
  • internal/equipo/chat/hosted_run.go +545 −0
  • internal/equipo/chat/macrecheck.go +1 −1
  • internal/equipo/chat/runners.go +93 −29
  • internal/equipo/chat/store.go +6 −0
  • internal/equipo/chat/tasks.go +14 −1
  • internal/equipo/chat_wiring.go +3 −0
  • internal/equipo/config.go +5 −0
  • internal/equipo/copy.go +3 −0
  • internal/equipo/hostedrun/dispatcher.go +500 −0
  • internal/equipo/hostedrun/dispatcher_test.go +873 −0
  • internal/equipo/hostedrun/sim_test.go +229 −0
  • internal/hostedclient/client.go +9 −3
  • internal/hostedclient/client_test.go +69 −21
  • internal/hostedctl/admission_test.go +5 −3
  • internal/hostedctl/http.go +1 −0
  • internal/hostedctl/http_test.go +17 −5
  • internal/hostedctl/launch.go +4 −0
  • internal/hostedctl/stop.go +10 −4
  • internal/hostedctl/stop_test.go +8 −2
  • internal/wire/hosted.go +10 −0
  • internal/wire/tasks.go +5 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 4421ea13..8d0e14f6 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -13,9 +13,10 @@ 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.
-size internal/equipo 24837 - 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.
-size internal/wire 9884 - 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.
+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.
size internal/equipotest - 12693 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures, Rastrillo asset contract, renderer archive link; measured 0/12693 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -59,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 46025 20290 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.
+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.
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.
@@ -85,4 +86,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin,
# branch uses an indexed primary-key lookup, one current-member/device check,
# and the same bounded cardView as the snapshot; no list scan or new route.
perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen.
-size internal/hostedctl 6038 9996 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996.
+size internal/hostedctl 6049 10016 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996. Task 21 ruling: Get and Admission answer a signed 404 absent for an attempt with no record at all (ErrAbsent), keeping the 403 for another key's attempt, and the tests that pin it; measured 6049/10016.
diff --git a/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json b/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json
index 74a58cc0..6bd448b5 100644
--- a/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json
+++ b/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json
@@ -68,5 +68,26 @@
"draft": "Each checks run happens on a new machine that Equipo starts for it and stops afterwards. Your own runner must still be online to send it the change.",
"paul_sees": true,
"reviewed": ""
+ },
+ {
+ "key": "work.reason.hosted_enrol_timeout",
+ "where": "Task view, why checks did not run: a hosted checks VM was running but did not enrol with the instance within 2 minutes, twice (Task 21)",
+ "draft": "the hosted machine did not connect in time",
+ "paul_sees": true,
+ "reviewed": ""
+ },
+ {
+ "key": "work.reason.hosted_vm_lost",
+ "where": "Task view, why checks did not run: a hosted checks VM stopped or went away before the checks finished, and its one retry did too (Task 21)",
+ "draft": "the hosted machine stopped before the checks finished",
+ "paul_sees": true,
+ "reviewed": ""
+ },
+ {
+ "key": "work.reason.hosted_unavailable",
+ "where": "Task view, why checks did not run: no hosted checks VM could be started for the step (its launch window passed, or the controller refused it), and its one retry failed too (Task 21)",
+ "draft": "a hosted machine could not be started",
+ "paul_sees": true,
+ "reviewed": ""
}
]
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 28f4823d..15cf4e0a 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -7229,6 +7229,9 @@ records remain unchanged.
| `hosted.lede` | Choose which projects run their checks on machines Equipo hosts. Only owners can change this. | Copy specialist | COPY REVIEW PENDING |
| `hosted.checks` | Run checks in a hosted VM | Copy specialist | COPY REVIEW PENDING |
| `hosted.checks_help` | Each checks run happens on a new machine that Equipo starts for it and stops afterwards. Your own runner must still be online to send it the change. | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.hosted_enrol_timeout` | the hosted machine did not connect in time | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.hosted_vm_lost` | the hosted machine stopped before the checks finished | Copy specialist | COPY REVIEW PENDING |
+| `work.reason.hosted_unavailable` | a hosted machine could not be started | Copy specialist | COPY REVIEW PENDING |
## Task 21
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 060c0ee6..5c798f36 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1548,3 +1548,86 @@ Green: `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestLimits|TestHoldSp
Mutation:
- **273** the empty-span check removed: `if !to.After(from) {` became `if false && !to.After(from) {`. `-run TestHoldSpansMonthEnd`: exit 1, `hosted_limits_test.go:280: an empty span 2026-11-08 12:00:00.5 +0000 UTC to 2026-11-08 12:00:00.5 +0000 UTC: map[2026-11-08:1] map[2026-11:1]`. Restored from a copy under `mktemp -d`; `cmp`: identical.
+
+## Task 21
+
+Placement on hosted VMs, the dispatcher and the VM's end.
+
+Controller ruling (Task 19's): `hostedctl.Controller.Get` and `Admission` answer an attempt with no record at all with `ErrAbsent`, a signed `404 absent`. The call is audited as before. Another key's attempt still gets `403 forbidden`, and so does a call with no key. Stop and the other routes still answer 403 for an unknown attempt. `hostedclient.ErrAbsent` is the client's kind for it. `TestClientMatchesHandlerErrorCodes` holds the pair.
+
+`internal/equipo/chat/hosted_run.go` (new) and changes in `runners.go`, `tasks.go`, `store.go`:
+- `place` calls `placeHosted` for checks before today's early return. Rules in order:
+ 1. The step's live job is read first. `pending`, `launching` and `enrolling` wait (`waiting_hosted`, no new hold). `enrolled` goes to the job's runner once that runner and the primary are both online at `ProtocolHostedRunners`; otherwise it waits. `stopping` waits. A live job for another step attempt is stopped (`step_moved`).
+ 2. Only with `SetHostedRunners(true)` and the project's setting on: the step attempt's last ended or failed job is retried once (`retry_of`); a second end resolves the step not run with the job's reason (`hosted_enrol_timeout`, `hosted_vm_lost`, else `hosted_unavailable`).
+ 3. Needs a VM cannot meet (anything beyond `linux`), or no valid base and candidate for the hosted pack: today's path.
+ 4. Primary offline or below 39: `waiting_hosted`, no job.
+ 5. `hostedAdmit` then `newHostedJob` with `hostedHoldFor(HostedChecksSize, HostedChecksLifetime, now)` at `now`, in the same transaction; refused: `hosted_limit` with the reason in `Reason`. A count or read error returns the error and nothing is written.
+- `runnerInfo.Hosted`/`HostedStep` (one query for the person's runners). `fits(step, needs, refused)`: a hosted runner fits only its live job's step. Engineering never picks or pins a hosted runner.
+- `Authorize`: a runner bound to a hosted job is granted only for that job's step and attempt while the job is `enrolled`, read in the transaction.
+- `waitingPlacements` includes `waiting_hosted` and `hosted_limit`.
+- `offline`: a `waiting_hosted` step resolves `runner_offline` once its primary has been offline (or below 39) for `OfflineLimit`, counting from the later of the wait's start and the primary's last sight. Its job stops through the step-terminal hook. A step on a hosted runner is never withdrawn, and a hosted runner is never the "other runner that fits".
+- `dispatchStep`: a step on its job's hosted runner opens the hosted pack (`openHostedPack`) instead of the ordinary checks transfer.
+- `saveStep`: a checks step that ends stops its live jobs (`step_ended`).
+- Store methods for the dispatcher, each one transaction: `HostedLive`, `HostedSweep` (step ended, gone, moved on, task ended or cancelling, person no longer a member: stopping; a roster lookup error stops nothing), `HostedLaunching` (pending to launching, or a new code for a launching job with no intent, no call in flight and no launch; the person must be a member), `HostedLaunchReturned`, `HostedLaunched` (or the VM recorded on a job already stopping), `HostedAdmitted` (valid only when the controller says so and it names the job's launch, VM, epoch and certificate; an older record is ignored), `HostedFailed`, `HostedStopped`, `HostedNeverLaunched`, `HostedReplaces` (the predecessor only when it ended with stop proof), `PlaceHosted` (steps whose placement can change now).
+- A job's end (`hostedFinish`): ended for `step_ended`/`step_moved`/`person_removed`, failed otherwise; settled (`hostedSettle`); its runner revoked (`Authority.RevokeRunner`, wired to `revokeRunnerAt`). An attempt that was on the VM is placed again under the same attempt (its VM is proven stopped; its dispatch is voided), so rule 2 counts the job. A cancelled task's attempt on the VM ends cancelled.
+
+`internal/equipo/hostedrun/dispatcher.go` (new): `Dispatcher{Store, Client Controller, Clock, Image, Account, Log}`. `Controller` is the four instance routes; `*hostedclient.Client` is one. `Admitter` is exported for Task 22. `Pass` sweeps, moves each live job, then `PlaceHosted`.
+- Pending: past launch-by, failed `hosted_unavailable`. Otherwise it is recorded launching (code hash, expiry launch-by + 10 min, launch-by), then `Launch` outside any transaction. `Replaces` comes from `HostedReplaces`. The VM is recorded, or `HostedLaunchReturned` and a backoff (10 s doubling to 5 min).
+- Launching: a stale in-flight mark from a dead process is cleared, and launch-by is checked. Then `Get`: a signed absent sends it again (the same code within a process, a new one after a restart); a VM is recorded; abandoned fails the job; waiting backs off.
+- Enrolling and enrolled: `Admission` every pass, recorded with the time the question was asked. A VM the controller reports abandoned, stopping or stopped fails the job `hosted_vm_lost`. An enrolling VM first seen running 2 minutes earlier (this process's memory) fails it `hosted_enrol_timeout`.
+- Stopping: `Stop(attempt, stop_reason)` until proof, then `HostedStopped`. A job with no launch, VM or runner on record may instead end with never-launched evidence. That evidence comes only from a `Get` asked at least 2 minutes past launch-by that answers `ErrAbsent` or abandoned with no VM. A VM in the answer is recorded instead.
+- `Probe`: `Admission` for a random 64-hex attempt; `ErrAbsent` logs `hosted_controller_reachable`, anything else `hosted_controller_unreachable` with the reason. `Run` probes, then passes every 10 s.
+- `New(store, Config, log)` refuses without `EQUIPO_HOSTED_RUNNERS=1` (`hostedclient.ErrRunnersOff`) and a missing or malformed connection (`ErrConfig`). It builds the client with the controller's TLS pin. `ReadConfig` reads `EQUIPO_HOSTED_CONTROLLER`, `_CONTROLLER_TLS_PIN`, `_CONTROLLER_PUB`, `_KEY_ID`, `_KEY`, `_IMAGE`, `_ACCOUNT`.
+- `internal/equipo/app.go`: with `EQUIPO_HOSTED_RUNNERS=1` and execution on, the dispatcher is built. If that fails it logs `hosted_dispatcher_off`, and hosted placement stays off. If it succeeds, `SetHostedRunners(true)` is called and `Run` starts in the background group.
+
+Copy: `work.reason.hosted_enrol_timeout` "the hosted machine did not connect in time", `work.reason.hosted_vm_lost` "the hosted machine stopped before the checks finished", `work.reason.hosted_unavailable` "a hosted machine could not be started". In `copy.go`, marked with `python3 scripts/copy-status.py pending` (stdin `{"candidate": <worktree>, "keys": [those three]}`), listed in `2026-11-30-hosted-slice-2-copy.json`. Not accepted. The reasons are registered in `wire.StepReasons`.
+
+`TestInstanceDoesNotCallHostedClient` is deleted. `TestOnlyHostedrunImportsHostedClient` lists every package of the module with its imports. The only importers it allows are `internal/equipo/hostedrun` and the operator's `cmd/equipo-hosted-certify`. It also checks that `cmd/equipo` reaches `hostedclient` through `hostedrun` alone.
+
+Red:
+- `CGO_ENABLED=0 go test ./internal/hostedctl -run 'TestInstanceKeySeesOnlyItsJobs|TestAdmissionCreatorOnly|TestStop' -count=1`: build failed (`undefined: ErrAbsent`). With `ErrAbsent` declared and nothing else: `admission_test.go:254: Admission("inst-1", "att-9") = (..., hostedctl: this key may not do that: att-9 is not an attempt of this key), want (zero, hostedctl: there is no record of that attempt)`, `stop_test.go:641: Get of an unknown attempt = ... want ErrAbsent`, `http_test.go:302: instance B GET /v1/jobs/nope = 403 {"code":"forbidden",...}, want 404 absent`.
+- `go test ./internal/hostedclient -run 'TestClientAgainstController|TestClientAdmissionVerified|TestSignedAnswersMapToKinds|TestOnlyHostedrun' -count=1`: `client_test.go:542: absent: Get = ..., hostedclient: the controller gave an unexpected answer (get: controller answered 404 "absent")`, `client_test.go:747: internal/equipo/hostedrun does not import internal/hostedclient; importers: map[.../cmd/equipo-hosted-certify:true]`.
+- Chat placement tests against the tree before this task: build failed (`r.s.authority.RevokeRunner undefined`, `r.s.SetHostedRunners undefined`, `r.s.HostedLaunching undefined`, `undefined: HostedChecksSize`, `undefined: hostedStopStepEnded`, `r.s.PlaceHosted undefined`, ...). The hostedrun package did not exist.
+
+Green: `CGO_ENABLED=0 go test ./internal/equipo/hostedrun ./internal/equipo/chat ./internal/hostedclient -run 'TestHosted|TestMacChecks|TestRepeated|TestEnrolled|TestBoundRunner|TestAuthorizeRefuses|TestPrimaryLost|TestEnrolTimeout|TestVMGone|TestStopUntil|TestThrottle|TestDispatcher|TestOnlyHostedrun' -count=1`: ok (29 top-level tests, the simulation's 200 seeds among them; hostedrun 10.2 s). The brief's regex does not match `TestPlacementDuringStopping` or `TestReachabilityProbeLogged`. Both were run by name: ok. Also ok: the whole `chat` (30.6 s), `hostedctl`, `hostedclient`, `wire` and `hostedrun` packages; `./internal/equipo -run 'TestStepReasons|Copy|Config|TestHostedSetting|Migration|Schema|Machines|MacWait|Placement'`; `./internal/thintest -run 'TestContractPlacement|TestPlacement|TestContractMac|TestMac|TestContractSandbox|TestSandbox|TestContractTransfer|TestContractWorker|TestWorker|Offline|Recheck|Hosted'`. `make migration-check budget build vet`: exit 0 after raising the records: chat 46665/20804, internal/equipo 24867, wire 9899, hostedctl 6049/10016, each with its reason. New time record: `internal/equipo/hostedrun 45s`. staticcheck on the changed packages: only the existing `preview_frames_fixture_test.go` U1000. gofmt and `git diff --check`: clean.
+
+Simulation coverage (a one-off count over the 200 seeds, not kept as a test): 543 jobs ended `step_ended`, 102 failed `hosted_enrol_timeout`, 24 failed `hosted_vm_lost`, 60 failed `hosted_unavailable` on stop proof, 30 on never-launched evidence (19 absent, 11 abandoned), and 160 retries. Steps: 344 passed and certified, 200 not certified (`cannot_run`, mostly certificates withdrawn or stale), 19 resolved `hosted_enrol_timeout`, 30 `hosted_unavailable` and 7 `hosted_vm_lost`.
+
+Mutations (an exact-string replace from a script under `mktemp -d`, one at a time, with `CGO_ENABLED=0`. Each was restored from a copy and compared with `filecmp`: identical every time):
+- **274** (the brief's) place after the early return. `-run TestHostedPlacementBeforeEarlyReturn`: exit 1, `hosted_place_test.go:167: hosted checks placed "" on "P1" (queued), want waiting_hosted on no runner`. Restored.
+- **275** (the brief's) a bound runner fits any step (`(true || !r.Hosted || ...)`). `-run TestBoundRunnerFitsOnlyItsStep`: exit 1, `hosted_place_test.go:360: H1 fits s1 true, s2 true, no step true; want s1 alone`. Restored.
+- **276** (the brief's) admit a new job on every placement pass (the live-job rule skipped). `-run TestRepeatedPlacementOneJob`: exit 1, `hosted_place_test.go:268: waiting since <nil>, want the admission 2026-11-08 12:00:01 +0000 UTC`. The store's one-live-job rule still blocks the second job, so the step falls through to rule 2 and resolves. Restored.
+- **287** (the brief's) retry without the predecessor's proof: `stop` records a made-up proof when the controller answers `stop_pending`. `-run TestDispatcherSimulation`: exit 1, `sim_test.go:113: seed 106: hj_5vyt... settled on a stop proof the controller never gave: &{... VMRef:vm-1 State:stopped ...}`, and the same for seeds 175, 174, 176, 164. Restored.
+- **277** Authorize without the job identity check. `-run TestAuthorizeRefusesOtherStep`: exit 1, `hosted_place_test.go:385: H1 authorizing another step: "" <nil>, want withdrawn`. Restored.
+- **278** a hosted step withdrawn like any worker's (`|| r.Hosted` dropped). `-run TestHostedExemptFromWithdrawal`: exit 1, `hosted_place_test.go:421: hosted step with its VM offline: on "" withdrawn false attempt 2 queued`. Restored.
+- **279** no step-terminal hook (`return t.hostedStepEnded(s.ID)` became `return nil`). `-run TestHostedNeedsCapablePrimary`: exit 1, `hosted_place_test.go:239: s1's job after the step resolved: pending "", want stopping`. Restored.
+- **280** a hosted step gets the ordinary checks transfer. `-run TestEnrolledJobDispatches`: exit 1, `hosted_place_test.go:301: send_pack {... Kind: ...}, want the hosted pack of s1`. Restored.
+- **281** dispatch with one end ready (`ready < 2` became `ready < 1`). `-run 'TestPrimaryLostDuringEnrolment|TestEnrolledJobDispatches'`: exit 1, `hosted_place_test.go:283: VM below the protocol: "" on "H1", want waiting` and `:450: enrolled with the primary away: "" on "H1"; want waiting, nothing sent`. Restored.
+- **282** a stopping job does not hold its step. `-run TestPlacementDuringStopping`: exit 1, `hosted_place_test.go:477: while stopping: 1 jobs (stopping), want the one stopping` (the step resolved). Restored.
+- **283** retried more than once (`Retries >= 1` became `>= 5`). Same test: exit 1, `hosted_place_test.go:490: retry spent: queued "" with 3 jobs; want cannot_run hosted_enrol_timeout`. Restored.
+- **284** a primary below 39 admits a job. `-run TestHostedNeedsCapablePrimary`: exit 1, `hosted_place_test.go:210: old primary: placed "waiting_hosted" on "" with 1 jobs, want waiting_hosted, no job`. Restored.
+- **285** Mac checks hosted. `-run TestMacChecksNeverHosted`: exit 1, `hosted_place_test.go:197: Mac checks placed "waiting_hosted" needs ["macos","xcode"] with 1 jobs, want waiting_mac and no job`. Restored.
+- **286** admitted at the limit. `-run TestHostedWaitsAtLimit`: exit 1, `hosted_place_test.go:319: at the limit: "waiting_hosted" "" with 1 jobs, want hosted_limit running`. Restored.
+- **288** never-launched evidence from a refusal (`ErrForbidden` taken as absent). `-run TestDispatcherNeverLaunchedEvidence`: exit 1, `dispatcher_test.go:742: Get answering hostedclient: this key may not do that: ended, settled 2026-11-08 12:12:00 +0000 UTC`. Restored.
+- **289** never-launched evidence asked at launch-by, not 2 minutes past it. Same test: exit 1, `dispatcher_test.go:732: pass at 12:10:00: hosted job hj_...: chat: hosted job has no proof it ended: hj_...`. The store refused the early evidence and the pass reported it. Restored.
+- **290** the enrolment window counted from admission, not from running. `-run TestEnrolTimeoutRetriesOnce`: exit 1, `dispatcher_test.go:567: first job within its enrolment window: stopping`. Restored.
+- **291** no backoff growth (`w := BackoffMin`). `-run TestThrottleBacksOff`: exit 1, `dispatcher_test.go:709: asked again after [10s 10s 10s ...], want [10s 20s 40s 1m20s 2m40s]`. Restored. (The first run of this mutation panicked in the test's slice expression. The assertion was made exact, and the mutation was then killed on it.)
+- **291b** no 5-minute cap. Same test: exit 1, `dispatcher_test.go:721: backoff [10s 20s 40s 1m20s 2m40s 5m20s 10m40s 21m20s]`. Restored.
+- **292** admission recorded valid whatever the controller says (`a.CertValid &&` dropped). `-run TestDispatcherSimulation`: exit 1, `sim_test.go:106: seed 173: s2 certified by hj_... with an admission (true at 2026-11-08 12:03:40 +0000 UTC) the controller did not give`, and seeds 150, 51, 168, 170. Restored.
+- **293** admission time recorded a minute late. Same test: exit 1, `sim_test.go:106: seed 3: s2 certified by hj_... with an admission (true at 2026-11-08 12:02:40 +0000 UTC) the controller did not give`, and seed 196. Restored.
+- **294** a VM the controller reports gone not failed. `-run TestVMGoneMidStep`: exit 1, `dispatcher_test.go:612: job ended: not within 1m0s`. Restored.
+- **295** the job's runner not revoked. `-run 'TestVMGoneMidStep|TestStopUntilProofThenSettle'`: exit 1, `dispatcher_test.go:620: the VM's runner was not revoked` and `:673: runner not revoked`. Restored.
+- **296** not settled at the end. `-run TestStopUntilProofThenSettle`: exit 1, `dispatcher_test.go:663: after the proof: ended settled <nil> used ""`. Restored.
+- **297** a retry's launch does not name the attempt it replaces (`Replaces: replaces[:0]`). `-run TestEnrolTimeoutRetriesOnce`: exit 1, `dispatcher_test.go:581: retry launches [... Replaces: ...], want one for hj_... replacing hj_...`. Restored. (A first spelling, `Replaces: ""`, did not compile: `replaces` was unused.)
+- **298** a dead process's in-flight mark kept. `-run TestDispatcherSimulation`: exit 1, `sim_test.go:86: pass at 12:09:40: hosted job hj_...: chat: hosted job cannot make that move: launch hj_... from launching`, and two more seeds. Restored.
+- **299** the sweep does not stop a job whose step ended. `-run TestStopUntilProofThenSettle`: exit 1, `dispatcher_test.go:651: while the stop is pending: enrolled "" settled <nil>`. Restored.
+- **300** the probe takes a 403 as reachable. `-run TestReachabilityProbeLogged`: exit 1, `dispatcher_test.go:840: signed forbidden: reachable true, asked [/v1/jobs/<64 hex>/admission]`. Restored.
+- **301** the controller answers 403 for an attempt with no record (`if false && by != "" && !found`). `go test ./internal/hostedctl -run 'TestInstanceKeySeesOnlyItsJobs|TestAdmissionCreatorOnly'` and `./internal/hostedclient -run TestClientAgainstController`: exit 1, `admission_test.go:254: Admission("inst-1", "att-9") = (..., ... att-9 is not an attempt of this key), want (zero, hostedctl: there is no record of that attempt)`, `http_test.go:302: instance B GET /v1/jobs/nope = 403 ..., want 404 absent`, `client_test.go:247: Get of an unknown attempt = hostedclient: this key may not do that (get: controller answered 403 "forbidden"), want a signed 404 ErrAbsent`. Restored.
+- **302** the client maps `absent` to `ErrNotFound`. `-run 'TestClientAgainstController|TestSignedAnswersMapToKinds'`: exit 1, `client_test.go:247: Get of an unknown attempt = hostedclient: not found (get: controller answered 404 "absent"), want a signed 404 ErrAbsent` and `client_test.go:542: absent: Get = ..., want nothing and hostedclient: the controller has no record of that attempt`. Restored.
+
+- **303** a removed person's job not stopped (`false &&` before `errors.Is(err, ErrForbidden)` in `hostedStale`). `-run TestHostedSweepStopsRemovedPerson`: exit 1, `hosted_place_test.go:510: chat: forbidden` (the sweep returned the roster's denial instead of stopping the job). Restored.
+- **304** a roster lookup error read as a removal (`err != nil || errors.Is(err, ErrForbidden)`). Same test: exit 1, `hosted_place_test.go:503: sweep with the roster unreadable: no error`. Restored. (A first spelling, `err != nil` alone, did not compile: `errors` was then unused.)
+
+`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.
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 71fa18ac..30d099ca 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -3,6 +3,7 @@ package equipo
import (
"amadan.net/oficina/equipo/internal/equipo/chat"
"amadan.net/oficina/equipo/internal/equipo/door"
+ "amadan.net/oficina/equipo/internal/equipo/hostedrun"
"amadan.net/oficina/equipo/internal/equipo/notifications"
"amadan.net/oficina/equipo/internal/equipo/oficina"
"amadan.net/oficina/equipo/internal/equipo/oficinaid"
@@ -44,6 +45,9 @@ type application struct {
executionEnabled bool
// hostedRunners is Config.HostedRunners (hosted_settings.go).
hostedRunners bool
+ // hosted is the hosted VM dispatcher: only with EQUIPO_HOSTED_RUNNERS=1,
+ // execution on and a controller configured.
+ hosted *hostedrun.Dispatcher
chi.Router
live *live.Hub
origin string
@@ -86,6 +90,11 @@ func (a *application) startBackground() *background.Group {
defer stop()
a.store.Chat().ServeRemoteCalls(calls)
})
+ // The hosted VM dispatcher, only where one was built.
+ if a.hosted != nil {
+ d := a.hosted
+ a.background.Go(func() { d.Run(calls) })
+ }
// The push sender, only where serving built a transport.
if a.push != nil {
sender := a.store.Chat().PushSender(a.push)
@@ -276,6 +285,16 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
return nil, err
}
a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, hostedRunners: cfg.HostedRunners, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin, push: cfg.Push}
+ if cfg.HostedRunners && cfg.ExecutionEnabled {
+ // Hosted placement only where the dispatcher runs: nothing is
+ // admitted that nothing would launch.
+ if hd, e := hostedrun.New(store.Chat(), cfg.Hosted, logger); e != nil {
+ logger.Error("hosted_dispatcher_off", "err", e)
+ } else {
+ a.hosted = hd
+ store.Chat().SetHostedRunners(true)
+ }
+ }
if cfg.Home != nil {
storeID, e := oficinaid.New(d.Writer(), cfg.Origin, cfg.Home)
if e != nil {
diff --git a/internal/equipo/chat/hosted_jobs.go b/internal/equipo/chat/hosted_jobs.go
index b8bcbfbc..b1296d1f 100644
--- a/internal/equipo/chat/hosted_jobs.go
+++ b/internal/equipo/chat/hosted_jobs.go
@@ -371,18 +371,30 @@ func (t *txn) moveHostedJob(attempt, to string, set func(*HostedJob) error, cols
// 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() || launchBy.IsZero() {
+ if checkCode(code) != nil || 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, by, now := expires.UTC(), launchBy.UTC(), t.now().UTC()
- j.CodeHash, j.CodeExpiresAt, j.LaunchBy, j.LaunchingSince = hex.EncodeToString(sum[:]), &e, &by, &now
+ j.CodeHash, j.CodeExpiresAt, j.LaunchBy, j.LaunchingSince = codeHash(code), &e, &by, &now
return nil
}, "code_hash", "code_expires_at", "launch_by", "launching_since")
}
+// checkCode: an instance code is 32 bytes in unpadded base64url.
+func checkCode(code string) error {
+ if raw, err := base64.RawURLEncoding.Strict().DecodeString(code); err != nil || len(raw) != 32 {
+ return fmt.Errorf("%w: instance code", ErrInvalid)
+ }
+ return nil
+}
+
+// codeHash is what the job keeps of its instance code.
+func codeHash(code string) string {
+ sum := sha256.Sum256([]byte(code))
+ return hex.EncodeToString(sum[:])
+}
+
// 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.
diff --git a/internal/equipo/chat/hosted_place_test.go b/internal/equipo/chat/hosted_place_test.go
new file mode 100644
index 00000000..3d92a07e
--- /dev/null
+++ b/internal/equipo/chat/hosted_place_test.go
@@ -0,0 +1,514 @@
+package chat
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Hosted slice 2, Task 21: placement of checks on hosted VMs.
+
+const hpPrimary = "P1"
+
+var (
+ hpBase = strings.Repeat("a", 40)
+ hpCandidate = strings.Repeat("b", 40)
+)
+
+// hostedPlaceRig is a roster rig with the hosted setting on for p1, the
+// instance's hosted runners on, and the owner's primary P1 online at
+// ProtocolHostedRunners. Runners are rows of a runners table, the
+// primary the newest unrevoked one; RevokeRunner revokes in it.
+func hostedPlaceRig(t *testing.T) *hkRig {
+ r, _ := rosterRig(t)
+ r.exec("CREATE TABLE runners (id text PRIMARY KEY, person text, role text, label text, revoked_at datetime, removing_at datetime, tainted_at datetime)")
+ r.s.authority.PrimaryRunner = func(tx *gorm.DB, person string) (string, error) {
+ var ids []string
+ err := tx.Raw(`SELECT id FROM runners WHERE person = ? AND revoked_at IS NULL AND coalesce(role, '') IN ('primary', '') ORDER BY rowid DESC LIMIT 1`, person).Scan(&ids).Error
+ if err != nil || len(ids) == 0 {
+ return "", err
+ }
+ return ids[0], nil
+ }
+ r.s.authority.RunnerRole = func(tx *gorm.DB, id string) (string, error) {
+ var roles []string
+ if err := tx.Raw(`SELECT coalesce(role, '') FROM runners WHERE id = ?`, id).Scan(&roles).Error; err != nil {
+ return "", err
+ }
+ if len(roles) == 1 && roles[0] == wire.RoleWorker {
+ return wire.RoleWorker, nil
+ }
+ return wire.RolePrimary, nil
+ }
+ r.s.authority.CurrentRunner = func(*gorm.DB, RunnerPrincipal) error { return nil }
+ r.s.authority.RevokeRunner = func(tx *gorm.DB, id string) error {
+ return tx.Exec("UPDATE runners SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL", r.now, id).Error
+ }
+ r.s.SetHostedRunners(true)
+ r.runner(hpPrimary, wire.RolePrimary)
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.task("tkp", "Hosted checks", hkOwner)
+ r.exec("UPDATE chat_projects SET hosted_checks = 1, hosted_checks_owner = ?, hosted_checks_revision = 1 WHERE id = 'p1'", hkOwner)
+ return r
+}
+
+func (r *hkRig) runner(id, role string) {
+ r.t.Helper()
+ r.exec("INSERT INTO runners(id, person, role, label) VALUES (?, ?, ?, ?)", id, hkOwner, role, id)
+}
+
+// online records runner id connected now at protocol.
+func (r *hkRig) online(id string, protocol int) {
+ r.t.Helper()
+ r.exec("DELETE FROM runner_sessions WHERE runner_id = ?", id)
+ r.must(r.s.db.G.Create(&runnerSessionRecord{RunnerID: id, Generation: 1, Connected: true, Process: "p", Revision: 1, SeenAt: r.now, Protocol: protocol}).Error)
+}
+
+// offlineSince records runner id disconnected, last seen at.
+func (r *hkRig) offlineSince(id string, at time.Time) {
+ r.t.Helper()
+ r.exec("UPDATE runner_sessions SET connected = 0, seen_at = ? WHERE runner_id = ?", at, id)
+}
+
+// checksStep records a queued checks step of task with a base and a
+// candidate, and places it as the instance does when it is created.
+func (r *hkRig) checksStep(id, task string) stepRecord {
+ r.t.Helper()
+ s := stepRecord{ID: id, TaskID: task, Idx: 2, Person: hkOwner, State: wire.StepQueued, Attempt: 1, Specialist: wire.SpecialistChecks, BaseSHA: hpBase, CandidateSHA: hpCandidate, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}
+ r.must(r.s.db.G.Create(&s).Error)
+ r.exec("UPDATE chat_tasks SET stage = ?, base_sha = ? WHERE id = ?", wire.StageInReview, hpBase, task)
+ r.must(r.tx(func(t *txn) error {
+ k, err := t.loadTask(task)
+ if err != nil {
+ return err
+ }
+ if err := t.dispatchStep(&k, &s); err != nil {
+ return err
+ }
+ return t.saveStep(&s, &k)
+ }))
+ return r.step(id)
+}
+
+func (r *hkRig) step(id string) stepRecord {
+ r.t.Helper()
+ var s stepRecord
+ r.must(r.s.db.G.Where("id = ?", id).First(&s).Error)
+ return s
+}
+
+// place runs the minute's placement pass.
+func (r *hkRig) place() {
+ r.t.Helper()
+ r.must(r.s.Place(r.ctx))
+}
+
+func (r *hkRig) jobsOf(step string) []HostedJob {
+ r.t.Helper()
+ var rows []HostedJob
+ r.must(r.s.db.G.Where("step_id = ?", step).Order("admitted_at, rowid").Find(&rows).Error)
+ return rows
+}
+
+// commands are the unacked commands of kind to runner.
+func (r *hkRig) commands(runner, kind string) []commandRecord {
+ r.t.Helper()
+ var rows []commandRecord
+ r.must(r.s.db.G.Where("runner_id = ? AND kind = ? AND acked_at IS NULL", runner, kind).Order("seq").Find(&rows).Error)
+ return rows
+}
+
+// launched takes job attempt to enrolling on VM vm, as the dispatcher
+// does.
+func (r *hkRig) launched(attempt, vm string) {
+ r.t.Helper()
+ j := r.job(attempt)
+ by := j.AdmittedAt.Add(HostedLaunchWindow)
+ sum := sha256.Sum256([]byte(vm))
+ r.must(r.s.HostedLaunching(r.ctx, attempt, base64.RawURLEncoding.EncodeToString(sum[:]), by.Add(HostedLaunchWindow), by))
+ r.must(r.s.HostedLaunched(r.ctx, attempt, hostedwire.JobView{AttemptID: attempt, LaunchID: "launch-" + vm, State: "running", VMRef: isolatedjob.Ref(vm), Epoch: 0}))
+}
+
+// enrol stands in for Task 22's enrolment: the VM's code is used, runner
+// id (a worker) is bound to the job, and connects at protocol.
+func (r *hkRig) enrol(attempt, runner string, protocol int) {
+ r.t.Helper()
+ r.runner(runner, wire.RoleWorker)
+ r.exec("UPDATE hosted_jobs SET code_used_at = ? WHERE attempt_id = ?", r.now, attempt)
+ r.must(r.tx(func(t *txn) error { return t.hostedEnrolled(attempt, runner, "machine-key") }))
+ r.online(runner, protocol)
+}
+
+// stopped ends attempt with a stop proof for its VM, observed now.
+func (r *hkRig) stopped(attempt, reason string) {
+ r.t.Helper()
+ r.must(r.s.HostedFailed(r.ctx, attempt, reason))
+ j := r.job(attempt)
+ r.must(r.s.HostedStopped(r.ctx, attempt, hostedwire.StopProof{AttemptID: attempt, VMRef: isolatedjob.Ref(j.VMRef), State: isolatedjob.StateStopped}, r.now))
+}
+
+// TestHostedPlacementBeforeEarlyReturn: checks with no special needs,
+// which today go straight to the primary, are hosted when the project's
+// setting and the instance's hosted runners are on: a pending job, the
+// step waiting_hosted, nothing sent to the primary. With either off they
+// run on the primary as before.
+func TestHostedPlacementBeforeEarlyReturn(t *testing.T) {
+ r := hostedPlaceRig(t)
+ s := r.checksStep("s1", "tkp")
+ if s.Placement != wire.PlacementHosted || s.RunnerID != "" || s.State != wire.StepQueued || s.WaitingSince == nil {
+ t.Fatalf("hosted checks placed %q on %q (%s), want waiting_hosted on no runner", s.Placement, s.RunnerID, s.State)
+ }
+ jobs := r.jobsOf("s1")
+ if len(jobs) != 1 || jobs[0].State != HostedJobPending || jobs[0].Size != HostedChecksSize || jobs[0].StepAttempt != 1 || jobs[0].RetryOf != "" {
+ t.Fatalf("jobs %+v, want one pending Large job for attempt 1", jobs)
+ }
+ if got := r.commands(hpPrimary, wire.FrameDispatch); len(got) != 0 {
+ t.Fatalf("hosted checks dispatched to the primary: %+v", got)
+ }
+
+ r.task("tk2", "Setting off", hkOwner)
+ r.exec("UPDATE chat_projects SET hosted_checks = 0 WHERE id = 'p1'")
+ if s := r.checksStep("s2", "tk2"); s.RunnerID != hpPrimary || s.Placement != "" || len(r.jobsOf("s2")) != 0 {
+ t.Fatalf("setting off: placed %q on %q, jobs %d; want the primary", s.Placement, s.RunnerID, len(r.jobsOf("s2")))
+ }
+ r.exec("UPDATE chat_projects SET hosted_checks = 1 WHERE id = 'p1'")
+ r.s.SetHostedRunners(false)
+ r.task("tk3", "Instance off", hkOwner)
+ if s := r.checksStep("s3", "tk3"); s.RunnerID != hpPrimary || s.Placement != "" || len(r.jobsOf("s3")) != 0 {
+ t.Fatalf("hosted runners off: placed %q on %q; want the primary", s.Placement, s.RunnerID)
+ }
+}
+
+// TestMacChecksNeverHosted: checks that need a Mac take today's path
+// (waiting for a Mac runner), never a hosted VM.
+func TestMacChecksNeverHosted(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.must(r.s.db.G.Create(&stepRecord{ID: "e1", TaskID: "tkp", Idx: 1, Person: hkOwner, State: wire.StepDone, Attempt: 1, Specialist: wire.SpecialistEngineering, Apple: true, CreatedAt: r.now, UpdatedAt: r.now}).Error)
+ s := r.checksStep("s1", "tkp")
+ if len(r.jobsOf("s1")) != 0 || s.Placement != wire.PlacementMac || !strings.Contains(s.Needs, wire.TagMacOS) {
+ t.Fatalf("Mac checks placed %q needs %s with %d jobs, want waiting_mac and no job", s.Placement, s.Needs, len(r.jobsOf("s1")))
+ }
+}
+
+// TestHostedNeedsCapablePrimary: a primary below ProtocolHostedRunners,
+// or offline, holds the step as hosted work with no job (it never runs on
+// the primary); after OfflineLimit it resolves runner_offline. Once the
+// primary can relay, the job is admitted.
+func TestHostedNeedsCapablePrimary(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.online(hpPrimary, wire.ProtocolHostedRunners-1)
+ s := r.checksStep("s1", "tkp")
+ if s.Placement != wire.PlacementHosted || s.RunnerID != "" || len(r.jobsOf("s1")) != 0 {
+ t.Fatalf("old primary: placed %q on %q with %d jobs, want waiting_hosted, no job", s.Placement, s.RunnerID, len(r.jobsOf("s1")))
+ }
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.offlineSince(hpPrimary, r.now)
+ r.now = r.now.Add(time.Minute)
+ r.place()
+ if s := r.step("s1"); s.Placement != wire.PlacementHosted || len(r.jobsOf("s1")) != 0 || len(r.commands(hpPrimary, wire.FrameDispatch)) != 0 {
+ t.Fatalf("offline primary: %q, %d jobs, want waiting_hosted, no job, nothing to the primary", s.Placement, len(r.jobsOf("s1")))
+ }
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.place()
+ if jobs := r.jobsOf("s1"); len(jobs) != 1 || r.step("s1").Placement != wire.PlacementHosted {
+ t.Fatalf("primary back: %d jobs, want one", len(jobs))
+ }
+
+ // Another step whose primary stays offline past the limit resolves.
+ r.task("tk2", "Offline", hkOwner)
+ r.offlineSince(hpPrimary, r.now)
+ r.checksStep("s2", "tk2")
+ r.now = r.now.Add(OfflineLimit + time.Second)
+ r.place()
+ if s := r.step("s2"); s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != reasonRunnerOffline || len(r.jobsOf("s2")) != 0 {
+ t.Fatalf("primary offline past the limit: %s %s %q, %d jobs; want cannot_run runner_offline", s.State, s.Checks, s.Reason, len(r.jobsOf("s2")))
+ }
+ // And the first step's waiting job stops with it.
+ if s := r.step("s1"); s.State != wire.StepDone || s.Reason != reasonRunnerOffline {
+ t.Fatalf("s1 with its primary offline past the limit: %s %q", s.State, s.Reason)
+ }
+ if j := r.jobsOf("s1")[0]; j.State != HostedJobStopping || j.StopReason != hostedStopStepEnded {
+ t.Fatalf("s1's job after the step resolved: %s %q, want stopping", j.State, j.StopReason)
+ }
+}
+
+// TestRepeatedPlacementOneJob: ten placement passes admit one job and
+// hold its window once.
+func TestRepeatedPlacementOneJob(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ for i := 0; i < 10; i++ {
+ r.now = r.now.Add(10 * time.Second)
+ r.place()
+ r.must(r.s.PlaceHosted(r.ctx))
+ }
+ jobs := r.jobsOf("s1")
+ if len(jobs) != 1 {
+ t.Fatalf("%d jobs after ten passes, want one", len(jobs))
+ }
+ hold, err := jobs[0].Hold()
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, _ := hostedHoldFor(HostedChecksSize, HostedChecksLifetime, *jobs[0].AdmittedAt)
+ var held int64
+ r.must(r.s.db.G.Raw("SELECT count(*) FROM hosted_jobs WHERE person = ?", hkOwner).Scan(&held).Error)
+ if held != 1 || hold.Seconds[r.now.Format(time.DateOnly)] != want.Seconds[r.now.Format(time.DateOnly)] {
+ t.Fatalf("held %d jobs, hold %+v, want one hold of %+v", held, hold, want)
+ }
+ if s := r.step("s1"); s.WaitingSince == nil || !s.WaitingSince.Equal(*jobs[0].AdmittedAt) {
+ t.Fatalf("waiting since %v, want the admission %v", s.WaitingSince, jobs[0].AdmittedAt)
+ }
+}
+
+// TestEnrolledJobDispatches: an enrolled job's step goes to its runner
+// with the hosted pack (base and candidate) asked of the primary; while
+// the VM's runner is away, or below ProtocolHostedRunners, it waits.
+func TestEnrolledJobDispatches(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ a := r.jobsOf("s1")[0].AttemptID
+ r.launched(a, "vm-1")
+ r.enrol(a, "H1", wire.ProtocolHostedRunners-1)
+ r.place()
+ if s := r.step("s1"); s.Placement != wire.PlacementHosted || s.RunnerID != "" || len(r.commands("H1", wire.FrameDispatch)) != 0 {
+ t.Fatalf("VM below the protocol: %q on %q, want waiting", s.Placement, s.RunnerID)
+ }
+ r.online("H1", wire.ProtocolHostedRunners)
+ r.place()
+ s := r.step("s1")
+ if s.RunnerID != "H1" || s.Placement != "" || s.State != wire.StepQueued || !s.OnWorker {
+ t.Fatalf("enrolled: placed %q on %q (%s), want H1", s.Placement, s.RunnerID, s.State)
+ }
+ if got := r.commands("H1", wire.FrameDispatch); len(got) != 1 || !strings.Contains(got[0].Body, `"step_id":"s1"`) {
+ t.Fatalf("dispatches to H1: %+v", got)
+ }
+ packs := r.commands(hpPrimary, wire.FrameSendPack)
+ if len(packs) != 1 {
+ t.Fatalf("send_pack to the primary: %d, want 1", len(packs))
+ }
+ var sp wire.SendPackCommand
+ r.must(json.Unmarshal([]byte(packs[0].Body), &sp))
+ if sp.Transfer.Kind != wire.TransferKindHostedPack || sp.Transfer.BaseSHA != hpBase || sp.Transfer.CandidateSHA != hpCandidate || sp.Transfer.StepID != "s1" {
+ t.Fatalf("send_pack %+v, want the hosted pack of s1", sp.Transfer)
+ }
+ if got := r.commands(hpPrimary, wire.FrameDispatch); len(got) != 0 {
+ t.Fatalf("dispatched to the primary as well: %+v", got)
+ }
+}
+
+// TestHostedWaitsAtLimit: with the person's two running jobs taken, a
+// third step waits hosted_limit with the reason, and is admitted once a
+// job has ended with proof.
+func TestHostedWaitsAtLimit(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ r.task("tk2", "Two", hkOwner)
+ r.checksStep("s2", "tk2")
+ r.task("tk3", "Three", hkOwner)
+ s := r.checksStep("s3", "tk3")
+ if s.Placement != wire.PlacementHostedLimit || s.Reason != HostedLimitRunning || len(r.jobsOf("s3")) != 0 || s.RunnerID != "" {
+ t.Fatalf("at the limit: %q %q with %d jobs, want hosted_limit running", s.Placement, s.Reason, len(r.jobsOf("s3")))
+ }
+ r.place()
+ if s := r.step("s3"); s.Placement != wire.PlacementHostedLimit || len(r.jobsOf("s3")) != 0 {
+ t.Fatalf("still at the limit: %q, %d jobs", s.Placement, len(r.jobsOf("s3")))
+ }
+ a := r.jobsOf("s1")[0].AttemptID
+ r.launched(a, "vm-1")
+ r.exec("UPDATE chat_steps SET state = ? WHERE id = 's1'", wire.StepDone)
+ r.must(r.s.HostedSweep(r.ctx))
+ r.now = r.now.Add(time.Minute)
+ r.must(r.s.HostedStopped(r.ctx, a, hostedwire.StopProof{AttemptID: a, VMRef: "vm-1", State: isolatedjob.StateStopped}, r.now))
+ r.must(r.s.PlaceHosted(r.ctx))
+ if s := r.step("s3"); s.Placement != wire.PlacementHosted || s.Reason != "" || len(r.jobsOf("s3")) != 1 {
+ t.Fatalf("a slot freed: %q %q, %d jobs; want admitted", s.Placement, s.Reason, len(r.jobsOf("s3")))
+ }
+}
+
+// TestBoundRunnerFitsOnlyItsStep: a hosted runner fits only its live
+// job's step, never another step, Engineering or its general pool; once
+// the job is not live it fits nothing.
+func TestBoundRunnerFitsOnlyItsStep(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ a := r.jobsOf("s1")[0].AttemptID
+ r.launched(a, "vm-1")
+ r.enrol(a, "H1", wire.ProtocolHostedRunners)
+ var h runnerInfo
+ r.must(r.tx(func(t *txn) error {
+ rs, err := t.runners(hkOwner)
+ for _, x := range rs {
+ if x.ID == "H1" {
+ h = x
+ }
+ }
+ return err
+ }))
+ if !h.Hosted || h.HostedStep != "s1" || h.Role != wire.RoleWorker {
+ t.Fatalf("H1 as placement sees it: %+v", h)
+ }
+ if !h.fits("s1", nil, nil) || h.fits("s2", nil, nil) || h.fits("", nil, nil) {
+ t.Fatalf("H1 fits s1 %t, s2 %t, no step %t; want s1 alone", h.fits("s1", nil, nil), h.fits("s2", nil, nil), h.fits("", nil, nil))
+ }
+ h.HostedStep = ""
+ if h.fits("s1", nil, nil) {
+ t.Fatal("a hosted runner whose job ended still fits its step")
+ }
+ plain := runnerInfo{ID: "W1", Role: wire.RoleWorker, Protocol: wire.ProtocolHostedRunners}
+ if !plain.fits("s2", nil, nil) || !plain.fits("", nil, nil) {
+ t.Fatal("a personal worker no longer fits")
+ }
+}
+
+// TestAuthorizeRefusesOtherStep: a hosted runner's start authorization is
+// granted only for its job's step and attempt while the job is enrolled.
+func TestAuthorizeRefusesOtherStep(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ a := r.jobsOf("s1")[0].AttemptID
+ r.launched(a, "vm-1")
+ r.enrol(a, "H1", wire.ProtocolHostedRunners)
+ r.place()
+ r.task("tk2", "Other", hkOwner)
+ r.must(r.s.db.G.Create(&stepRecord{ID: "s2", TaskID: "tk2", Idx: 2, Person: hkOwner, State: wire.StepQueued, Attempt: 1, Specialist: wire.SpecialistChecks, RunnerID: "H1", CreatedAt: r.now, UpdatedAt: r.now}).Error)
+ l := Lease{Runner: RunnerPrincipal{RunnerID: "H1", Person: hkOwner}, Generation: 1, Process: "p", Protocol: wire.ProtocolHostedRunners, Role: wire.RoleWorker}
+ if got, err := r.s.Authorize(r.ctx, l, "s2", 1, "", "", ""); err != nil || got != "withdrawn" {
+ t.Fatalf("H1 authorizing another step: %q %v, want withdrawn", got, err)
+ }
+ r.exec("UPDATE chat_steps SET attempt = 2 WHERE id = 's2'")
+ r.exec("UPDATE hosted_jobs SET step_attempt = 7 WHERE attempt_id = ?", a)
+ if got, err := r.s.Authorize(r.ctx, l, "s1", 1, "", "", ""); err != nil || got != "withdrawn" {
+ t.Fatalf("H1 authorizing another attempt of its step: %q %v, want withdrawn", got, err)
+ }
+ r.exec("UPDATE hosted_jobs SET step_attempt = 1 WHERE attempt_id = ?", a)
+ if got, err := r.s.Authorize(r.ctx, l, "s1", 1, "", "", ""); err != nil || got != "" {
+ t.Fatalf("H1 authorizing its own step: %q %v, want granted", got, err)
+ }
+ r.must(r.s.HostedFailed(r.ctx, a, wire.ReasonHostedVMLost))
+ r.exec("UPDATE chat_steps SET started_at = NULL WHERE id = 's1'")
+ if got, err := r.s.Authorize(r.ctx, l, "s1", 1, "", "", ""); err != nil || got != "withdrawn" {
+ t.Fatalf("H1 authorizing with its job stopping: %q %v, want withdrawn", got, err)
+ }
+}
+
+// TestHostedExemptFromWithdrawal: a step on a hosted runner that went
+// offline is never withdrawn for another runner, however long: its job,
+// not the offline rule, decides its end.
+func TestHostedExemptFromWithdrawal(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ a := r.jobsOf("s1")[0].AttemptID
+ r.launched(a, "vm-1")
+ r.enrol(a, "H1", wire.ProtocolHostedRunners)
+ r.place()
+ r.runner("W1", wire.RoleWorker)
+ r.online("W1", wire.ProtocolHostedRunners)
+ r.offlineSince("H1", r.now)
+ r.now = r.now.Add(OfflineLimit + time.Minute)
+ r.online("W1", wire.ProtocolHostedRunners)
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.place()
+ if s := r.step("s1"); s.RunnerID != "H1" || s.Withdrawn || s.Attempt != 1 || wire.StepTerminal(s.State) {
+ t.Fatalf("hosted step with its VM offline: on %q withdrawn %t attempt %d %s", s.RunnerID, s.Withdrawn, s.Attempt, s.State)
+ }
+ if got := r.commands("H1", wire.FrameCancelStep); len(got) != 0 {
+ t.Fatalf("cancel sent to H1: %+v", got)
+ }
+ if got := r.commands("W1", wire.FrameDispatch); len(got) != 0 {
+ t.Fatalf("s1 dispatched to W1: %+v", got)
+ }
+}
+
+// TestPrimaryLostDuringEnrolment: the primary goes away while the VM
+// enrols: the job is kept, the step waits as hosted work and nothing runs
+// on (or is sent to) the primary; once it is back the step goes to the
+// VM.
+func TestPrimaryLostDuringEnrolment(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ a := r.jobsOf("s1")[0].AttemptID
+ r.launched(a, "vm-1")
+ r.offlineSince(hpPrimary, r.now)
+ r.now = r.now.Add(time.Minute)
+ r.place()
+ if j := r.job(a); j.State != HostedJobEnrolling || len(r.jobsOf("s1")) != 1 {
+ t.Fatalf("job with the primary away: %s, %d jobs", j.State, len(r.jobsOf("s1")))
+ }
+ r.enrol(a, "H1", wire.ProtocolHostedRunners)
+ r.place()
+ s := r.step("s1")
+ if s.Placement != wire.PlacementHosted || s.RunnerID != "" || len(r.commands("H1", wire.FrameDispatch)) != 0 || len(r.commands(hpPrimary, wire.FrameDispatch)) != 0 {
+ t.Fatalf("enrolled with the primary away: %q on %q; want waiting, nothing sent", s.Placement, s.RunnerID)
+ }
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.place()
+ if s := r.step("s1"); s.RunnerID != "H1" || len(r.commands("H1", wire.FrameDispatch)) != 1 || len(r.commands(hpPrimary, wire.FrameDispatch)) != 0 {
+ t.Fatalf("primary back: on %q, want H1 alone", s.RunnerID)
+ }
+ if j := r.job(a); j.State != HostedJobEnrolled {
+ t.Fatalf("job after the primary came back: %s", j.State)
+ }
+}
+
+// TestPlacementDuringStopping: ten passes while the job stops admit
+// nothing; its proof ends it, and the step's one retry is admitted with
+// retry_of; the retry's own end resolves the step with its reason.
+func TestPlacementDuringStopping(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ first := r.jobsOf("s1")[0].AttemptID
+ r.launched(first, "vm-1")
+ r.must(r.s.HostedFailed(r.ctx, first, wire.ReasonHostedEnrolTimeout))
+ for i := 0; i < 10; i++ {
+ r.now = r.now.Add(10 * time.Second)
+ r.place()
+ r.must(r.s.PlaceHosted(r.ctx))
+ }
+ if jobs := r.jobsOf("s1"); len(jobs) != 1 || jobs[0].State != HostedJobStopping || r.step("s1").Placement != wire.PlacementHosted {
+ t.Fatalf("while stopping: %d jobs (%s), want the one stopping", len(jobs), jobs[0].State)
+ }
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.must(r.s.HostedStopped(r.ctx, first, hostedwire.StopProof{AttemptID: first, VMRef: "vm-1", State: isolatedjob.StateStopped}, r.now))
+ jobs := r.jobsOf("s1")
+ if len(jobs) != 2 || jobs[0].State != HostedJobFailed || jobs[0].SettledAt == nil || jobs[1].State != HostedJobPending || jobs[1].RetryOf != first || jobs[1].Retries != 1 {
+ t.Fatalf("after the proof: %+v", jobs)
+ }
+ second := jobs[1].AttemptID
+ r.launched(second, "vm-2")
+ r.stopped(second, wire.ReasonHostedEnrolTimeout)
+ s := r.step("s1")
+ if s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != wire.ReasonHostedEnrolTimeout || len(r.jobsOf("s1")) != 2 {
+ t.Fatalf("retry spent: %s %s %q with %d jobs; want cannot_run hosted_enrol_timeout", s.State, s.Checks, s.Reason, len(r.jobsOf("s1")))
+ }
+}
+
+// TestHostedSweepStopsRemovedPerson: a job whose person is no longer a
+// current member stops at the next sweep, read in its transaction; a
+// roster that cannot be read stops nothing.
+func TestHostedSweepStopsRemovedPerson(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ a := r.jobsOf("s1")[0].AttemptID
+ r.exec("ALTER TABLE members RENAME TO members_gone")
+ if err := r.s.HostedSweep(r.ctx); err == nil {
+ t.Fatal("sweep with the roster unreadable: no error")
+ }
+ if j := r.job(a); j.State != HostedJobPending {
+ t.Fatalf("roster unreadable: job %s", j.State)
+ }
+ r.exec("ALTER TABLE members_gone RENAME TO members")
+ r.exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner)
+ r.must(r.s.HostedSweep(r.ctx))
+ if j := r.job(a); j.State != HostedJobStopping || j.StopReason != hostedStopPersonRemoved {
+ t.Fatalf("person removed: job %s %q, want stopping", j.State, j.StopReason)
+ }
+}
diff --git a/internal/equipo/chat/hosted_run.go b/internal/equipo/chat/hosted_run.go
new file mode 100644
index 00000000..d8835117
--- /dev/null
+++ b/internal/equipo/chat/hosted_run.go
@@ -0,0 +1,545 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// Hosted checks placement and the instance's side of a job's life (hosted
+// runners slice 2, Task 21). place puts a checks step of a project with
+// the hosted setting on a hosted VM (placeHosted); the dispatcher
+// (internal/equipo/hostedrun) launches, watches and stops each VM through
+// the exported Hosted* methods below, each one transaction.
+
+// HostedChecksSize is a checks VM's size (decision S2-5: Large).
+const HostedChecksSize = isolatedjob.SizeLarge
+
+// HostedEnrolTimeout is how long a VM the controller reports running has
+// to enrol before it is stopped (spec §10).
+const HostedEnrolTimeout = 2 * time.Minute
+
+// Why a job stops when its VM did not fail it: its step ended (or its
+// task did), its step moved on to another attempt, or its person is no
+// longer a current member. A job stopped for one of these ends as ended;
+// for any other reason (the wire.ReasonHosted* failures) as failed.
+const (
+ hostedStopStepEnded = "step_ended"
+ hostedStopStepMoved = "step_moved"
+ hostedStopPersonRemoved = "person_removed"
+)
+
+// hostedTags is what a hosted checks VM offers: checks that need more (a
+// Mac, Xcode) are never hosted.
+var hostedTags = []string{wire.TagLinux}
+
+// SetHostedRunners turns hosted placement on: only the instance that runs
+// the dispatcher (EQUIPO_HOSTED_RUNNERS=1 with a controller configured)
+// sets it, so no job is ever admitted that nothing would launch.
+func (s *Store) SetHostedRunners(on bool) { s.hostedRunners.Store(on) }
+
+// hostedPlacement reports whether a step waits as hosted work.
+func hostedPlacement(p string) bool {
+ return p == wire.PlacementHosted || p == wire.PlacementHostedLimit
+}
+
+// hostedFailure is the step reason a failed job's stop reason resolves
+// its step with once the retry is spent.
+func hostedFailure(stop string) string {
+ switch stop {
+ case wire.ReasonHostedEnrolTimeout, wire.ReasonHostedVMLost, wire.ReasonHostedUnavailable:
+ return stop
+ }
+ return wire.ReasonHostedUnavailable
+}
+
+// stepJobs are the step's hosted jobs, newest admission first.
+func (t *txn) stepJobs(step string) ([]HostedJob, error) {
+ var rows []HostedJob
+ err := t.db.Where("step_id = ?", step).Order("admitted_at DESC, rowid DESC").Find(&rows).Error
+ return rows, err
+}
+
+// placeHosted is place for a checks step, before today's early return
+// (hosted runners spec §8): done false leaves the step to today's path.
+//
+// 1. A live job is read first, whatever else has changed: pending,
+// launching and enrolling wait (waiting_hosted) with no new hold;
+// enrolled goes to the job's runner once it and the primary speak
+// ProtocolHostedRunners and are online; stopping waits for its proof.
+// 2. Otherwise, with the instance's hosted runners on and the project's
+// setting on: the step attempt's last job ended or failed (it held
+// proof to), so it is retried once (retry_of) or the step resolves
+// not run with that job's reason.
+// 3. Checks a VM cannot meet (a Mac, a tag the image lacks, no
+// base and candidate to pack) take today's path.
+// 4. A primary offline or below ProtocolHostedRunners: the step waits as
+// hosted work, never on the primary; offline resolves it after
+// OfflineLimit.
+// 5. Admission against the person's limits: a pending job and
+// waiting_hosted, or hosted_limit with the limit's reason.
+func (t *txn) placeHosted(k *taskRecord, s *stepRecord, primary string, needs []string) (placed, done bool, err error) {
+ jobs, err := t.stepJobs(s.ID)
+ if err != nil {
+ return false, false, err
+ }
+ now := t.now()
+ wait := func(placement, reason string) (bool, bool, error) {
+ s.RunnerID, s.Placement, s.WaitingSince, s.Reason = "", placement, &now, reason
+ return false, true, nil
+ }
+ if len(jobs) > 0 && jobs[0].Live() {
+ j := jobs[0]
+ if j.StepAttempt != s.Attempt && j.State != HostedJobStopping {
+ // The step moved on to another attempt: this VM is not for it.
+ if err := t.hostedStopping(j.AttemptID, hostedStopStepMoved); err != nil {
+ return false, false, err
+ }
+ return wait(wire.PlacementHosted, "")
+ }
+ if j.State != HostedJobEnrolled || primary == "" {
+ return wait(wire.PlacementHosted, "")
+ }
+ rs, err := t.runners(s.Person)
+ if err != nil {
+ return false, false, err
+ }
+ ready := 0
+ for _, r := range rs {
+ if (r.ID == primary || r.ID == j.RunnerID) && r.Online && r.Protocol >= wire.ProtocolHostedRunners {
+ ready++
+ }
+ }
+ if ready < 2 {
+ // Its primary (which sends the pack) or its VM is away: the job
+ // is kept and the step waits for them, never for the primary
+ // to run it.
+ return wait(wire.PlacementHosted, "")
+ }
+ s.RunnerID, s.Placement, s.WaitingSince, s.Reason = j.RunnerID, "", nil, ""
+ return true, true, nil
+ }
+ if !t.s.hostedRunners.Load() {
+ return false, false, nil
+ }
+ if on, err := t.hostedChecks(k.ProjectID); err != nil || !on {
+ return false, false, err
+ }
+ retryOf := ""
+ if len(jobs) > 0 && jobs[0].StepAttempt == s.Attempt {
+ last := jobs[0]
+ if last.Retries >= 1 || !last.proven() {
+ return false, true, t.resolveNotRun(k, s, hostedFailure(last.StopReason))
+ }
+ retryOf = last.AttemptID
+ }
+ base := s.BaseSHA
+ if base == "" && !s.Rebase {
+ base = k.BaseSHA
+ }
+ if !wire.Covers(hostedTags, needs) || !(wire.TransferHeader{Direction: wire.TransferInbound, Kind: wire.TransferKindHostedPack, BaseSHA: base, CandidateSHA: s.CandidateSHA}).Valid() {
+ return false, false, nil
+ }
+ rs, err := t.runners(s.Person)
+ if err != nil {
+ return false, false, err
+ }
+ capable := false
+ for _, r := range rs {
+ capable = capable || r.ID == primary && r.Online && r.Protocol >= wire.ProtocolHostedRunners
+ }
+ if !capable {
+ return wait(wire.PlacementHosted, "")
+ }
+ ok, why, err := t.hostedAdmit(s.Person, HostedChecksSize, HostedChecksLifetime, now)
+ if err != nil {
+ // An unknown count denies: nothing is written and the step keeps
+ // waiting as it was.
+ return false, false, err
+ }
+ if !ok {
+ return wait(wire.PlacementHostedLimit, why)
+ }
+ hold, err := hostedHoldFor(HostedChecksSize, HostedChecksLifetime, now)
+ 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 {
+ return false, false, err
+ }
+ return wait(wire.PlacementHosted, "")
+}
+
+// hostedBound reports whether runner is a hosted runner bound to a live
+// job for step s's current attempt.
+func (t *txn) hostedBound(s stepRecord, runner string) (bool, error) {
+ if runner == "" {
+ return false, nil
+ }
+ j, found, err := t.hostedJobForRunner(runner)
+ if err != nil || !found {
+ return false, err
+ }
+ return j.Live() && j.StepID == s.ID && j.StepAttempt == s.Attempt, nil
+}
+
+// hostedStepEnded stops the step's live jobs: it ended, however it ended.
+func (t *txn) hostedStepEnded(step string) error {
+ var rows []HostedJob
+ if err := t.db.Where("step_id = ? AND state IN ?", step, []string{HostedJobPending, HostedJobLaunching, HostedJobEnrolling, HostedJobEnrolled}).Find(&rows).Error; err != nil {
+ return err
+ }
+ for _, j := range rows {
+ if err := t.hostedStopping(j.AttemptID, hostedStopStepEnded); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// HostedLive is every job not ended or failed, oldest admission first.
+func (s *Store) HostedLive(ctx context.Context) ([]HostedJob, error) {
+ var rows []HostedJob
+ err := s.read(ctx, func(tx *gorm.DB) error {
+ return tx.Where("state NOT IN ?", []string{HostedJobEnded, HostedJobFailed}).Order("admitted_at, attempt_id").Find(&rows).Error
+ })
+ return rows, err
+}
+
+// HostedSweep stops, in one transaction, each live job whose step ended,
+// went away or moved on to another attempt, whose task ended or is being
+// cancelled, or whose person is no longer a current member (read in the
+// transaction; any other lookup error is returned and stops nothing).
+func (s *Store) HostedSweep(ctx context.Context) error {
+ return s.tx(ctx, func(t *txn) error {
+ var rows []HostedJob
+ if err := t.db.Where("state IN ?", []string{HostedJobPending, HostedJobLaunching, HostedJobEnrolling, HostedJobEnrolled}).Order("admitted_at, attempt_id").Find(&rows).Error; err != nil {
+ return err
+ }
+ for _, j := range rows {
+ why, err := t.hostedStale(j)
+ if err != nil {
+ return err
+ }
+ if why != "" {
+ if err := t.hostedStopping(j.AttemptID, why); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+ })
+}
+
+// hostedStale is why a live job must stop now ("" when it need not).
+func (t *txn) hostedStale(j HostedJob) (string, error) {
+ if _, err := t.s.authority.Me(t.db, j.Person); errors.Is(err, ErrForbidden) {
+ return hostedStopPersonRemoved, nil
+ } else if err != nil {
+ return "", err
+ }
+ var steps []stepRecord
+ if err := t.db.Where("id = ?", j.StepID).Limit(1).Find(&steps).Error; err != nil {
+ return "", err
+ }
+ if len(steps) == 0 || steps[0].Retired || wire.StepTerminal(steps[0].State) {
+ return hostedStopStepEnded, nil
+ }
+ if steps[0].Attempt != j.StepAttempt {
+ return hostedStopStepMoved, nil
+ }
+ var tasks []taskRecord
+ if err := t.db.Where("id = ?", j.TaskID).Limit(1).Find(&tasks).Error; err != nil {
+ return "", err
+ }
+ if len(tasks) == 0 || wire.FinalStage(tasks[0].Stage) || tasks[0].CancelRequested {
+ return hostedStopStepEnded, nil
+ }
+ return "", nil
+}
+
+// HostedLaunching records, before the dispatcher asks the controller to
+// launch, the instance code's hash, its expiry and the launch-by, and
+// that a launch call may be in flight: a pending job becomes launching. A
+// launching job the controller has no intent for, with no call in flight
+// and no launch recorded, takes a new code the same way (the code is
+// never stored, so a restarted dispatcher cannot resend the old one). The
+// person must be a current member.
+func (s *Store) HostedLaunching(ctx context.Context, attempt, code string, expires, launchBy time.Time) error {
+ return s.tx(ctx, func(t *txn) error {
+ var j HostedJob
+ if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil {
+ return err
+ }
+ if _, err := t.s.authority.Me(t.db, j.Person); err != nil {
+ return err
+ }
+ if j.State == HostedJobPending {
+ return t.hostedLaunching(attempt, code, expires, launchBy)
+ }
+ if j.State != HostedJobLaunching || j.LaunchID != "" || j.LaunchingSince != nil || j.LaunchBy == nil || !j.LaunchBy.Equal(launchBy.UTC()) {
+ return fmt.Errorf("%w: launch %s from %s", ErrHostedTransition, attempt, j.State)
+ }
+ return t.hostedRelaunch(j, code, expires)
+ })
+}
+
+// HostedLaunchReturned records that the job's launch call returned with
+// no VM to record: no call is in flight.
+func (s *Store) HostedLaunchReturned(ctx context.Context, attempt string) error {
+ return s.tx(ctx, func(t *txn) error { return t.hostedLaunchReturned(attempt) })
+}
+
+// HostedLaunched records the controller's view of the job's VM: a
+// launching job now waits for its VM to enrol. A job already stopping
+// keeps its state but records the VM, so only proof for it ends the job.
+func (s *Store) HostedLaunched(ctx context.Context, attempt string, v hostedwire.JobView) error {
+ return s.tx(ctx, func(t *txn) error {
+ var j HostedJob
+ if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil {
+ return err
+ }
+ if j.State == HostedJobStopping && j.VMRef == "" {
+ return t.hostedLearnVM(j, v)
+ }
+ return t.hostedEnrolling(attempt, v)
+ })
+}
+
+// HostedAdmitted records the controller's admission record for the job's
+// VM, observed at at on the instance's clock: valid only when the
+// controller says the certificate is valid and it names the job's launch,
+// VM, epoch and (once recorded) certificate. A record older than the one
+// held is ignored.
+func (s *Store) HostedAdmitted(ctx context.Context, attempt string, a hostedwire.AdmissionView, at time.Time) error {
+ return s.tx(ctx, func(t *txn) error {
+ var j HostedJob
+ if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil {
+ return err
+ }
+ if a.AttemptID != attempt || !j.Live() || j.VMRef == "" || at.IsZero() {
+ return fmt.Errorf("%w: admission for %s", ErrHostedTransition, attempt)
+ }
+ valid := a.CertValid && a.LaunchID == j.LaunchID && string(a.VMRef) == j.VMRef && a.Epoch == j.Epoch && a.CertDigest != "" &&
+ (j.CertDigest == "" || j.CertDigest == a.CertDigest)
+ digest := j.CertDigest
+ if digest == "" {
+ digest = a.CertDigest
+ }
+ when := at.UTC()
+ res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND (cert_checked_at IS NULL OR cert_checked_at <= ?)", attempt, when).
+ Updates(map[string]any{"cert_digest": digest, "cert_valid": valid, "cert_checked_at": when})
+ if res.Error != nil || res.RowsAffected == 0 || valid == j.CertValid {
+ return res.Error
+ }
+ return t.s.authority.Audit(t.db, "system", "hosted.job", fmt.Sprintf("%s:cert_valid:%t", attempt, valid))
+ })
+}
+
+// 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
+// is.
+func (s *Store) HostedFailed(ctx context.Context, attempt, reason string) error {
+ return s.tx(ctx, func(t *txn) error {
+ var j HostedJob
+ if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil {
+ return err
+ }
+ if !j.Live() || j.State == HostedJobStopping {
+ return nil
+ }
+ return t.hostedStopping(attempt, reason)
+ })
+}
+
+// HostedStopped ends a stopping job with the controller's stop proof,
+// received at observed on the instance's clock (hostedFinish).
+func (s *Store) HostedStopped(ctx context.Context, attempt string, p hostedwire.StopProof, observed time.Time) error {
+ return s.tx(ctx, func(t *txn) error {
+ return t.hostedFinish(attempt, HostedEndProof{Stop: &p, ObservedAt: observed})
+ })
+}
+
+// HostedNeverLaunched ends a stopping job with never-launched evidence
+// (HostedNeverLaunched.holds decides; hostedFinish).
+func (s *Store) HostedNeverLaunched(ctx context.Context, attempt string, n HostedNeverLaunched) error {
+ return s.tx(ctx, func(t *txn) error {
+ return t.hostedFinish(attempt, HostedEndProof{NeverLaunched: &n, ObservedAt: n.ObservedAt})
+ })
+}
+
+// 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).
+func (s *Store) HostedReplaces(ctx context.Context, attempt string) (string, error) {
+ var out string
+ err := s.read(ctx, func(tx *gorm.DB) error {
+ var j, prior HostedJob
+ if err := tx.Where("attempt_id = ?", attempt).First(&j).Error; err != nil || j.RetryOf == "" {
+ return err
+ }
+ if err := tx.Where("attempt_id = ?", j.RetryOf).First(&prior).Error; err != nil {
+ return err
+ }
+ var p HostedEndProof
+ if prior.proven() && json.Unmarshal([]byte(prior.StopProofJSON), &p) == nil && p.Stop != nil {
+ out = prior.AttemptID
+ }
+ return nil
+ })
+ return out, err
+}
+
+// PlaceHosted places again each step waiting as hosted work whose
+// placement can change now (as Place does each minute): one with no live
+// job (waiting for its primary or for the limits, or whose job just
+// ended) or with its job enrolled. A pending, launching, enrolling or
+// stopping job's step waits as it is (placeHosted's rule 1).
+func (s *Store) PlaceHosted(ctx context.Context) error {
+ return s.tx(ctx, func(t *txn) error {
+ var rows []stepRecord
+ if err := t.db.Where("state = ? AND placement IN ? AND NOT EXISTS (SELECT 1 FROM hosted_jobs j WHERE j.step_id = chat_steps.id AND j.state IN ?)",
+ wire.StepQueued, []string{wire.PlacementHosted, wire.PlacementHostedLimit},
+ []string{HostedJobPending, HostedJobLaunching, HostedJobEnrolling, HostedJobStopping}).Order("created_at").Find(&rows).Error; err != nil {
+ return err
+ }
+ for i := range rows {
+ k, err := t.loadTask(rows[i].TaskID)
+ if err != nil {
+ return err
+ }
+ if wire.FinalStage(k.Stage) || k.CancelRequested {
+ continue
+ }
+ if err := t.placeAgain(&k, &rows[i]); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
+// hostedRelaunch gives a launching job with no launch, no VM and no call
+// in flight a new code, and records that a call may be in flight again.
+func (t *txn) hostedRelaunch(j HostedJob, code string, expires time.Time) error {
+ if err := checkCode(code); err != nil || expires.IsZero() {
+ return fmt.Errorf("%w: instance code", ErrHostedTransition)
+ }
+ e, now := expires.UTC(), t.now().UTC()
+ res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND state = ? AND revision = ? AND launching_since IS NULL AND launch_id = ''", j.AttemptID, HostedJobLaunching, j.Revision).
+ Updates(map[string]any{"code_hash": codeHash(code), "code_expires_at": e, "launching_since": now, "revision": j.Revision + 1})
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected != 1 {
+ return fmt.Errorf("%w: hosted job %s moved", ErrConflict, j.AttemptID)
+ }
+ return t.s.authority.Audit(t.db, "system", "hosted.job", j.AttemptID+":relaunch")
+}
+
+// hostedLearnVM records the VM of a job that is already stopping, so it
+// ends only with that VM's stop proof.
+func (t *txn) hostedLearnVM(j HostedJob, v hostedwire.JobView) error {
+ if v.AttemptID != j.AttemptID || v.LaunchID == "" || len(v.LaunchID) > hostedwire.MaxLaunchIDLen || !v.VMRef.Valid() || v.Epoch < 0 {
+ return fmt.Errorf("%w: launch view for %s", ErrHostedTransition, j.AttemptID)
+ }
+ res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND revision = ? AND vm_ref = ''", j.AttemptID, j.Revision).
+ Updates(map[string]any{"launch_id": v.LaunchID, "vm_ref": string(v.VMRef), "epoch": v.Epoch, "launching_since": nil, "revision": j.Revision + 1})
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected != 1 {
+ return fmt.Errorf("%w: hosted job %s moved", ErrConflict, j.AttemptID)
+ }
+ return t.s.authority.Audit(t.db, "system", "hosted.job", j.AttemptID+":vm_learned")
+}
+
+// hostedFinish ends a stopping job with p (ended when its step ended or
+// moved on, failed otherwise), settles it, revokes its runner, and moves
+// its step on: an attempt that was on the job's VM cannot go on (its VM
+// is proven stopped), so it is placed again under the same attempt, and a
+// step waiting as hosted work is placed again (placeHosted's rule 2
+// retries it once or resolves it).
+func (t *txn) hostedFinish(attempt string, p HostedEndProof) error {
+ var j HostedJob
+ if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil {
+ return err
+ }
+ to := HostedJobFailed
+ if slices.Contains([]string{hostedStopStepEnded, hostedStopStepMoved, hostedStopPersonRemoved}, j.StopReason) {
+ to = HostedJobEnded
+ }
+ if err := t.hostedEnd(attempt, to, p); err != nil {
+ return err
+ }
+ if _, err := t.hostedSettle(attempt); err != nil {
+ return err
+ }
+ if j.RunnerID != "" {
+ if t.s.authority.RevokeRunner == nil {
+ return fmt.Errorf("%w: no runner revocation", ErrInvalid)
+ }
+ if err := t.s.authority.RevokeRunner(t.db, j.RunnerID); err != nil {
+ return err
+ }
+ }
+ return t.hostedStepAgain(j)
+}
+
+// hostedStepAgain moves on the step of a job that just ended.
+func (t *txn) hostedStepAgain(j HostedJob) error {
+ var steps []stepRecord
+ if err := t.db.Where("id = ?", j.StepID).Limit(1).Find(&steps).Error; err != nil {
+ return err
+ }
+ if len(steps) == 0 {
+ return nil
+ }
+ s := steps[0]
+ if s.Retired || wire.StepTerminal(s.State) || s.Attempt != j.StepAttempt {
+ return nil
+ }
+ k, err := t.loadTask(s.TaskID)
+ if err != nil {
+ return err
+ }
+ onVM := j.RunnerID != "" && s.RunnerID == j.RunnerID
+ if wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" {
+ if !onVM {
+ return nil
+ }
+ // Its VM is proven stopped: the cancellation is finished.
+ now := t.now()
+ s.State, s.Reason, s.Terminated, s.FinishedAt, s.Withdrawn = wire.StepCancelled, "cancelled", true, &now, false
+ if !wire.FinalStage(k.Stage) && k.MoveProject == "" {
+ k.Stage = wire.StageCancelled
+ }
+ return t.saveStep(&s, &k)
+ }
+ if onVM {
+ if err := t.voidAttempt(s); err != nil {
+ return err
+ }
+ s.State, s.Reason, s.Terminated, s.StartedAt, s.FinishedAt, s.Withdrawn, s.TerminationKind = wire.StepQueued, "", false, nil, nil, false, ""
+ s.Summary, s.LogTail, s.Checks, s.Gate, s.ExitCode, s.Output = "", "", "", "", nil, ""
+ if err := t.dispatchStep(&k, &s); err != nil {
+ return err
+ }
+ return t.saveStep(&s, &k)
+ }
+ if s.State == wire.StepQueued && hostedPlacement(s.Placement) {
+ return t.placeAgain(&k, &s)
+ }
+ return nil
+}
diff --git a/internal/equipo/chat/macrecheck.go b/internal/equipo/chat/macrecheck.go
index d7fbed84..f8745aa8 100644
--- a/internal/equipo/chat/macrecheck.go
+++ b/internal/equipo/chat/macrecheck.go
@@ -64,7 +64,7 @@ func (t *txn) recheckMac(person, runner string) error {
return err
}
}
- if !slices.Contains(needs, wire.TagMacOS) || !mac.fits(needs, decodeList(c.RefusedBy)) {
+ if !slices.Contains(needs, wire.TagMacOS) || !mac.fits("", needs, decodeList(c.RefusedBy)) {
continue
}
var ran int64
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index f7001021..fe7a23b3 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -272,6 +272,11 @@ type runnerInfo struct {
SeenAt time.Time
Hello wire.Hello
Running int64
+ // Hosted: a hosted runner, bound to one job (hostedJobForRunner);
+ // HostedStep is that job's step while the job is live, "" once it
+ // is not. It never joins its person's general pool.
+ Hosted bool
+ HostedStep string
}
func (r runnerInfo) tags() []string {
@@ -282,10 +287,12 @@ func (r runnerInfo) tags() []string {
return r.Hello.Capabilities.Tags
}
-// fits reports whether checks with needs, refused by those runners, may
-// be placed on r.
-func (r runnerInfo) fits(needs, refused []string) bool {
- return wire.Covers(r.tags(), needs) && !slices.Contains(refused, r.ID) && r.Protocol >= wire.Protocol2 && !r.Removing
+// fits reports whether step's checks with needs, refused by those
+// runners, may be placed on r. A hosted runner fits only its live job's
+// step ("" is no step: Engineering, a primary's own checks).
+func (r runnerInfo) fits(step string, needs, refused []string) bool {
+ return wire.Covers(r.tags(), needs) && !slices.Contains(refused, r.ID) && r.Protocol >= wire.Protocol2 && !r.Removing &&
+ (!r.Hosted || step != "" && r.HostedStep == step)
}
// runners are the person's unrevoked runners in enrolment order, with
@@ -301,9 +308,25 @@ func (t *txn) runners(person string) ([]runnerInfo, error) {
WHERE person = ? AND revoked_at IS NULL ORDER BY rowid`, person).Scan(&rows).Error; err != nil {
return nil, err
}
+ ids := make([]string, 0, len(rows))
+ for _, r := range rows {
+ ids = append(ids, r.ID)
+ }
+ var bound []HostedJob
+ if err := t.db.Where("runner_id IN ?", ids).Find(&bound).Error; err != nil {
+ return nil, err
+ }
out := make([]runnerInfo, 0, len(rows))
for _, r := range rows {
info := runnerInfo{ID: r.ID, Role: wire.RolePrimary, Label: r.Label, Seq: r.Seq, Removing: r.Removing, Tainted: r.Tainted}
+ for _, j := range bound {
+ if j.RunnerID == r.ID {
+ info.Hosted = true
+ if j.Live() {
+ info.HostedStep = j.StepID
+ }
+ }
+ }
if r.Role == wire.RoleWorker {
info.Role = wire.RoleWorker
}
@@ -544,6 +567,9 @@ func (t *txn) place(k *taskRecord, s *stepRecord) (placed bool, err error) {
}
s.Needs = encodeList(needs)
s.RunnerID = primary
+ if placed, done, err := t.placeHosted(k, s, primary, needs); err != nil || done {
+ return placed, err
+ }
if len(needs) == 0 {
return true, nil
}
@@ -558,7 +584,7 @@ func (t *txn) place(k *taskRecord, s *stepRecord) (placed bool, err error) {
if r.ID == primary && r.Protocol >= wire.Protocol2 {
relay = true
}
- if r.fits(needs, refused) {
+ if r.fits(s.ID, needs, refused) {
fit = append(fit, r)
}
}
@@ -709,7 +735,7 @@ func (t *txn) engineeringDecide(k taskRecord, s stepRecord, primary string, need
switch r := &rs[i]; {
case r.ID == primary:
prim = r
- case r.ID == k.EngineeringRunner && r.Role == wire.RoleWorker && !r.Removing:
+ case r.ID == k.EngineeringRunner && r.Role == wire.RoleWorker && !r.Removing && !r.Hosted:
pin = r
}
}
@@ -721,7 +747,7 @@ func (t *txn) engineeringDecide(k taskRecord, s stepRecord, primary string, need
mac := macTags(needs)
fit := false
for _, r := range rs {
- if r.fits(mac, nil) {
+ if r.fits("", mac, nil) {
if r.ID == primary {
return engineeringPlacement{runner: primary}, nil
}
@@ -737,7 +763,7 @@ func (t *txn) engineeringDecide(k taskRecord, s stepRecord, primary string, need
if prim == nil {
return engineeringPlacement{placement: wire.PlacementWaiting, needs: needs}, nil
}
- if pin == nil && len(mac) > 0 && prim.fits(needs, nil) {
+ if pin == nil && len(mac) > 0 && prim.fits("", needs, nil) {
// A primary that is a Mac takes it.
return engineeringPlacement{runner: primary}, nil
}
@@ -770,7 +796,7 @@ func (t *txn) engineeringDecide(k taskRecord, s stepRecord, primary string, need
first := map[string]string{}
for i := range rs {
r := &rs[i]
- if r.Role != wire.RoleWorker || r.Removing || !macFor(*r, mac) {
+ if r.Role != wire.RoleWorker || r.Removing || r.Hosted || !macFor(*r, mac) {
continue
}
why, who := readiness(*r)
@@ -944,6 +970,14 @@ func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt i
refused = "withdrawn"
return nil
}
+ // A hosted runner starts only its job's step and attempt, while
+ // the job is enrolled: by job identity, in this transaction.
+ if j, bound, err := t.hostedJobForRunner(l.Runner.RunnerID); err != nil {
+ return err
+ } else if bound && (j.State != HostedJobEnrolled || j.StepID != st.ID || j.StepAttempt != attempt) {
+ refused = "withdrawn"
+ return nil
+ }
// A purpose this instance does not check for this step is refused,
// never taken for a start check.
if !leasePurposeKnown(st.Specialist, purpose) {
@@ -1040,11 +1074,13 @@ func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt i
}
// waitingPlacements are the placements of a step waiting to be placed,
-// a runner that can run Design's among them. A Design step the autonomy
-// limit held goes only once its person acts (releaseDesignHeld).
-// waiting_base is not one: the attempt waits for the primary's base
-// report, never placed again meanwhile (base_prepare.go).
-var waitingPlacements = []string{wire.PlacementWaiting, wire.PlacementSandbox, wire.PlacementMac, wire.PlacementMacEngineering, wire.PlacementMacConnection, wire.PlacementMacUpdate, wire.PlacementDesign}
+// a runner that can run Design's among them, and hosted work waiting for
+// its VM or its primary (waiting_hosted) or for the hosted limits
+// (hosted_limit). A Design step the autonomy limit held goes only once
+// its person acts (releaseDesignHeld). waiting_base is not one: the
+// attempt waits for the primary's base report, never placed again
+// meanwhile (base_prepare.go).
+var waitingPlacements = []string{wire.PlacementWaiting, wire.PlacementSandbox, wire.PlacementMac, wire.PlacementMacEngineering, wire.PlacementMacConnection, wire.PlacementMacUpdate, wire.PlacementDesign, wire.PlacementHosted, wire.PlacementHostedLimit}
// placeWaiting places the person's steps waiting for a runner, when one
// that fits may have come online or been added, or for a Mac's sandbox,
@@ -1063,25 +1099,28 @@ func (t *txn) placeWaiting(person string) error {
if wire.FinalStage(k.Stage) || k.CancelRequested {
continue
}
- since, was, mac, why := s.WaitingSince, s.Placement, s.SandboxRunner, s.Reason
- if err := t.dispatchStep(&k, &s); err != nil {
- return err
- }
- if s.Placement == was && s.SandboxRunner == mac && s.Reason == why {
- // Still waiting: the clock does not restart.
- s.WaitingSince = since
- if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Update("waiting_since", since).Error; err != nil {
- return err
- }
- continue
- }
- if err := t.saveStep(&s, &k); err != nil {
+ if err := t.placeAgain(&k, &s); err != nil {
return err
}
}
return nil
}
+// placeAgain places a waiting step again, and saves it unless it still
+// waits as it did.
+func (t *txn) placeAgain(k *taskRecord, s *stepRecord) error {
+ since, was, mac, why := s.WaitingSince, s.Placement, s.SandboxRunner, s.Reason
+ if err := t.dispatchStep(k, s); err != nil {
+ return err
+ }
+ if s.Placement == was && s.SandboxRunner == mac && s.Reason == why && !wire.StepTerminal(s.State) {
+ // Still waiting: the clock does not restart.
+ s.WaitingSince = since
+ return t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Update("waiting_since", since).Error
+ }
+ return t.saveStep(s, k)
+}
+
// Place runs placement for every person: steps waiting for a runner are
// placed when one that fits is online; checks that waited OfflineLimit
// resolve as not run (runner_offline, never a pass) and review goes on;
@@ -1121,6 +1160,10 @@ func (t *txn) offline(person string) error {
for _, r := range rs {
byID[r.ID] = r
}
+ primary, err := t.s.authority.PrimaryRunner(t.db, person)
+ if err != nil {
+ return err
+ }
var rows []stepRecord
if err := t.db.Where("person = ? AND specialist = ? AND state IN ?", person, wire.SpecialistChecks, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil {
return err
@@ -1144,8 +1187,29 @@ func (t *txn) offline(person string) error {
}
continue
}
+ if s.Placement == wire.PlacementHosted {
+ // Hosted work waits for its primary, which sends the pack:
+ // offline (or too old) for the limit, the step resolves
+ // runner_offline and its job stops (hostedStepEnded).
+ if s.WaitingSince == nil {
+ continue
+ }
+ p, ok := byID[primary]
+ away := t.now().Sub(*s.WaitingSince)
+ if ok && !p.Online && !p.SeenAt.IsZero() {
+ away = min(away, t.now().Sub(p.SeenAt))
+ }
+ if (!ok || !p.Online || p.Protocol < wire.ProtocolHostedRunners) && away >= OfflineLimit {
+ if err := t.resolveOffline(&k, &s); err != nil {
+ return err
+ }
+ }
+ continue
+ }
r, ok := byID[s.RunnerID]
- if !ok || r.Role != wire.RoleWorker || r.Online {
+ if !ok || r.Role != wire.RoleWorker || r.Online || r.Hosted {
+ // A hosted runner's step is never withdrawn: the dispatcher sees
+ // its VM to its end, and its end moves the step on.
continue
}
// Placed on a worker that is offline: withdraw it if another
@@ -1153,7 +1217,7 @@ func (t *txn) offline(person string) error {
// the limit (the next attempt then waits, or resolves).
alt := false
for _, o := range rs {
- if o.ID != r.ID && o.Online && !o.Removing && o.Protocol >= wire.Protocol2 && wire.Covers(o.tags(), decodeList(s.Needs)) && !slices.Contains(decodeList(s.RefusedBy), o.ID) {
+ if o.ID != r.ID && o.Online && o.fits(s.ID, decodeList(s.Needs), decodeList(s.RefusedBy)) {
alt = true
}
}
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 2abf798b..4f085260 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -73,6 +73,9 @@ type Authority struct {
// FinishRemoval revokes a runner whose removal waited for its work's
// end, once that end is proven.
FinishRemoval func(tx *gorm.DB, runnerID string) error
+ // RevokeRunner revokes a hosted runner once its job's VM is proven
+ // stopped (hostedFinish).
+ RevokeRunner func(tx *gorm.DB, runnerID string) error
// Audit records an action in the instance's audit log.
Audit func(tx *gorm.DB, actor, kind, record string) error
// ActivityLabel is the line a client shows for an activity, in a turn
@@ -153,6 +156,9 @@ type Store struct {
// Engineering for Mac work is placed on a Mac worker. Off, it waits as
// mac-placement-wait left it.
macEngineering atomic.Bool
+ // hostedRunners is hosted placement (SetHostedRunners): set only
+ // where the dispatcher runs.
+ hostedRunners atomic.Bool
}
// SetFrameTap sees every frame the instance sends a runner, as sent
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index 02671396..8cec2583 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -838,6 +838,10 @@ func (t *txn) saveStep(s *stepRecord, k *taskRecord) error {
// Research ended, however it ended: the Engineering it held goes.
return t.releaseResearch(k)
}
+ if s.Specialist == wire.SpecialistChecks && wire.StepTerminal(s.State) {
+ // Checks ended, however they ended: a hosted VM for them stops.
+ return t.hostedStepEnded(s.ID)
+ }
return nil
}
@@ -1348,7 +1352,16 @@ func (t *txn) dispatchStep(k *taskRecord, s *stepRecord) error {
cmd.Needs = decodeList(s.Needs)
switch s.Specialist {
case wire.SpecialistChecks:
- if _, err := t.openTransfer(*k, *s, primary, s.RunnerID, wire.TransferHeader{Direction: wire.TransferInbound, BaseSHA: cmd.BaseSHA, CandidateSHA: s.CandidateSHA}); err != nil {
+ // A hosted runner's checks get the hosted pack: the base and
+ // the candidate, for its empty store (placeHosted made sure
+ // both ends speak ProtocolHostedRunners).
+ if hosted, err := t.hostedBound(*s, s.RunnerID); err != nil {
+ return err
+ } else if hosted {
+ if _, err := t.openHostedPack(*k, *s, primary, cmd.BaseSHA); err != nil {
+ return err
+ }
+ } else if _, err := t.openTransfer(*k, *s, primary, s.RunnerID, wire.TransferHeader{Direction: wire.TransferInbound, BaseSHA: cmd.BaseSHA, CandidateSHA: s.CandidateSHA}); err != nil {
return err
}
case wire.SpecialistEngineering:
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index 1b2e9341..a02fae10 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -44,6 +44,9 @@ func (s *Store) Chat() *chat.Store {
FinishRemoval: func(tx *gorm.DB, id string) error {
return revokeRunnerAt(tx, id, s.runnerClock.Now().UTC())
},
+ RevokeRunner: func(tx *gorm.DB, id string) error {
+ return revokeRunnerAt(tx, id, s.runnerClock.Now().UTC())
+ },
Audit: func(tx *gorm.DB, actor, kind, record string) error {
return appendAudit(tx, Actor{Address: actor}, kind, record)
},
diff --git a/internal/equipo/config.go b/internal/equipo/config.go
index 6464adbd..ce69d407 100644
--- a/internal/equipo/config.go
+++ b/internal/equipo/config.go
@@ -2,6 +2,7 @@ package equipo
import (
"amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/equipo/hostedrun"
"amadan.net/oficina/equipo/internal/equipo/oficina"
"amadan.net/oficina/equipo/internal/equipo/push"
"amadan.net/oficina/equipo/internal/websearch"
@@ -81,6 +82,9 @@ type Config struct {
// shows owners the "Run checks in a hosted VM" setting. Unset, the
// instance does nothing hosted.
HostedRunners bool
+ // Hosted is the controller connection the hosted dispatcher uses
+ // (EQUIPO_HOSTED_CONTROLLER and the rest, hostedrun.ReadConfig).
+ Hosted hostedrun.Config
}
func LoadConfig(getenv func(string) string) (Config, error) {
@@ -89,6 +93,7 @@ func LoadConfig(getenv func(string) string) (Config, error) {
ExecutionEnabled: getenv("EQUIPO_EXECUTION_ENABLED") == "1",
MacEngineering: getenv("EQUIPO_MAC_ENGINEERING") == "1",
HostedRunners: getenv("EQUIPO_HOSTED_RUNNERS") == "1",
+ Hosted: hostedrun.ReadConfig(getenv),
ExecutionMarkerPath: getenv("EQUIPO_EXECUTION_MARKER_PATH"),
Origin: strings.TrimSpace(getenv("EQUIPO_ORIGIN")),
InstanceKey: strings.TrimSpace(getenv("EQUIPO_INSTANCE_KEY")),
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index f3a6fe76..4548fca8 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -992,6 +992,9 @@ var pageCopy = map[string]string{
"work.reason.deps_too_large": "the dependencies were too large to send to the hosted machine", // COPY REVIEW PENDING
"work.reason.token_renewal_failed": "the hosted machine could not renew its sign-in before the checks finished", // COPY REVIEW PENDING
"work.reason.pack_incomplete": "the hosted machine did not receive both commits it needed", // COPY REVIEW PENDING
+ "work.reason.hosted_enrol_timeout": "the hosted machine did not connect in time", // COPY REVIEW PENDING
+ "work.reason.hosted_vm_lost": "the hosted machine stopped before the checks finished", // COPY REVIEW PENDING
+ "work.reason.hosted_unavailable": "a hosted machine could not be started", // COPY REVIEW PENDING
"work.reason.placement_refused": "no runner could take it", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"work.reason.withdrawn": "it was withdrawn before it started", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"work.reason.transfer_refused": "the work could not move between runners", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
diff --git a/internal/equipo/hostedrun/dispatcher.go b/internal/equipo/hostedrun/dispatcher.go
new file mode 100644
index 00000000..88365e89
--- /dev/null
+++ b/internal/equipo/hostedrun/dispatcher.go
@@ -0,0 +1,500 @@
+// Package hostedrun is the instance's hosted VM dispatcher (hosted runners
+// slice 2, Task 21): it launches each admitted job's VM, keeps its
+// admission record fresh, and sees each VM to its end with the
+// controller's proof. It is the only package in the instance that talks to
+// the hosted controller (internal/hostedclient).
+//
+// Placement (chat's placeHosted) admits jobs; the dispatcher reaches the
+// store only through chat's exported Hosted* methods, each one
+// transaction. Controller calls are made outside any transaction.
+package hostedrun
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "crypto/tls"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "os"
+ "regexp"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/hostedclient"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Controller is what the dispatcher asks of the hosted controller.
+// *hostedclient.Client is the production one; its errors (ErrAbsent,
+// ErrStopPending and the rest) are what the dispatcher reads.
+type Controller interface {
+ Launch(ctx context.Context, q hostedwire.LaunchRequest) (hostedwire.JobView, error)
+ Get(ctx context.Context, attempt string) (hostedwire.JobView, error)
+ Admission(ctx context.Context, attempt string) (hostedwire.AdmissionView, error)
+ Stop(ctx context.Context, attempt, reason string) (hostedwire.StopProof, error)
+}
+
+// Admitter reads an attempt's admission record (hosted enrolment, Task
+// 22): implemented here over hostedclient and injected, so only this
+// package imports hostedclient.
+type Admitter interface {
+ Admission(ctx context.Context, attempt string) (hostedwire.AdmissionView, error)
+}
+
+// Every is how often the dispatcher makes a pass.
+const Every = 10 * time.Second
+
+// A launch the controller did not take, or an intent it has not yet
+// given a VM (a throttle), is tried again after a wait that doubles from
+// BackoffMin to BackoffMax.
+const (
+ BackoffMin = 10 * time.Second
+ BackoffMax = 5 * time.Minute
+)
+
+// The controller's job states the dispatcher reads (hostedctl's states).
+const (
+ ctlAbandoned = "abandoned"
+ ctlRunning = "running"
+ ctlStopping = "stopping"
+ ctlStopped = "stopped"
+)
+
+// Dispatcher sees hosted jobs from admission to proof. Store, Client and
+// Clock are required; Image and Account are what every launch names (the
+// certified image digest, the instance's account); Log may be nil.
+type Dispatcher struct {
+ Store *chat.Store
+ Client Controller
+ Clock func() time.Time
+ Image isolatedjob.ImageDigest
+ Account string
+ Log *slog.Logger
+
+ mu sync.Mutex
+ // codes are the instance codes this process sent, so a launch whose
+ // 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
+}
+
+type backoff struct {
+ next time.Time
+ wait time.Duration
+}
+
+func (d *Dispatcher) now() time.Time { return d.Clock().UTC() }
+
+func (d *Dispatcher) log() *slog.Logger {
+ if d.Log != nil {
+ return d.Log
+ }
+ return slog.Default()
+}
+
+// Run probes the controller, then makes a pass every Every until ctx ends.
+func (d *Dispatcher) Run(ctx context.Context) {
+ d.Probe(ctx)
+ tick := time.NewTicker(Every)
+ defer tick.Stop()
+ for {
+ if err := d.Pass(ctx); err != nil && ctx.Err() == nil {
+ d.log().Error("hosted_dispatch_failed", "err", err)
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ }
+ }
+}
+
+// Probe asks the controller for the admission of a made-up attempt: the
+// signed not-found answer (hostedclient.ErrAbsent) shows it is there, it
+// knows this instance's key and its answers verify. It logs
+// hosted_controller_reachable, or hosted_controller_unreachable with the
+// reason, and reports which.
+func (d *Dispatcher) Probe(ctx context.Context) bool {
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ d.log().Warn("hosted_controller_unreachable", "reason", err.Error())
+ return false
+ }
+ _, err := d.Client.Admission(ctx, hex.EncodeToString(raw))
+ if errors.Is(err, hostedclient.ErrAbsent) {
+ d.log().Info("hosted_controller_reachable")
+ return true
+ }
+ reason := "the controller answered for an attempt it cannot have"
+ if err != nil {
+ reason = err.Error()
+ }
+ d.log().Warn("hosted_controller_unreachable", "reason", reason)
+ return false
+}
+
+// Pass is one round: jobs whose step ended stop (chat.HostedSweep); each
+// live job moves on by its state; steps waiting as hosted work are placed
+// again (chat.PlaceHosted). A job's error is reported and the others go
+// on.
+func (d *Dispatcher) Pass(ctx context.Context) error {
+ if err := d.Store.HostedSweep(ctx); err != nil {
+ return err
+ }
+ jobs, err := d.Store.HostedLive(ctx)
+ if err != nil {
+ return err
+ }
+ var errs []error
+ live := map[string]bool{}
+ for _, j := range jobs {
+ live[j.AttemptID] = true
+ if err := d.job(ctx, j); err != nil {
+ errs = append(errs, fmt.Errorf("hosted job %s: %w", j.AttemptID, err))
+ }
+ }
+ d.forget(live)
+ if err := d.Store.PlaceHosted(ctx); err != nil {
+ errs = append(errs, err)
+ }
+ return errors.Join(errs...)
+}
+
+// launchBy is the job's launch-by: its admission plus the launch window.
+func launchBy(j chat.HostedJob) time.Time {
+ if j.LaunchBy != nil {
+ return j.LaunchBy.UTC()
+ }
+ return j.AdmittedAt.UTC().Add(chat.HostedLaunchWindow)
+}
+
+func (d *Dispatcher) job(ctx context.Context, j chat.HostedJob) error {
+ now := d.now()
+ by := launchBy(j)
+ switch j.State {
+ case chat.HostedJobPending, chat.HostedJobLaunching:
+ if j.State == chat.HostedJobLaunching && j.LaunchingSince != nil {
+ // A call an earlier process made and never saw return: none is
+ // in flight now.
+ if err := d.Store.HostedLaunchReturned(ctx, j.AttemptID); err != nil {
+ return err
+ }
+ }
+ if !now.Before(by) {
+ // Not launched in its window: failed, and admitted again only
+ // once its end is proven (placement's rule 2).
+ return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedUnavailable)
+ }
+ if !d.due(j.AttemptID, now) {
+ return nil
+ }
+ if j.State == chat.HostedJobPending {
+ return d.launch(ctx, j, by)
+ }
+ v, err := d.Client.Get(ctx, j.AttemptID)
+ switch {
+ case errors.Is(err, hostedclient.ErrAbsent):
+ // The controller has no intent for it: send it (again).
+ return d.launch(ctx, j, by)
+ case err != nil:
+ d.later(j.AttemptID, now)
+ d.log().Warn("hosted_get_failed", "attempt", j.AttemptID, "err", err)
+ return nil
+ case v.VMRef.Valid():
+ d.settled(j.AttemptID)
+ return d.Store.HostedLaunched(ctx, j.AttemptID, v)
+ case v.State == ctlAbandoned:
+ return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedUnavailable)
+ }
+ // Waiting: the controller launches it when the provider allows.
+ d.later(j.AttemptID, now)
+ return nil
+ case chat.HostedJobEnrolling, chat.HostedJobEnrolled:
+ return d.watch(ctx, j)
+ case chat.HostedJobStopping:
+ return d.stop(ctx, j)
+ }
+ return nil
+}
+
+// launch records a launch before asking for it, then asks, outside any
+// transaction, and records what came back: the VM, or that the call
+// returned without one (a throttle, a refusal, a lost reply), with a
+// backoff before the next try.
+func (d *Dispatcher) launch(ctx context.Context, j chat.HostedJob, by time.Time) error {
+ code, err := d.code(j.AttemptID)
+ if err != nil {
+ return err
+ }
+ if err := d.Store.HostedLaunching(ctx, j.AttemptID, code, by.Add(chat.HostedLaunchWindow), by); err != nil {
+ return err
+ }
+ replaces, err := d.Store.HostedReplaces(ctx, j.AttemptID)
+ if err != nil {
+ 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,
+ Person: j.Person, Purpose: hostedwire.PurposeChecks, LaunchByUnixMS: by.UnixMilli()}
+ v, err := d.Client.Launch(ctx, q)
+ if err == nil && v.VMRef.Valid() {
+ d.settled(j.AttemptID)
+ return d.Store.HostedLaunched(ctx, j.AttemptID, v)
+ }
+ if rerr := d.Store.HostedLaunchReturned(ctx, j.AttemptID); rerr != nil {
+ return rerr
+ }
+ d.later(j.AttemptID, d.now())
+ if err != nil {
+ d.log().Warn("hosted_launch_failed", "attempt", j.AttemptID, "err", err)
+ }
+ return nil
+}
+
+// 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.
+func (d *Dispatcher) watch(ctx context.Context, j chat.HostedJob) error {
+ asked := d.now()
+ a, err := d.Client.Admission(ctx, j.AttemptID)
+ if err != nil {
+ d.log().Warn("hosted_admission_failed", "attempt", j.AttemptID, "err", err)
+ return nil
+ }
+ if err := d.Store.HostedAdmitted(ctx, j.AttemptID, a, asked); err != nil {
+ return err
+ }
+ switch a.State {
+ 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)
+ }
+ }
+ return nil
+}
+
+// stop asks the controller to stop a stopping job's VM until it returns
+// proof, then records it (the store ends and settles the job, revokes its
+// runner and moves its step on). A job with no launch, VM or runner on
+// record may instead end with never-launched evidence.
+func (d *Dispatcher) stop(ctx context.Context, j chat.HostedJob) error {
+ proof, err := d.Client.Stop(ctx, j.AttemptID, j.StopReason)
+ if err == nil {
+ return d.Store.HostedStopped(ctx, j.AttemptID, proof, d.now())
+ }
+ if !errors.Is(err, hostedclient.ErrStopPending) {
+ d.log().Warn("hosted_stop_failed", "attempt", j.AttemptID, "err", err)
+ }
+ if j.LaunchID != "" || j.VMRef != "" || j.RunnerID != "" {
+ return nil
+ }
+ return d.neverLaunched(ctx, j)
+}
+
+// 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.
+func (d *Dispatcher) neverLaunched(ctx context.Context, j chat.HostedJob) error {
+ by := launchBy(j)
+ observed := d.now()
+ if observed.Before(by.Add(chat.HostedNeverLaunchedAfter)) {
+ return nil
+ }
+ if j.LaunchingSince != nil {
+ if err := d.Store.HostedLaunchReturned(ctx, j.AttemptID); err != nil {
+ return err
+ }
+ }
+ v, err := d.Client.Get(ctx, j.AttemptID)
+ state := ""
+ switch {
+ case errors.Is(err, hostedclient.ErrAbsent):
+ state = chat.HostedControllerAbsent
+ case err != nil:
+ return nil
+ case v.VMRef != "":
+ return d.Store.HostedLaunched(ctx, j.AttemptID, v)
+ case v.State == ctlAbandoned:
+ state = chat.HostedControllerAbandoned
+ default:
+ return nil
+ }
+ return d.Store.HostedNeverLaunched(ctx, j.AttemptID, chat.HostedNeverLaunched{AttemptID: j.AttemptID, ObservedAt: observed,
+ LaunchBy: by, ControllerState: state, Signed: true})
+}
+
+// code is the instance code for attempt: the one this process already
+// sent, or 32 new random bytes in unpadded base64url.
+func (d *Dispatcher) code(attempt string) (string, error) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if c := d.codes[attempt]; c != "" {
+ return c, nil
+ }
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ return "", err
+ }
+ if d.codes == nil {
+ d.codes = map[string]string{}
+ }
+ c := base64.RawURLEncoding.EncodeToString(raw)
+ d.codes[attempt] = c
+ return c, nil
+}
+
+func (d *Dispatcher) due(attempt string, now time.Time) bool {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return !now.Before(d.waits[attempt].next)
+}
+
+// later backs attempt off: BackoffMin, doubling to BackoffMax.
+func (d *Dispatcher) later(attempt string, now time.Time) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if d.waits == nil {
+ d.waits = map[string]backoff{}
+ }
+ w := min(max(2*d.waits[attempt].wait, BackoffMin), BackoffMax)
+ d.waits[attempt] = backoff{next: now.Add(w), wait: w}
+}
+
+func (d *Dispatcher) settled(attempt string) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ delete(d.waits, attempt)
+}
+
+// forget drops what the process holds of jobs no longer live.
+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)
+ }
+ }
+ for a := range d.waits {
+ if !live[a] {
+ delete(d.waits, a)
+ }
+ }
+}
+
+// Config is the instance's controller connection (EQUIPO_HOSTED_*).
+type Config struct {
+ // Controller is the controller's https origin; TLSPin the hex SHA-256
+ // of its certificate's public key (SPKI), the only identity accepted.
+ Controller, TLSPin string
+ // ControllerKey is the controller's Ed25519 public key (standard
+ // base64); KeyID and Key the instance's key ID and Ed25519 seed
+ // (standard base64).
+ ControllerKey, KeyID, Key string
+ // Image is the certified image every checks launch names; Account the
+ // instance's account name in the controller's records.
+ Image, Account string
+}
+
+// ReadConfig reads Config from the environment. It checks nothing; New
+// does.
+func ReadConfig(getenv func(string) string) Config {
+ return Config{Controller: getenv("EQUIPO_HOSTED_CONTROLLER"), TLSPin: getenv("EQUIPO_HOSTED_CONTROLLER_TLS_PIN"),
+ ControllerKey: getenv("EQUIPO_HOSTED_CONTROLLER_PUB"), KeyID: getenv("EQUIPO_HOSTED_KEY_ID"), Key: getenv("EQUIPO_HOSTED_KEY"),
+ Image: getenv("EQUIPO_HOSTED_IMAGE"), Account: getenv("EQUIPO_HOSTED_ACCOUNT")}
+}
+
+// imageDigest is an isolatedjob.ImageDigest: "sha256:" and 64 lower-case
+// hex digits.
+var imageDigest = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
+
+// ed25519Key is the private key of a 32-byte seed.
+func ed25519Key(seed []byte) ed25519.PrivateKey { return ed25519.NewKeyFromSeed(seed) }
+
+// ErrConfig is a controller connection that is missing or malformed.
+var ErrConfig = errors.New("hostedrun: the hosted controller connection is not configured")
+
+// New builds the dispatcher over a hostedclient for cfg. Without
+// EQUIPO_HOSTED_RUNNERS=1 it refuses (hostedclient.ErrRunnersOff): the
+// instance does nothing hosted.
+func New(store *chat.Store, cfg Config, log *slog.Logger) (*Dispatcher, error) {
+ if os.Getenv(hostedclient.FlagEnv) != "1" {
+ return nil, hostedclient.ErrRunnersOff
+ }
+ pin, err := hex.DecodeString(cfg.TLSPin)
+ pub, perr := base64.StdEncoding.DecodeString(cfg.ControllerKey)
+ seed, serr := base64.StdEncoding.DecodeString(cfg.Key)
+ image := isolatedjob.ImageDigest(cfg.Image)
+ switch {
+ case store == nil, cfg.Controller == "", err != nil, len(pin) != sha256.Size, perr != nil, serr != nil, len(seed) != 32,
+ cfg.KeyID == "", !imageDigest.MatchString(string(image)), cfg.Account == "":
+ return nil, ErrConfig
+ }
+ tlsCfg := &tls.Config{MinVersion: tls.VersionTLS12,
+ // The pin is the controller's identity: the leaf's key must be the
+ // pinned one. VerifyConnection runs either way.
+ InsecureSkipVerify: true,
+ VerifyConnection: func(cs tls.ConnectionState) error {
+ if len(cs.PeerCertificates) == 0 {
+ return errors.New("hostedrun: the controller sent no certificate")
+ }
+ got := sha256.Sum256(cs.PeerCertificates[0].RawSubjectPublicKeyInfo)
+ if subtle.ConstantTimeCompare(got[:], pin) != 1 {
+ return errors.New("hostedrun: the controller's certificate is not the pinned one")
+ }
+ return nil
+ }}
+ client, err := hostedclient.New(hostedclient.Config{BaseURL: cfg.Controller, KeyID: hostedwire.KeyID(cfg.KeyID), Key: ed25519Key(seed),
+ ControllerKey: pub, HTTP: &http.Client{Transport: &http.Transport{TLSClientConfig: tlsCfg, Proxy: nil}, Timeout: 30 * time.Second}})
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", ErrConfig, err)
+ }
+ return &Dispatcher{Store: store, Client: client, Clock: time.Now, Image: image, Account: cfg.Account, Log: log}, nil
+}
+
+// Admitter is the dispatcher's controller as Task 22's enrolment reads
+// it.
+func (d *Dispatcher) Admitter() Admitter { return d.Client }
diff --git a/internal/equipo/hostedrun/dispatcher_test.go b/internal/equipo/hostedrun/dispatcher_test.go
new file mode 100644
index 00000000..4e8a739b
--- /dev/null
+++ b/internal/equipo/hostedrun/dispatcher_test.go
@@ -0,0 +1,873 @@
+package hostedrun
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "math/rand"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/hostedclient"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/wire"
+ "amadan.net/rastrillo/rastrillo/budget"
+ "amadan.net/rastrillo/rastrillo/db"
+ "gorm.io/gorm"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+const (
+ owner = "owner@example.com"
+ primary = "P1"
+ image = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
+)
+
+var (
+ baseSHA = strings.Repeat("a", 40)
+ candidateSHA = strings.Repeat("b", 40)
+ start = time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)
+)
+
+// template is the migrated database every rig copies.
+var template struct {
+ once sync.Once
+ dir string
+ err error
+}
+
+func templatePath() (string, error) {
+ template.once.Do(func() {
+ dir, err := os.MkdirTemp("", "hostedrun-")
+ if err != nil {
+ template.err = err
+ return
+ }
+ template.dir = dir
+ d, err := db.Open(filepath.Join(dir, "template.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ template.err = err
+ return
+ }
+ defer d.Close()
+ if err := d.G.AutoMigrate(chat.Models...); err != nil {
+ template.err = err
+ return
+ }
+ for _, q := range []string{
+ "CREATE TABLE members (address text PRIMARY KEY, active integer, role text)",
+ "CREATE TABLE teams (id text PRIMARY KEY)",
+ "CREATE TABLE runners (id text PRIMARY KEY, person text, role text, label text, revoked_at datetime, removing_at datetime, tainted_at datetime)",
+ "INSERT INTO teams(id) VALUES ('TEAM1')",
+ "INSERT INTO members(address, active, role) VALUES ('owner@example.com', 1, 'owner')",
+ "INSERT INTO chat_projects(id, repo, state, revision, hosted_checks, hosted_checks_owner, hosted_checks_revision) VALUES ('p1', 'amadan.net/oficina/sample', 'active', 1, 1, 'owner@example.com', 1)",
+ "INSERT INTO runners(id, person, role, label) VALUES ('P1', 'owner@example.com', 'primary', 'P1')",
+ "PRAGMA wal_checkpoint(TRUNCATE)",
+ } {
+ if _, err := d.Writer().Exec(q); err != nil {
+ template.err = err
+ return
+ }
+ }
+ })
+ return filepath.Join(template.dir, "template.db"), template.err
+}
+
+// rig is a chat store over a copy of the template, on a fake clock,
+// with hosted runners on, the owner's primary P1 online at
+// ProtocolHostedRunners, a fake controller and a dispatcher over both.
+type rig struct {
+ t testing.TB
+ ctx context.Context
+ now time.Time
+ d *db.DB
+ s *chat.Store
+ ctl *fakeCtl
+ disp *Dispatcher
+ logs *bytes.Buffer
+}
+
+func newRig(t testing.TB, rng *rand.Rand) *rig {
+ t.Helper()
+ src, err := templatePath()
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := os.ReadFile(src)
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(t.TempDir(), "hosted.db")
+ if err := os.WriteFile(path, raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = d.Close() })
+ r := &rig{t: t, ctx: context.Background(), now: start, d: d, logs: &bytes.Buffer{}}
+ r.s = chat.NewStore(d, chat.Authority{
+ CurrentPerson: func(context.Context, *gorm.DB) error { return nil },
+ Audit: func(*gorm.DB, string, string, string) error { return nil },
+ Copy: func(k string) string { return k },
+ Me: func(tx *gorm.DB, address string) (wire.Me, error) {
+ var rows []struct {
+ Active bool
+ Role string
+ }
+ if err := tx.Raw("SELECT active, role FROM members WHERE address = ?", address).Scan(&rows).Error; err != nil {
+ return wire.Me{}, err
+ }
+ if len(rows) != 1 || !rows[0].Active {
+ return wire.Me{}, chat.ErrForbidden
+ }
+ return wire.Me{Address: address, Role: rows[0].Role}, nil
+ },
+ PrimaryRunner: func(tx *gorm.DB, person string) (string, error) {
+ var ids []string
+ err := tx.Raw(`SELECT id FROM runners WHERE person = ? AND revoked_at IS NULL AND coalesce(role, '') IN ('primary', '') ORDER BY rowid DESC LIMIT 1`, person).Scan(&ids).Error
+ if err != nil || len(ids) == 0 {
+ return "", err
+ }
+ return ids[0], nil
+ },
+ RunnerRole: func(tx *gorm.DB, id string) (string, error) {
+ var roles []string
+ if err := tx.Raw(`SELECT coalesce(role, '') FROM runners WHERE id = ?`, id).Scan(&roles).Error; err != nil {
+ return "", err
+ }
+ if len(roles) == 1 && roles[0] == wire.RoleWorker {
+ return wire.RoleWorker, nil
+ }
+ return wire.RolePrimary, nil
+ },
+ CurrentRunner: func(*gorm.DB, chat.RunnerPrincipal) error { return nil },
+ RevokeRunner: func(tx *gorm.DB, id string) error {
+ return tx.Exec("UPDATE runners SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL", r.now, id).Error
+ },
+ }, nil)
+ r.s.SetClock(func() time.Time { return r.now })
+ r.s.SetHostedRunners(true)
+ r.ctl = &fakeCtl{now: func() time.Time { return r.now }, rng: rng, jobs: map[string]*fakeVM{}, certValid: true, stopDelay: 1}
+ r.restart()
+ r.online(primary)
+ return r
+}
+
+// restart is a new dispatcher process: nothing remembered.
+func (r *rig) restart() {
+ r.disp = &Dispatcher{Store: r.s, Client: r.ctl, Clock: func() time.Time { return r.now }, Image: image, Account: "acct-1",
+ Log: slog.New(slog.NewTextHandler(r.logs, nil))}
+}
+
+func (r *rig) exec(q string, args ...any) {
+ r.t.Helper()
+ if err := r.d.G.Exec(q, args...).Error; err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func (r *rig) must(err error) {
+ r.t.Helper()
+ if err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+// online records runner id connected now at ProtocolHostedRunners.
+func (r *rig) online(id string) {
+ r.t.Helper()
+ r.exec("INSERT INTO runner_sessions(runner_id, generation, connected, process, revision, hello, seen_at, protocol) VALUES (?, 1, 1, 'p', 1, '', ?, ?) ON CONFLICT(runner_id) DO UPDATE SET connected = 1, seen_at = excluded.seen_at", id, r.now, wire.ProtocolHostedRunners)
+}
+
+// checks records task tk with checks step id waiting to be placed as
+// hosted work; the next pass places it.
+func (r *rig) checks(id, tk string) {
+ r.t.Helper()
+ r.exec("INSERT INTO chat_tasks(id, project_id, title, stage, creator, revision, created_at, updated_at, branch, base_sha) VALUES (?, 'p1', 'Checks', ?, ?, 1, ?, ?, ?, ?)",
+ tk, wire.StageInReview, owner, r.now, r.now, "equipo/"+tk, baseSHA)
+ r.exec("INSERT INTO chat_steps(id, task_id, idx, person, state, attempt, specialist, base_sha, candidate_sha, revision, created_at, updated_at, placement, waiting_since) VALUES (?, ?, 1, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?)",
+ id, tk, owner, wire.StepQueued, wire.SpecialistChecks, baseSHA, candidateSHA, r.now, r.now, wire.PlacementHosted, r.now)
+}
+
+type stepRow struct {
+ State, Placement, RunnerID, Reason, Checks string
+ Attempt int64
+}
+
+func (r *rig) step(id string) stepRow {
+ r.t.Helper()
+ var rows []stepRow
+ r.must(r.d.G.Raw("SELECT coalesce(state, '') AS state, coalesce(placement, '') AS placement, coalesce(runner_id, '') AS runner_id, coalesce(reason, '') AS reason, coalesce(checks, '') AS checks, attempt FROM chat_steps WHERE id = ?", id).Scan(&rows).Error)
+ if len(rows) != 1 {
+ r.t.Fatalf("step %s: %d rows", id, len(rows))
+ }
+ return rows[0]
+}
+
+func (r *rig) jobs(step string) []chat.HostedJob {
+ r.t.Helper()
+ var rows []chat.HostedJob
+ r.must(r.d.G.Where("step_id = ?", step).Order("admitted_at, rowid").Find(&rows).Error)
+ return rows
+}
+
+func (r *rig) job(attempt string) chat.HostedJob {
+ r.t.Helper()
+ var j chat.HostedJob
+ r.must(r.d.G.Where("attempt_id = ?", attempt).First(&j).Error)
+ return j
+}
+
+// pass is one dispatcher pass at the rig's time; the controller moves
+// its VMs on first.
+func (r *rig) pass() {
+ r.t.Helper()
+ r.ctl.tick()
+ if err := r.disp.Pass(r.ctx); err != nil {
+ r.t.Fatalf("pass at %s: %v", r.now.Format(time.TimeOnly), err)
+ }
+}
+
+// passes runs a pass every 10 s for d, the primary kept online.
+func (r *rig) passes(d time.Duration) {
+ r.t.Helper()
+ for end := r.now.Add(d); r.now.Before(end); {
+ r.now = r.now.Add(Every)
+ r.online(primary)
+ r.pass()
+ }
+}
+
+// until runs passes every 10 s until done holds, for at most d.
+func (r *rig) until(d time.Duration, what string, done func() bool) {
+ r.t.Helper()
+ for end := r.now.Add(d); !done(); {
+ if !r.now.Before(end) {
+ r.t.Fatalf("%s: not within %v", what, d)
+ }
+ r.passes(Every)
+ }
+}
+
+// enrol stands in for Task 22's enrolment of attempt's VM as runner:
+// the VM's code (the one its launch carried) is used, the runner bound
+// and connected. It reports whether the VM could.
+func (r *rig) enrol(attempt, runner string) bool {
+ r.t.Helper()
+ j := r.job(attempt)
+ vm := r.ctl.vm(attempt)
+ if j.State != chat.HostedJobEnrolling || vm == nil || vm.state != ctlRunning || codeHash(vm.q.InstanceCode) != j.CodeHash || r.now.After(*j.CodeExpiresAt) {
+ return false
+ }
+ r.exec("INSERT INTO runners(id, person, role, label) VALUES (?, ?, 'worker', ?)", runner, owner, runner)
+ r.exec("UPDATE hosted_jobs SET state = ?, runner_id = ?, machine_public_key = 'key', code_used_at = ?, enrolled_at = ?, revision = revision + 1 WHERE attempt_id = ? AND state = ?",
+ chat.HostedJobEnrolled, runner, r.now, r.now, attempt, chat.HostedJobEnrolling)
+ r.online(runner)
+ return true
+}
+
+func codeHash(code string) string {
+ sum := sha256.Sum256([]byte(code))
+ return hex.EncodeToString(sum[:])
+}
+
+// fakeVM is one attempt as the fake controller holds it.
+type fakeVM struct {
+ q hostedwire.LaunchRequest
+ state string
+ ref isolatedjob.Ref
+ launchID string
+ stopAsked bool
+ everVM bool
+ stopTicks int
+ proof *hostedwire.StopProof
+ proofAt time.Time
+ noEnrol bool
+}
+
+func (v *fakeVM) view() hostedwire.JobView {
+ return hostedwire.JobView{AttemptID: v.q.AttemptID, LaunchID: v.launchID, State: v.state, VMRef: v.ref}
+}
+
+// alive reports whether the VM may be running.
+func (v *fakeVM) alive() bool { return v.everVM && 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
+ certValid bool
+ // certs is when the certificate's validity changed, oldest first.
+ certs []certChange
+ stopDelay int
+ launchErr error
+ // getErr is what every Get answers, when set.
+ getErr error
+ // down: the controller cannot be reached; no request arrives.
+ down bool
+ launches []launchCall
+ gets []time.Time
+}
+
+type certChange struct {
+ at time.Time
+ valid bool
+}
+
+type launchCall struct {
+ q hostedwire.LaunchRequest
+ at time.Time
+}
+
+func (f *fakeCtl) chance(p float64) bool { return f.rng != nil && p > 0 && f.rng.Float64() < p }
+
+func (f *fakeCtl) vm(attempt string) *fakeVM {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.jobs[attempt]
+}
+
+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.noEnrol = f.chance(f.noEnrol)
+}
+
+func (f *fakeCtl) prove(v *fakeVM) {
+ v.state = ctlStopped
+ v.proof = &hostedwire.StopProof{AttemptID: v.q.AttemptID, VMRef: v.ref, State: isolatedjob.StateStopped}
+ v.proofAt = f.now()
+}
+
+// tick moves every VM on one step, as the provider and the controller's
+// refresh would.
+func (f *fakeCtl) tick() {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for _, v := range f.ordered() {
+ switch v.state {
+ case "waiting":
+ if f.now().UnixMilli() > v.q.LaunchByUnixMS || v.stopAsked {
+ v.state = ctlAbandoned
+ } else if !f.chance(f.throttle) {
+ f.start(v)
+ }
+ case "starting":
+ v.state = ctlRunning
+ case ctlRunning:
+ if f.chance(f.death) {
+ f.prove(v)
+ }
+ case ctlStopping:
+ if v.stopTicks--; v.stopTicks <= 0 {
+ f.prove(v)
+ }
+ case ctlAbandoned:
+ if v.stopAsked && v.proof == nil {
+ v.proof = &hostedwire.StopProof{AttemptID: v.q.AttemptID, State: isolatedjob.StateStopped}
+ v.proofAt = f.now()
+ }
+ }
+ }
+}
+
+func (f *fakeCtl) ordered() []*fakeVM {
+ out := make([]*fakeVM, 0, len(f.jobs))
+ for i := 1; i <= len(f.jobs); i++ {
+ for _, v := range f.jobs {
+ if v.launchID == fmt.Sprintf("launch-%d", i) {
+ out = append(out, v)
+ }
+ }
+ }
+ return out
+}
+
+func (f *fakeCtl) Launch(_ context.Context, q hostedwire.LaunchRequest) (hostedwire.JobView, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.down {
+ return hostedwire.JobView{}, hostedclient.ErrTransport
+ }
+ f.launches = append(f.launches, launchCall{q: q, at: f.now()})
+ if f.launchErr != nil {
+ return hostedwire.JobView{}, f.launchErr
+ }
+ if f.now().UnixMilli() > q.LaunchByUnixMS {
+ return hostedwire.JobView{}, hostedclient.ErrLaunchExpired
+ }
+ if v, ok := f.jobs[q.AttemptID]; ok {
+ if v.q != q {
+ return hostedwire.JobView{}, hostedclient.ErrConflict
+ }
+ return f.answer(v.view())
+ }
+ if q.Replaces != "" {
+ if p := f.jobs[q.Replaces]; p == nil || p.proof == nil {
+ return hostedwire.JobView{}, hostedclient.ErrReplacementLive
+ }
+ }
+ v := &fakeVM{q: q, state: "waiting", launchID: fmt.Sprintf("launch-%d", len(f.jobs)+1)}
+ f.jobs[q.AttemptID] = v
+ if !f.chance(f.throttle) {
+ f.start(v)
+ }
+ return f.answer(v.view())
+}
+
+// answer is v, or a lost reply.
+func (f *fakeCtl) answer(v hostedwire.JobView) (hostedwire.JobView, error) {
+ if f.chance(f.lose) {
+ return hostedwire.JobView{}, hostedclient.ErrTransport
+ }
+ return v, nil
+}
+
+func (f *fakeCtl) Get(_ context.Context, attempt string) (hostedwire.JobView, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.down {
+ return hostedwire.JobView{}, hostedclient.ErrTransport
+ }
+ f.gets = append(f.gets, f.now())
+ if f.getErr != nil {
+ return hostedwire.JobView{}, f.getErr
+ }
+ v, ok := f.jobs[attempt]
+ if !ok {
+ return hostedwire.JobView{}, hostedclient.ErrAbsent
+ }
+ return f.answer(v.view())
+}
+
+func (f *fakeCtl) Admission(_ context.Context, attempt string) (hostedwire.AdmissionView, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.down {
+ return hostedwire.AdmissionView{}, hostedclient.ErrTransport
+ }
+ v, ok := f.jobs[attempt]
+ if !ok {
+ return hostedwire.AdmissionView{}, hostedclient.ErrAbsent
+ }
+ 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,
+ CertDigest: "cert-1", CertValid: f.certValid, CheckedNS: f.now().UnixNano()}, nil
+}
+
+func (f *fakeCtl) Stop(_ context.Context, attempt, reason string) (hostedwire.StopProof, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.down {
+ return hostedwire.StopProof{}, hostedclient.ErrTransport
+ }
+ v, ok := f.jobs[attempt]
+ if !ok {
+ return hostedwire.StopProof{}, hostedclient.ErrForbidden
+ }
+ if reason == "" {
+ return hostedwire.StopProof{}, hostedclient.ErrInvalid
+ }
+ v.stopAsked = true
+ if v.proof != nil {
+ if f.chance(f.lose) {
+ return hostedwire.StopProof{}, hostedclient.ErrTransport
+ }
+ return *v.proof, nil
+ }
+ switch v.state {
+ case "waiting":
+ v.state = ctlAbandoned
+ case "starting", ctlRunning:
+ v.state, v.stopTicks = ctlStopping, f.stopDelay
+ }
+ return hostedwire.StopProof{}, hostedclient.ErrStopPending
+}
+
+// setCert changes the certificate's validity now.
+func (f *fakeCtl) setCert(valid bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.certValid != valid {
+ f.certValid = valid
+ f.certs = append(f.certs, certChange{at: f.now(), valid: valid})
+ }
+}
+
+// validAt is whether the certificate was valid at t.
+func (f *fakeCtl) validAt(t time.Time) bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ valid := true
+ for _, c := range f.certs {
+ if !c.at.After(t) {
+ valid = c.valid
+ }
+ }
+ return valid
+}
+
+// TestEnrolTimeoutRetriesOnce: a VM running 2 minutes without enrolling
+// is stopped; the retry is launched only after the first VM's stop proof,
+// naming it as replaced; when the retry does not enrol either, the step
+// ends not run, hosted_enrol_timeout.
+func TestEnrolTimeoutRetriesOnce(t *testing.T) {
+ r := newRig(t, nil)
+ r.checks("s1", "tk1")
+ r.pass()
+ jobs := r.jobs("s1")
+ if len(jobs) != 1 || jobs[0].State != chat.HostedJobPending {
+ t.Fatalf("after placement: %+v", jobs)
+ }
+ first := jobs[0].AttemptID
+ r.passes(10 * time.Second)
+ if j := r.job(first); j.State != chat.HostedJobEnrolling || j.VMRef == "" || len(r.ctl.launches) != 1 {
+ t.Fatalf("after the launch: %s %q, %d launches", j.State, j.VMRef, len(r.ctl.launches))
+ }
+ q := r.ctl.launches[0].q
+ if q.Person != owner || q.Purpose != hostedwire.PurposeChecks || q.Replaces != "" || q.Size != chat.HostedChecksSize || q.Image != image ||
+ q.LaunchByUnixMS != jobs[0].AdmittedAt.Add(chat.HostedLaunchWindow).UnixMilli() || q.MaxLifetimeMS != chat.HostedChecksLifetime.Milliseconds() ||
+ codeHash(q.InstanceCode) != r.job(first).CodeHash {
+ t.Fatalf("launch request %+v", q)
+ }
+ r.passes(chat.HostedEnrolTimeout)
+ if j := r.job(first); j.State != chat.HostedJobEnrolling || len(r.jobs("s1")) != 1 {
+ t.Fatalf("first job within its enrolment window: %s", j.State)
+ }
+ r.until(time.Minute, "first job ended", func() bool { return !r.job(first).Live() })
+ proof := r.ctl.vm(first).proofAt
+ jobs = r.jobs("s1")
+ if len(jobs) != 2 || jobs[0].State != chat.HostedJobFailed || jobs[0].StopReason != wire.ReasonHostedEnrolTimeout || jobs[0].SettledAt == nil {
+ t.Fatalf("after the first timeout: %+v", jobs)
+ }
+ second := jobs[1].AttemptID
+ if jobs[1].RetryOf != first || jobs[1].Retries != 1 {
+ t.Fatalf("retry %+v, want retry_of %s", jobs[1], first)
+ }
+ r.passes(10 * time.Second)
+ if len(r.ctl.launches) != 2 || r.ctl.launches[1].q.AttemptID != second || r.ctl.launches[1].q.Replaces != first || r.ctl.launches[1].at.Before(proof) {
+ t.Fatalf("retry launches %+v, want one for %s replacing %s after %v", r.ctl.launches, second, first, proof)
+ }
+ r.until(chat.HostedEnrolTimeout+time.Minute, "step resolved", func() bool { return r.step("s1").State == wire.StepDone })
+ s := r.step("s1")
+ if s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != wire.ReasonHostedEnrolTimeout || len(r.jobs("s1")) != 2 {
+ t.Fatalf("retry spent: %+v with %d jobs", s, len(r.jobs("s1")))
+ }
+ if j := r.job(second); j.State != chat.HostedJobFailed || j.SettledAt == nil || r.ctl.vm(second).alive() {
+ t.Fatalf("second job %s settled %v, VM alive %t", j.State, j.SettledAt, r.ctl.vm(second).alive())
+ }
+}
+
+// TestVMGoneMidStep: a VM that stops while its step runs fails the job
+// (hosted_vm_lost); with its proof the runner is revoked, the job
+// settled, and the step's attempt placed again on a retry job.
+func TestVMGoneMidStep(t *testing.T) {
+ r := newRig(t, nil)
+ r.checks("s1", "tk1")
+ r.passes(30 * time.Second)
+ first := r.jobs("s1")[0].AttemptID
+ if !r.enrol(first, "H1") {
+ t.Fatalf("VM did not enrol: job %s, VM %+v", r.job(first).State, r.ctl.vm(first))
+ }
+ r.passes(10 * time.Second)
+ if s := r.step("s1"); s.RunnerID != "H1" {
+ t.Fatalf("enrolled step on %q", s.RunnerID)
+ }
+ r.exec("UPDATE chat_steps SET state = ?, started_at = ? WHERE id = 's1'", wire.StepRunning, r.now)
+ r.ctl.mu.Lock()
+ r.ctl.prove(r.ctl.jobs[first])
+ r.ctl.mu.Unlock()
+ r.until(time.Minute, "job ended", func() bool { return !r.job(first).Live() })
+ j := r.job(first)
+ if j.State != chat.HostedJobFailed || j.StopReason != wire.ReasonHostedVMLost || j.SettledAt == nil {
+ t.Fatalf("job after its VM went: %s %q settled %v", j.State, j.StopReason, j.SettledAt)
+ }
+ var revoked int64
+ r.must(r.d.G.Raw("SELECT count(*) FROM runners WHERE id = 'H1' AND revoked_at IS NOT NULL").Scan(&revoked).Error)
+ if revoked != 1 {
+ t.Fatal("the VM's runner was not revoked")
+ }
+ s := r.step("s1")
+ jobs := r.jobs("s1")
+ if s.State != wire.StepQueued || s.RunnerID == "H1" || s.Attempt != 1 || len(jobs) != 2 || jobs[1].RetryOf != first {
+ t.Fatalf("step after the VM went: %+v, jobs %+v", s, jobs)
+ }
+ var voided int64
+ r.must(r.d.G.Raw("SELECT count(*) FROM runner_commands WHERE runner_id = 'H1' AND kind = ? AND acked_at IS NULL", wire.FrameDispatch).Scan(&voided).Error)
+ if voided != 0 {
+ t.Fatalf("the dead VM's dispatch is still served")
+ }
+}
+
+// TestStopUntilProofThenSettle: a job whose step ended is stopped until
+// the controller proves it; a pending stop or a lost reply ends nothing
+// and keeps the hold; the proof ends, settles and revokes.
+func TestStopUntilProofThenSettle(t *testing.T) {
+ r := newRig(t, nil)
+ r.ctl.stopDelay = 6
+ r.checks("s1", "tk1")
+ r.passes(30 * time.Second)
+ a := r.jobs("s1")[0].AttemptID
+ if !r.enrol(a, "H1") {
+ t.Fatal("VM did not enrol")
+ }
+ r.passes(10 * time.Second)
+ r.exec("UPDATE chat_steps SET state = ?, checks = ? WHERE id = 's1'", wire.StepDone, wire.ChecksPassed)
+ r.passes(30 * time.Second)
+ j := r.job(a)
+ if j.State != chat.HostedJobStopping || j.StopReason != "step_ended" || j.SettledAt != nil || j.HoldSecondsJSON == "" {
+ t.Fatalf("while the stop is pending: %s %q settled %v", j.State, j.StopReason, j.SettledAt)
+ }
+ r.ctl.lose = 1
+ r.ctl.rng = rand.New(rand.NewSource(1))
+ r.passes(time.Minute)
+ if j := r.job(a); j.State != chat.HostedJobStopping || r.ctl.vm(a).proof == nil {
+ t.Fatalf("with every reply lost: %s, proof at the controller %v", j.State, r.ctl.vm(a).proof)
+ }
+ r.ctl.lose = 0
+ r.passes(10 * time.Second)
+ j = r.job(a)
+ if j.State != chat.HostedJobEnded || j.SettledAt == nil || j.UsedSecondsJSON == "" || j.EndedAt == nil {
+ t.Fatalf("after the proof: %s settled %v used %q", j.State, j.SettledAt, j.UsedSecondsJSON)
+ }
+ var used map[string]int64
+ r.must(json.Unmarshal([]byte(j.UsedSecondsJSON), &used))
+ if want := int64(j.EndedAt.Sub(*j.AdmittedAt) / time.Second); used[start.Format(time.DateOnly)] != want {
+ t.Fatalf("settled %v, want %d s from admission to proof", used, want)
+ }
+ var revoked int64
+ r.must(r.d.G.Raw("SELECT count(*) FROM runners WHERE id = 'H1' AND revoked_at IS NOT NULL").Scan(&revoked).Error)
+ if revoked != 1 {
+ t.Fatal("runner not revoked")
+ }
+ if len(r.jobs("s1")) != 1 {
+ t.Fatal("a job was admitted for an ended step")
+ }
+}
+
+// TestThrottleBacksOff: while the provider throttles, the job's intent
+// waits at the controller and the step stays waiting_hosted; the
+// dispatcher asks again after 10 s, 20 s, 40 s and so on to 5 minutes,
+// and the job is failed once its launch window has passed.
+func TestThrottleBacksOff(t *testing.T) {
+ r := newRig(t, rand.New(rand.NewSource(1)))
+ r.ctl.throttle = 1
+ r.checks("s1", "tk1")
+ r.pass()
+ a := r.jobs("s1")[0].AttemptID
+ for i := 0; i < 59; i++ {
+ r.now = r.now.Add(Every)
+ r.online(primary)
+ r.pass()
+ if s := r.step("s1"); s.Placement != wire.PlacementHosted || s.RunnerID != "" {
+ t.Fatalf("throttled step: %+v", s)
+ }
+ }
+ if len(r.ctl.launches) != 1 {
+ t.Fatalf("%d launch requests, want one (the intent waits at the controller)", len(r.ctl.launches))
+ }
+ var gaps []time.Duration
+ last := r.ctl.launches[0].at
+ for _, g := range r.ctl.gets {
+ gaps = append(gaps, g.Sub(last))
+ last = g
+ }
+ want := []time.Duration{10 * time.Second, 20 * time.Second, 40 * time.Second, 80 * time.Second, 160 * time.Second}
+ if fmt.Sprint(gaps) != fmt.Sprint(want) {
+ t.Fatalf("asked again after %v, want %v", gaps, want)
+ }
+ if j := r.job(a); j.State != chat.HostedJobLaunching || j.LaunchingSince != nil || j.VMRef != "" {
+ t.Fatalf("throttled job: %s since %v vm %q", j.State, j.LaunchingSince, j.VMRef)
+ }
+ // The wait stops growing at 5 minutes.
+ var waits []time.Duration
+ for i := 0; i < 8; i++ {
+ r.disp.later("x", start)
+ waits = append(waits, r.disp.waits["x"].wait)
+ }
+ if got := fmt.Sprint(waits); got != "[10s 20s 40s 1m20s 2m40s 5m0s 5m0s 5m0s]" {
+ t.Fatalf("backoff %s", got)
+ }
+ r.passes(20 * time.Second)
+ if j := r.job(a); j.State != chat.HostedJobStopping || j.StopReason != wire.ReasonHostedUnavailable {
+ t.Fatalf("past the launch window: %s %q", j.State, j.StopReason)
+ }
+}
+
+// TestDispatcherNeverLaunchedEvidence: a job stopped before any launch
+// ends only on the controller's verified word that it has no record of
+// the attempt, asked at least 2 minutes past the launch-by: never before,
+// and never on a refusal, an unverified answer or a transport error.
+func TestDispatcherNeverLaunchedEvidence(t *testing.T) {
+ r := newRig(t, nil)
+ r.checks("s1", "tk1")
+ r.pass()
+ j := r.jobs("s1")[0]
+ r.exec("UPDATE chat_steps SET state = ?, checks = ? WHERE id = 's1'", wire.StepDone, wire.ChecksPassed)
+ r.pass()
+ by := j.AdmittedAt.Add(chat.HostedLaunchWindow)
+ r.until(chat.HostedLaunchWindow+chat.HostedNeverLaunchedAfter, "the evidence's earliest time", func() bool {
+ return !r.now.Add(Every).Before(by.Add(chat.HostedNeverLaunchedAfter))
+ })
+ if got := r.job(j.AttemptID); got.State != chat.HostedJobStopping || len(r.ctl.launches) != 0 {
+ t.Fatalf("before launch-by + 2 min: %s, %d launches", got.State, len(r.ctl.launches))
+ }
+ for _, e := range []error{hostedclient.ErrForbidden, hostedclient.ErrTransport, hostedclient.ErrUnverified, hostedclient.ErrNotFound} {
+ r.ctl.getErr = e
+ r.passes(Every)
+ if got := r.job(j.AttemptID); got.State != chat.HostedJobStopping || got.SettledAt != nil {
+ t.Fatalf("Get answering %v: %s, settled %v", e, got.State, got.SettledAt)
+ }
+ }
+ r.ctl.getErr = nil
+ r.passes(Every)
+ got := r.job(j.AttemptID)
+ var p chat.HostedEndProof
+ r.must(json.Unmarshal([]byte(got.StopProofJSON), &p))
+ if got.State != chat.HostedJobEnded || got.SettledAt == nil || p.NeverLaunched == nil || p.NeverLaunched.ControllerState != chat.HostedControllerAbsent ||
+ p.NeverLaunched.ObservedAt.Before(by.Add(chat.HostedNeverLaunchedAfter)) || !p.NeverLaunched.LaunchBy.Equal(by) {
+ t.Fatalf("on a signed absent: %s settled %v, proof %+v", got.State, got.SettledAt, p.NeverLaunched)
+ }
+}
+
+// TestDispatcherOffWithoutFlag: without EQUIPO_HOSTED_RUNNERS=1 there is
+// no dispatcher (and no client); with it, a missing or malformed
+// connection is refused too.
+func TestDispatcherOffWithoutFlag(t *testing.T) {
+ r := newRig(t, nil)
+ cfg := Config{Controller: "https://controller.example:8443", TLSPin: strings.Repeat("ab", 32),
+ ControllerKey: base64.StdEncoding.EncodeToString(make([]byte, ed25519.PublicKeySize)), KeyID: "inst-1",
+ Key: base64.StdEncoding.EncodeToString(make([]byte, ed25519.SeedSize)), Image: string(image), Account: "acct-1"}
+ for _, v := range []string{"", "0", "true"} {
+ t.Setenv(hostedclient.FlagEnv, v)
+ if d, err := New(r.s, cfg, nil); !errors.Is(err, hostedclient.ErrRunnersOff) || d != nil {
+ t.Fatalf("%s=%q: %v %v, want no dispatcher", hostedclient.FlagEnv, v, d, err)
+ }
+ }
+ t.Setenv(hostedclient.FlagEnv, "1")
+ for name, edit := range map[string]func(*Config){
+ "no controller": func(c *Config) { c.Controller = "" },
+ "bad pin": func(c *Config) { c.TLSPin = "ab" },
+ "bad image": func(c *Config) { c.Image = "latest" },
+ "no account": func(c *Config) { c.Account = "" },
+ "bad key": func(c *Config) { c.Key = "x" },
+ "http origin": func(c *Config) { c.Controller = "http://controller.example" },
+ } {
+ c := cfg
+ edit(&c)
+ if d, err := New(r.s, c, nil); !errors.Is(err, ErrConfig) || d != nil {
+ t.Fatalf("%s: %v %v, want ErrConfig", name, d, err)
+ }
+ }
+ d, err := New(r.s, cfg, nil)
+ if err != nil || d == nil || d.Image != image || d.Account != "acct-1" || d.Admitter() == nil {
+ t.Fatalf("configured: %+v %v", d, err)
+ }
+ if got := ReadConfig(func(k string) string { return "v:" + k }); got.Controller != "v:EQUIPO_HOSTED_CONTROLLER" || got.Key != "v:EQUIPO_HOSTED_KEY" {
+ t.Fatalf("ReadConfig: %+v", got)
+ }
+}
+
+// TestReachabilityProbeLogged: at start the dispatcher asks the real
+// client for a made-up attempt's admission: a signed 404 absent logs
+// hosted_controller_reachable; a signed refusal, an unsigned answer or
+// one signed by another key logs hosted_controller_unreachable with the
+// reason.
+func TestReachabilityProbeLogged(t *testing.T) {
+ ctlKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize))
+ other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{5}, ed25519.SeedSize))
+ instKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
+ refusal := func(code string) []byte {
+ b, _ := json.Marshal(hostedwire.ErrorResponse{Code: code, Message: "m"})
+ return b
+ }
+ for _, c := range []struct {
+ name string
+ status int
+ body []byte
+ key ed25519.PrivateKey
+ reachable bool
+ reason string
+ }{
+ {"signed absent", http.StatusNotFound, refusal("absent"), ctlKey, true, ""},
+ {"signed forbidden", http.StatusForbidden, refusal("forbidden"), ctlKey, false, "this key may not do that"},
+ {"unsigned absent", http.StatusNotFound, refusal("absent"), nil, false, "could not be verified"},
+ {"absent signed by another key", http.StatusNotFound, refusal("absent"), other, false, "could not be verified"},
+ {"a record for a made-up attempt", http.StatusOK, []byte(`{"attempt_id":"x"}`), ctlKey, false, "does not fit"},
+ } {
+ var asked []string
+ srv := serveTLS(t, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ asked = append(asked, req.URL.Path)
+ if c.key != nil {
+ hostedwire.SignResponse(w.Header(), c.status, req.Header.Get(hostedwire.HeaderNonce), c.body, c.key)
+ }
+ w.WriteHeader(c.status)
+ _, _ = w.Write(c.body)
+ }))
+ 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)
+ }
+ var logs bytes.Buffer
+ d := &Dispatcher{Client: cl, Clock: time.Now, Log: slog.New(slog.NewTextHandler(&logs, nil))}
+ got := d.Probe(context.Background())
+ if got != c.reachable || len(asked) != 1 || !strings.HasPrefix(asked[0], "/v1/jobs/") || !strings.HasSuffix(asked[0], "/admission") ||
+ len(strings.TrimSuffix(strings.TrimPrefix(asked[0], "/v1/jobs/"), "/admission")) != 64 {
+ t.Fatalf("%s: reachable %t, asked %v", c.name, got, asked)
+ }
+ want := "msg=hosted_controller_unreachable"
+ if c.reachable {
+ want = "msg=hosted_controller_reachable"
+ }
+ if !strings.Contains(logs.String(), want) || !strings.Contains(logs.String(), c.reason) || strings.Count(logs.String(), "\n") != 1 {
+ t.Fatalf("%s: logged %q, want %s with %q", c.name, logs.String(), want, c.reason)
+ }
+ }
+}
+
+// serveTLS serves h over TLS on 127.0.0.1 only.
+func serveTLS(t *testing.T, h http.Handler) *httptest.Server {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewUnstartedServer(h)
+ srv.Listener = ln
+ srv.StartTLS()
+ t.Cleanup(srv.Close)
+ return srv
+}
diff --git a/internal/equipo/hostedrun/sim_test.go b/internal/equipo/hostedrun/sim_test.go
new file mode 100644
index 00000000..5cf65bcf
--- /dev/null
+++ b/internal/equipo/hostedrun/sim_test.go
@@ -0,0 +1,229 @@
+package hostedrun
+
+import (
+ "encoding/json"
+ "fmt"
+ "math/rand"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// simSeeds is how many seeded runs TestDispatcherSimulation makes.
+const simSeeds = 200
+
+// simEvery is the simulation's pass period: twice the dispatcher's, so
+// 200 seeds of a real store stay within the package's time budget. Every
+// rule the dispatcher keeps is in clock time, not in passes.
+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
+// 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;
+// - 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.
+//
+// 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) {
+ t.Parallel()
+ simulate(t, seed)
+ })
+ }
+}
+
+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
+ outage := 0
+ c.stopDelay = 1 + rng.Intn(4)
+ steps := []string{"s1", "s2", "s3"}
+ for i, s := range steps {
+ r.checks(s, fmt.Sprintf("tk%d", i+1))
+ }
+ limits := chat.DefaultHostedLimits
+ runners := 0
+ for tick := 0; ; tick++ {
+ if tick > 300 {
+ t.Fatalf("seed %d: not settled after 100 minutes: %s", seed, r.summary(steps))
+ }
+ r.now = r.now.Add(simEvery)
+ r.online(primary)
+ if rng.Float64() < 0.06 {
+ // The instance restarts; one that died mid-launch left its
+ // call marked in flight.
+ if rng.Float64() < 0.5 {
+ r.exec("UPDATE hosted_jobs SET launching_since = ? WHERE state = ? AND launch_id = ''", r.now, chat.HostedJobLaunching)
+ }
+ r.restart()
+ }
+ if rng.Float64() < 0.04 {
+ c.setCert(!c.certValid)
+ }
+ // The controller is unreachable for 5 to 15 minutes now and then.
+ if outage > 0 {
+ outage--
+ } else if rng.Float64() < 0.02 {
+ outage = 15 + rng.Intn(30)
+ }
+ c.mu.Lock()
+ c.down = outage > 0
+ c.mu.Unlock()
+ r.pass()
+ // VMs enrol (Task 22's part), and steps on a VM report.
+ for _, j := range r.liveJobs() {
+ switch j.State {
+ case chat.HostedJobEnrolling:
+ if v := c.vm(j.AttemptID); v != nil && !v.noEnrol && rng.Float64() < 0.7 {
+ runners++
+ r.enrol(j.AttemptID, fmt.Sprintf("H%d", runners))
+ }
+ case chat.HostedJobEnrolled:
+ s := r.step(j.StepID)
+ v := c.vm(j.AttemptID)
+ 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.invariants(seed, limits)
+ done := len(r.liveJobs()) == 0
+ for _, s := range steps {
+ done = done && wire.StepTerminal(r.step(s).State)
+ }
+ if done {
+ break
+ }
+ }
+ var all []chat.HostedJob
+ r.must(r.d.G.Find(&all).Error)
+ for _, j := range all {
+ if j.SettledAt == nil {
+ t.Fatalf("seed %d: %s ended %s unsettled", seed, j.AttemptID, j.State)
+ }
+ if v := c.vm(j.AttemptID); v != nil && v.alive() {
+ t.Fatalf("seed %d: %s's VM %s is still alive", seed, j.AttemptID, v.ref)
+ }
+ }
+}
+
+func (r *rig) liveJobs() []chat.HostedJob {
+ r.t.Helper()
+ var rows []chat.HostedJob
+ r.must(r.d.G.Where("state NOT IN ?", []string{chat.HostedJobEnded, chat.HostedJobFailed}).Order("admitted_at, rowid").Find(&rows).Error)
+ return rows
+}
+
+func (r *rig) summary(steps []string) string {
+ out := ""
+ for _, s := range steps {
+ out += fmt.Sprintf("%s=%+v; ", s, r.step(s))
+ }
+ for _, j := range r.liveJobs() {
+ out += fmt.Sprintf("%s %s %s; ", j.AttemptID, j.StepID, j.State)
+ }
+ return out
+}
+
+// invariants checks the simulation's rules after a pass.
+func (r *rig) invariants(seed int64, limits chat.HostedLimits) {
+ r.t.Helper()
+ var all []chat.HostedJob
+ r.must(r.d.G.Find(&all).Error)
+ stepOf := map[string]string{}
+ running := 0
+ days, months := map[string]int64{}, map[string]int64{}
+ for _, j := range all {
+ stepOf[j.AttemptID] = j.StepID
+ if j.Live() {
+ running++
+ }
+ c, err := j.Hold()
+ if j.SettledAt != nil {
+ c, err = j.Used()
+ }
+ r.must(err)
+ for k, v := range c.Seconds {
+ days[k] += v
+ }
+ for k, v := range c.Micros {
+ months[k] += v
+ }
+ if j.SettledAt == nil {
+ continue
+ }
+ var p chat.HostedEndProof
+ if err := json.Unmarshal([]byte(j.StopProofJSON), &p); err != nil || j.Live() {
+ r.t.Fatalf("seed %d: %s settled %s with proof %q", seed, j.AttemptID, j.State, j.StopProofJSON)
+ }
+ v := r.ctl.vm(j.AttemptID)
+ switch {
+ case p.Stop != nil:
+ if v == nil || v.proof == nil || v.proof.VMRef != p.Stop.VMRef {
+ r.fail(seed, "%s settled on a stop proof the controller never gave: %+v", j.AttemptID, p.Stop)
+ }
+ case p.NeverLaunched != nil:
+ if v != nil && v.everVM {
+ r.fail(seed, "%s settled as never launched, but its VM %s ran", j.AttemptID, v.ref)
+ }
+ default:
+ r.fail(seed, "%s settled with no proof", j.AttemptID)
+ }
+ }
+ if running > limits.Running {
+ r.fail(seed, "%d running jobs, limit %d", running, limits.Running)
+ }
+ for k, v := range days {
+ if v > limits.DailySeconds {
+ r.fail(seed, "%d s held on %s, limit %d", v, k, limits.DailySeconds)
+ }
+ }
+ for k, v := range months {
+ if v > limits.MonthlyMicros {
+ r.fail(seed, "%d micros held in %s, limit %d", v, k, limits.MonthlyMicros)
+ }
+ }
+ alive := map[string]int{}
+ r.ctl.mu.Lock()
+ for a, v := range r.ctl.jobs {
+ if v.alive() {
+ alive[stepOf[a]]++
+ }
+ }
+ r.ctl.mu.Unlock()
+ for s, n := range alive {
+ if n > 1 {
+ r.fail(seed, "step %s has %d live VMs", s, n)
+ }
+ }
+}
+
+// fail fails the run, naming its seed.
+func (r *rig) fail(seed int64, format string, args ...any) {
+ r.t.Helper()
+ r.t.Fatalf("seed %d: "+format, append([]any{seed}, args...)...)
+}
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go
index 53cc58f7..b9240ef2 100644
--- a/internal/hostedclient/client.go
+++ b/internal/hostedclient/client.go
@@ -3,9 +3,9 @@
// key and a fresh nonce, and every response must carry the controller's
// signature bound to that nonce before its status or body is read.
//
-// New refuses to build a client unless EQUIPO_HOSTED_RUNNERS=1. In slice 1a
-// nothing in the instance calls this package; TestInstanceDoesNotCallHostedClient
-// holds that until slice 2.
+// New refuses to build a client unless EQUIPO_HOSTED_RUNNERS=1. In the
+// instance only the hosted dispatcher (internal/equipo/hostedrun) calls this
+// package; TestOnlyHostedrunImportsHostedClient holds that.
package hostedclient
import (
@@ -80,6 +80,11 @@ var (
ErrInternal = errors.New("hostedclient: the controller failed")
)
+// ErrAbsent is Get or Admission of an attempt the controller has no record
+// of at all, as a signed 404 absent. Another key's attempt is ErrForbidden;
+// an unsigned answer is ErrUnverified, never this.
+var ErrAbsent = errors.New("hostedclient: the controller has no record of that attempt")
+
// refusals maps a signed refusal's code to the status the controller sends
// with it and its kind. A code with any other status is ErrUnexpected.
var refusals = map[string]struct {
@@ -99,6 +104,7 @@ var refusals = map[string]struct {
"forbidden": {http.StatusForbidden, ErrForbidden},
"proxy_refused": {http.StatusForbidden, ErrForbidden}, // proxy routes only; an instance key never gets it
"not_found": {http.StatusNotFound, ErrNotFound},
+ "absent": {http.StatusNotFound, ErrAbsent},
"too_large": {http.StatusRequestEntityTooLarge, ErrTooLarge},
"stop_pending": {http.StatusAccepted, ErrStopPending},
"generation_cancelled": {http.StatusConflict, ErrGenerationCancelled},
diff --git a/internal/hostedclient/client_test.go b/internal/hostedclient/client_test.go
index c9c15a0b..66d84360 100644
--- a/internal/hostedclient/client_test.go
+++ b/internal/hostedclient/client_test.go
@@ -239,8 +239,12 @@ func TestClientAgainstController(t *testing.T) {
}
// Refusals come back as the controller's kinds.
- if _, err := cl.Get(ctx, "nope"); !errors.Is(err, ErrForbidden) {
- t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err)
+ // An attempt with no record at all is a signed 404 absent, its own
+ // kind: never-launched evidence is built from it alone (Task 21).
+ var absent *APIError
+ if _, err := cl.Get(ctx, "nope"); !errors.Is(err, ErrAbsent) || errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) ||
+ !errors.As(err, &absent) || absent.Status != http.StatusNotFound || absent.Code != "absent" {
+ t.Fatalf("Get of an unknown attempt = %v, want a signed 404 ErrAbsent", err)
}
changed := launchReq("a1")
changed.TaskID = "task-2"
@@ -276,8 +280,8 @@ func TestClientAdmissionVerified(t *testing.T) {
a.CertDigest != want || !a.CertValid {
t.Fatalf("Admission = (%+v, %v), want a1's VM under %s, valid", a, err, want)
}
- if _, err := cl.Admission(ctx, "nope"); !errors.Is(err, ErrForbidden) {
- t.Fatalf("Admission of an unknown attempt = %v, want ErrForbidden", err)
+ if _, err := cl.Admission(ctx, "nope"); !errors.Is(err, ErrAbsent) || errors.Is(err, ErrForbidden) {
+ t.Fatalf("Admission of an unknown attempt = %v, want ErrAbsent", err)
}
// A genuine admission answer, captured and replayed to a later request,
@@ -524,6 +528,8 @@ func TestSignedAnswersMapToKinds(t *testing.T) {
{"store lost", http.StatusServiceUnavailable, refusal("store_lost"), ErrStoreLost},
{"throttled", http.StatusTooManyRequests, refusal("throttled"), ErrThrottled},
{"past deadline", http.StatusGone, refusal("past_deadline"), ErrPastDeadline},
+ {"absent", http.StatusNotFound, refusal("absent"), ErrAbsent},
+ {"absent with another status", http.StatusForbidden, refusal("absent"), ErrUnexpected},
{"code and status disagree", http.StatusConflict, refusal("disabled"), ErrUnexpected},
{"unknown code", http.StatusTeapot, refusal("teapot"), ErrUnexpected},
{"refusal body not strict", http.StatusConflict, []byte(`{"code":"conflict","message":"x","extra":1}`), ErrUnexpected},
@@ -685,36 +691,78 @@ func TestEmptyAttemptRefused(t *testing.T) {
}
}
-// TestInstanceDoesNotCallHostedClient holds slice 1a's promise that the
-// instance never calls the hosted controller. Slice 2 deletes it.
-func TestInstanceDoesNotCallHostedClient(t *testing.T) {
+// TestOnlyHostedrunImportsHostedClient: in the instance, only the hosted
+// dispatcher's package (internal/equipo/hostedrun) talks to the controller;
+// the operator's certification tool is the one other importer. Every
+// package of the module is listed with its imports (tests aside), so a new
+// importer anywhere fails here.
+func TestOnlyHostedrunImportsHostedClient(t *testing.T) {
gobin, err := exec.LookPath("go")
if err != nil {
t.Fatalf("go not on PATH: %v", err)
}
- const instance = "amadan.net/oficina/equipo/cmd/equipo"
- ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ const (
+ module = "amadan.net/oficina/equipo"
+ self = module + "/internal/hostedclient"
+ hostedrun = module + "/internal/equipo/hostedrun"
+ instance = module + "/cmd/equipo"
+ )
+ allowed := map[string]bool{hostedrun: true, module + "/cmd/equipo-hosted-certify": true}
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
- cmd := exec.CommandContext(ctx, gobin, "list", "-deps", instance)
- // The child reads cmd/equipo's source, which go test does not see:
- // declare it, so adding the import reruns this test instead of
+ cmd := exec.CommandContext(ctx, gobin, "list", "-f", "{{.ImportPath}} {{join .Imports \" \"}}", module+"/...")
+ // The child reads every package's source, which go test does not
+ // see: declare it, so a new import reruns this test instead of
// replaying a cached pass.
testci.GoCommand(t, cmd)
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.Output()
if err != nil {
- t.Fatalf("go list -deps %s: %v\n%s", instance, err, stderr.Bytes())
+ t.Fatalf("go list %s/...: %v\n%s", module, err, stderr.Bytes())
}
- deps := strings.Fields(string(out))
- var self bool
- for _, d := range deps {
- if d == "amadan.net/oficina/equipo/internal/hostedclient" {
- t.Fatalf("%s depends on internal/hostedclient; slice 1a keeps the instance off the hosted controller", instance)
+ importers := map[string]bool{}
+ listed := 0
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ f := strings.Fields(line)
+ if len(f) == 0 {
+ continue
+ }
+ listed++
+ for _, imp := range f[1:] {
+ if imp == self {
+ importers[f[0]] = true
+ }
+ }
+ }
+ if listed < 50 {
+ t.Fatalf("go list listed %d packages; the module has more", listed)
+ }
+ for p := range importers {
+ if !allowed[p] {
+ t.Errorf("%s imports internal/hostedclient; only internal/equipo/hostedrun may (and the operator's certify tool)", p)
+ }
+ }
+ if !importers[hostedrun] {
+ t.Fatalf("internal/equipo/hostedrun does not import internal/hostedclient; importers: %v", importers)
+ }
+ // And the instance reaches the controller through hostedrun alone.
+ deps := exec.CommandContext(ctx, gobin, "list", "-deps", "-f", "{{.ImportPath}} {{join .Imports \" \"}}", instance)
+ testci.GoCommand(t, deps)
+ out, err = deps.Output()
+ if err != nil {
+ t.Fatalf("go list -deps %s: %v", instance, err)
+ }
+ via := []string{}
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ f := strings.Fields(line)
+ for _, imp := range f[1:] {
+ if imp == self {
+ via = append(via, f[0])
+ }
}
- self = self || d == instance
}
- if !self {
- t.Fatalf("go list -deps %s did not list the package itself; got %d lines", instance, len(deps))
+ if len(via) != 1 || via[0] != hostedrun {
+ t.Fatalf("%s reaches internal/hostedclient through %v, want %s alone", instance, via, hostedrun)
}
}
diff --git a/internal/hostedctl/admission_test.go b/internal/hostedctl/admission_test.go
index 2dcb8b0f..80507311 100644
--- a/internal/hostedctl/admission_test.go
+++ b/internal/hostedctl/admission_test.go
@@ -228,8 +228,8 @@ func TestAdmissionKeyRemoved(t *testing.T) {
}
// TestAdmissionCreatorOnly: only the key that launched an attempt reads its
-// admission; another key, no key and an unknown attempt get the same
-// refusal, audited.
+// admission; another key and no key get the same refusal, and an attempt
+// with no record at all is ErrAbsent (Task 21 ruling), each audited.
func TestAdmissionCreatorOnly(t *testing.T) {
t.Parallel()
e := newLaunchEnv(t)
@@ -243,7 +243,9 @@ func TestAdmissionCreatorOnly(t *testing.T) {
}{
{"inst-2", "att-1", ErrForbidden},
{"", "att-1", ErrForbidden},
- {"inst-1", "att-9", ErrForbidden},
+ {"inst-1", "att-9", ErrAbsent},
+ {"inst-2", "att-9", ErrAbsent},
+ {"", "att-9", ErrForbidden},
{"inst-1", "", isolatedjob.ErrInvalid},
{"inst-1", "att-\n", isolatedjob.ErrInvalid},
} {
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go
index 69284083..2318324a 100644
--- a/internal/hostedctl/http.go
+++ b/internal/hostedctl/http.go
@@ -96,6 +96,7 @@ var apiErrors = []apiError{
{ctlproxy.ErrRefused, http.StatusForbidden, "proxy_refused", "The proxy request was refused."},
{ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."},
{errNoRoute, http.StatusNotFound, "no_route", "No such route."},
+ {ErrAbsent, http.StatusNotFound, "absent", "There is no record of that attempt."},
{isolatedjob.ErrNotFound, http.StatusNotFound, "not_found", "Not found."},
{errMethod, http.StatusMethodNotAllowed, "method", "This route does not take that method."},
{ErrStopPending, http.StatusAccepted, "stop_pending", "Stop accepted. The VM is not proven stopped yet; ask again."},
diff --git a/internal/hostedctl/http_test.go b/internal/hostedctl/http_test.go
index 6275a473..93750fda 100644
--- a/internal/hostedctl/http_test.go
+++ b/internal/hostedctl/http_test.go
@@ -286,16 +286,28 @@ func TestInstanceKeySeesOnlyItsJobs(t *testing.T) {
t.Fatalf("creator GET = %d %s", r.status, r.body)
}
- // Another instance key gets the same 403 for a1 and for an attempt
- // that does not exist, so it learns nothing of a1.
+ // Another instance key gets a 403 for a1 and reads none of it. An
+ // attempt with no record at all is a signed 404 absent on the read
+ // routes (get and admission), for any instance key: attempt IDs are
+ // random, so absence says nothing of anyone's jobs (Task 21 ruling).
+ // Every other route keeps the 403 for it.
for _, attempt := range []string{"a1", "nope"} {
- for _, rt := range jobRoutes(attempt) {
+ for i, rt := range jobRoutes(attempt) {
+ status, code := http.StatusForbidden, "forbidden"
+ if attempt == "nope" && i < 2 {
+ status, code = http.StatusNotFound, "absent"
+ }
r := e.call(rt.method, rt.path, rt.body, idInstB, keyInstB)
- if r.status != http.StatusForbidden || string(r.body) != fixedBody(t, "forbidden") {
- t.Fatalf("instance B %s %s = %d %s, want 403", rt.method, rt.path, r.status, r.body)
+ if r.status != status || string(r.body) != fixedBody(t, code) {
+ t.Fatalf("instance B %s %s = %d %s, want %d %s", rt.method, rt.path, r.status, r.body, status, code)
}
}
}
+ for _, path := range []string{"/v1/jobs/nope", "/v1/jobs/nope/admission"} {
+ if r := e.call("GET", path, nil, idInstA, keyInstA); r.status != http.StatusNotFound || string(r.body) != fixedBody(t, "absent") {
+ t.Fatalf("instance A GET %s = %d %s, want a signed 404 absent", path, r.status, r.body)
+ }
+ }
if j, _ := e.job("a1"); j.state != JobStarting || j.stopRequested.Valid {
t.Fatalf("a1 after instance B's calls = %s (stop asked %v), want starting with no stop", j.state, j.stopRequested.Valid)
}
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go
index fa04fce3..109e30ca 100644
--- a/internal/hostedctl/launch.go
+++ b/internal/hostedctl/launch.go
@@ -27,6 +27,10 @@ var (
ErrDisabled = errors.New("hostedctl: hosted launches are disabled")
// ErrForbidden: the verified key's role may not make this call.
ErrForbidden = errors.New("hostedctl: this key may not do that")
+ // ErrAbsent: Get or Admission for an attempt with no record at all.
+ // The dispatcher builds never-launched evidence from it (signed 404
+ // absent); another key's attempt is ErrForbidden instead.
+ ErrAbsent = errors.New("hostedctl: there is no record of that attempt")
// ErrLaunchExpired: the controller's wall clock is past the request's
// launch-by time.
ErrLaunchExpired = errors.New("hostedctl: the launch-by time has passed")
diff --git a/internal/hostedctl/stop.go b/internal/hostedctl/stop.go
index 289c4ba7..53b53941 100644
--- a/internal/hostedctl/stop.go
+++ b/internal/hostedctl/stop.go
@@ -92,8 +92,9 @@ func notCreator(attempt string) error {
}
// Get returns attempt's job as the store holds it. Only the instance key
-// that launched it may read it; anyone else, and any unknown attempt, gets
-// ErrForbidden and an audit row. Get makes no provider call.
+// that launched it may read it; another key gets ErrForbidden and an
+// audit row, and an attempt with no record at all gets ErrAbsent and an
+// audit row. Get makes no provider call.
func (c *Controller) Get(ctx context.Context, by hostedwire.KeyID, attemptID string) (JobView, error) {
var view JobView
err := c.readOwn(ctx, by, attemptID, actionGetRefused, func(j jobRow, now T) error { view = j.view(now); return nil })
@@ -106,8 +107,10 @@ func (c *Controller) Get(ctx context.Context, by hostedwire.KeyID, attemptID str
// readOwn calls read with attemptID's row and the controller time, in one
// transaction, if by is the key that launched it, and returns read's error.
// Otherwise it audits a row with action refused and returns
-// isolatedjob.ErrInvalid for a malformed attempt ID, or the same
-// ErrForbidden for another key's attempt and for an unknown one.
+// isolatedjob.ErrInvalid for a malformed attempt ID, ErrAbsent for an
+// attempt with no record at all (attempt IDs are random, so its absence
+// tells nobody of anyone's jobs), or ErrForbidden for another key's
+// attempt and for a call with no key.
func (c *Controller) readOwn(ctx context.Context, by hostedwire.KeyID, attemptID, refused string, read func(jobRow, T) error) error {
var refusal error
err := c.store.Tx(ctx, func(tx *sql.Tx) error {
@@ -126,6 +129,9 @@ func (c *Controller) readOwn(ctx context.Context, by hostedwire.KeyID, attemptID
}
if by == "" || !found || j.actor != string(by) {
refusal = notCreator(attemptID)
+ if by != "" && !found {
+ refusal = fmt.Errorf("%w: %s", ErrAbsent, attemptID)
+ }
if found {
a.Account, a.Task = j.account, j.task
}
diff --git a/internal/hostedctl/stop_test.go b/internal/hostedctl/stop_test.go
index e3814ee4..aab5ef06 100644
--- a/internal/hostedctl/stop_test.go
+++ b/internal/hostedctl/stop_test.go
@@ -637,8 +637,14 @@ func TestStopRoles(t *testing.T) {
if a := e.lastAudit(); a.Actor != "inst-2" || a.Action != actionGetRefused {
t.Fatalf("audit after Get by another instance = %+v, want get_refused", a)
}
- if _, err := e.c.Get(e.ctx, "inst-1", "att-9"); !errors.Is(err, ErrForbidden) {
- t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err)
+ if _, err := e.c.Get(e.ctx, "inst-1", "att-9"); !errors.Is(err, ErrAbsent) || errors.Is(err, ErrForbidden) {
+ t.Fatalf("Get of an unknown attempt = %v, want ErrAbsent", err)
+ }
+ if a := e.lastAudit(); a.Actor != "inst-1" || a.Action != actionGetRefused || a.Attempt != "att-9" {
+ t.Fatalf("audit after Get of an unknown attempt = %+v, want get_refused", a)
+ }
+ if _, err := e.c.Get(e.ctx, "", "att-9"); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("Get of an unknown attempt with no key = %v, want ErrForbidden", err)
}
if v, err := e.c.Get(e.ctx, "inst-1", "att-1"); err != nil || v.VMRef != ref || v.AttemptID != "att-1" {
t.Fatalf("Get by the creator = (%+v, %v), want the job", v, err)
diff --git a/internal/wire/hosted.go b/internal/wire/hosted.go
index 6a260c12..39eb9774 100644
--- a/internal/wire/hosted.go
+++ b/internal/wire/hosted.go
@@ -45,6 +45,16 @@ const (
ReasonTokenRenewalFailed = "token_renewal_failed"
)
+// A hosted checks step that ends not run (cannot_run) once its one retry
+// is spent: its VM did not enrol in time after it was running; its VM
+// stopped or went away before the checks finished; or no VM could be
+// started for it (its launch window passed, or the controller refused).
+const (
+ ReasonHostedEnrolTimeout = "hosted_enrol_timeout"
+ ReasonHostedVMLost = "hosted_vm_lost"
+ ReasonHostedUnavailable = "hosted_unavailable"
+)
+
// DepsTransferMax is a deps transfer's own byte limit. Every other kind
// keeps MaxTransferBytes.
const DepsTransferMax = 256 << 20
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go
index 81d39e81..38e327f9 100644
--- a/internal/wire/tasks.go
+++ b/internal/wire/tasks.go
@@ -1133,6 +1133,11 @@ var StepReasons = map[string]bool{
ReasonDepsMissing: true,
ReasonDepsTooLarge: true,
ReasonTokenRenewalFailed: true,
+ // A hosted checks VM never enrolled, went away mid-step, or could not
+ // be started, its one retry spent.
+ ReasonHostedEnrolTimeout: true,
+ ReasonHostedVMLost: true,
+ ReasonHostedUnavailable: true,
// Merge: the branch conflicts with the default branch; the branch is
// no longer at the judged SHA; the hub's own CI on the commit is not
// green (still running, or failed); the agent may not merge here; or