equipo: Task 22 review 1, fresh admission, controller deadline, window
An enrolment is admitted only by an admission record that was kept, so a stale answer never outranks a newer refusal. The controller's deadline from the launch view (counted from the request's start, earliest kept, hosted_jobs.deadline in 0128) caps enrolment and renewal credentials. The enrolment records the VM's first running sighting when none was and applies the two-minute window from the earliest. A test isolates the code's single use.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+248
−40
.rastrillo/budgets.txt+2 −2docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+25 −0internal/equipo/chat/hosted_enrol.go+33 −10internal/equipo/chat/hosted_jobs.go+5 −0internal/equipo/chat/hosted_place_test.go+2 −2internal/equipo/chat/hosted_run.go+38 −11internal/equipo/hosted_enrol.go+15 −7internal/equipo/hosted_enrol_test.go+111 −5internal/equipo/hostedrun/dispatcher.go+6 −3internal/equipo/migrations/0128_hosted_job_deadline.sql+5 −0internal/equipo/migrations/schema.sql+6 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 9f406c4d..081ff40b 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re |
| 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 60s Hosted slice 2 Task 21: TestDispatcherSimulation runs 200 seeds of the real chat store (SQLite) and dispatcher against a fake controller, with unlinked VMs that run to their 90-minute lifetime since review round 1, and one test drives the real controller over TLS for 90 simulated minutes; about 35 s of CPU in parallel subtests; measured 14 s on a 16 CPU docs-t1 under load 2.4; 60s covers a loaded 4 CPU runner. |
| -size internal/equipo 25248 8563 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. Task 22: hosted_enrol.go, a hosted VM's enrolment (POST /api/hosted/enrol) and its runner's challenge and renewal under /api/runner/v2 (the store methods over the runner and credential rows, the handlers, the routes only with EQUIPO_HOSTED_RUNNERS=1 and an admission reader), and mintRunnerCredential's lifetime and cap; 25248. Its tests (hosted_enrol_test.go: the routes through the whole application, and the runner's hosted.Start end to end through the test proxy) drive the unexported store, router and admission reader, so they live beside them and take the directory past the 8000-line test default; measured 8563 test lines. |
| +size internal/equipo 25256 8669 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. Task 22: hosted_enrol.go, a hosted VM's enrolment (POST /api/hosted/enrol) and its runner's challenge and renewal under /api/runner/v2 (the store methods over the runner and credential rows, the handlers, the routes only with EQUIPO_HOSTED_RUNNERS=1 and an admission reader), and mintRunnerCredential's lifetime and cap; 25248. Its tests (hosted_enrol_test.go: the routes through the whole application, and the runner's hosted.Start end to end through the test proxy) drive the unexported store, router and admission reader, so they live beside them and take the directory past the 8000-line test default; measured 8563 test lines. Task 22 review 1: the controller's deadline in the credential cap, and tests for a stale admission after a newer refusal, the first sighting and its window, code single use alone and the controller's deadline; 25256/8669. |
| 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); |
| @@ -60,7 +60,7 @@ perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| perf GET /api/v1/assistant/abilities skip Assistant person API: bearer-only JSON for Base's Settings line, not a browser screen. |
| -size internal/equipo/chat 46848 20971 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. |
| +size internal/equipo/chat 46903 20971 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index c4b5bed9..744d8695 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1715,3 +1715,28 @@ Mutations (each through the Edit tool, then restored and the brief's command run |
| - **319** (extra) the deadline cap ignored in `mintRunnerCredential`. `... -run TestHostedCredentialCappedAtDeadline`: exit 1, `hosted_enrol_test.go:560: credential expires 2026-12-01 11:00:00 +0000 UTC, want 2026-12-01 10:30:00 +0000 UTC`. Restored. |
| - **320** (extra) `/api/hosted/enrol` dropped from the public allowlist. `... -run TestEnrolRouteIsPublicNotCSRF`: exit 1, `hosted_enrol_test.go:424: with a browser cookie: 403 cross-origin form submission refused`. Restored. |
| - **321** (extra) the roster check in transaction 2 skipped. `... -run TestEnrolRemovedPersonRefused`: exit 1, `hosted_enrol_test.go:408: a removed person's job: 200 {"credential":...}`. Restored. |
| + |
| +### Task 22 review round 1 (t22-r1.md: items 1 to 4; concern 5 deferred) |
| + |
| +1. **A stale admission no longer authorises.** `hostedAdmitted` now returns `(valid, accepted, err)`; `accepted` is false when the record is older than the one held and was not written. `HostedEnrolAdmit` admits only an accepted record. Test (in `TestEnrolNeedsCertifiedAdmission`): while the enrolment's admission call is in flight, a refusal is recorded at `hostedNow + 1s` (`HostedAdmitted`); the older positive answer then arrives. Refused, no runner, and the newer refusal stays (`cert_valid` false, checked at `+1s`). |
| +2. **The controller's deadline caps credentials.** New column `hosted_jobs.deadline` (migration `0128_hosted_job_deadline.sql`, one `ALTER TABLE ... ADD COLUMN`; `schema.sql` appended). `HostedLaunched(ctx, attempt, v, asked)` now takes the time the request that returned `v` was made. The dispatcher passes the time read before its `Launch` or `Get` call (`launch`, `job`, `neverLaunched`). The store keeps `asked + v.DeadlineInMS` (`hostedDeadlineSeen`, applied on both the enrolling and the learn-VM branches), written only when no earlier deadline is held, so it is never extended. `hostedDeadline` in the instance is `min(launch_by + lifetime, deadline)`, and a job with no recorded deadline is issued nothing. Test (in `TestHostedCredentialCappedAtDeadline`): a launching job gets a launch view with 40 minutes left, from a request started a minute before (`hostedNow - 1m`). The deadline is kept as `hostedNow + 39m`, before launch-by plus lifetime (`+95m`), and the enrolment and a renewal 20 minutes later both expire at `+39m`. |
| +3. **The 2-minute window always applies (coordinator ruling).** In transaction 2, a recorded, valid, running admission is a sighting. With `running_seen_at` unset, it is recorded at the admission's asked time, in the same transaction, revision bumped and audited `<attempt>:running_seen`. Enrolment then requires `now` before the earliest sighting plus `HostedEnrolTimeout`. On a refusal the sighting and the record are committed. Tests (in `TestEnrolRefusesReplayAndWrongVM`): |
| + - With no prior sighting, a prompt enrolment succeeds and records the sighting at the admission's time. |
| + - An enrolment whose admission call takes the full 2 minutes (the fake clock moves while it is in flight) is refused, with no runner, and its sighting is recorded. |
| +4. **Single use, isolated.** Test (in `TestEnrolRefusesReplayAndWrongVM`): an enrolment whose admission read fails (503) uses the code, and the job stays enrolling. The same request again, with the controller answering, is refused, the admission reader is not called again, and no runner is created. |
| + |
| +The chat test callers of `HostedLaunched` pass a time (`r.now`) and, in `launched`, a 90-minute `DeadlineInMS`. |
| + |
| +RED: these tests were written with the fixes in this round. Each one's failure on the pre-fix behaviour is shown by the mutation that restores that behaviour (322 to 326). Item 4's test is a guard: the code already refused it. |
| + |
| +Mutations (Edit tool, restored, brief's command green after): |
| +- **322** an ignored, stale record still admits (`ok := (accepted || true) && ...`). `CGO_ENABLED=0 go test ./internal/equipo -run TestEnrolNeedsCertifiedAdmission -count=1`: exit 1, `hosted_enrol_test.go:469: an older positive answer after a newer refusal: 200 {"credential":...}`. Restored. |
| +- **323** the controller's deadline ignored in `hostedDeadline` (`if false && j.Deadline.Before(deadline)`). `... -run TestHostedCredentialCappedAtDeadline`: exit 1, `hosted_enrol_test.go:664: credential {... ExpiresAt:2026-12-01 11:00:00 +0000 UTC ...} epoch 2 deadline 2026-12-01 11:35:00 +0000 UTC; want ... deadline 2026-12-01 10:39:00 +0000 UTC`. Restored. |
| +- **324** the pre-fix window: with no sighting recorded, admit without recording one or applying the window (`if j.RunningSeenAt == nil { return j, true, nil }`). `... -run TestEnrolRefusesReplayAndWrongVM`: exit 1, `hosted_enrol_test.go:407: first sighting <nil>, want the admission's 2026-12-01 10:15:00 +0000 UTC`. Restored. |
| +- **325** the sighting recorded but the window not applied (`true || now.Before(...)`). Same command: exit 1, `hosted_enrol_test.go:411: an enrolment completing two minutes after its first sighting: 200 {"credential":...}`. Restored. |
| +- **326** code single use removed (`j.CodeUsedAt != nil` dropped from `HostedClaimCode`'s refusals and `code_used_at IS NULL` from its update). Same command: exit 1, `hosted_enrol_test.go:372: the code again after a failed admission: 200 {"credential":...}`. Restored. |
| +- **327** (extra) the deadline counted from when it is recorded, not from the request (`t.now()` for `asked` in `hostedDeadlineSeen`). `... -run TestHostedCredentialCappedAtDeadline`: exit 1, `hosted_enrol_test.go:657: controller deadline 2026-12-01 09:07:35.057543558 +0000 UTC, want 2026-12-01 10:39:00 +0000 UTC`. Restored. |
| + |
| +Green: the brief's command passes (6.3 s). Also passing: the whole `./internal/equipo/chat` (25.3 s, `TestMigrationAdditive` included), `./internal/equipo/hostedrun` (14.4 s), `personapi`, `setup`, the hostedclient import guard, `./internal/equipotest -run 'Migration|Schema|TestRunnerAppCSRF'`, and `./internal/equipo -run 'Migration|Schema'`. `make migration-check budget build vet` exits 0. Budgets: `internal/equipo` 25256/8669, `internal/equipo/chat` 46903 source, each with its reason. |
| + |
| +The instance reads the controller's deadline only from launch views (Launch, and Get while launching). A deadline the controller shortens later is not re-read, but the earliest one is never extended. |
diff --git a/internal/equipo/chat/hosted_enrol.go b/internal/equipo/chat/hosted_enrol.go| index 5f40b717..5706981d 100644 |
| --- a/internal/equipo/chat/hosted_enrol.go |
| +++ b/internal/equipo/chat/hosted_enrol.go |
| @@ -27,8 +27,9 @@ func (s *Store) hostedTx(tx *gorm.DB) *txn { |
| // HostedClaimCode uses the instance code code for launchID's job, at now: |
| // the job must be enrolling, its code unused and unexpired, and within |
| // HostedEnrolTimeout of its VM first being seen running (the controller's |
| -// proxy code keeps the same window). The code is used even if the |
| -// enrolment goes no further. |
| +// proxy code keeps the same window; with no sighting recorded yet, |
| +// HostedEnrolAdmit records one and applies it). The code is used even if |
| +// the enrolment goes no further. |
| func (s *Store) HostedClaimCode(tx *gorm.DB, code, launchID string, now time.Time) (HostedJob, error) { |
| t := s.hostedTx(tx) |
| if checkCode(code) != nil || launchID == "" { |
| @@ -63,11 +64,14 @@ func (s *Store) HostedClaimCode(tx *gorm.DB, code, launchID string, now time.Tim |
| // HostedEnrolAdmit records the controller's admission record a for the |
| // enrolling job attempt, asked at at, and reports whether it admits the |
| -// VM vmRef of launch launchID: the job is enrolling with its code used |
| -// and no runner yet; a shows its VM running, at the job's VM (the one |
| -// enrolling), with a valid certificate, at the job's epoch. The record is |
| -// kept either way. |
| -func (s *Store) HostedEnrolAdmit(tx *gorm.DB, attempt, launchID, vmRef string, a hostedwire.AdmissionView, at time.Time) (HostedJob, bool, error) { |
| +// VM vmRef of launch launchID at now: the job is enrolling with its code |
| +// used and no runner yet; a was recorded (not older than the record held) |
| +// and shows its VM running, at the job's VM (the one enrolling), with a |
| +// valid certificate, at the job's epoch; and now is within |
| +// HostedEnrolTimeout of the earliest sighting of the VM running. A |
| +// verified running record is a sighting: with none recorded, at is |
| +// recorded as the first. The record and the sighting are kept either way. |
| +func (s *Store) HostedEnrolAdmit(tx *gorm.DB, attempt, launchID, vmRef string, a hostedwire.AdmissionView, at, now time.Time) (HostedJob, bool, error) { |
| t := s.hostedTx(tx) |
| var j HostedJob |
| if err := tx.Where("attempt_id = ?", attempt).First(&j).Error; err != nil { |
| @@ -76,12 +80,31 @@ func (s *Store) HostedEnrolAdmit(tx *gorm.DB, attempt, launchID, vmRef string, a |
| if j.State != HostedJobEnrolling || j.CodeUsedAt == nil || j.RunnerID != "" || j.LaunchID != launchID { |
| return j, false, nil |
| } |
| - valid, err := t.hostedAdmitted(j, a, at) |
| + valid, accepted, err := t.hostedAdmitted(j, a, at) |
| if err != nil { |
| return j, false, err |
| } |
| - ok := valid && a.State == hostedRunning && string(a.VMRef) == vmRef && j.VMRef == vmRef && a.CertValid && a.Epoch == j.Epoch |
| - return j, ok, nil |
| + ok := accepted && valid && a.State == hostedRunning && string(a.VMRef) == vmRef && j.VMRef == vmRef && a.CertValid && a.Epoch == j.Epoch |
| + if !ok { |
| + return j, false, nil |
| + } |
| + seen := at.UTC() |
| + if j.RunningSeenAt == nil { |
| + res := tx.Model(&HostedJob{}).Where("attempt_id = ? AND state = ? AND running_seen_at IS NULL", attempt, HostedJobEnrolling). |
| + Updates(map[string]any{"running_seen_at": seen, "revision": gorm.Expr("revision + 1")}) |
| + if res.Error != nil { |
| + return j, false, res.Error |
| + } |
| + if res.RowsAffected == 1 { |
| + if err := t.s.authority.Audit(tx, "system", "hosted.job", attempt+":running_seen"); err != nil { |
| + return j, false, err |
| + } |
| + } |
| + j.RunningSeenAt = &seen |
| + } else if j.RunningSeenAt.Before(seen) { |
| + seen = j.RunningSeenAt.UTC() |
| + } |
| + return j, now.Before(seen.Add(HostedEnrolTimeout)), nil |
| } |
| // HostedEnrolBind binds the enrolling job attempt to the worker runner |
diff --git a/internal/equipo/chat/hosted_jobs.go b/internal/equipo/chat/hosted_jobs.go| index 9766572b..f72ee0bd 100644 |
| --- a/internal/equipo/chat/hosted_jobs.go |
| +++ b/internal/equipo/chat/hosted_jobs.go |
| @@ -75,6 +75,11 @@ type HostedJob struct { |
| // launching until its reply or its return is recorded. |
| LaunchBy *time.Time |
| LaunchingSince *time.Time |
| + // Deadline is the controller's deadline for the job's VM, on the |
| + // instance's clock: the earliest a launch view gave (the time the |
| + // request was made plus the view's deadline_in_ms), never extended. |
| + // A hosted runner's credentials never outlive it. |
| + Deadline *time.Time |
| // RunningSeenAt is when the dispatcher first saw the job's VM |
| // running while it waited to enrol: the enrolment window runs from it |
| // (HostedEnrolTimeout), across restarts and controller outages. |
diff --git a/internal/equipo/chat/hosted_place_test.go b/internal/equipo/chat/hosted_place_test.go| index 6a864ee6..8ae18da5 100644 |
| --- a/internal/equipo/chat/hosted_place_test.go |
| +++ b/internal/equipo/chat/hosted_place_test.go |
| @@ -135,7 +135,7 @@ func (r *hkRig) launched(attempt, vm string) { |
| 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})) |
| + r.must(r.s.HostedLaunched(r.ctx, attempt, hostedwire.JobView{AttemptID: attempt, LaunchID: "launch-" + vm, State: "running", VMRef: isolatedjob.Ref(vm), Epoch: 0, DeadlineInMS: HostedChecksLifetime.Milliseconds()}, r.now)) |
| } |
| // enrol stands in for Task 22's enrolment: the VM's code is used, runner |
| @@ -611,7 +611,7 @@ func TestHostedLaunchedWhileStopping(t *testing.T) { |
| r.must(r.s.HostedLaunching(r.ctx, a, hostedCode, by.Add(HostedLaunchWindow), by)) |
| r.must(r.s.HostedLaunchReturned(r.ctx, a)) |
| r.must(r.s.HostedFailed(r.ctx, a, wire.ReasonHostedUnavailable)) |
| - r.must(r.s.HostedLaunched(r.ctx, a, hostedwire.JobView{AttemptID: a, LaunchID: "launch-7", State: "running", VMRef: "vm-7"})) |
| + r.must(r.s.HostedLaunched(r.ctx, a, hostedwire.JobView{AttemptID: a, LaunchID: "launch-7", State: "running", VMRef: "vm-7"}, r.now)) |
| if j := r.job(a); j.State != HostedJobStopping || j.VMRef != "vm-7" || j.LaunchID != "launch-7" { |
| t.Fatalf("VM learned while stopping: %s %q %q", j.State, j.VMRef, j.LaunchID) |
| } |
diff --git a/internal/equipo/chat/hosted_run.go b/internal/equipo/chat/hosted_run.go| index 7ab0c422..e0296227 100644 |
| --- a/internal/equipo/chat/hosted_run.go |
| +++ b/internal/equipo/chat/hosted_run.go |
| @@ -301,19 +301,40 @@ func (s *Store) HostedLaunchReturned(ctx context.Context, attempt string) error |
| // 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 { |
| +// asked is when the request that returned v was made, on the instance's |
| +// clock: the view's deadline is kept counted from it (hostedDeadlineSeen). |
| +func (s *Store) HostedLaunched(ctx context.Context, attempt string, v hostedwire.JobView, asked 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 |
| } |
| + var err error |
| if j.State == HostedJobStopping && j.VMRef == "" { |
| - return t.hostedLearnVM(j, v) |
| + err = t.hostedLearnVM(j, v) |
| + } else { |
| + err = t.hostedEnrolling(attempt, v) |
| } |
| - return t.hostedEnrolling(attempt, v) |
| + if err != nil { |
| + return err |
| + } |
| + return t.hostedDeadlineSeen(attempt, v, asked) |
| }) |
| } |
| +// hostedDeadlineSeen keeps the controller's deadline v gives for |
| +// attempt's job: asked plus v's deadline_in_ms. The controller counts it |
| +// from its answer, which comes after asked, so this is never later than |
| +// its deadline. An earlier deadline already kept stays: it is never |
| +// extended. |
| +func (t *txn) hostedDeadlineSeen(attempt string, v hostedwire.JobView, asked time.Time) error { |
| + if asked.IsZero() || v.DeadlineInMS < 0 { |
| + return fmt.Errorf("%w: deadline for %s", ErrHostedTransition, attempt) |
| + } |
| + at := asked.UTC().Add(time.Duration(v.DeadlineInMS) * time.Millisecond) |
| + return t.db.Model(&HostedJob{}).Where("attempt_id = ? AND (deadline IS NULL OR deadline > ?)", attempt, at).Update("deadline", at).Error |
| +} |
| + |
| // 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, |
| @@ -325,19 +346,21 @@ func (s *Store) HostedAdmitted(ctx context.Context, attempt string, a hostedwire |
| if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil { |
| return err |
| } |
| - _, err := t.hostedAdmitted(j, a, at) |
| + _, _, err := t.hostedAdmitted(j, a, at) |
| return err |
| }) |
| } |
| // hostedAdmitted records a for the live job j (HostedAdmitted) and |
| -// reports whether it is valid for j. |
| -func (t *txn) hostedAdmitted(j HostedJob, a hostedwire.AdmissionView, at time.Time) (bool, error) { |
| +// reports whether it is valid for j, and whether it was recorded: a |
| +// record older than the one held (a newer refusal among them) is |
| +// ignored, and accepted is false. |
| +func (t *txn) hostedAdmitted(j HostedJob, a hostedwire.AdmissionView, at time.Time) (valid, accepted bool, err error) { |
| attempt := j.AttemptID |
| if a.AttemptID != attempt || !j.Live() || j.VMRef == "" || at.IsZero() { |
| - return false, fmt.Errorf("%w: admission for %s", ErrHostedTransition, attempt) |
| + return false, false, 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 != "" && |
| + 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 == "" { |
| @@ -346,10 +369,14 @@ func (t *txn) hostedAdmitted(j HostedJob, a hostedwire.AdmissionView, at time.Ti |
| 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 valid, res.Error |
| + if res.Error != nil { |
| + return false, false, res.Error |
| + } |
| + accepted = res.RowsAffected > 0 |
| + if !accepted || valid == j.CertValid { |
| + return valid, accepted, nil |
| } |
| - return valid, t.s.authority.Audit(t.db, "system", "hosted.job", fmt.Sprintf("%s:cert_valid:%t", attempt, valid)) |
| + return valid, accepted, t.s.authority.Audit(t.db, "system", "hosted.job", fmt.Sprintf("%s:cert_valid:%t", attempt, valid)) |
| } |
| // HostedRunning records when the dispatcher first saw an enrolling job's |
diff --git a/internal/equipo/hosted_enrol.go b/internal/equipo/hosted_enrol.go| index 29b5922c..2bbe4f6e 100644 |
| --- a/internal/equipo/hosted_enrol.go |
| +++ b/internal/equipo/hosted_enrol.go |
| @@ -40,14 +40,20 @@ const ( |
| maxHostedCode = 64 |
| ) |
| -// hostedDeadline is the job's deadline: the provider ends any VM of the |
| -// attempt by its launch-by plus its lifetime. A job without both has |
| -// none (ok false) and is issued nothing. |
| +// hostedDeadline is the job's deadline: the controller's, as the instance |
| +// first saw it (chat.HostedJob.Deadline), and never later than its |
| +// launch-by plus its lifetime, by which the provider ends any VM of the |
| +// attempt. A job without all three has none (ok false) and is issued |
| +// nothing. |
| func hostedDeadline(j chat.HostedJob) (time.Time, bool) { |
| - if j.LaunchBy == nil || j.Lifetime <= 0 { |
| + if j.LaunchBy == nil || j.Lifetime <= 0 || j.Deadline == nil { |
| return time.Time{}, false |
| } |
| - return j.LaunchBy.UTC().Add(j.Lifetime), true |
| + deadline := j.LaunchBy.UTC().Add(j.Lifetime) |
| + if j.Deadline.Before(deadline) { |
| + deadline = j.Deadline.UTC() |
| + } |
| + return deadline, true |
| } |
| // hostedStoreError is a chat refusal as the runner routes say it, and any |
| @@ -90,7 +96,9 @@ func validHostedEnrol(q wire.HostedEnrolRequest) bool { |
| // uses the code (chat.Store.HostedClaimCode). The controller's admission |
| // record is read outside any transaction. Transaction 2 checks the job's |
| // person is a current member, records the admission and requires it to |
| -// admit this VM (chat.Store.HostedEnrolAdmit), then creates the worker |
| +// be recorded (not older than the record held) and to admit this VM |
| +// within two minutes of its first sighting running, recording that |
| +// sighting when none was (chat.Store.HostedEnrolAdmit), then creates the worker |
| // runner bound to the job, with no device code, and issues its first |
| // credential: an hour, never past the job's deadline. |
| func (s *Store) HostedEnrol(ctx context.Context, q wire.HostedEnrolRequest) (runnerproto.HostedEnrolResponse, error) { |
| @@ -152,7 +160,7 @@ func (s *Store) HostedEnrol(ctx context.Context, q wire.HostedEnrolRequest) (run |
| return err |
| } |
| now := s.runnerClock.Now().UTC() |
| - j, admitted, err := s.Chat().HostedEnrolAdmit(tx, job.AttemptID, q.LaunchID, q.VMRef, a, asked) |
| + j, admitted, err := s.Chat().HostedEnrolAdmit(tx, job.AttemptID, q.LaunchID, q.VMRef, a, asked, now) |
| if err != nil { |
| return hostedStoreError(err) |
| } |
diff --git a/internal/equipo/hosted_enrol_test.go b/internal/equipo/hosted_enrol_test.go| index cf7dc7b4..53f69375 100644 |
| --- a/internal/equipo/hosted_enrol_test.go |
| +++ b/internal/equipo/hosted_enrol_test.go |
| @@ -53,10 +53,18 @@ type fakeAdmitter struct { |
| mu sync.Mutex |
| views map[string]hostedwire.AdmissionView |
| errs map[string]error |
| - calls int |
| + // during runs while the call is in flight, before its answer. |
| + during map[string]func() |
| + calls int |
| } |
| func (f *fakeAdmitter) Admission(_ context.Context, attempt string) (hostedwire.AdmissionView, error) { |
| + f.mu.Lock() |
| + during := f.during[attempt] |
| + f.mu.Unlock() |
| + if during != nil { |
| + during() |
| + } |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.calls++ |
| @@ -97,7 +105,7 @@ func newHostedRig(t *testing.T, now time.Time, opts ...hostedJobOpts) *hostedRig |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { d.Close() }) |
| - r := &hostedRig{s: NewStore(d), clock: team.NewFakeClock(now), adm: &fakeAdmitter{views: map[string]hostedwire.AdmissionView{}, errs: map[string]error{}}} |
| + r := &hostedRig{s: NewStore(d), clock: team.NewFakeClock(now), adm: &fakeAdmitter{views: map[string]hostedwire.AdmissionView{}, errs: map[string]error{}, during: map[string]func(){}}} |
| r.s.runnerClock = r.clock |
| r.s.hostedAdmitter = r.adm |
| r.h = hostedApp(t, r.s, true) |
| @@ -139,9 +147,11 @@ func (r *hostedRig) vm(t *testing.T, n int, opts ...hostedJobOpts) *hostedRig { |
| } |
| sum := sha256.Sum256([]byte(v.code)) |
| at, by, expires := now.Add(-5*time.Minute), now.Add(5*time.Minute), now.Add(15*time.Minute) |
| + // The controller's deadline as a launch at launch-by would set it. |
| + deadline := by.Add(chat.HostedChecksLifetime) |
| v.job = chat.HostedJob{AttemptID: fmt.Sprintf("hj-test-%d", n), StepID: fmt.Sprintf("st-%d", n), StepAttempt: 1, TaskID: "tk-1", Project: "p-1", |
| Person: hostedOwner, Size: isolatedjob.SizeLarge, Lifetime: chat.HostedChecksLifetime, State: chat.HostedJobEnrolling, LaunchID: launch, |
| - VMRef: ref, Epoch: proxytest.Epoch, LaunchBy: &by, CertDigest: "cd", CertValid: true, |
| + VMRef: ref, Epoch: proxytest.Epoch, LaunchBy: &by, Deadline: &deadline, CertDigest: "cd", CertValid: true, |
| CodeHash: hex.EncodeToString(sum[:]), CodeExpiresAt: &expires, AdmittedAt: &at, Revision: 1} |
| for _, o := range opts { |
| o(&v.job) |
| @@ -170,6 +180,19 @@ func (r *hostedRig) setErr(err error) { |
| r.adm.errs[r.job.AttemptID] = err |
| } |
| +// setDuring runs fn while the rig's job's admission call is in flight. |
| +func (r *hostedRig) setDuring(fn func()) { |
| + r.adm.mu.Lock() |
| + defer r.adm.mu.Unlock() |
| + r.adm.during[r.job.AttemptID] = fn |
| +} |
| + |
| +func (r *hostedRig) calls() int { |
| + r.adm.mu.Lock() |
| + defer r.adm.mu.Unlock() |
| + return r.adm.calls |
| +} |
| + |
| func (r *hostedRig) rawWrite(t *testing.T, fn func(*gorm.DB) error) { |
| t.Helper() |
| if err := r.s.write(context.Background(), fn); err != nil { |
| @@ -298,6 +321,9 @@ func (r *hostedRig) wantCredential(t *testing.T, out runnerproto.HostedEnrolResp |
| t.Helper() |
| c := out.Credential |
| deadline := r.job.LaunchBy.Add(r.job.Lifetime) |
| + if r.job.Deadline.Before(deadline) { |
| + deadline = *r.job.Deadline |
| + } |
| if c.Token == "" || c.Role != wire.RoleWorker || c.Person != hostedOwner || out.Epoch != r.job.Epoch || !out.Deadline.Equal(deadline) { |
| t.Fatalf("credential %+v epoch %d deadline %v; want a worker credential for %s at epoch %d, deadline %v", c, out.Epoch, out.Deadline, hostedOwner, r.job.Epoch, deadline) |
| } |
| @@ -331,14 +357,32 @@ func TestEnrolRefusesReplayAndWrongVM(t *testing.T) { |
| t.Fatalf("%d runners, want 1", n) |
| } |
| + // Single use on its own: an enrolment whose admission could not be |
| + // read uses the code, and the job stays enrolling; the same request |
| + // again, with the controller answering, is refused before the |
| + // controller is asked. |
| + once := r.vm(t, 6) |
| + once.setErr(errors.New("connection refused")) |
| + if w := once.enrolling(); w.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("enrolment with the controller away: %d %s, want 503", w.Code, w.Body) |
| + } |
| + once.notEnrolled(t) |
| + once.setErr(nil) |
| + asked := r.calls() |
| + refused(t, "the code again after a failed admission", once.enrolling()) |
| + if r.calls() != asked { |
| + t.Fatal("a used code reached the controller") |
| + } |
| + once.notEnrolled(t) |
| + |
| wrongVM := r.vm(t, 1) |
| refused(t, "the right code from another VM", wrongVM.post("/api/hosted/enrol", wrongVM.enrolBody(wrongVM.code, "vm-other"), "", "")) |
| wrongVM.notEnrolled(t) |
| - calls := r.adm.calls |
| + calls := r.calls() |
| other := r.vm(t, 2) |
| refused(t, "another code", other.post("/api/hosted/enrol", other.enrolBody("JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJA", other.job.VMRef), "", "")) |
| - if r.adm.calls != calls { |
| + if r.calls() != calls { |
| t.Fatal("the controller was asked about a code that matched nothing") |
| } |
| other.notEnrolled(t) |
| @@ -352,6 +396,26 @@ func TestEnrolRefusesReplayAndWrongVM(t *testing.T) { |
| if n := r.runnerCount(t); n != 1 { |
| t.Fatalf("%d runners, want 1", n) |
| } |
| + |
| + // No sighting recorded yet: the verified running admission is the |
| + // first, recorded in the enrolment's transaction, and the two-minute |
| + // window runs from it, never from the code's longer expiry. |
| + t0 := r.clock.Now() |
| + first := r.vm(t, 7) |
| + first.wantCredential(t, first.enrol(t), t0.Add(time.Hour)) |
| + if j := first.jobRow(t); j.RunningSeenAt == nil || !j.RunningSeenAt.Equal(t0) { |
| + t.Fatalf("first sighting %v, want the admission's %v", j.RunningSeenAt, t0) |
| + } |
| + slow := r.vm(t, 8) |
| + slow.setDuring(func() { r.clock.Advance(chat.HostedEnrolTimeout) }) |
| + refused(t, "an enrolment completing two minutes after its first sighting", slow.enrolling()) |
| + slow.notEnrolled(t) |
| + if j := slow.jobRow(t); j.RunningSeenAt == nil || !j.RunningSeenAt.Equal(t0) { |
| + t.Fatalf("first sighting %v, want the admission's %v", j.RunningSeenAt, t0) |
| + } |
| + if n := r.runnerCount(t); n != 2 { |
| + t.Fatalf("%d runners, want 2", n) |
| + } |
| } |
| // TestEnrolNeedsCertifiedAdmission: the controller's record must show the |
| @@ -389,6 +453,24 @@ func TestEnrolNeedsCertifiedAdmission(t *testing.T) { |
| } |
| } |
| } |
| + // A newer refusal recorded while the enrolment's admission call is in |
| + // flight: the older positive answer is not recorded, and admits |
| + // nothing. |
| + stale := r.vm(t, 8) |
| + stale.setDuring(func() { |
| + r.adm.mu.Lock() |
| + refusal := r.adm.views[stale.job.AttemptID] |
| + r.adm.mu.Unlock() |
| + refusal.CertValid = false |
| + if err := r.s.Chat().HostedAdmitted(context.Background(), stale.job.AttemptID, refusal, hostedNow.Add(time.Second)); err != nil { |
| + t.Error(err) |
| + } |
| + }) |
| + refused(t, "an older positive answer after a newer refusal", stale.enrolling()) |
| + stale.notEnrolled(t) |
| + if j := stale.jobRow(t); j.CertValid || j.CertCheckedAt == nil || !j.CertCheckedAt.Equal(hostedNow.Add(time.Second)) { |
| + t.Fatalf("the newer refusal was replaced: valid %t checked %v", j.CertValid, j.CertCheckedAt) |
| + } |
| if n := r.runnerCount(t); n != 0 { |
| t.Fatalf("%d runners, want 0", n) |
| } |
| @@ -558,8 +640,32 @@ func TestHostedCredentialCappedAtDeadline(t *testing.T) { |
| past.notEnrolled(t) |
| out := r.enrol(t) |
| r.wantCredential(t, out, deadline) |
| + |
| + // The controller's deadline, earlier than launch-by plus lifetime: |
| + // recorded from the launch view counted from when the request started |
| + // (a minute before the answer), it caps enrolment and renewal. |
| + ctl := r.vm(t, 2, func(j *chat.HostedJob) { |
| + j.State, j.LaunchID, j.VMRef, j.Epoch, j.Deadline = chat.HostedJobLaunching, "", "", 0, nil |
| + }) |
| + view := hostedwire.JobView{AttemptID: ctl.job.AttemptID, LaunchID: "l-3", State: "running", VMRef: "vm-3", Epoch: proxytest.Epoch, |
| + DeadlineInMS: (40 * time.Minute).Milliseconds()} |
| + if err := r.s.Chat().HostedLaunched(context.Background(), ctl.job.AttemptID, view, hostedNow.Add(-time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctlDeadline := hostedNow.Add(39 * time.Minute) |
| + if j := ctl.jobRow(t); j.Deadline == nil || !j.Deadline.Equal(ctlDeadline) || !j.Deadline.Before(j.LaunchBy.Add(j.Lifetime)) { |
| + t.Fatalf("controller deadline %v, want %v (before %v)", j.Deadline, ctlDeadline, j.LaunchBy.Add(j.Lifetime)) |
| + } |
| + ctl.job.LaunchID, ctl.job.VMRef, ctl.job.Epoch, ctl.job.Deadline = view.LaunchID, string(view.VMRef), view.Epoch, &ctlDeadline |
| + ctl.setView(func(a *hostedwire.AdmissionView) { |
| + a.LaunchID, a.VMRef, a.Epoch = view.LaunchID, view.VMRef, view.Epoch |
| + }) |
| + ctlOut := ctl.enrol(t) |
| + ctl.wantCredential(t, ctlOut, ctlDeadline) |
| + |
| r.clock.Advance(20 * time.Minute) |
| r.wantCredential(t, r.renew(t, out.Credential), deadline) |
| + ctl.wantCredential(t, ctl.renew(t, ctlOut.Credential), ctlDeadline) |
| ch := r.challenge(t, out.Credential.Token) |
| r.clock.Advance(10 * time.Minute) |
| refused(t, "a renewal at the deadline", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch, ch.Nonce), out.Credential.Token, "")) |
diff --git a/internal/equipo/hostedrun/dispatcher.go b/internal/equipo/hostedrun/dispatcher.go| index 25a37eed..a34b847e 100644 |
| --- a/internal/equipo/hostedrun/dispatcher.go |
| +++ b/internal/equipo/hostedrun/dispatcher.go |
| @@ -207,7 +207,9 @@ func (d *Dispatcher) job(ctx context.Context, j chat.HostedJob) error { |
| return nil |
| case v.VMRef.Valid(): |
| d.settled(j.AttemptID) |
| - return d.Store.HostedLaunched(ctx, j.AttemptID, v) |
| + // now was read before the Get: the view's deadline counts |
| + // from no earlier. |
| + return d.Store.HostedLaunched(ctx, j.AttemptID, v, now) |
| case v.State == ctlAbandoned: |
| return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedUnavailable) |
| } |
| @@ -244,10 +246,11 @@ func (d *Dispatcher) launch(ctx context.Context, j chat.HostedJob, by time.Time) |
| q := hostedwire.LaunchRequest{AttemptID: j.AttemptID, TaskID: j.TaskID, Account: d.Account, Replaces: replaces, Image: d.Image, |
| Size: j.Size, MaxLifetimeMS: j.Lifetime.Milliseconds(), InstanceCode: code, |
| Person: j.Person, Purpose: hostedwire.PurposeChecks, LaunchByUnixMS: by.UnixMilli()} |
| + asked := d.now() |
| 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) |
| + return d.Store.HostedLaunched(ctx, j.AttemptID, v, asked) |
| } |
| if rerr := d.Store.HostedLaunchReturned(ctx, j.AttemptID); rerr != nil { |
| return rerr |
| @@ -334,7 +337,7 @@ func (d *Dispatcher) neverLaunched(ctx context.Context, j chat.HostedJob) error |
| case err != nil: |
| return nil |
| case v.VMRef != "": |
| - return d.Store.HostedLaunched(ctx, j.AttemptID, v) |
| + return d.Store.HostedLaunched(ctx, j.AttemptID, v, observed) |
| case v.State == ctlAbandoned && !observed.Before(by.Add(j.Lifetime+chat.HostedNeverLaunchedAfter)): |
| state = chat.HostedControllerAbandoned |
| default: |
diff --git a/internal/equipo/migrations/0128_hosted_job_deadline.sql b/internal/equipo/migrations/0128_hosted_job_deadline.sql| new file mode 100644 |
| index 00000000..e066b1d0 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0128_hosted_job_deadline.sql |
| @@ -0,0 +1,5 @@ |
| +-- Hosted runners slice 2 (Task 22 review 1): the controller's deadline |
| +-- for a hosted job's VM, as the instance first saw it (the earliest wins), |
| +-- so a hosted runner's credentials never outlive it. One new column; no |
| +-- existing row changes. |
| +ALTER TABLE hosted_jobs ADD COLUMN deadline datetime; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 79a26cf7..071a5088 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -947,3 +947,9 @@ CREATE INDEX hosted_challenges_runner ON hosted_challenges(runner_id); |
| -- existing row changes. |
| CREATE TABLE hosted_limits (person text, running integer, daily_seconds integer, monthly_micros integer, owner text, revision integer, updated_at datetime, PRIMARY KEY (person)); |
| CREATE TABLE hosted_admit_locks (person text, admissions integer, PRIMARY KEY (person)); |
| + |
| +-- Hosted runners slice 2 (Task 22 review 1): the controller's deadline |
| +-- for a hosted job's VM, as the instance first saw it (the earliest wins), |
| +-- so a hosted runner's credentials never outlive it. One new column; no |
| +-- existing row changes. |
| +ALTER TABLE hosted_jobs ADD COLUMN deadline datetime; |