oficina / equipo Public

hosted slice 2: review fixes, start needs a current admission

Task 32 finding 1 (M8). A hosted runner's start authorization and its
step's placement on the VM now need the job's latest admission record
to hold (fresh within AdmissionFresh, valid, naming the attempt,
launch, VM, epoch, image and certificate recorded at enrolment) and
its deadline to be known and ahead. Certification shares the same
check (hostedAdmissionHolds).

Tests: withdrawn certificate, stale record, another image, attempt or
launch, a passed or unknown deadline, for Authorize and for placement.
The placement rig enrols through HostedEnrolAdmit; the dispatcher
fakes answer the real controller's deadline_in_ms and the enrolment
image.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 0cce094e6ed35eca515d5b13cbe16a6a83ed85e5 parent d67ba3d
7 files changed, +187 −23
  • .rastrillo/budgets.txt +1 −1
  • internal/equipo/chat/hosted_place_test.go +11 −3
  • internal/equipo/chat/hosted_results.go +22 −7
  • internal/equipo/chat/hosted_run.go +6 −2
  • internal/equipo/chat/hosted_start_test.go +116 −0
  • internal/equipo/chat/runners.go +3 −2
  • internal/equipo/hostedrun/dispatcher_test.go +28 −8
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index bb1234a1..0cd00f42 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -61,7 +61,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 47573 22524 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. Its review round 2: an admission record's current deadline is kept too (hostedAdmitted, for the dispatcher's refresh and the renewal's HostedRenewAdmit); 46932/20971. Round 3: HostedEnrolAdmit returns the job re-read after recording the admission, so the enrolment caps by its deadline; 46937/20971. Task 23: openHostedPack opens the deps bundle after the hosted pack (send_pack with Deps), the instance's chunk and byte checks per kind (wire.MaxChunks, wire.MaxBytes), deps_too_large for a bundle past its limit, and a hosted attempt's pack and bundle closed when its checks end; hosted_deps_test.go; 46957/21199. Task 24: hosted_results.go (hostedCertified, AdmissionFresh: a hosted worker's checks count as sandboxed and its base checks as trusted only through the job's fresh, valid admission record, never its hello; an uncertified hosted result is not kept, its job stops and the step goes again once; deps_new_module and deps_missing presented as needs_network), stepReport and acceptBaseChecks wired to it, the admission kept whole and the enrolment image (0129), and hosted_results_test.go; 47094/21522. Task 24 review round 1: the certification decision moved before any terminal checks report from a worker (done, failed, unsolicited cancelled, the early failure branches), the person's cancellation kept, and tests for those, a wrong step, a stopping job and each admission identity substitution; 47096/21714. Task 24 review round 2: hostedSettleCancel (under the person's cancellation or an ended task, an uncertified hosted runner's report settles only its termination, with no checks evidence, taint or retry) and TestHostedUncertifiedCancelRace; 47123/21758. Task 25: HostedUsage (a person's running jobs and this UTC day's and month's held or used figures, errors returned) and HostedLimitList (owner only, the roster in the transaction) in usage.go, with hostedCounted shared with hostedAdmit; 47210/21758. Task 25 review round 1: HostedMinLimits and ErrHostedLimitTooLow (SetHostedLimits refuses limits that could never admit one checks job) and hosted_limits_floor_test.go (the floor, and each limit chip's promise through admission); 47224/21852. Task 26: protocol_floor.go (Research placed and started only at ProtocolHostedRunners, runner_update_needed, rechecked at Authorize) and protocol_floor_test.go; 47304/21967. Task 26 review 1: the Research floor before the legacy protocol 13 check, and the reconnect fence's runner_update_needed for a step not started (a protocol 12 placement case, TestResearchFencedAtReconnect); 47301/21998. Task 27: checkpoint.go (AcknowledgeCheckpoint binds a hosted runner's checkpoint to its job's recorded task, repository, base, candidate, attempt and launch, needs the current primary's signed pack receipt, recomputes the notes digest and stores it immutably; RenderResume renders only from the acknowledgement's ID, each note JSON-quoted), Authority.RunnerMachineKey, the checkpoints model, and checkpoint_test.go; 47548/22421. Task 27 review 1: TestAckImmutable alters each digest-bound stored field separately; 47548/22440. Task 30 review 1: the feed-lost latch (decision S2-3): HostedFeedLost and feedLost, an enrolled job whose latest admission record is the feed's lifetime old takes no new record, renews nothing and fails hosted_unavailable, also when its result arrives first; hosted_feedlost_test.go; 47573/22524.
+size internal/equipo/chat 47593 22648 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. Its review round 1: hostedAdmitted reports whether the record was kept, the enrolment records the first sighting and applies the window from it, and the launch view's deadline is kept (hosted_jobs.deadline, earliest wins); 46903/20971. Its review round 2: an admission record's current deadline is kept too (hostedAdmitted, for the dispatcher's refresh and the renewal's HostedRenewAdmit); 46932/20971. Round 3: HostedEnrolAdmit returns the job re-read after recording the admission, so the enrolment caps by its deadline; 46937/20971. Task 23: openHostedPack opens the deps bundle after the hosted pack (send_pack with Deps), the instance's chunk and byte checks per kind (wire.MaxChunks, wire.MaxBytes), deps_too_large for a bundle past its limit, and a hosted attempt's pack and bundle closed when its checks end; hosted_deps_test.go; 46957/21199. Task 24: hosted_results.go (hostedCertified, AdmissionFresh: a hosted worker's checks count as sandboxed and its base checks as trusted only through the job's fresh, valid admission record, never its hello; an uncertified hosted result is not kept, its job stops and the step goes again once; deps_new_module and deps_missing presented as needs_network), stepReport and acceptBaseChecks wired to it, the admission kept whole and the enrolment image (0129), and hosted_results_test.go; 47094/21522. Task 24 review round 1: the certification decision moved before any terminal checks report from a worker (done, failed, unsolicited cancelled, the early failure branches), the person's cancellation kept, and tests for those, a wrong step, a stopping job and each admission identity substitution; 47096/21714. Task 24 review round 2: hostedSettleCancel (under the person's cancellation or an ended task, an uncertified hosted runner's report settles only its termination, with no checks evidence, taint or retry) and TestHostedUncertifiedCancelRace; 47123/21758. Task 25: HostedUsage (a person's running jobs and this UTC day's and month's held or used figures, errors returned) and HostedLimitList (owner only, the roster in the transaction) in usage.go, with hostedCounted shared with hostedAdmit; 47210/21758. Task 25 review round 1: HostedMinLimits and ErrHostedLimitTooLow (SetHostedLimits refuses limits that could never admit one checks job) and hosted_limits_floor_test.go (the floor, and each limit chip's promise through admission); 47224/21852. Task 26: protocol_floor.go (Research placed and started only at ProtocolHostedRunners, runner_update_needed, rechecked at Authorize) and protocol_floor_test.go; 47304/21967. Task 26 review 1: the Research floor before the legacy protocol 13 check, and the reconnect fence's runner_update_needed for a step not started (a protocol 12 placement case, TestResearchFencedAtReconnect); 47301/21998. Task 27: checkpoint.go (AcknowledgeCheckpoint binds a hosted runner's checkpoint to its job's recorded task, repository, base, candidate, attempt and launch, needs the current primary's signed pack receipt, recomputes the notes digest and stores it immutably; RenderResume renders only from the acknowledgement's ID, each note JSON-quoted), Authority.RunnerMachineKey, the checkpoints model, and checkpoint_test.go; 47548/22421. Task 27 review 1: TestAckImmutable alters each digest-bound stored field separately; 47548/22440. Task 30 review 1: the feed-lost latch (decision S2-3): HostedFeedLost and feedLost, an enrolled job whose latest admission record is the feed's lifetime old takes no new record, renews nothing and fails hosted_unavailable, also when its result arrives first; hosted_feedlost_test.go; 47573/22524. Task 32 fix wave (whole-branch review finding 1, M8): a hosted runner's start (Authorize) and its step's placement on the VM need the job's admission to hold now, as certification does (hostedAdmissionHolds shared with hostedCertified), and its deadline ahead (hostedStartAdmitted); hosted_start_test.go (withdrawn, stale, mismatched records, a passed or unknown deadline) and the placement rig's enrolment through HostedEnrolAdmit; 47593/22648.
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/internal/equipo/chat/hosted_place_test.go b/internal/equipo/chat/hosted_place_test.go
index 9e18be7f..f02714ae 100644
--- a/internal/equipo/chat/hosted_place_test.go
+++ b/internal/equipo/chat/hosted_place_test.go
@@ -138,13 +138,21 @@ func (r *hkRig) launched(attempt, vm string) {
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
-// id (a worker) is bound to the job, and connects at protocol.
+// enrol stands in for Task 22's enrolment: the VM's code is used, the
+// controller's valid admission record is kept (as HostedEnrolAdmit does,
+// at r.now), 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") }))
+ vm := r.job(attempt).VMRef
+ r.must(r.tx(func(t *txn) error {
+ if _, ok, err := r.s.HostedEnrolAdmit(t.db, attempt, "launch-"+vm, vm, hrAdmission(attempt, vm, true), r.now, r.now); err != nil || !ok {
+ r.t.Fatalf("enrolment of %s admitted %t: %v", attempt, ok, err)
+ }
+ return t.hostedEnrolled(attempt, runner, "machine-key")
+ }))
r.online(runner, protocol)
}
diff --git a/internal/equipo/chat/hosted_results.go b/internal/equipo/chat/hosted_results.go
index b0f7bf89..2a35dd6a 100644
--- a/internal/equipo/chat/hosted_results.go
+++ b/internal/equipo/chat/hosted_results.go
@@ -36,9 +36,7 @@ const hostedStopUncertified = "uncertified"
// hostedCertified reports whether runnerID's checks result for attempt
// stepAttempt of step stepID, arriving at now, is certified: the runner
// is bound to an enrolled job for exactly that step and attempt, and the
-// job's latest admission record (asked for within AdmissionFresh of now)
-// was valid, shows the VM running and names the launch, VM, epoch, image
-// and certificate the job recorded at its enrolment. Everything is read
+// job's admission holds at now (hostedAdmissionHolds). Everything is read
// in the caller's transaction; a read error is false (and returned).
func (t *txn) hostedCertified(runnerID, stepID string, stepAttempt int64, now time.Time) (bool, error) {
if runnerID == "" {
@@ -48,12 +46,20 @@ func (t *txn) hostedCertified(runnerID, stepID string, stepAttempt int64, now ti
if err != nil || !found {
return false, err
}
+ return j.StepID == stepID && j.StepAttempt == stepAttempt && hostedAdmissionHolds(j, now), nil
+}
+
+// hostedAdmissionHolds reports whether enrolled job j's latest admission
+// record still admits its VM at now: asked for within AdmissionFresh of
+// now, valid, showing the VM running and naming the attempt, launch, VM,
+// epoch, image and certificate the job recorded at its enrolment.
+func hostedAdmissionHolds(j HostedJob, now time.Time) bool {
var a hostedwire.AdmissionView
if j.AdmissionJSON == "" || json.Unmarshal([]byte(j.AdmissionJSON), &a) != nil {
- return false, nil
+ return false
}
switch {
- case j.State != HostedJobEnrolled, j.StepID != stepID, j.StepAttempt != stepAttempt:
+ case j.State != HostedJobEnrolled:
case !j.CertValid, j.CertCheckedAt == nil:
case now.Sub(*j.CertCheckedAt) > AdmissionFresh, j.CertCheckedAt.Sub(now) > AdmissionFresh:
case !a.CertValid, a.State != hostedRunning, a.AttemptID != j.AttemptID:
@@ -61,9 +67,18 @@ func (t *txn) hostedCertified(runnerID, stepID string, stepAttempt int64, now ti
case j.ImageDigest == "" || string(a.Image) != j.ImageDigest:
case j.CertDigest == "" || a.CertDigest != j.CertDigest:
default:
- return true, nil
+ return true
}
- return false, nil
+ return false
+}
+
+// hostedStartAdmitted reports whether enrolled job j's VM may be given,
+// or start, its step at now: its admission holds (hostedAdmissionHolds)
+// and its deadline is known and ahead. An enrolment is not enough (M8): a
+// certificate withdrawn, or a record gone stale, while the VM waits for
+// its pack stops the start.
+func hostedStartAdmitted(j HostedJob, now time.Time) bool {
+ return hostedAdmissionHolds(j, now) && j.Deadline != nil && now.Before(*j.Deadline)
}
// hostedUncertified stops j, whose runner's checks result could not be
diff --git a/internal/equipo/chat/hosted_run.go b/internal/equipo/chat/hosted_run.go
index aa526971..71d79dd5 100644
--- a/internal/equipo/chat/hosted_run.go
+++ b/internal/equipo/chat/hosted_run.go
@@ -74,7 +74,8 @@ func (t *txn) stepJobs(step string) ([]HostedJob, error) {
// 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.
+// ProtocolHostedRunners and are online, while its admission admits
+// a start (hostedStartAdmitted); 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
@@ -105,7 +106,10 @@ func (t *txn) placeHosted(k *taskRecord, s *stepRecord, primary string, needs []
}
return wait(wire.PlacementHosted, "")
}
- if j.State != HostedJobEnrolled || primary == "" {
+ if j.State != HostedJobEnrolled || primary == "" || !hostedStartAdmitted(j, now) {
+ // Not enrolled, or its admission no longer admits a start
+ // (withdrawn, stale, mismatched, past its deadline): the step
+ // waits; the dispatcher's next record, or its stop, decides.
return wait(wire.PlacementHosted, "")
}
rs, err := t.runners(s.Person)
diff --git a/internal/equipo/chat/hosted_start_test.go b/internal/equipo/chat/hosted_start_test.go
new file mode 100644
index 00000000..a82d5e19
--- /dev/null
+++ b/internal/equipo/chat/hosted_start_test.go
@@ -0,0 +1,116 @@
+package chat
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Hosted slice 2, Task 32 (whole-branch review finding 1; Fable M8): a
+// hosted runner starts its step only while its job's latest admission
+// record is fresh, valid and names what the VM enrolled with, and the
+// job's deadline is ahead; placement puts the step on the VM under the
+// same rule. Enrolment alone is not enough: a certificate can be
+// withdrawn, or the record go stale, while the VM waits for its pack.
+
+// startSpoilers each spoil job j (on VM vm) after its enrolment, at
+// r.now, so that its admission no longer admits a start.
+var startSpoilers = []struct {
+ name string
+ spoil func(r *hkRig, j HostedJob, vm string)
+}{
+ {"withdrawn certificate", func(r *hkRig, j HostedJob, vm string) {
+ r.now = r.now.Add(10 * time.Second)
+ r.must(r.s.HostedAdmitted(r.ctx, j.AttemptID, hrAdmission(j.AttemptID, vm, false), r.now))
+ }},
+ {"stale admission", func(r *hkRig, _ HostedJob, _ string) {
+ r.now = r.now.Add(AdmissionFresh + time.Second)
+ }},
+ {"another image", func(r *hkRig, j HostedJob, vm string) {
+ a := hrAdmission(j.AttemptID, vm, true)
+ a.Image = isolatedjob.ImageDigest("sha256:" + strings.Repeat("d", 64))
+ r.keepRecord(j, a)
+ }},
+ {"another attempt", func(r *hkRig, j HostedJob, vm string) {
+ a := hrAdmission(j.AttemptID, vm, true)
+ a.AttemptID = "hj-other"
+ r.keepRecord(j, a)
+ }},
+ {"another launch", func(r *hkRig, j HostedJob, vm string) {
+ a := hrAdmission(j.AttemptID, vm, true)
+ a.LaunchID = "launch-other"
+ r.keepRecord(j, a)
+ }},
+ {"deadline passed", func(r *hkRig, j HostedJob, _ string) {
+ r.exec("UPDATE hosted_jobs SET deadline = ? WHERE attempt_id = ?", r.now.Add(-time.Second), j.AttemptID)
+ }},
+ {"no deadline", func(r *hkRig, j HostedJob, _ string) {
+ r.exec("UPDATE hosted_jobs SET deadline = NULL WHERE attempt_id = ?", j.AttemptID)
+ }},
+}
+
+// keepRecord stores a as j's latest admission record, the columns left
+// saying valid, as a record the store could hold.
+func (r *hkRig) keepRecord(j HostedJob, a hostedwire.AdmissionView) {
+ r.t.Helper()
+ raw, err := json.Marshal(a)
+ r.must(err)
+ r.exec("UPDATE hosted_jobs SET admission_json = ?, cert_valid = 1 WHERE attempt_id = ?", string(raw), j.AttemptID)
+}
+
+// TestHostedStartNeedsCurrentAdmission: a hosted runner placed on its
+// step while its admission held is refused the start once the record is
+// withdrawn, stale or mismatched, or the job's deadline is gone; with a
+// current record it is granted.
+func TestHostedStartNeedsCurrentAdmission(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ r.hostedOnVM("vm-1", "H1")
+ if got, err := r.s.Authorize(r.ctx, hostedLease("H1"), "s1", 1, "", "", ""); err != nil || got != "" {
+ t.Fatalf("H1 with a current admission: %q %v, want granted", got, err)
+ }
+ for _, sp := range startSpoilers {
+ t.Run(sp.name, func(t *testing.T) {
+ r := hostedPlaceRig(t)
+ r.checksStep("s1", "tkp")
+ j := r.hostedOnVM("vm-1", "H1")
+ sp.spoil(r, j, "vm-1")
+ if got, err := r.s.Authorize(r.ctx, hostedLease("H1"), "s1", 1, "", "", ""); err != nil || got != "withdrawn" {
+ t.Fatalf("H1 after %s: %q %v, want withdrawn", sp.name, got, err)
+ }
+ if s := r.step("s1"); s.StartedAt != nil {
+ t.Fatalf("after %s the step was recorded started", sp.name)
+ }
+ })
+ }
+}
+
+// TestHostedPlacementNeedsCurrentAdmission: an enrolled job whose
+// admission no longer admits its VM does not get its step: the step
+// waits as hosted work and nothing is dispatched to the VM's runner.
+func TestHostedPlacementNeedsCurrentAdmission(t *testing.T) {
+ for _, sp := range startSpoilers {
+ t.Run(sp.name, func(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)
+ sp.spoil(r, r.job(a), "vm-1")
+ r.online("H1", wire.ProtocolHostedRunners)
+ r.online(hpPrimary, wire.ProtocolHostedRunners)
+ r.place()
+ if s := r.step("s1"); s.RunnerID != "" || s.Placement != wire.PlacementHosted {
+ t.Fatalf("after %s: s1 placed %q on %q, want waiting hosted", sp.name, s.Placement, s.RunnerID)
+ }
+ if got := r.commands("H1", wire.FrameDispatch); len(got) != 0 {
+ t.Fatalf("after %s: dispatched to H1: %+v", sp.name, got)
+ }
+ })
+ }
+}
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index e527fdb2..3da6608d 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -973,10 +973,11 @@ func (s *Store) Authorize(ctx context.Context, l Lease, stepID string, attempt i
return nil
}
// A hosted runner starts only its job's step and attempt, while
- // the job is enrolled: by job identity, in this transaction.
+ // the job is enrolled and its admission admits a start
+ // (hostedStartAdmitted): 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) {
+ } else if bound && (j.State != HostedJobEnrolled || j.StepID != st.ID || j.StepAttempt != attempt || !hostedStartAdmitted(j, t.now())) {
refused = "withdrawn"
return nil
}
diff --git a/internal/equipo/hostedrun/dispatcher_test.go b/internal/equipo/hostedrun/dispatcher_test.go
index 3e800579..bf3c19e3 100644
--- a/internal/equipo/hostedrun/dispatcher_test.go
+++ b/internal/equipo/hostedrun/dispatcher_test.go
@@ -280,8 +280,10 @@ func (r *rig) until(d time.Duration, what string, done func() bool) {
}
// 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.
+// the VM's code (the one its launch carried) is used, the image its
+// launch named recorded as the enrolment's (HostedEnrolAdmit does), the
+// runner bound and connected. The dispatcher's next pass records the
+// admission its placement needs. It reports whether the VM could.
func (r *rig) enrol(attempt, runner string) bool {
r.t.Helper()
j := r.job(attempt)
@@ -290,8 +292,8 @@ func (r *rig) enrol(attempt, runner string) bool {
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.exec("UPDATE hosted_jobs SET state = ?, runner_id = ?, machine_public_key = 'key', code_used_at = ?, enrolled_at = ?, image_digest = ?, revision = revision + 1 WHERE attempt_id = ? AND state = ?",
+ chat.HostedJobEnrolled, runner, r.now, r.now, string(vm.q.Image), attempt, chat.HostedJobEnrolling)
r.online(runner)
return true
}
@@ -330,6 +332,24 @@ func (v *fakeVM) view() hostedwire.JobView {
return w
}
+// deadlineIn is v's deadline as the controller answers it at now, counted
+// from the answer: the VM's lifetime from its start (from now while it
+// waits to start), never below zero.
+func (v *fakeVM) deadlineIn(now time.Time) int64 {
+ from := now
+ if v.everVM {
+ from = v.startedAt
+ }
+ return max(0, from.Add(time.Duration(v.q.MaxLifetimeMS)*time.Millisecond).Sub(now).Milliseconds())
+}
+
+// viewAt is v's view with its deadline at now.
+func (f *fakeCtl) viewAt(v *fakeVM) hostedwire.JobView {
+ w := v.view()
+ w.DeadlineInMS = v.deadlineIn(f.now())
+ return w
+}
+
// alive reports whether the VM may be running, linked or not.
func (v *fakeVM) alive() bool { return v.everVM && !v.vmEnded && v.proof == nil }
@@ -473,7 +493,7 @@ func (f *fakeCtl) Launch(_ context.Context, q hostedwire.LaunchRequest) (hostedw
if v.q != q {
return hostedwire.JobView{}, hostedclient.ErrConflict
}
- return f.answer(v.view())
+ return f.answer(f.viewAt(v))
}
if q.Replaces != "" {
if p := f.jobs[q.Replaces]; p == nil || p.proof == nil {
@@ -491,7 +511,7 @@ func (f *fakeCtl) Launch(_ context.Context, q hostedwire.LaunchRequest) (hostedw
if !f.chance(f.throttle) {
f.start(v)
}
- return f.answer(v.view())
+ return f.answer(f.viewAt(v))
}
// answer is v, or a lost reply.
@@ -516,7 +536,7 @@ func (f *fakeCtl) Get(_ context.Context, attempt string) (hostedwire.JobView, er
if !ok {
return hostedwire.JobView{}, hostedclient.ErrAbsent
}
- return f.answer(v.view())
+ return f.answer(f.viewAt(v))
}
func (f *fakeCtl) Admission(_ context.Context, attempt string) (hostedwire.AdmissionView, error) {
@@ -537,7 +557,7 @@ func (f *fakeCtl) Admission(_ context.Context, attempt string) (hostedwire.Admis
}
f.admitted[attempt] = append(f.admitted[attempt], f.now())
return hostedwire.AdmissionView{AttemptID: attempt, LaunchID: v.launchID, State: v.state, VMRef: v.view().VMRef, Image: v.q.Image,
- CertDigest: "cert-1", CertValid: f.certValid, CheckedNS: f.now().UnixNano()}, nil
+ CertDigest: "cert-1", CertValid: f.certValid, CheckedNS: f.now().UnixNano(), DeadlineInMS: v.deadlineIn(f.now())}, nil
}
func (f *fakeCtl) Stop(_ context.Context, attempt, reason string) (hostedwire.StopProof, error) {