equipo: hosted jobs table and lifecycle
Migration 0126 adds hosted_jobs (the brief's columns; one live job a step, one job a runner, one job a code hash) and hosted_challenges, new tables only. HostedJob moves only pending, launching, enrolling, enrolled, stopping, then ended or failed; any live state may stop; an end needs the controller's stop proof for its attempt and VM, or never-launched evidence for a job with no launch. Each move is conditional on the state and revision read and audited in the transaction. newHostedJob reads the step and task in the transaction, checks the person's roster, keeps only the code's SHA-256 later, and retries only a proven job of the same step. settleHostedJob settles once; hostedJobForRunner returns a lookup error rather than no job. TestMigrationAdditive covers every migration from 0125 on. Budget record raised for internal/equipo/chat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+977
−2
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+32 −0internal/equipo/chat/hosted_jobs.go+450 −0internal/equipo/chat/hosted_jobs_test.go+464 −0internal/equipo/chat/models.go+1 −1internal/equipo/migrations/0126_hosted_jobs.sql+14 −0internal/equipo/migrations/schema.sql+15 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 427e2e8d..1c784575 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -59,7 +59,7 @@ perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| perf GET /api/v1/assistant/abilities skip Assistant person API: bearer-only JSON for Base's Settings line, not a browser screen. |
| -size internal/equipo/chat 45208 19113 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. |
| +size internal/equipo/chat 45658 19577 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. |
| 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 4133bff9..cda2e533 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1415,3 +1415,35 @@ Mutations (exact-string replace from a script under `$TMPDIR`, one at a time, re |
| - **232** no normalisation. In `chat_wiring.go`, `if errors.Is(err, ErrForbidden) {` (before `return wire.Me{}, chatDenied{err}`) became `if false && errors.Is(err, ErrForbidden) {`. `CGO_ENABLED=0 go test ./internal/equipo -run TestHostedSettingRemovedOwnerProductionWiring -count=1`: exit 1, `hosted_settings_test.go:180: owner B after A's removal: [] You do not have access to this page. Ask an owner for access.` Restored (identical). |
| - **233** database errors read as denials. The same line became `if err != nil && errors.Is(err, err) {`. Same command: exit 1, `hosted_settings_test.go:206: a database error became a denial: The information is unavailable. Try again in a minute.: SQL logic error: no such table: members (1)`. Restored (`cmp` identical). A first form of this mutation left `errors` unused and did not compile, so it is not counted. |
| - **234** audit through `s.db` instead of the transaction. In `chat/hosted_setting.go`, `s.authority.Audit(t.db, person, "project.hosted_checks"` became `s.authority.Audit(s.db.G, person, "project.hosted_checks"`. `CGO_ENABLED=0 go test ./internal/equipo/chat -run TestHostedSettingAuditAtomic -count=1`: exit 1, `hosted_setting_test.go:187: audited write: audit outside the roster check's transaction`. Restored (identical). |
| + |
| +## Task 19 |
| + |
| +Hosted jobs store. Migration `0126_hosted_jobs.sql` (new tables only; `schema.sql` appended): `hosted_jobs` with the brief's columns verbatim (`attempt_id` primary key), partial unique indexes `hosted_jobs_live_step` (`step_id` where `state <> 'ended' AND state <> 'failed'`: one live job a step), `hosted_jobs_runner` (`runner_id <> ''`: a runner bound to one job), `hosted_jobs_code` (`code_hash <> ''`), index `hosted_jobs_person(person, state)`; `hosted_challenges` (`runner_id`, `nonce_hash` primary key, `expires_at`, `used_at`; index on `runner_id`). `internal/equipo/chat/hosted_jobs.go`: the record `HostedJob` (exported, `TableName` `hosted_jobs`) and `hostedChallengeRecord`, both in `Models`; states `HostedJobPending` ... `HostedJobFailed`; `HostedCharge` (seconds per UTC day `2006-01-02`, USD micros per UTC month `2006-01`; keys and non-negative amounts checked; stored as JSON in the `*_json` columns, `Hold()` and `Used()` read them back); `HostedEndProof` (`Stop *hostedwire.StopProof`, `NeverLaunched`, `ObservedAt` on the instance's clock), stored in `stop_proof_json`. |
| + |
| +Lifecycle (`moveHostedJob`, the one place every move goes through: listed move, then proof for an end, then a write conditional on the state and revision read, then `system hosted.job <attempt>:<from>><to>` audited in the transaction): |
| +- `newHostedJob(hostedJobSpec{Step, Size, Hold, RetryOf, At})`: reads the step and its task in the transaction (task, project, person and step attempt come from them, not the caller), the person must pass `authority.Me` (a removed member or a lookup error denies), a known size, a non-empty hold, no live job for the step (`ErrHostedJobLive`), and a retry only of the same step's ended or failed job that holds proof (`Retries` = its `Retries` + 1). Attempt ID `hj_` + 26 characters (under the 64 of Task 4's ruling). `admitted_at` = `At`. Audited `<attempt>:pending`. |
| +- `hostedLaunching(attempt, code, expires)` pending to launching: the 32-byte base64url code is checked and only its SHA-256 (hex) is kept, with its expiry. |
| +- `hostedEnrolling(attempt, hostedwire.JobView)` launching to enrolling: the view must name the attempt, a launch ID of 1 to 64 bytes and a valid VM Ref; records `launch_id`, `vm_ref`, `epoch`. |
| +- `hostedEnrolled(attempt, runnerID, machineKey)` enrolling to enrolled: only once the code is used (`code_used_at`, set by Task 22's enrolment); records `runner_id`, `machine_public_key`, `enrolled_at`. |
| +- `hostedStopping(attempt, reason)` from pending, launching, enrolling or enrolled: `stop_reason`, 1 to 128 printable ASCII. |
| +- `hostedEnd(attempt, ended|failed, HostedEndProof)` from stopping only: a terminal stop proof naming the attempt and, once the job has a VM Ref, that VM; or never-launched evidence, accepted only for a job with no launch ID, VM Ref or runner (the controller never reported a launch). Exactly one of the two, and an observation time. `ended_at` = the observation time. |
| +- `settleHostedJob(attempt, used, at)`: ended or failed with valid proof only (`ErrHostedNoProof` otherwise); an already settled job is left untouched and reports false (settled_at checked, and the write is also conditional on `settled_at IS NULL`). The hold columns are kept as admission wrote them. |
| +- `hostedJobForRunner(runnerID)`: the job the runner is bound to, whatever its state; a lookup error is returned, never read as no job; an empty ID is refused. |
| + |
| +Red: `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestHostedJob|TestEndNeedsProof|TestOneLiveJob|TestSettleIdempotent' -count=1`: build failed (`undefined: HostedCharge`, `undefined: HostedJob`, `t.newHostedJob undefined`, `undefined: hostedJobSpec`, `undefined: HostedEndProof`). `TestMigrationAdditive` (first written in `internal/equipo`): FAIL, `no 0126_hosted_jobs`. It was moved into `chat/hosted_jobs_test.go` (the brief's file), reading the migrations from `../migrations` with `migrate.FromFS`, because `internal/equipo` tests would have passed their 8,000-line budget (8,027). |
| + |
| +Tests (chat): `TestHostedJobTransitions` (every state to every target, through the store, accepted exactly when listed; a refused move changes nothing), `TestHostedJobLifecycle` (the whole path, fields recorded, only the code's hash stored, six exact audit lines, a failed audit keeps no job), `TestEndNeedsProof` (ended and failed: no evidence, never-launched for a launched job, another attempt's proof, a live VM, another VM, no observation time, both kinds at once: all `ErrHostedNoProof`, nothing written; then valid proof; never-launched accepted for an unlaunched job), `TestOneLiveJobPerStep` (store and table refuse a second live job, including while stopping; retries only of the same step's proven job; a job for no step; a removed person), `TestHostedJobForRunner`, `TestSettleIdempotent` (refused while live or unproven; bad keys and negative amounts refused; settling twice changes nothing and audits once), `TestMigrationAdditive` (from 0125 on, each migration keeps every earlier table's columns and indexes unchanged; 0126 adds exactly the two tables; its live index refuses a second live job in each live state and allows ended and failed ones; one runner, one job). |
| + |
| +Green: `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestHostedJob|TestEndNeedsProof|TestOneLiveJob|TestSettleIdempotent|TestMigrationAdditive' -count=1`: ok (7 tests). The whole chat package once: ok (24.6 s). `./internal/equipo -run 'Migration|Schema'`: ok (snapshot included). `make migration-check budget build vet`: exit 0 after raising the chat record to 45658/19577 with the reason. gofmt clean. |
| + |
| +Mutations (exact-string replace from a script under `mktemp -d`, one at a time, `CGO_ENABLED=0 go test ./internal/equipo/chat -run '<test>' -count=1`, the file restored from a copy and compared with `filecmp`: identical each time): |
| +- **235** (the brief's) allow `ended` without proof. In `moveHostedJob`, `if to == HostedJobEnded || to == HostedJobFailed {` became `if to == HostedJobFailed {`. `-run TestEndNeedsProof`: exit 1, `hosted_jobs_test.go:211: ended: hj_... with another attempt's proof = <nil>, state ended`. Restored. |
| +- **236** an unlisted move. `HostedJobEnrolled: {HostedJobStopping},` became `{HostedJobStopping, HostedJobEnded},`. `-run TestHostedJobTransitions`: exit 1, `hosted_jobs_test.go:119: enrolled -> ended = <nil>, want ErrHostedTransition`. Restored. |
| +- **237** settle not idempotent. `if j.SettledAt != nil {` became `if false && j.SettledAt != nil {`. `-run TestSettleIdempotent`: exit 1, `hosted_jobs_test.go:364: second settle: false chat: idempotency conflict: hosted job hj_... moved`. Restored. |
| +- **238** never-launched evidence for a launched job. `if j.LaunchID == "" && j.VMRef == "" && j.RunnerID == "" {` became `if true || ...`. `-run 'TestEndNeedsProof|TestHostedJobForRunner'`: exit 1, `hosted_jobs_test.go:211: ended: hj_... with never launched, but it launched = <nil>, state ended` and `hosted_jobs_test.go:302: an enrolled job ended as never launched: <nil>`. Restored. |
| +- **239** no live-job check in the store. `if live != 0 {` became `if false && live != 0 {`. `-run TestOneLiveJobPerStep`: exit 1, `hosted_jobs_test.go:243: second live job: duplicated key not allowed` (the table's index still refused it, but not as `ErrHostedJobLive`). Restored. |
| +- **240** retry of an unproven job. `prior.StepID != s.ID || prior.Live() || !prior.proven()` lost `|| !prior.proven()`. First run: exit 0 (no test reached it, since no move ends a job without proof); a case was added (a job set to `failed` by hand, no proof). Rerun: exit 1, `hosted_jobs_test.go:273: a retry of a job with no proof: <nil>`. Restored. |
| +- **241** a non-additive migration. `ALTER TABLE chat_projects DROP COLUMN hosted_checks_revision;` appended to 0126. `-run TestMigrationAdditive`: exit 1, `hosted_jobs_test.go:439: equipo/0126_hosted_jobs changed chat_projects:` (the column missing after). Restored. |
| +- **242** the live index without its condition. `ON hosted_jobs(step_id) WHERE state <> 'ended' AND state <> 'failed';` became `ON hosted_jobs(step_id);`. Same command: exit 1, `hosted_jobs_test.go:450: constraint failed: UNIQUE constraint failed: hosted_jobs.step_id (2067)`. Restored. |
| + |
| +Notes for Tasks 20 to 22: `failed` is reached only through `stopping` (any live state goes to stopping on a failure, then needs proof), so the dispatcher's `HostedFailed` should move the job to stopping with its reason and end it once proof or never-launched evidence arrives. `admitted_at` is the limit admission time (Task 20's settle start). The admission record columns (`cert_*`), `code_used_at` and `hosted_challenges` have no writers yet (Tasks 21 and 22). |
diff --git a/internal/equipo/chat/hosted_jobs.go b/internal/equipo/chat/hosted_jobs.go| new file mode 100644 |
| index 00000000..7133c332 |
| --- /dev/null |
| +++ b/internal/equipo/chat/hosted_jobs.go |
| @@ -0,0 +1,450 @@ |
| +package chat |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// A hosted job's states (hosted runners spec §8, §10). pending to ended is |
| +// the path; any live state may go to stopping when its step ends or the |
| +// job fails; stopping ends in ended or failed, and only with proof. |
| +const ( |
| + HostedJobPending = "pending" |
| + HostedJobLaunching = "launching" |
| + HostedJobEnrolling = "enrolling" |
| + HostedJobEnrolled = "enrolled" |
| + HostedJobStopping = "stopping" |
| + HostedJobEnded = "ended" |
| + HostedJobFailed = "failed" |
| +) |
| + |
| +// hostedMoves are the only moves a job makes. |
| +var hostedMoves = map[string][]string{ |
| + HostedJobPending: {HostedJobLaunching, HostedJobStopping}, |
| + HostedJobLaunching: {HostedJobEnrolling, HostedJobStopping}, |
| + HostedJobEnrolling: {HostedJobEnrolled, HostedJobStopping}, |
| + HostedJobEnrolled: {HostedJobStopping}, |
| + HostedJobStopping: {HostedJobEnded, HostedJobFailed}, |
| +} |
| + |
| +var ( |
| + // ErrHostedTransition is a move the lifecycle does not list, or one |
| + // whose inputs are not what that move records. |
| + ErrHostedTransition = errors.New("chat: hosted job cannot make that move") |
| + // ErrHostedNoProof is an end, or a settlement, without stop proof or |
| + // never-launched evidence that holds for the job. |
| + ErrHostedNoProof = errors.New("chat: hosted job has no proof it ended") |
| + // ErrHostedJobLive is a second live job for one step. |
| + ErrHostedJobLive = errors.New("chat: the step already has a live hosted job") |
| +) |
| + |
| +// HostedJob is one hosted VM attempt for one checks step (hosted_jobs). The |
| +// instance code is never stored, only its SHA-256 (CodeHash). Hold* is what |
| +// admission held against the person's limits and Used* what settlement |
| +// charged: seconds per UTC day ("2006-01-02") and USD micros per UTC month |
| +// ("2006-01"), as JSON (HostedCharge). |
| +type HostedJob struct { |
| + AttemptID string `gorm:"primaryKey"` |
| + StepID string `gorm:"uniqueIndex:hosted_jobs_live_step,where:state <> 'ended' AND state <> 'failed'"` |
| + StepAttempt int64 |
| + TaskID string |
| + Project string |
| + Person string `gorm:"index:hosted_jobs_person,priority:1"` |
| + Size isolatedjob.Size |
| + State string `gorm:"index:hosted_jobs_person,priority:2"` |
| + // LaunchID, VMRef and Epoch are the controller's, from its launch view. |
| + LaunchID string |
| + VMRef string `gorm:"column:vm_ref"` |
| + Epoch int64 |
| + // Cert* is the controller's latest admission record for the VM. |
| + CertDigest string |
| + CertValid bool |
| + CertCheckedAt *time.Time |
| + CodeHash string `gorm:"uniqueIndex:hosted_jobs_code,where:code_hash <> ''"` |
| + CodeExpiresAt *time.Time |
| + CodeUsedAt *time.Time |
| + // RunnerID is the worker runner the VM enrolled as, bound to this job |
| + // alone; MachinePublicKey signs its renewals. |
| + RunnerID string `gorm:"uniqueIndex:hosted_jobs_runner,where:runner_id <> ''"` |
| + MachinePublicKey string |
| + // AdmittedAt is when the limits admitted the job (its hold's start); |
| + // EndedAt is when the instance received the proof. |
| + AdmittedAt *time.Time |
| + EnrolledAt *time.Time |
| + EndedAt *time.Time |
| + HoldSecondsJSON string `gorm:"column:hold_seconds_json"` |
| + HoldMicrosJSON string `gorm:"column:hold_micros_json"` |
| + UsedSecondsJSON string `gorm:"column:used_seconds_json"` |
| + UsedMicrosJSON string `gorm:"column:used_micros_json"` |
| + SettledAt *time.Time |
| + StopReason string |
| + // StopProofJSON is the HostedEndProof the job ended with. |
| + StopProofJSON string `gorm:"column:stop_proof_json"` |
| + // RetryOf is the proven job of the same step this one tries again; |
| + // Retries counts the attempts before it. |
| + RetryOf string |
| + Retries int64 |
| + Revision int64 |
| +} |
| + |
| +func (HostedJob) TableName() string { return "hosted_jobs" } |
| + |
| +// hostedChallengeRecord is one renewal challenge for a hosted runner: the |
| +// nonce's SHA-256 only, single use, short lived. |
| +type hostedChallengeRecord struct { |
| + RunnerID string `gorm:"index:hosted_challenges_runner"` |
| + NonceHash string `gorm:"primaryKey"` |
| + ExpiresAt time.Time |
| + UsedAt *time.Time |
| +} |
| + |
| +func (hostedChallengeRecord) TableName() string { return "hosted_challenges" } |
| + |
| +// Live reports whether the job may still have, or come to have, a VM. |
| +func (j HostedJob) Live() bool { return j.State != HostedJobEnded && j.State != HostedJobFailed } |
| + |
| +// HostedCharge is an amount against a person's hosted limits: seconds per |
| +// UTC day and USD micros per UTC month. |
| +type HostedCharge struct { |
| + Seconds map[string]int64 |
| + Micros map[string]int64 |
| +} |
| + |
| +// Hold is what admission held for the job. |
| +func (j HostedJob) Hold() (HostedCharge, error) { |
| + return decodeCharge(j.HoldSecondsJSON, j.HoldMicrosJSON) |
| +} |
| + |
| +// Used is what settlement charged; empty until the job settles. |
| +func (j HostedJob) Used() (HostedCharge, error) { |
| + return decodeCharge(j.UsedSecondsJSON, j.UsedMicrosJSON) |
| +} |
| + |
| +func decodeCharge(seconds, micros string) (HostedCharge, error) { |
| + var c HostedCharge |
| + for _, f := range []struct { |
| + raw string |
| + out *map[string]int64 |
| + }{{seconds, &c.Seconds}, {micros, &c.Micros}} { |
| + if f.raw == "" { |
| + continue |
| + } |
| + if err := json.Unmarshal([]byte(f.raw), f.out); err != nil { |
| + return HostedCharge{}, err |
| + } |
| + } |
| + return c, c.valid() |
| +} |
| + |
| +// valid: day keys are UTC dates, month keys UTC months, every amount at |
| +// least zero. |
| +func (c HostedCharge) valid() error { |
| + for _, f := range []struct { |
| + m map[string]int64 |
| + layout string |
| + }{{c.Seconds, time.DateOnly}, {c.Micros, "2006-01"}} { |
| + for k, v := range f.m { |
| + at, err := time.Parse(f.layout, k) |
| + if err != nil || at.Format(f.layout) != k || v < 0 { |
| + return fmt.Errorf("%w: hosted charge %q: %d", ErrInvalid, k, v) |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// encode is the charge's two JSON columns; an empty map is "". |
| +func (c HostedCharge) encode() (seconds, micros string, err error) { |
| + if err := c.valid(); err != nil { |
| + return "", "", err |
| + } |
| + one := func(m map[string]int64) (string, error) { |
| + if len(m) == 0 { |
| + return "", nil |
| + } |
| + raw, err := json.Marshal(m) |
| + return string(raw), err |
| + } |
| + if seconds, err = one(c.Seconds); err != nil { |
| + return "", "", err |
| + } |
| + micros, err = one(c.Micros) |
| + return seconds, micros, err |
| +} |
| + |
| +// HostedEndProof is what lets a job end: the controller's stop proof for |
| +// its attempt, or never-launched evidence (the controller's Get answered |
| +// not found for an intent it never dispatched). ObservedAt is when the |
| +// instance received it, on the instance's clock. |
| +type HostedEndProof struct { |
| + Stop *hostedwire.StopProof `json:"stop,omitempty"` |
| + NeverLaunched bool `json:"never_launched,omitempty"` |
| + ObservedAt time.Time `json:"observed_at"` |
| +} |
| + |
| +// proofFor checks p against j: a terminal stop proof for j's attempt and, |
| +// once j has a VM, that VM; or never-launched evidence for a job the |
| +// controller never reported launching. Exactly one of the two. |
| +func (p HostedEndProof) proofFor(j HostedJob) error { |
| + switch { |
| + case p.ObservedAt.IsZero(): |
| + case p.Stop != nil && !p.NeverLaunched: |
| + if p.Stop.AttemptID == j.AttemptID && p.Stop.State.Terminal() && (j.VMRef == "" || string(p.Stop.VMRef) == j.VMRef) { |
| + return nil |
| + } |
| + case p.Stop == nil && p.NeverLaunched: |
| + if j.LaunchID == "" && j.VMRef == "" && j.RunnerID == "" { |
| + return nil |
| + } |
| + } |
| + return fmt.Errorf("%w: %s", ErrHostedNoProof, j.AttemptID) |
| +} |
| + |
| +// proven reports whether the job holds proof it ended. |
| +func (j HostedJob) proven() bool { return j.provenErr() == nil } |
| + |
| +func (j HostedJob) provenErr() error { |
| + var p HostedEndProof |
| + dec := json.NewDecoder(bytes.NewReader([]byte(j.StopProofJSON))) |
| + dec.DisallowUnknownFields() |
| + if j.StopProofJSON == "" || dec.Decode(&p) != nil { |
| + return fmt.Errorf("%w: %s", ErrHostedNoProof, j.AttemptID) |
| + } |
| + return p.proofFor(j) |
| +} |
| + |
| +// hostedJobSpec is what placement admits: the step (its task, project, |
| +// person and attempt are read from it), the VM size, the hold the limits |
| +// computed at At, and the proven job of the same step it retries. |
| +type hostedJobSpec struct { |
| + Step string |
| + Size isolatedjob.Size |
| + Hold HostedCharge |
| + RetryOf string |
| + At time.Time |
| +} |
| + |
| +// newHostedJob records a pending job for a current member's step: at most |
| +// one live job a step, a non-empty hold, a retry only of its own step's |
| +// ended or failed job that holds proof. Audited in the transaction. |
| +func (t *txn) newHostedJob(sp hostedJobSpec) (HostedJob, error) { |
| + if sp.Size.MemoryMiB() == 0 || sp.At.IsZero() || len(sp.Hold.Seconds) == 0 || len(sp.Hold.Micros) == 0 { |
| + return HostedJob{}, fmt.Errorf("%w: hosted job size, time or hold", ErrInvalid) |
| + } |
| + hs, hm, err := sp.Hold.encode() |
| + if err != nil { |
| + return HostedJob{}, err |
| + } |
| + var s stepRecord |
| + if err := t.db.Where("id = ?", sp.Step).First(&s).Error; err != nil { |
| + return HostedJob{}, err |
| + } |
| + var k taskRecord |
| + if err := t.db.Where("id = ?", s.TaskID).First(&k).Error; err != nil { |
| + return HostedJob{}, err |
| + } |
| + if _, err := t.s.authority.Me(t.db, s.Person); err != nil { |
| + return HostedJob{}, err |
| + } |
| + var live int64 |
| + if err := t.db.Model(&HostedJob{}).Where("step_id = ? AND state NOT IN ?", s.ID, []string{HostedJobEnded, HostedJobFailed}).Count(&live).Error; err != nil { |
| + return HostedJob{}, err |
| + } |
| + if live != 0 { |
| + return HostedJob{}, ErrHostedJobLive |
| + } |
| + at := sp.At.UTC() |
| + j := HostedJob{AttemptID: newID("hj_"), StepID: s.ID, StepAttempt: s.Attempt, TaskID: k.ID, Project: k.ProjectID, Person: s.Person, Size: sp.Size, |
| + State: HostedJobPending, AdmittedAt: &at, HoldSecondsJSON: hs, HoldMicrosJSON: hm, RetryOf: sp.RetryOf, Revision: 1} |
| + if sp.RetryOf != "" { |
| + var prior HostedJob |
| + if err := t.db.Where("attempt_id = ?", sp.RetryOf).Limit(1).Find(&prior).Error; err != nil { |
| + return HostedJob{}, err |
| + } |
| + if prior.AttemptID == "" || prior.StepID != s.ID || prior.Live() || !prior.proven() { |
| + return HostedJob{}, fmt.Errorf("%w: hosted retry of %s", ErrInvalid, sp.RetryOf) |
| + } |
| + j.Retries = prior.Retries + 1 |
| + } |
| + if err := t.db.Create(&j).Error; err != nil { |
| + return HostedJob{}, err |
| + } |
| + return j, t.s.authority.Audit(t.db, "system", "hosted.job", j.AttemptID+":"+HostedJobPending) |
| +} |
| + |
| +// moveHostedJob makes one listed move of attempt's job: set writes what |
| +// the move records (the named columns), and an end must hold proof. The |
| +// write is conditional on the state and revision read, and audited. |
| +func (t *txn) moveHostedJob(attempt, to string, set func(*HostedJob) error, cols ...string) error { |
| + var j HostedJob |
| + if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil { |
| + return err |
| + } |
| + from, rev := j.State, j.Revision |
| + ok := false |
| + for _, s := range hostedMoves[from] { |
| + ok = ok || s == to |
| + } |
| + if !ok { |
| + return fmt.Errorf("%w: %s %s to %s", ErrHostedTransition, attempt, from, to) |
| + } |
| + if err := set(&j); err != nil { |
| + return err |
| + } |
| + if to == HostedJobEnded || to == HostedJobFailed { |
| + if err := j.provenErr(); err != nil { |
| + return err |
| + } |
| + } |
| + j.State, j.Revision = to, rev+1 |
| + res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND state = ? AND revision = ?", attempt, from, rev).Select(append(cols, "state", "revision")).Updates(&j) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected != 1 { |
| + return fmt.Errorf("%w: hosted job %s moved", ErrConflict, attempt) |
| + } |
| + return t.s.authority.Audit(t.db, "system", "hosted.job", attempt+":"+from+">"+to) |
| +} |
| + |
| +// hostedLaunching records the instance code's hash before the launch is |
| +// asked for: code is the 32-byte base64url code the VM's payload carries. |
| +func (t *txn) hostedLaunching(attempt, code string, expires time.Time) error { |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(code) |
| + if err != nil || len(raw) != 32 || expires.IsZero() { |
| + return fmt.Errorf("%w: instance code", ErrHostedTransition) |
| + } |
| + return t.moveHostedJob(attempt, HostedJobLaunching, func(j *HostedJob) error { |
| + sum := sha256.Sum256([]byte(code)) |
| + e := expires.UTC() |
| + j.CodeHash, j.CodeExpiresAt = hex.EncodeToString(sum[:]), &e |
| + return nil |
| + }, "code_hash", "code_expires_at") |
| +} |
| + |
| +// hostedEnrolling records the controller's launch view: the VM now waits |
| +// to enrol. |
| +func (t *txn) hostedEnrolling(attempt string, v hostedwire.JobView) error { |
| + if v.AttemptID != attempt || v.LaunchID == "" || len(v.LaunchID) > hostedwire.MaxLaunchIDLen || !v.VMRef.Valid() || v.Epoch < 0 { |
| + return fmt.Errorf("%w: launch view for %s", ErrHostedTransition, attempt) |
| + } |
| + return t.moveHostedJob(attempt, HostedJobEnrolling, func(j *HostedJob) error { |
| + j.LaunchID, j.VMRef, j.Epoch = v.LaunchID, string(v.VMRef), v.Epoch |
| + return nil |
| + }, "launch_id", "vm_ref", "epoch") |
| +} |
| + |
| +// hostedEnrolled binds the job to the runner its VM enrolled as, once the |
| +// enrolment has used the job's code. |
| +func (t *txn) hostedEnrolled(attempt, runnerID, machineKey string) error { |
| + if runnerID == "" || machineKey == "" { |
| + return fmt.Errorf("%w: enrolment of %s", ErrHostedTransition, attempt) |
| + } |
| + return t.moveHostedJob(attempt, HostedJobEnrolled, func(j *HostedJob) error { |
| + if j.CodeUsedAt == nil { |
| + return fmt.Errorf("%w: %s enrolled without its code", ErrHostedTransition, attempt) |
| + } |
| + now := t.now().UTC() |
| + j.RunnerID, j.MachinePublicKey, j.EnrolledAt = runnerID, machineKey, &now |
| + return nil |
| + }, "runner_id", "machine_public_key", "enrolled_at") |
| +} |
| + |
| +// hostedStopping records why a live job stops: its step ended or it |
| +// failed. reason is 1 to 128 printable ASCII characters. |
| +func (t *txn) hostedStopping(attempt, reason string) error { |
| + bad := reason == "" || len(reason) > 128 |
| + for i := 0; i < len(reason); i++ { |
| + bad = bad || reason[i] < 0x20 || reason[i] > 0x7e |
| + } |
| + if bad { |
| + return fmt.Errorf("%w: stop reason", ErrHostedTransition) |
| + } |
| + return t.moveHostedJob(attempt, HostedJobStopping, func(j *HostedJob) error { |
| + j.StopReason = reason |
| + return nil |
| + }, "stop_reason") |
| +} |
| + |
| +// hostedEnd ends a stopping job as ended or failed with p, which must |
| +// hold for it (HostedEndProof.proofFor). |
| +func (t *txn) hostedEnd(attempt, to string, p HostedEndProof) error { |
| + if to != HostedJobEnded && to != HostedJobFailed { |
| + return fmt.Errorf("%w: end as %s", ErrHostedTransition, to) |
| + } |
| + p.ObservedAt = p.ObservedAt.UTC() |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + return err |
| + } |
| + return t.moveHostedJob(attempt, to, func(j *HostedJob) error { |
| + j.StopProofJSON, j.EndedAt = string(raw), &p.ObservedAt |
| + return nil |
| + }, "stop_proof_json", "ended_at") |
| +} |
| + |
| +// settleHostedJob charges an ended or failed job that holds proof what it |
| +// used, once. A job already settled is left as it is: settling again |
| +// changes nothing and reports false. |
| +func (t *txn) settleHostedJob(attempt string, used HostedCharge, at time.Time) (bool, error) { |
| + us, um, err := used.encode() |
| + if err != nil { |
| + return false, err |
| + } |
| + if at.IsZero() { |
| + return false, fmt.Errorf("%w: settlement time", ErrInvalid) |
| + } |
| + var j HostedJob |
| + if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil { |
| + return false, err |
| + } |
| + if j.SettledAt != nil { |
| + return false, nil |
| + } |
| + if j.Live() { |
| + return false, fmt.Errorf("%w: %s is %s", ErrHostedNoProof, attempt, j.State) |
| + } |
| + if err := j.provenErr(); err != nil { |
| + return false, err |
| + } |
| + when := at.UTC() |
| + j.UsedSecondsJSON, j.UsedMicrosJSON, j.SettledAt = us, um, &when |
| + j.Revision++ |
| + res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND revision = ? AND settled_at IS NULL", attempt, j.Revision-1).Select("used_seconds_json", "used_micros_json", "settled_at", "revision").Updates(&j) |
| + if res.Error != nil { |
| + return false, res.Error |
| + } |
| + if res.RowsAffected != 1 { |
| + return false, fmt.Errorf("%w: hosted job %s moved", ErrConflict, attempt) |
| + } |
| + return true, t.s.authority.Audit(t.db, "system", "hosted.job", attempt+":settled") |
| +} |
| + |
| +// hostedJobForRunner is the job runnerID is bound to, whatever its state: |
| +// a hosted runner never joins its person's general pool. A lookup error is |
| +// returned, never read as no job. |
| +func (t *txn) hostedJobForRunner(runnerID string) (HostedJob, bool, error) { |
| + if runnerID == "" { |
| + return HostedJob{}, false, fmt.Errorf("%w: runner ID", ErrInvalid) |
| + } |
| + var rows []HostedJob |
| + if err := t.db.Where("runner_id = ?", runnerID).Limit(2).Find(&rows).Error; err != nil { |
| + return HostedJob{}, false, err |
| + } |
| + switch len(rows) { |
| + case 0: |
| + return HostedJob{}, false, nil |
| + case 1: |
| + return rows[0], true, nil |
| + } |
| + return HostedJob{}, false, fmt.Errorf("%w: runner %s bound to more than one hosted job", ErrInvalid, runnerID) |
| +} |
diff --git a/internal/equipo/chat/hosted_jobs_test.go b/internal/equipo/chat/hosted_jobs_test.go| new file mode 100644 |
| index 00000000..7c46460e |
| --- /dev/null |
| +++ b/internal/equipo/chat/hosted_jobs_test.go |
| @@ -0,0 +1,464 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "os" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// hostedCode is a 32-byte instance code in unpadded base64url. |
| +const hostedCode = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8" |
| + |
| +// hostedRig is a roster rig with task tkh in p1 and an audit log. |
| +func hostedRig(t *testing.T) (*hkRig, *[]string) { |
| + r, _ := rosterRig(t) |
| + r.task("tkh", "Hosted", hkOwner) |
| + audits := new([]string) |
| + r.s.authority.Audit = func(tx *gorm.DB, actor, kind, detail string) error { |
| + if tx == nil { |
| + t.Fatal("audit outside the transaction") |
| + } |
| + *audits = append(*audits, actor+" "+kind+" "+detail) |
| + return nil |
| + } |
| + return r, audits |
| +} |
| + |
| +// hostedStep records checks step id of task tkh, the owner's, attempt 2. |
| +func (r *hkRig) hostedStep(id string) { |
| + r.t.Helper() |
| + r.must(r.s.db.G.Create(&stepRecord{ID: id, TaskID: "tkh", Person: hkOwner, State: "queued", Attempt: 2, Specialist: "checks", Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error) |
| +} |
| + |
| +func hostedHold() HostedCharge { |
| + return HostedCharge{Seconds: map[string]int64{"2026-11-08": 6000}, Micros: map[string]int64{"2026-11": 1_033_334}} |
| +} |
| + |
| +func (r *hkRig) newJob(step, retryOf string) (HostedJob, error) { |
| + var j HostedJob |
| + err := r.tx(func(t *txn) error { |
| + var err error |
| + j, err = t.newHostedJob(hostedJobSpec{Step: step, Size: isolatedjob.SizeSmall, Hold: hostedHold(), RetryOf: retryOf, At: r.now}) |
| + return err |
| + }) |
| + return j, err |
| +} |
| + |
| +func (r *hkRig) job(attempt string) HostedJob { |
| + r.t.Helper() |
| + var j HostedJob |
| + r.must(r.s.db.G.Where("attempt_id = ?", attempt).First(&j).Error) |
| + return j |
| +} |
| + |
| +func (r *hkRig) hosted(fn func(t *txn) error) error { return r.tx(fn) } |
| + |
| +func hostedView(attempt string) hostedwire.JobView { |
| + return hostedwire.JobView{AttemptID: attempt, LaunchID: "launch-1", State: "running", VMRef: "vm-1", Epoch: 3} |
| +} |
| + |
| +func stopProof(attempt string) HostedEndProof { |
| + return HostedEndProof{Stop: &hostedwire.StopProof{AttemptID: attempt, VMRef: "vm-1", State: isolatedjob.StateStopped, ObservedAt: 90 * time.Second}, ObservedAt: time.Date(2026, 11, 8, 12, 40, 0, 0, time.UTC)} |
| +} |
| + |
| +// moveTo makes the one move that reaches to, with valid inputs; the |
| +// proof for ended or failed is never-launched evidence. |
| +func (r *hkRig) moveTo(attempt, to string) error { |
| + return r.hosted(func(t *txn) error { |
| + switch to { |
| + case HostedJobLaunching: |
| + return t.hostedLaunching(attempt, hostedCode, r.now.Add(2*time.Minute)) |
| + case HostedJobEnrolling: |
| + return t.hostedEnrolling(attempt, hostedView(attempt)) |
| + case HostedJobEnrolled: |
| + return t.hostedEnrolled(attempt, "RUNNERH", "machine-key") |
| + case HostedJobStopping: |
| + return t.hostedStopping(attempt, "step_ended") |
| + default: |
| + return t.hostedEnd(attempt, to, HostedEndProof{NeverLaunched: true, ObservedAt: r.now}) |
| + } |
| + }) |
| +} |
| + |
| +// TestHostedJobTransitions: a job makes only the listed moves. From every |
| +// state to every target, a move is taken exactly when the plan lists it; |
| +// a refused move changes nothing. |
| +func TestHostedJobTransitions(t *testing.T) { |
| + r, _ := hostedRig(t) |
| + allowed := map[string]bool{ |
| + "pending>launching": true, "launching>enrolling": true, "enrolling>enrolled": true, "enrolled>stopping": true, "stopping>ended": true, |
| + "pending>stopping": true, "launching>stopping": true, "enrolling>stopping": true, |
| + "stopping>failed": true, |
| + } |
| + states := []string{HostedJobPending, HostedJobLaunching, HostedJobEnrolling, HostedJobEnrolled, HostedJobStopping, HostedJobEnded, HostedJobFailed} |
| + for _, from := range states { |
| + for _, to := range states[1:] { |
| + step := "st-" + from + "-" + to |
| + r.hostedStep(step) |
| + j, err := r.newJob(step, "") |
| + r.must(err) |
| + r.exec("UPDATE hosted_jobs SET state = ?, code_used_at = ? WHERE attempt_id = ?", from, r.now, j.AttemptID) |
| + before := r.job(j.AttemptID) |
| + err = r.moveTo(j.AttemptID, to) |
| + after := r.job(j.AttemptID) |
| + switch { |
| + case allowed[from+">"+to] && (err != nil || after.State != to || after.Revision != before.Revision+1): |
| + t.Errorf("%s -> %s refused: %v (state %s)", from, to, err, after.State) |
| + case !allowed[from+">"+to] && !errors.Is(err, ErrHostedTransition): |
| + t.Errorf("%s -> %s = %v, want ErrHostedTransition", from, to, err) |
| + case !allowed[from+">"+to] && !reflect.DeepEqual(before, after): |
| + t.Errorf("%s -> %s refused but changed the job:\n%+v\n%+v", from, to, before, after) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestHostedJobLifecycle: the whole path records what each move carries, |
| +// keeps only the code's hash, and audits each move in its transaction. |
| +func TestHostedJobLifecycle(t *testing.T) { |
| + r, audits := hostedRig(t) |
| + r.hostedStep("st1") |
| + j, err := r.newJob("st1", "") |
| + r.must(err) |
| + if j.State != HostedJobPending || j.StepID != "st1" || j.StepAttempt != 2 || j.TaskID != "tkh" || j.Project != "p1" || j.Person != hkOwner || j.Size != isolatedjob.SizeSmall || j.Revision != 1 || j.AdmittedAt == nil || !j.AdmittedAt.Equal(r.now) || len(j.AttemptID) > hostedwire.MaxLaunchIDLen { |
| + t.Fatalf("new job: %+v", j) |
| + } |
| + if hold, err := j.Hold(); err != nil || !reflect.DeepEqual(hold, hostedHold()) { |
| + t.Fatalf("hold %+v %v", hold, err) |
| + } |
| + r.must(r.moveTo(j.AttemptID, HostedJobLaunching)) |
| + sum := sha256.Sum256([]byte(hostedCode)) |
| + if got := r.job(j.AttemptID); got.CodeHash != hex.EncodeToString(sum[:]) || got.CodeExpiresAt == nil || r.count("SELECT count(*) FROM hosted_jobs WHERE code_hash LIKE ?", "%"+hostedCode+"%") != 0 { |
| + t.Fatalf("code kept as %q", got.CodeHash) |
| + } |
| + r.must(r.moveTo(j.AttemptID, HostedJobEnrolling)) |
| + if got := r.job(j.AttemptID); got.LaunchID != "launch-1" || got.VMRef != "vm-1" || got.Epoch != 3 { |
| + t.Fatalf("launch not recorded: %+v", got) |
| + } |
| + if err := r.moveTo(j.AttemptID, HostedJobEnrolled); !errors.Is(err, ErrHostedTransition) { |
| + t.Fatalf("enrolled before the code was used: %v", err) |
| + } |
| + r.exec("UPDATE hosted_jobs SET code_used_at = ? WHERE attempt_id = ?", r.now, j.AttemptID) |
| + r.must(r.moveTo(j.AttemptID, HostedJobEnrolled)) |
| + if got := r.job(j.AttemptID); got.RunnerID != "RUNNERH" || got.MachinePublicKey != "machine-key" || got.EnrolledAt == nil { |
| + t.Fatalf("enrolment not recorded: %+v", got) |
| + } |
| + r.must(r.moveTo(j.AttemptID, HostedJobStopping)) |
| + r.must(r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobEnded, stopProof(j.AttemptID)) })) |
| + got := r.job(j.AttemptID) |
| + if got.State != HostedJobEnded || got.StopReason != "step_ended" || got.EndedAt == nil || !got.EndedAt.Equal(stopProof("").ObservedAt) || got.Revision != 6 || !strings.Contains(got.StopProofJSON, `"vm_ref":"vm-1"`) { |
| + t.Fatalf("end not recorded: %+v", got) |
| + } |
| + want := []string{"pending", "pending>launching", "launching>enrolling", "enrolling>enrolled", "enrolled>stopping", "stopping>ended"} |
| + if len(*audits) != len(want) { |
| + t.Fatalf("audits %q", *audits) |
| + } |
| + for i, w := range want { |
| + if (*audits)[i] != "system hosted.job "+j.AttemptID+":"+w { |
| + t.Fatalf("audit %d = %q, want %s", i, (*audits)[i], w) |
| + } |
| + } |
| + r.s.authority.Audit = func(*gorm.DB, string, string, string) error { return errors.New("audit unavailable") } |
| + r.hostedStep("st2") |
| + if _, err := r.newJob("st2", ""); err == nil || r.count("SELECT count(*) FROM hosted_jobs WHERE step_id = 'st2'") != 0 { |
| + t.Fatalf("an unaudited job was kept: %v", err) |
| + } |
| +} |
| + |
| +// TestEndNeedsProof: a job reaches ended or failed only with the |
| +// controller's stop proof for its attempt and VM, or, for a job the |
| +// controller never reported launching, never-launched evidence. |
| +func TestEndNeedsProof(t *testing.T) { |
| + for _, to := range []string{HostedJobEnded, HostedJobFailed} { |
| + r, _ := hostedRig(t) |
| + r.hostedStep("st1") |
| + j, err := r.newJob("st1", "") |
| + r.must(err) |
| + for _, s := range []string{HostedJobLaunching, HostedJobEnrolling, HostedJobStopping} { |
| + r.must(r.moveTo(j.AttemptID, s)) |
| + } |
| + other := stopProof("someone-else") |
| + running := stopProof(j.AttemptID) |
| + running.Stop.State = isolatedjob.StateRunning |
| + wrongVM := stopProof(j.AttemptID) |
| + wrongVM.Stop.VMRef = "vm-2" |
| + noTime := stopProof(j.AttemptID) |
| + noTime.ObservedAt = time.Time{} |
| + both := stopProof(j.AttemptID) |
| + both.NeverLaunched = true |
| + for name, p := range map[string]HostedEndProof{ |
| + "no evidence": {ObservedAt: r.now}, |
| + "never launched, but it launched": {NeverLaunched: true, ObservedAt: r.now}, |
| + "another attempt's proof": other, |
| + "a live VM": running, |
| + "another VM": wrongVM, |
| + "no observation time": noTime, |
| + "proof and never launched": both, |
| + } { |
| + err := r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, to, p) }) |
| + if got := r.job(j.AttemptID); !errors.Is(err, ErrHostedNoProof) || got.State != HostedJobStopping || got.StopProofJSON != "" || got.EndedAt != nil { |
| + t.Fatalf("%s: %s with %s = %v, state %s", to, j.AttemptID, name, err, got.State) |
| + } |
| + } |
| + r.must(r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, to, stopProof(j.AttemptID)) })) |
| + if got := r.job(j.AttemptID); got.State != to || !got.proven() { |
| + t.Fatalf("%s with proof: %+v", to, got) |
| + } |
| + // A job the controller never reported launching ends on its |
| + // not-found answer. |
| + r.hostedStep("st2") |
| + k, err := r.newJob("st2", "") |
| + r.must(err) |
| + r.must(r.moveTo(k.AttemptID, HostedJobStopping)) |
| + r.must(r.hosted(func(t *txn) error { |
| + return t.hostedEnd(k.AttemptID, to, HostedEndProof{NeverLaunched: true, ObservedAt: r.now}) |
| + })) |
| + if got := r.job(k.AttemptID); got.State != to { |
| + t.Fatalf("never launched: %+v", got) |
| + } |
| + } |
| +} |
| + |
| +// TestOneLiveJobPerStep: a step has at most one live job, refused by the |
| +// store and by the table itself; a retry follows only its own step's |
| +// proven predecessor. |
| +func TestOneLiveJobPerStep(t *testing.T) { |
| + r, _ := hostedRig(t) |
| + r.hostedStep("st1") |
| + r.hostedStep("st2") |
| + first, err := r.newJob("st1", "") |
| + r.must(err) |
| + if _, err := r.newJob("st1", ""); !errors.Is(err, ErrHostedJobLive) { |
| + t.Fatalf("second live job: %v", err) |
| + } |
| + if err := r.s.db.G.Exec("INSERT INTO hosted_jobs(attempt_id, step_id, state) VALUES ('raw', 'st1', 'enrolled')").Error; err == nil { |
| + t.Fatal("the table took a second live job for st1") |
| + } |
| + other, err := r.newJob("st2", "") |
| + r.must(err) |
| + if _, err := r.newJob("st1", first.AttemptID); !errors.Is(err, ErrHostedJobLive) { |
| + t.Fatalf("a retry of a live job: %v", err) |
| + } |
| + r.must(r.moveTo(first.AttemptID, HostedJobStopping)) |
| + if _, err := r.newJob("st1", ""); !errors.Is(err, ErrHostedJobLive) { |
| + t.Fatalf("a new job while the first is stopping: %v", err) |
| + } |
| + r.must(r.moveTo(first.AttemptID, HostedJobFailed)) |
| + for name, retryOf := range map[string]string{"another step's job": other.AttemptID, "an unknown job": "nope"} { |
| + if _, err := r.newJob("st1", retryOf); !errors.Is(err, ErrInvalid) { |
| + t.Fatalf("retry of %s: %v", name, err) |
| + } |
| + } |
| + retry, err := r.newJob("st1", first.AttemptID) |
| + r.must(err) |
| + if retry.RetryOf != first.AttemptID || retry.Retries != 1 || retry.AttemptID == first.AttemptID { |
| + t.Fatalf("retry %+v", retry) |
| + } |
| + r.hostedStep("st4") |
| + unproven, err := r.newJob("st4", "") |
| + r.must(err) |
| + r.exec("UPDATE hosted_jobs SET state = 'failed' WHERE attempt_id = ?", unproven.AttemptID) |
| + if _, err := r.newJob("st4", unproven.AttemptID); !errors.Is(err, ErrInvalid) { |
| + t.Fatalf("a retry of a job with no proof: %v", err) |
| + } |
| + if _, err := r.newJob("missing", ""); err == nil { |
| + t.Fatal("a job for no step") |
| + } |
| + r.exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner) |
| + r.hostedStep("st3") |
| + if _, err := r.newJob("st3", ""); !errors.Is(err, ErrForbidden) { |
| + t.Fatalf("a job for a removed person: %v", err) |
| + } |
| +} |
| + |
| +// TestHostedJobForRunner: a runner is bound to at most one job, which it |
| +// keeps after the job ends; an unbound runner has none. |
| +func TestHostedJobForRunner(t *testing.T) { |
| + r, _ := hostedRig(t) |
| + r.hostedStep("st1") |
| + r.hostedStep("st2") |
| + j, err := r.newJob("st1", "") |
| + r.must(err) |
| + k, err := r.newJob("st2", "") |
| + r.must(err) |
| + r.exec("UPDATE hosted_jobs SET state = 'enrolling', code_used_at = ?", r.now) |
| + r.must(r.moveTo(j.AttemptID, HostedJobEnrolled)) |
| + if err := r.moveTo(k.AttemptID, HostedJobEnrolled); err == nil { |
| + t.Fatal("a runner bound to two jobs") |
| + } |
| + r.must(r.moveTo(j.AttemptID, HostedJobStopping)) |
| + if err := r.moveTo(j.AttemptID, HostedJobEnded); !errors.Is(err, ErrHostedNoProof) { |
| + t.Fatalf("an enrolled job ended as never launched: %v", err) |
| + } |
| + r.must(r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobEnded, stopProof(j.AttemptID)) })) |
| + var got HostedJob |
| + var found bool |
| + r.must(r.hosted(func(t *txn) (err error) { got, found, err = t.hostedJobForRunner("RUNNERH"); return })) |
| + if !found || got.AttemptID != j.AttemptID || got.State != HostedJobEnded { |
| + t.Fatalf("bound job %+v %t", got, found) |
| + } |
| + r.must(r.hosted(func(t *txn) (err error) { got, found, err = t.hostedJobForRunner("RUNNER1"); return })) |
| + if found { |
| + t.Fatalf("an unbound runner has %+v", got) |
| + } |
| + if err := r.hosted(func(t *txn) (err error) { _, found, err = t.hostedJobForRunner(""); return }); found || err == nil { |
| + t.Fatalf("an empty runner ID: %t %v", found, err) |
| + } |
| +} |
| + |
| +// TestSettleIdempotent: a job settles once, after its proof; settling |
| +// again changes nothing, whatever it carries. |
| +func TestSettleIdempotent(t *testing.T) { |
| + r, audits := hostedRig(t) |
| + r.hostedStep("st1") |
| + j, err := r.newJob("st1", "") |
| + r.must(err) |
| + used := HostedCharge{Seconds: map[string]int64{"2026-11-08": 600}, Micros: map[string]int64{"2026-11": 103_334}} |
| + settle := func(c HostedCharge, at time.Time) (bool, error) { |
| + var did bool |
| + err := r.hosted(func(t *txn) (err error) { did, err = t.settleHostedJob(j.AttemptID, c, at); return }) |
| + return did, err |
| + } |
| + if _, err := settle(used, r.now); !errors.Is(err, ErrHostedNoProof) { |
| + t.Fatalf("settled a live job: %v", err) |
| + } |
| + r.must(r.moveTo(j.AttemptID, HostedJobStopping)) |
| + if _, err := settle(used, r.now); !errors.Is(err, ErrHostedNoProof) { |
| + t.Fatalf("settled without proof: %v", err) |
| + } |
| + r.must(r.moveTo(j.AttemptID, HostedJobFailed)) |
| + for name, c := range map[string]HostedCharge{ |
| + "a day that is not a day": {Seconds: map[string]int64{"2026-11-8": 1}}, |
| + "a month in days": {Seconds: map[string]int64{"2026-11": 1}}, |
| + "a day in months": {Micros: map[string]int64{"2026-11-08": 1}}, |
| + "a negative amount": {Seconds: map[string]int64{"2026-11-08": -1}}, |
| + } { |
| + if _, err := settle(c, r.now); !errors.Is(err, ErrInvalid) { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + if did, err := settle(used, r.now); !did || err != nil { |
| + t.Fatalf("first settle: %t %v", did, err) |
| + } |
| + once := r.job(j.AttemptID) |
| + if got, err := once.Used(); err != nil || !reflect.DeepEqual(got, used) || once.SettledAt == nil || !once.SettledAt.Equal(r.now) { |
| + t.Fatalf("settled %+v %v (%+v)", got, err, once) |
| + } |
| + if hold, err := once.Hold(); err != nil || !reflect.DeepEqual(hold, hostedHold()) { |
| + t.Fatalf("settling changed the hold: %+v %v", hold, err) |
| + } |
| + n := len(*audits) |
| + more := HostedCharge{Seconds: map[string]int64{"2026-11-09": 9000}, Micros: map[string]int64{"2026-12": 9}} |
| + if did, err := settle(more, r.now.Add(time.Hour)); did || err != nil { |
| + t.Fatalf("second settle: %t %v", did, err) |
| + } |
| + if twice := r.job(j.AttemptID); !reflect.DeepEqual(once, twice) || len(*audits) != n { |
| + t.Fatalf("settling twice changed the job:\n%+v\n%+v", once, twice) |
| + } |
| +} |
| + |
| +// TestMigrationAdditive: from the hosted slice 2 migrations on, each one |
| +// only adds. Every table, column and index before it is still there, |
| +// unchanged, after it; 0126 adds exactly hosted_jobs and |
| +// hosted_challenges, and its live-job index keeps one live job a step. |
| +// The migrations are internal/equipo's (its Schema), read from disk. |
| +func TestMigrationAdditive(t *testing.T) { |
| + ctx := context.Background() |
| + schema, err := migrate.FromFS(os.DirFS(".."), "equipo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + all := schema.All() |
| + first := -1 |
| + for i, m := range all { |
| + if m.ID == "equipo/0125_hosted_checks_setting" { |
| + first = i |
| + } |
| + } |
| + d, err := migrate.Replay(ctx, all[:max(first, 0)]) |
| + if first < 0 || err != nil { |
| + t.Fatal("no 0125_hosted_checks_setting, or", err) |
| + } |
| + defer d.Close() |
| + sawJobs := false |
| + for _, m := range all[first:] { |
| + before, err := migrate.Read(ctx, d) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.ExecContext(ctx, m.SQL); err != nil { |
| + t.Fatalf("%s: %v", m.ID, err) |
| + } |
| + after, err := migrate.Read(ctx, d) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // now is each table after m, cut to the columns and indexes the |
| + // table had before m; added are the tables m created. |
| + now, old, added := map[string]migrate.Table{}, map[string]bool{}, []string{} |
| + for _, tb := range before.Tables { |
| + old[tb.Name] = true |
| + } |
| + for _, tb := range after.Tables { |
| + now[tb.Name] = tb |
| + if !old[tb.Name] { |
| + added = append(added, tb.Name) |
| + } |
| + } |
| + for _, tb := range before.Tables { |
| + had := map[string]bool{} |
| + for _, c := range tb.Columns { |
| + had["c:"+c.Name] = true |
| + } |
| + for _, x := range tb.Indexes { |
| + had["i:"+x.Name] = true |
| + } |
| + cut := migrate.Table{Name: now[tb.Name].Name} |
| + for _, c := range now[tb.Name].Columns { |
| + if had["c:"+c.Name] { |
| + cut.Columns = append(cut.Columns, c) |
| + } |
| + } |
| + for _, x := range now[tb.Name].Indexes { |
| + if had["i:"+x.Name] { |
| + cut.Indexes = append(cut.Indexes, x) |
| + } |
| + } |
| + if !reflect.DeepEqual(tb, cut) { |
| + t.Errorf("%s changed %s:\n%+v\n%+v", m.ID, tb.Name, tb, cut) |
| + } |
| + } |
| + if m.ID != "equipo/0126_hosted_jobs" { |
| + continue |
| + } |
| + sawJobs = true |
| + if strings.Join(added, " ") != "hosted_challenges hosted_jobs" { |
| + t.Fatalf("0126 added %v", added) |
| + } |
| + if _, err := d.ExecContext(ctx, "INSERT INTO hosted_jobs(attempt_id, step_id, state) VALUES ('a1', 's1', 'ended'), ('a2', 's1', 'failed'), ('a3', 's1', 'pending')"); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, state := range []string{"launching", "enrolling", "enrolled", "stopping"} { |
| + if _, err := d.ExecContext(ctx, "INSERT INTO hosted_jobs(attempt_id, step_id, state) VALUES ('b', 's1', ?)", state); err == nil { |
| + t.Fatalf("a second live job (%s) for one step", state) |
| + } |
| + } |
| + if _, err := d.ExecContext(ctx, "INSERT INTO hosted_jobs(attempt_id, step_id, state, runner_id) VALUES ('c1', 's2', 'ended', 'r1'), ('c2', 's3', 'pending', 'r1')"); err == nil { |
| + t.Fatal("one runner bound to two jobs") |
| + } |
| + } |
| + if !sawJobs { |
| + t.Fatal("no 0126_hosted_jobs") |
| + } |
| +} |
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go| index 5694bdd2..b970b156 100644 |
| --- a/internal/equipo/chat/models.go |
| +++ b/internal/equipo/chat/models.go |
| @@ -11,7 +11,7 @@ import ( |
| ) |
| // Models are the tables this package owns, for the migration check. |
| -var Models = append([]any{&changeDiffRecord{}, ¬ificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &instancePrefixRecord{}, &instanceAddressRecord{}, &instanceInventoryCardRecord{}, &webSearchUsageRecord{}, &lookupRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &stepRenderRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &abilitiesRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &specialistTurnRecord{}, &carriedRecord{}, &zoneRecord{}, &placeRecord{}, &projectPlaceRecord{}}, push.Models...) |
| +var Models = append([]any{&changeDiffRecord{}, ¬ificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &instancePrefixRecord{}, &instanceAddressRecord{}, &instanceInventoryCardRecord{}, &webSearchUsageRecord{}, &lookupRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &stepRenderRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &abilitiesRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &specialistTurnRecord{}, &carriedRecord{}, &zoneRecord{}, &placeRecord{}, &projectPlaceRecord{}, &HostedJob{}, &hostedChallengeRecord{}}, push.Models...) |
| type turnRecord struct { |
| CreateRepo string |
diff --git a/internal/equipo/migrations/0126_hosted_jobs.sql b/internal/equipo/migrations/0126_hosted_jobs.sql| new file mode 100644 |
| index 00000000..b35488af |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0126_hosted_jobs.sql |
| @@ -0,0 +1,14 @@ |
| +-- Hosted runners slice 2 (Task 19): one row per hosted VM attempt for a |
| +-- checks step, and the hosted runners' renewal challenges. New tables |
| +-- only; no existing row changes. The instance code and the challenge |
| +-- nonce are kept as SHA-256 hashes, never as text. Holds and usage are |
| +-- JSON: seconds per UTC day, USD micros per UTC month. |
| +CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, state text, launch_id text, vm_ref text, epoch integer, cert_digest text, cert_valid numeric, cert_checked_at datetime, code_hash text, code_expires_at datetime, code_used_at datetime, runner_id text, machine_public_key text, admitted_at datetime, enrolled_at datetime, ended_at datetime, hold_seconds_json text, hold_micros_json text, used_seconds_json text, used_micros_json text, settled_at datetime, stop_reason text, stop_proof_json text, retry_of text, retries integer, revision integer, PRIMARY KEY (attempt_id)); |
| +-- At most one live job a step; a runner is bound to one job; a code |
| +-- names one job. |
| +CREATE UNIQUE INDEX hosted_jobs_live_step ON hosted_jobs(step_id) WHERE state <> 'ended' AND state <> 'failed'; |
| +CREATE UNIQUE INDEX hosted_jobs_runner ON hosted_jobs(runner_id) WHERE runner_id <> ''; |
| +CREATE UNIQUE INDEX hosted_jobs_code ON hosted_jobs(code_hash) WHERE code_hash <> ''; |
| +CREATE INDEX hosted_jobs_person ON hosted_jobs(person, state); |
| +CREATE TABLE hosted_challenges (runner_id text, nonce_hash text, expires_at datetime, used_at datetime, PRIMARY KEY (nonce_hash)); |
| +CREATE INDEX hosted_challenges_runner ON hosted_challenges(runner_id); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 429487fc..d9baa97c 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -923,3 +923,18 @@ CREATE TABLE chat_step_renders (step_id text, attempt integer, renders text NOT |
| ALTER TABLE chat_projects ADD COLUMN hosted_checks numeric; |
| ALTER TABLE chat_projects ADD COLUMN hosted_checks_owner text; |
| ALTER TABLE chat_projects ADD COLUMN hosted_checks_revision integer; |
| + |
| +-- Hosted runners slice 2 (Task 19): one row per hosted VM attempt for a |
| +-- checks step, and the hosted runners' renewal challenges. New tables |
| +-- only; no existing row changes. The instance code and the challenge |
| +-- nonce are kept as SHA-256 hashes, never as text. Holds and usage are |
| +-- JSON: seconds per UTC day, USD micros per UTC month. |
| +CREATE TABLE hosted_jobs (attempt_id text, step_id text, step_attempt integer, task_id text, project text, person text, size text, state text, launch_id text, vm_ref text, epoch integer, cert_digest text, cert_valid numeric, cert_checked_at datetime, code_hash text, code_expires_at datetime, code_used_at datetime, runner_id text, machine_public_key text, admitted_at datetime, enrolled_at datetime, ended_at datetime, hold_seconds_json text, hold_micros_json text, used_seconds_json text, used_micros_json text, settled_at datetime, stop_reason text, stop_proof_json text, retry_of text, retries integer, revision integer, PRIMARY KEY (attempt_id)); |
| +-- At most one live job a step; a runner is bound to one job; a code |
| +-- names one job. |
| +CREATE UNIQUE INDEX hosted_jobs_live_step ON hosted_jobs(step_id) WHERE state <> 'ended' AND state <> 'failed'; |
| +CREATE UNIQUE INDEX hosted_jobs_runner ON hosted_jobs(runner_id) WHERE runner_id <> ''; |
| +CREATE UNIQUE INDEX hosted_jobs_code ON hosted_jobs(code_hash) WHERE code_hash <> ''; |
| +CREATE INDEX hosted_jobs_person ON hosted_jobs(person, state); |
| +CREATE TABLE hosted_challenges (runner_id text, nonce_hash text, expires_at datetime, used_at datetime, PRIMARY KEY (nonce_hash)); |
| +CREATE INDEX hosted_challenges_runner ON hosted_challenges(runner_id); |