oficina / equipo Public

equipo: per-person hosted limits, held then settled

Migration 0127 adds hosted_limits (a person's limits as an owner set
them, at a revision) and hosted_admit_locks, new tables only.
hostedAdmit writes the person's lock row first, so its counts and the
caller's job insert hold the write. It counts every job not ended or
failed as running, a settled job's usage and any other job's hold, and
refuses running, daily or monthly. Any read error denies with the
error. A hold is the whole window (launch window plus lifetime) against
each UTC day and month it touches, at 4x the baseline rate.
hostedSettle replaces it, once and only with proof, with the span from
admission to proof, allocated per day and month, still at 4x.
SetHostedLimits: owner only, roster and revision in the transaction,
audited there; no row means the defaults. Budget record raised for
internal/equipo/chat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 09fb1f096999a29d97e541d2b60fe62d4bd5cfc1 parent f8df06a
7 files changed, +826 −2
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +47 −0
  • internal/equipo/chat/hosted_limits.go +285 −0
  • internal/equipo/chat/hosted_limits_test.go +475 −0
  • internal/equipo/chat/models.go +1 −1
  • internal/equipo/migrations/0127_hosted_limits.sql +8 −0
  • internal/equipo/migrations/schema.sql +9 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index b8c0ea64..acc5e8d1 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 45728 19739 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.
+size internal/equipo/chat 46013 20214 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.
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 5b80d13c..82b71be2 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -1476,3 +1476,50 @@ Mutations (exact-string replace in `internal/equipo/chat/hosted_jobs.go` from a
- **257** creation audit outside the transaction. `-run TestHostedJobLifecycle`: exit 1, `hosted_jobs_test.go:158: audit outside the move's transaction`. Restored.
For Task 21: the dispatcher builds `HostedNeverLaunched` only from a verified controller answer: Get's not-found as `absent`, and an `abandoned` view with no VM Ref as `abandoned`. It never builds one from a refusal (`ErrForbidden`) or a transport error. It moves a job to launching before calling Launch and records `hostedLaunchReturned` (or the view) once the call returns.
+
+## Task 20
+
+Per-person hosted limits, held then settled (S2-9 as ruled: 2 running VMs, 8 VM-hours a UTC day, $50 a UTC month per person; window = `HostedLaunchWindow` + lifetime; holds and settlements at 4x the Large or Small baseline, compute only; a job without stop proof keeps its hold). Migration `0127_hosted_limits.sql` (the next free after 0126; new tables only; `schema.sql` appended): `hosted_limits` (`person` primary key, `running`, `daily_seconds`, `monthly_micros`, `owner`, `revision`, `updated_at`) and `hosted_admit_locks` (`person` primary key, `admissions`). Both records are in `Models`.
+
+`internal/equipo/chat/hosted_limits.go`:
+- The brief's `HostedLimits`, `DefaultHostedLimits`, `RateSmallMicrosPerHour`/`RateLargeMicrosPerHour` (155,000 / 310,000), `BurstHoldFactor` (4), `HostedLaunchWindow` (10 min), `HostedChecksLifetime` (90 min), and the reasons `running`, `daily`, `monthly` (`HostedLimitRunning` and the rest).
+- `Allocate(from, to)`: `[from, to)` widened to whole seconds, split at UTC midnights into seconds per day and per month.
+- `hostedHoldFor(size, lifetime, now)`: the hold `newHostedJob` records. The whole window in seconds against each UTC day `[now, now+window]` touches, and `ceil(window × rate × 4 / 3600)` micros against each UTC month it touches. A Large checks hold is 6,000 s and 2,066,667 micros ($2.07); Small 1,033,334, matching Task 19's fixture. Unknown size, a lifetime of zero or over 24 h, or a zero time: `ErrInvalid`. (The test file already had a `hostedHold()` fixture, hence the name.)
+- `(t *txn) hostedAdmit(person, size, lifetime, now)`: validates, then writes the person's `hosted_admit_locks` row first (an upsert). The transaction holds the write through its reads and the caller's insert of the job. On SQLite, every transaction already runs on the one writer connection. The person must pass `authority.Me`. Limits come from the person's row, or the defaults when there is none. One read of the person's jobs (`settled_at IS NULL OR ended_at >= ` the start of now's UTC month) gives both numbers. Running counts every job not `ended` or `failed`. A settled job counts its `used_*` and any other job its `hold_*`. Refused `running`, then `daily` (any touched day over), then `monthly`. Any read error (roster, limits, jobs, an unreadable hold) returns `ok=false` with the error and no reason.
+- `(t *txn) hostedSettle(attempt)`: the settlement for an ended or failed job. `Allocate(admitted_at, ended_at)` seconds per day, and each month's seconds × rate × 4 (rounded up), passed to Task 19's `settleHostedJob`, which checks proof and settles once. `ended_at` is `HostedEndProof.ObservedAt`, when the instance received the proof. A live job, or one with no `ended_at`: `ErrHostedNoProof`. An end before admission: `ErrInvalid`. Either way the hold stays.
+- `(t *txn) hostedLimits(person)`: limits and revision (the defaults at 0). A read error is returned, never read as the defaults.
+- `(s *Store) SetHostedLimits(ctx, owner, person, l, revision)`: `CurrentPerson`, then `isOwner(owner)` and `Me(person)` in the transaction (lookup errors deny). Bounds: 0 to 1,000 running, 0 to 1,000 days of seconds, 0 to $1M. The write names the revision (0 for no row; `ErrCardConflict` otherwise, as Task 18). It is conditional on that revision, and audited `<owner> hosted.limits <person>/revision:N/running:R/daily_seconds:D/monthly_micros:M` in the same transaction.
+
+Red: `CGO_ENABLED=0 go test ./internal/equipo/chat -run 'TestLimits|TestHoldSpans|TestDelayedLaunch|TestSettleStays|TestNoProofKeepsHold|TestLimitCount|TestOwnerRaises' -count=1`: build failed (`t.hostedAdmit undefined`, `undefined: HostedChecksLifetime`, `undefined: hostedHoldFor`, `t.hostedSettle undefined`, `undefined: HostedLimits`, `undefined: hostedLimitRecord`, `undefined: DefaultHostedLimits`, `undefined: HostedLaunchWindow`).
+
+Tests (`hosted_limits_test.go`):
+- `TestLimitsHoldAndSettle`: the Large and Small holds; a third job is refused `running` while two are pending, and again while one is enrolling. A 40-minute Large job settles to 2,400 s and 826,667 micros, and its hold columns are untouched. A second settle changes nothing. The slot is then free.
+- `TestLimitsRace`: 20 goroutines, one slot. Exactly one is admitted, 19 are refused `running`, and there is one job row.
+- `TestHoldSpansMidnight`: admitted at 23:00, it holds 6,000 s on both days. With a 6,000 s daily limit a job on the second day is refused `daily`. Settling at 23:20 (1,200 s on day one) frees it, and the new hold names only the second day.
+- `TestDelayedLaunchReadmitted`: admitted at 23:55, launch-by 00:05, the launch returned, then stopping. Readmission of the same step (retry of the job) is refused `running`. Abandoned evidence observed at 00:06 is refused (`ErrHostedNoProof`). At 00:07 it is accepted and the job is failed. While unsettled, readmission is refused `daily`. Settled (300 s and 420 s, 248,000 micros), it is readmitted with a hold on the new day only.
+- `TestSettleStaysConservative`: 10 minutes settles to 206,667 micros Large and 103,334 Small.
+- `TestHoldSpansMonthEnd`: `Allocate` across the month end and for an empty span. A 23:00 hold on 30 November counts in full against November and December. A second December job fits, a third is refused `monthly`, and settling the first before midnight frees it.
+- `TestNoProofKeepsHold`: a stopping job with the wrong attempt's proof cannot end or settle, and keeps its hold (`daily`). Marked failed by hand with no proof, it still cannot settle, records no usage and keeps its hold.
+- `TestLimitCountErrorDenies`: admission's own answer with the jobs table, the limits table or the roster table renamed away, the person removed, or a hold that cannot be read: `ok=false`, no reason, an error. Bad size and lifetimes: `ErrInvalid`.
+- `TestOwnerRaisesLimit`: the defaults at revision 0 when there is no row, applied as two running. Refused cases: a member, a person not on the roster, out-of-range limits, a stale revision, the roster unavailable, a failing audit. None of them takes effect. An owner raises the limit to three: revision 1, one exact audit line and one audit row from inside the transaction, and the third job is admitted. A second write at revision 0 is a conflict. A removed owner is refused.
+
+Green: the same command, ok (9 tests). The whole chat package once: ok (25.2 s). `./internal/equipo -run 'Migration|Schema'`: ok. `TestMigrationAdditive` (covers 0127 as additive): ok. `make migration-check budget build vet`: exit 0 after raising the chat record to 46013/20214 with the reason. gofmt and `git diff --check`: clean.
+
+Mutations (exact-string replace in `internal/equipo/chat/hosted_limits.go` from a script under `mktemp -d`, one at a time, `CGO_ENABLED=0 go test ./internal/equipo/chat -run '<test>' -count=1`, restored from a copy and compared with `filecmp`: identical each time):
+- **258** (the brief's) count only `enrolled` jobs: `if j.Live() {` became `if j.State == HostedJobEnrolled {`. `-run 'TestLimitsHoldAndSettle|TestLimitsRace'`: exit 1, `hosted_limits_test.go:118: admission of st-c at 2026-11-08 12:10:00 +0000 UTC: hj_... "" <nil>, want refused "running"` and `hosted_limits_test.go:189: admitted 4, refused 0, jobs 4`. Restored.
+- **259** (the brief's) hold at the baseline rate: in `hostedHoldFor`, `hostedMicros(seconds, rate)` became `(seconds*rate + 3599) / 3600`. `-run 'TestLimitsHoldAndSettle|TestHoldSpansMonthEnd'`: exit 1, `hosted_limits_test.go:114: Large hold: {... Micros:map[2026-11:516667]} <nil>, want ... map[2026-11:2066667]`. Restored.
+- **260** (the brief's) a count error as zero: the jobs read's `return false, "", err` became `rows = nil`. `-run TestLimitCountErrorDenies`: exit 1, `hosted_limits_test.go:337: count: admission true "" <nil>, want denied with the error`. The first run of this mutation exited 0, because the test's helper also inserted the job, and that failed on the same renamed table. The test now reads admission's own answer. Restored.
+- **261** settle at the baseline: in `hostedSettle`, `hostedMicros(s, rate)` became `(s*rate + 3599) / 3600`. `-run TestSettleStaysConservative`: exit 1, `hosted_limits_test.go:264: Large, 10 minutes: {... Micros:map[2026-11:51667]} <nil>, want ... map[2026-11:206667]`. Restored.
+- **262** a settled job counts its hold: `if j.SettledAt != nil {` became `if false && j.SettledAt != nil {`. `-run TestHoldSpansMidnight`: exit 1, `hosted_limits_test.go:205: admit st-c at 2026-11-09 00:50:00 +0000 UTC: "daily" <nil>`. Restored.
+- **263** hold only the first day: `d = d.AddDate(0, 0, 1)` became `d = d.AddDate(0, 0, 400)`. Same: exit 1, `hosted_limits_test.go:200: hold across midnight: {Seconds:map[2026-11-08:6000] ...}, want map[2026-11-08:6000 2026-11-09:6000] ...`. Restored. (A first spelling of this mutation did not compile and was not counted.)
+- **264** limits read error as the defaults: `return HostedLimits{}, 0, err` became `return DefaultHostedLimits, 0, nil`. `-run TestLimitCountErrorDenies`: exit 1, `hosted_limits_test.go:340: limits: admission true "" <nil>, want denied with the error`. Restored.
+- **265** no roster check in admission (`false &&` before `err != nil` after `Me`). Same: exit 1, `hosted_limits_test.go:343: roster: admission true "" <nil>, want denied with the error`. Restored.
+- **266** an unreadable hold ignored (`false &&` on the charge decode error). Same: exit 1, `hosted_limits_test.go:349: hold: admission true "" <nil>, want denied with the error`. Restored.
+- **267** no revision check in `SetHostedLimits`. `-run TestOwnerRaisesLimit`: exit 1, `hosted_limits_test.go:469: a second write at revision 0: duplicated key not allowed`. Restored.
+- **268** no owner check in `SetHostedLimits`. Same: exit 1, `hosted_limits_test.go:427: a member set limits: <nil>`. Restored.
+- **269** daily limit not checked. `-run 'TestHoldSpansMidnight|TestNoProofKeepsHold|TestDelayedLaunchReadmitted'`: exit 1, `hosted_limits_test.go:201: ... want refused "daily"`, `:239: readmitted before settling: "" <nil>`, `:304: ... want refused "daily"`. Restored.
+- **270** monthly limit not checked. `-run TestHoldSpansMonthEnd`: exit 1, `hosted_limits_test.go:285: admission of st-c at 2026-12-01 03:00:00 +0000 UTC: hj_... "" <nil>, want refused "monthly"`. Restored.
+
+Not mutation-checked: the `hosted_admit_locks` write. On SQLite every transaction runs on rastrillo's single writer connection (`SetMaxOpenConns(1)`), so admissions are already serial, and `TestLimitsRace` passes with or without the row. The row keeps the counts and the insert atomic if the store ever gets more than one writer.
+
+For Task 21: call `hostedAdmit`, then `newHostedJob` with `hostedHoldFor(size, lifetime, now)` and `At: now`, in the same transaction. On an error the step keeps waiting. Settle with `hostedSettle(attempt)` once the job has ended or failed with proof.
diff --git a/internal/equipo/chat/hosted_limits.go b/internal/equipo/chat/hosted_limits.go
new file mode 100644
index 00000000..547ffe11
--- /dev/null
+++ b/internal/equipo/chat/hosted_limits.go
@@ -0,0 +1,285 @@
+package chat
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// HostedLimits is one person's hosted VM limits (decision S2-9): jobs
+// running at once, VM seconds a UTC day and USD micros a UTC month.
+type HostedLimits struct {
+ Running int
+ DailySeconds int64
+ MonthlyMicros int64 // USD micros
+}
+
+// DefaultHostedLimits apply to a person no owner has set limits for.
+var DefaultHostedLimits = HostedLimits{Running: 2, DailySeconds: 8 * 3600, MonthlyMicros: 50_000_000}
+
+// The baseline compute rates (spec §10, eu-west-1 x86_64). Holds and
+// settlements count BurstHoldFactor times them, because AWS bills burst
+// up to four times the baseline and does not report it.
+const RateSmallMicrosPerHour, RateLargeMicrosPerHour = 155_000, 310_000
+
+const BurstHoldFactor = 4
+
+// HostedLaunchWindow is how long a job has to launch after admission; a
+// job's hold window is this plus its lifetime.
+const HostedLaunchWindow = 10 * time.Minute
+
+// HostedChecksLifetime is a checks VM's lifetime; slice 4 adds its own.
+const HostedChecksLifetime = 90 * time.Minute
+
+// The refusal reasons hostedAdmit gives.
+const (
+ HostedLimitRunning = "running"
+ HostedLimitDaily = "daily"
+ HostedLimitMonthly = "monthly"
+)
+
+// hostedMaxLifetime bounds the lifetime admission accepts, and
+// hostedMaxLimits what an owner may set, so no sum can overflow.
+const hostedMaxLifetime = 24 * time.Hour
+
+var hostedMaxLimits = HostedLimits{Running: 1000, DailySeconds: 1000 * 86400, MonthlyMicros: 1_000_000_000_000}
+
+// hostedLimitRecord is a person's limits as an owner set them, at a
+// revision a write must name. A person with no row has the defaults.
+type hostedLimitRecord struct {
+ Person string `gorm:"primaryKey"`
+ Running int64
+ DailySeconds int64
+ MonthlyMicros int64
+ Owner string
+ Revision int64
+ UpdatedAt time.Time
+}
+
+func (hostedLimitRecord) TableName() string { return "hosted_limits" }
+
+// hostedAdmitLock is written first by every admission for the person, so
+// the admission holds the write for its counts and its job's insert.
+type hostedAdmitLock struct {
+ Person string `gorm:"primaryKey"`
+ Admissions int64
+}
+
+func (hostedAdmitLock) TableName() string { return "hosted_admit_locks" }
+
+func hostedRate(size isolatedjob.Size) (int64, error) {
+ switch size {
+ case isolatedjob.SizeSmall:
+ return RateSmallMicrosPerHour, nil
+ case isolatedjob.SizeLarge:
+ return RateLargeMicrosPerHour, nil
+ }
+ return 0, fmt.Errorf("%w: hosted size %q", ErrInvalid, size)
+}
+
+// hostedMicros is seconds of a VM at rate, times BurstHoldFactor, rounded
+// up to a whole micro.
+func hostedMicros(seconds, rate int64) int64 {
+ return (seconds*rate*BurstHoldFactor + 3599) / 3600
+}
+
+// Allocate splits [from, to), widened to whole seconds, into seconds per
+// UTC day ("2006-01-02") and per UTC month ("2006-01"). An empty span has
+// none.
+func Allocate(from, to time.Time) (days map[string]int64, months map[string]int64) {
+ days, months = map[string]int64{}, map[string]int64{}
+ from, to = from.UTC().Truncate(time.Second), to.UTC()
+ if t := to.Truncate(time.Second); t.Before(to) {
+ to = t.Add(time.Second)
+ }
+ for at := from; at.Before(to); {
+ next := time.Date(at.Year(), at.Month(), at.Day()+1, 0, 0, 0, 0, time.UTC)
+ if next.After(to) {
+ next = to
+ }
+ s := int64(next.Sub(at) / time.Second)
+ days[at.Format(time.DateOnly)] += s
+ months[at.Format("2006-01")] += s
+ at = next
+ }
+ return days, months
+}
+
+// hostedHoldFor is what admission at now holds for a job of size and
+// lifetime: with window = HostedLaunchWindow + lifetime, the whole window
+// in seconds against each UTC day [now, now+window] touches, and its cost
+// at BurstHoldFactor times the rate against each UTC month it touches.
+func hostedHoldFor(size isolatedjob.Size, lifetime time.Duration, now time.Time) (HostedCharge, error) {
+ rate, err := hostedRate(size)
+ if err != nil {
+ return HostedCharge{}, err
+ }
+ if lifetime <= 0 || lifetime > hostedMaxLifetime || now.IsZero() {
+ return HostedCharge{}, fmt.Errorf("%w: hosted lifetime or time", ErrInvalid)
+ }
+ window := HostedLaunchWindow + lifetime
+ seconds := int64((window + time.Second - 1) / time.Second)
+ c := HostedCharge{Seconds: map[string]int64{}, Micros: map[string]int64{}}
+ start, end := now.UTC(), now.UTC().Add(window)
+ for d := time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, time.UTC); !d.After(end); d = d.AddDate(0, 0, 1) {
+ c.Seconds[d.Format(time.DateOnly)] = seconds
+ c.Micros[d.Format("2006-01")] = hostedMicros(seconds, rate)
+ }
+ return c, nil
+}
+
+// hostedLimits is person's limits and the revision a write must name: the
+// defaults at revision 0 when no owner has set any. A read error is
+// returned, never read as the defaults.
+func (t *txn) hostedLimits(person string) (HostedLimits, int64, error) {
+ var rows []hostedLimitRecord
+ if err := t.db.Where("person = ?", person).Limit(1).Find(&rows).Error; err != nil {
+ return HostedLimits{}, 0, err
+ }
+ if len(rows) == 0 {
+ return DefaultHostedLimits, 0, nil
+ }
+ r := rows[0]
+ return HostedLimits{Running: int(r.Running), DailySeconds: r.DailySeconds, MonthlyMicros: r.MonthlyMicros}, r.Revision, nil
+}
+
+// hostedAdmit decides, in the caller's transaction, whether person may
+// start a job of size and lifetime at now. It first writes the person's
+// admission lock row, so the transaction holds the write through its
+// counts and the caller's insert of the job (newHostedJob with
+// hostedHoldFor's hold). Running counts every job not ended or failed; a
+// settled job counts what it used, any other job its hold. The person
+// must be a current member. Any read error denies with the error: an
+// unknown count stays unknown.
+func (t *txn) hostedAdmit(person string, size isolatedjob.Size, lifetime time.Duration, now time.Time) (ok bool, reason string, err error) {
+ hold, err := hostedHoldFor(size, lifetime, now)
+ if err != nil {
+ return false, "", err
+ }
+ if err := t.db.Exec("INSERT INTO hosted_admit_locks(person, admissions) VALUES (?, 1) ON CONFLICT(person) DO UPDATE SET admissions = admissions + 1", person).Error; err != nil {
+ return false, "", err
+ }
+ if _, err := t.s.authority.Me(t.db, person); err != nil {
+ return false, "", err
+ }
+ limits, _, err := t.hostedLimits(person)
+ if err != nil {
+ return false, "", err
+ }
+ // A settled job's usage ends at its proof, so one that ended before
+ // this month cannot count against now's days or months; every live
+ // job is unsettled.
+ month := time.Date(now.UTC().Year(), now.UTC().Month(), 1, 0, 0, 0, 0, time.UTC)
+ var rows []HostedJob
+ if err := t.db.Where("person = ? AND (settled_at IS NULL OR ended_at >= ?)", person, month).Find(&rows).Error; err != nil {
+ return false, "", err
+ }
+ running := 0
+ held := HostedCharge{Seconds: map[string]int64{}, Micros: map[string]int64{}}
+ for _, j := range rows {
+ if j.Live() {
+ running++
+ }
+ c, err := j.Hold()
+ if j.SettledAt != nil {
+ c, err = j.Used()
+ }
+ if err != nil {
+ return false, "", err
+ }
+ for k, v := range c.Seconds {
+ held.Seconds[k] += v
+ }
+ for k, v := range c.Micros {
+ held.Micros[k] += v
+ }
+ }
+ if running >= limits.Running {
+ return false, HostedLimitRunning, nil
+ }
+ for day, s := range hold.Seconds {
+ if held.Seconds[day]+s > limits.DailySeconds {
+ return false, HostedLimitDaily, nil
+ }
+ }
+ for m, v := range hold.Micros {
+ if held.Micros[m]+v > limits.MonthlyMicros {
+ return false, HostedLimitMonthly, nil
+ }
+ }
+ return true, "", nil
+}
+
+// hostedSettle settles an ended or failed job that holds proof, once: the
+// span from its admission to when the instance received its proof,
+// allocated to UTC days and months, at BurstHoldFactor times its size's
+// rate, replaces its hold. A job without proof keeps its hold.
+func (t *txn) hostedSettle(attempt string) (bool, error) {
+ 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() || j.EndedAt == nil || j.AdmittedAt == nil {
+ return false, fmt.Errorf("%w: %s is %s", ErrHostedNoProof, attempt, j.State)
+ }
+ if j.EndedAt.Before(*j.AdmittedAt) {
+ return false, fmt.Errorf("%w: %s ended before its admission", ErrInvalid, attempt)
+ }
+ rate, err := hostedRate(j.Size)
+ if err != nil {
+ return false, err
+ }
+ days, months := Allocate(*j.AdmittedAt, *j.EndedAt)
+ for m, s := range months {
+ months[m] = hostedMicros(s, rate)
+ }
+ return t.settleHostedJob(attempt, HostedCharge{Seconds: days, Micros: months}, t.now())
+}
+
+// SetHostedLimits sets a current member's hosted limits. owner is the
+// verified session's address, never a submitted actor, and must be a
+// current owner; the roster is read in the transaction and a lookup error
+// denies. The write names the revision the owner saw (0 for the
+// defaults) and is audited in the same transaction.
+func (s *Store) SetHostedLimits(ctx context.Context, owner, person string, l HostedLimits, revision int64) error {
+ return s.tx(ctx, func(t *txn) error {
+ if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
+ return err
+ }
+ if err := t.isOwner(owner); err != nil {
+ return err
+ }
+ if _, err := s.authority.Me(t.db, person); err != nil {
+ return err
+ }
+ m := hostedMaxLimits
+ if l.Running < 0 || l.DailySeconds < 0 || l.MonthlyMicros < 0 || l.Running > m.Running || l.DailySeconds > m.DailySeconds || l.MonthlyMicros > m.MonthlyMicros {
+ return fmt.Errorf("%w: hosted limits", ErrInvalid)
+ }
+ _, current, err := t.hostedLimits(person)
+ if err != nil {
+ return err
+ }
+ if current != revision {
+ return ErrCardConflict
+ }
+ r := hostedLimitRecord{Person: person, Running: int64(l.Running), DailySeconds: l.DailySeconds, MonthlyMicros: l.MonthlyMicros, Owner: owner, Revision: revision + 1, UpdatedAt: t.now()}
+ if revision == 0 {
+ err = t.db.Create(&r).Error
+ } else {
+ res := t.db.Model(&hostedLimitRecord{}).Where("person = ? AND revision = ?", person, revision).Select("running", "daily_seconds", "monthly_micros", "owner", "revision", "updated_at").Updates(&r)
+ if err = res.Error; err == nil && res.RowsAffected != 1 {
+ err = ErrCardConflict
+ }
+ }
+ if err != nil {
+ return err
+ }
+ return s.authority.Audit(t.db, owner, "hosted.limits", fmt.Sprintf("%s/revision:%d/running:%d/daily_seconds:%d/monthly_micros:%d", person, r.Revision, l.Running, l.DailySeconds, l.MonthlyMicros))
+ })
+}
diff --git a/internal/equipo/chat/hosted_limits_test.go b/internal/equipo/chat/hosted_limits_test.go
new file mode 100644
index 00000000..c9f8f9e5
--- /dev/null
+++ b/internal/equipo/chat/hosted_limits_test.go
@@ -0,0 +1,475 @@
+package chat
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "gorm.io/gorm"
+)
+
+// at is a UTC time on 2026-11-dd hh:mm, or in December when dd > 30.
+func at(dd, hh, mm int) time.Time {
+ return time.Date(2026, 11, dd, hh, mm, 0, 0, time.UTC)
+}
+
+// admit runs admission for hkOwner's step at now and, when it admits,
+// records the job with the hold the limits computed, in one transaction.
+func (r *hkRig) admit(step string, size isolatedjob.Size, now time.Time, retryOf string) (HostedJob, string, error) {
+ r.t.Helper()
+ var j HostedJob
+ var reason string
+ err := r.hosted(func(t *txn) error {
+ ok, why, err := t.hostedAdmit(hkOwner, size, HostedChecksLifetime, now)
+ if err != nil || !ok {
+ reason = why
+ return err
+ }
+ hold, err := hostedHoldFor(size, HostedChecksLifetime, now)
+ if err != nil {
+ return err
+ }
+ j, err = t.newHostedJob(hostedJobSpec{Step: step, Size: size, Hold: hold, RetryOf: retryOf, At: now})
+ return err
+ })
+ return j, reason, err
+}
+
+// mustAdmit records a step and admits it, or fails the test.
+func (r *hkRig) mustAdmit(step string, size isolatedjob.Size, now time.Time) HostedJob {
+ r.t.Helper()
+ r.hostedStep(step)
+ j, reason, err := r.admit(step, size, now, "")
+ if err != nil || j.AttemptID == "" {
+ r.t.Fatalf("admit %s at %s: %q %v", step, now, reason, err)
+ }
+ return j
+}
+
+// refused admits a new step at now and wants the reason.
+func (r *hkRig) refused(step string, now time.Time, want string) {
+ r.t.Helper()
+ r.hostedStep(step)
+ j, reason, err := r.admit(step, isolatedjob.SizeLarge, now, "")
+ if err != nil || reason != want || j.AttemptID != "" {
+ r.t.Fatalf("admission of %s at %s: %+v %q %v, want refused %q", step, now, j.AttemptID, reason, err, want)
+ }
+ var n int64
+ r.must(r.s.db.G.Model(&HostedJob{}).Where("step_id = ?", step).Count(&n).Error)
+ if n != 0 {
+ r.t.Fatalf("a refused admission left a job for %s", step)
+ }
+}
+
+// stopAt ends a job with the controller's stop proof received at when,
+// and settles it.
+func (r *hkRig) stopAt(attempt string, when time.Time) {
+ r.t.Helper()
+ r.must(r.moveTo(attempt, HostedJobStopping))
+ p := HostedEndProof{Stop: &hostedwire.StopProof{AttemptID: attempt, VMRef: "vm-1", State: isolatedjob.StateStopped}, ObservedAt: when}
+ r.must(r.hosted(func(t *txn) error { return t.hostedEnd(attempt, HostedJobEnded, p) }))
+ r.settle(attempt)
+}
+
+func (r *hkRig) settle(attempt string) {
+ r.t.Helper()
+ r.must(r.hosted(func(t *txn) error {
+ ok, err := t.hostedSettle(attempt)
+ if err == nil && !ok {
+ err = errors.New("not settled")
+ }
+ return err
+ }))
+}
+
+// setLimits writes a person's limits directly, as an owner's write would.
+func (r *hkRig) setLimits(l HostedLimits) {
+ r.t.Helper()
+ r.must(r.s.db.G.Create(&hostedLimitRecord{Person: hkOwner, Running: int64(l.Running), DailySeconds: l.DailySeconds, MonthlyMicros: l.MonthlyMicros, Owner: hkOwner, Revision: 1, UpdatedAt: r.now}).Error)
+}
+
+func wantCharge(t *testing.T, what string, got HostedCharge, err error, seconds, micros map[string]int64) {
+ t.Helper()
+ if err != nil || !reflect.DeepEqual(got.Seconds, seconds) || !reflect.DeepEqual(got.Micros, micros) {
+ t.Fatalf("%s: %+v %v, want %v %v", what, got, err, seconds, micros)
+ }
+}
+
+// TestLimitsHoldAndSettle: a Large checks job holds its whole 100-minute
+// window at four times the baseline; every job not ended or failed counts
+// as running, so a third is refused at the default two; settling replaces
+// the hold with the span to the stop proof, once, and frees the slot.
+func TestLimitsHoldAndSettle(t *testing.T) {
+ r, _ := hostedRig(t)
+ if DefaultHostedLimits != (HostedLimits{Running: 2, DailySeconds: 8 * 3600, MonthlyMicros: 50_000_000}) || HostedLaunchWindow+HostedChecksLifetime != 100*time.Minute {
+ t.Fatalf("defaults %+v", DefaultHostedLimits)
+ }
+ a := r.mustAdmit("st-a", isolatedjob.SizeLarge, at(8, 12, 0))
+ h, err := r.job(a.AttemptID).Hold()
+ wantCharge(t, "Large hold", h, err, map[string]int64{"2026-11-08": 6000}, map[string]int64{"2026-11": 2_066_667})
+ b := r.mustAdmit("st-b", isolatedjob.SizeSmall, at(8, 12, 5))
+ h, err = r.job(b.AttemptID).Hold()
+ wantCharge(t, "Small hold", h, err, map[string]int64{"2026-11-08": 6000}, map[string]int64{"2026-11": 1_033_334})
+ r.refused("st-c", at(8, 12, 10), "running")
+ // Each live state holds a slot: still refused while a job enrols.
+ r.must(r.moveTo(b.AttemptID, HostedJobLaunching))
+ r.must(r.moveTo(b.AttemptID, HostedJobEnrolling))
+ r.refused("st-d", at(8, 12, 11), "running")
+
+ r.stopAt(a.AttemptID, at(8, 12, 40))
+ u, err := r.job(a.AttemptID).Used()
+ wantCharge(t, "settled", u, err, map[string]int64{"2026-11-08": 2400}, map[string]int64{"2026-11": 826_667})
+ if h, _ := r.job(a.AttemptID).Hold(); h.Seconds["2026-11-08"] != 6000 {
+ t.Fatalf("settling rewrote the hold: %+v", h)
+ }
+ r.must(r.hosted(func(t *txn) error {
+ if ok, err := t.hostedSettle(a.AttemptID); ok || err != nil {
+ return fmt.Errorf("second settle: %t %v", ok, err)
+ }
+ return nil
+ }))
+ r.mustAdmit("st-e", isolatedjob.SizeLarge, at(8, 12, 41))
+}
+
+// TestLimitsRace: 20 admissions at once for one person with one slot
+// admit exactly one.
+func TestLimitsRace(t *testing.T) {
+ r, _ := rosterRig(t)
+ r.task("tkh", "Hosted", hkOwner)
+ r.setLimits(HostedLimits{Running: 1, DailySeconds: DefaultHostedLimits.DailySeconds, MonthlyMicros: DefaultHostedLimits.MonthlyMicros})
+ const n = 20
+ for i := range n {
+ r.hostedStep(fmt.Sprintf("st-%d", i))
+ }
+ var wg sync.WaitGroup
+ results := make([]string, n)
+ for i := range n {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ step := fmt.Sprintf("st-%d", i)
+ results[i] = "?"
+ err := r.tx(func(t *txn) error {
+ ok, why, err := t.hostedAdmit(hkOwner, isolatedjob.SizeLarge, HostedChecksLifetime, r.now)
+ if err != nil || !ok {
+ results[i] = why
+ return err
+ }
+ hold, err := hostedHoldFor(isolatedjob.SizeLarge, HostedChecksLifetime, r.now)
+ if err != nil {
+ return err
+ }
+ _, err = t.newHostedJob(hostedJobSpec{Step: step, Size: isolatedjob.SizeLarge, Hold: hold, At: r.now})
+ results[i] = "admitted"
+ return err
+ })
+ if err != nil {
+ results[i] = err.Error()
+ }
+ }()
+ }
+ wg.Wait()
+ admitted, running := 0, 0
+ for _, s := range results {
+ switch s {
+ case "admitted":
+ admitted++
+ case "running":
+ running++
+ }
+ }
+ var jobs int64
+ r.must(r.s.db.G.Model(&HostedJob{}).Count(&jobs).Error)
+ if admitted != 1 || running != n-1 || jobs != 1 {
+ t.Fatalf("admitted %d, refused %d, jobs %d: %v", admitted, running, jobs, results)
+ }
+}
+
+// TestHoldSpansMidnight: admitted at 23:00 UTC, the whole window is held
+// against both days; settling at 23:20 frees the second.
+func TestHoldSpansMidnight(t *testing.T) {
+ r, _ := hostedRig(t)
+ r.setLimits(HostedLimits{Running: 5, DailySeconds: 6000, MonthlyMicros: DefaultHostedLimits.MonthlyMicros})
+ a := r.mustAdmit("st-a", isolatedjob.SizeLarge, at(8, 23, 0))
+ h, err := r.job(a.AttemptID).Hold()
+ wantCharge(t, "hold across midnight", h, err, map[string]int64{"2026-11-08": 6000, "2026-11-09": 6000}, map[string]int64{"2026-11": 2_066_667})
+ r.refused("st-b", at(9, 0, 50), "daily")
+ r.stopAt(a.AttemptID, at(8, 23, 20))
+ u, err := r.job(a.AttemptID).Used()
+ wantCharge(t, "settled before midnight", u, err, map[string]int64{"2026-11-08": 1200}, map[string]int64{"2026-11": 413_334})
+ b := r.mustAdmit("st-c", isolatedjob.SizeLarge, at(9, 0, 50))
+ h, err = r.job(b.AttemptID).Hold()
+ wantCharge(t, "the second day's hold", h, err, map[string]int64{"2026-11-09": 6000}, map[string]int64{"2026-11": 2_066_667})
+}
+
+// TestDelayedLaunchReadmitted: a job admitted at 23:55 and not launched by
+// 00:05 is failed, and its step is admitted again against the new day only
+// once the controller shows the intent abandoned and the job settles.
+func TestDelayedLaunchReadmitted(t *testing.T) {
+ r, _ := hostedRig(t)
+ r.setLimits(HostedLimits{Running: 1, DailySeconds: 6000 + 420, MonthlyMicros: DefaultHostedLimits.MonthlyMicros})
+ r.hostedStep("st-a")
+ j, reason, err := r.admit("st-a", isolatedjob.SizeLarge, at(8, 23, 55), "")
+ if err != nil || j.AttemptID == "" {
+ t.Fatalf("admit: %q %v", reason, err)
+ }
+ launchBy := at(8, 23, 55).Add(HostedLaunchWindow)
+ r.must(r.hosted(func(t *txn) error {
+ return t.hostedLaunching(j.AttemptID, hostedCode, launchBy, launchBy)
+ }))
+ r.must(r.hosted(func(t *txn) error { return t.hostedLaunchReturned(j.AttemptID) }))
+ r.must(r.hosted(func(t *txn) error { return t.hostedStopping(j.AttemptID, "launch_expired") }))
+ if _, reason, err := r.admit("st-a", isolatedjob.SizeLarge, at(9, 0, 6), j.AttemptID); reason != "running" || err != nil {
+ t.Fatalf("readmitted while stopping: %q %v", reason, err)
+ }
+ abandoned := func(when time.Time) HostedEndProof {
+ return HostedEndProof{NeverLaunched: &HostedNeverLaunched{AttemptID: j.AttemptID, ObservedAt: when, LaunchBy: launchBy, ControllerState: HostedControllerAbandoned, Signed: true}, ObservedAt: when}
+ }
+ if err := r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobFailed, abandoned(at(9, 0, 6))) }); !errors.Is(err, ErrHostedNoProof) {
+ t.Fatalf("failed before launch-by plus 2 minutes: %v", err)
+ }
+ r.must(r.hosted(func(t *txn) error { return t.hostedEnd(j.AttemptID, HostedJobFailed, abandoned(at(9, 0, 7))) }))
+ // Failed but not settled: the whole hold still counts on both days.
+ if _, reason, err := r.admit("st-a", isolatedjob.SizeLarge, at(9, 0, 8), j.AttemptID); reason != "daily" || err != nil {
+ t.Fatalf("readmitted before settling: %q %v", reason, err)
+ }
+ r.settle(j.AttemptID)
+ u, err := r.job(j.AttemptID).Used()
+ wantCharge(t, "settled across midnight", u, err, map[string]int64{"2026-11-08": 300, "2026-11-09": 420}, map[string]int64{"2026-11": 248_000})
+ again, reason, err := r.admit("st-a", isolatedjob.SizeLarge, at(9, 0, 8), j.AttemptID)
+ if err != nil || again.AttemptID == "" || again.RetryOf != j.AttemptID {
+ t.Fatalf("not readmitted: %q %v", reason, err)
+ }
+ h, err := again.Hold()
+ wantCharge(t, "fresh hold", h, err, map[string]int64{"2026-11-09": 6000}, map[string]int64{"2026-11": 2_066_667})
+}
+
+// TestSettleStaysConservative: a 10-minute job settles at four times the
+// baseline rate, for either size.
+func TestSettleStaysConservative(t *testing.T) {
+ r, _ := hostedRig(t)
+ if RateSmallMicrosPerHour != 155_000 || RateLargeMicrosPerHour != 310_000 || BurstHoldFactor != 4 {
+ t.Fatal("rates")
+ }
+ l := r.mustAdmit("st-l", isolatedjob.SizeLarge, at(8, 12, 0))
+ s := r.mustAdmit("st-s", isolatedjob.SizeSmall, at(8, 12, 0))
+ r.stopAt(l.AttemptID, at(8, 12, 10))
+ r.stopAt(s.AttemptID, at(8, 12, 10))
+ u, err := r.job(l.AttemptID).Used()
+ wantCharge(t, "Large, 10 minutes", u, err, map[string]int64{"2026-11-08": 600}, map[string]int64{"2026-11": 206_667})
+ u, err = r.job(s.AttemptID).Used()
+ wantCharge(t, "Small, 10 minutes", u, err, map[string]int64{"2026-11-08": 600}, map[string]int64{"2026-11": 103_334})
+}
+
+// TestHoldSpansMonthEnd: a window across the month end holds its whole
+// cost against both months; settling before midnight frees the second.
+func TestHoldSpansMonthEnd(t *testing.T) {
+ days, months := Allocate(at(30, 23, 30), at(31, 0, 15))
+ if !reflect.DeepEqual(days, map[string]int64{"2026-11-30": 1800, "2026-12-01": 900}) || !reflect.DeepEqual(months, map[string]int64{"2026-11": 1800, "2026-12": 900}) {
+ t.Fatalf("Allocate: %v %v", days, months)
+ }
+ if d, m := Allocate(at(8, 12, 0), at(8, 12, 0)); len(d) != 0 || len(m) != 0 {
+ t.Fatalf("an empty span: %v %v", d, m)
+ }
+ r, _ := hostedRig(t)
+ r.setLimits(HostedLimits{Running: 5, DailySeconds: DefaultHostedLimits.DailySeconds, MonthlyMicros: 2 * 2_066_667})
+ a := r.mustAdmit("st-a", isolatedjob.SizeLarge, at(30, 23, 0))
+ h, err := r.job(a.AttemptID).Hold()
+ wantCharge(t, "hold across the month end", h, err, map[string]int64{"2026-11-30": 6000, "2026-12-01": 6000}, map[string]int64{"2026-11": 2_066_667, "2026-12": 2_066_667})
+ r.mustAdmit("st-b", isolatedjob.SizeLarge, at(31, 1, 0))
+ r.refused("st-c", at(31, 3, 0), "monthly")
+ r.stopAt(a.AttemptID, at(30, 23, 30))
+ r.mustAdmit("st-d", isolatedjob.SizeLarge, at(31, 3, 0))
+}
+
+// TestNoProofKeepsHold: a job without stop proof cannot settle and keeps
+// its whole hold, whether it is stopping or was marked failed by hand.
+func TestNoProofKeepsHold(t *testing.T) {
+ r, _ := hostedRig(t)
+ r.setLimits(HostedLimits{Running: 5, DailySeconds: 6000, MonthlyMicros: DefaultHostedLimits.MonthlyMicros})
+ a := r.mustAdmit("st-a", isolatedjob.SizeLarge, at(8, 9, 0))
+ r.must(r.moveTo(a.AttemptID, HostedJobStopping))
+ lost := HostedEndProof{Stop: &hostedwire.StopProof{AttemptID: "another", State: isolatedjob.StateStopped}, ObservedAt: at(8, 9, 10)}
+ if err := r.hosted(func(t *txn) error { return t.hostedEnd(a.AttemptID, HostedJobEnded, lost) }); !errors.Is(err, ErrHostedNoProof) {
+ t.Fatalf("ended without its proof: %v", err)
+ }
+ if err := r.hosted(func(t *txn) error { _, err := t.hostedSettle(a.AttemptID); return err }); !errors.Is(err, ErrHostedNoProof) {
+ t.Fatalf("settled while stopping: %v", err)
+ }
+ r.refused("st-b", at(8, 20, 0), "daily")
+ r.exec("UPDATE hosted_jobs SET state = 'failed', ended_at = ? WHERE attempt_id = ?", at(8, 9, 10), a.AttemptID)
+ if err := r.hosted(func(t *txn) error { _, err := t.hostedSettle(a.AttemptID); return err }); !errors.Is(err, ErrHostedNoProof) {
+ t.Fatalf("settled without proof: %v", err)
+ }
+ if j := r.job(a.AttemptID); j.SettledAt != nil || j.UsedSecondsJSON != "" {
+ t.Fatalf("usage recorded without proof: %+v", j)
+ }
+ r.refused("st-c", at(8, 20, 0), "daily")
+}
+
+// TestLimitCountErrorDenies: a roster, limits or jobs read that fails, or
+// a hold that cannot be read, denies admission with the error; it is
+// never read as no jobs or the default limits.
+func TestLimitCountErrorDenies(t *testing.T) {
+ r, _ := hostedRig(t)
+ r.mustAdmit("st-a", isolatedjob.SizeLarge, at(8, 9, 0))
+ // try reads admission's own answer: the job's insert would fail on
+ // the same broken table, so it is not asked for.
+ try := func(what string) {
+ t.Helper()
+ var ok bool
+ var reason string
+ err := r.hosted(func(t *txn) error {
+ var err error
+ ok, reason, err = t.hostedAdmit(hkOwner, isolatedjob.SizeLarge, HostedChecksLifetime, at(8, 10, 0))
+ return err
+ })
+ if ok || err == nil || reason != "" {
+ t.Fatalf("%s: admission %t %q %v, want denied with the error", what, ok, reason, err)
+ }
+ }
+ r.exec("ALTER TABLE hosted_jobs RENAME TO hosted_jobs_away")
+ try("count")
+ r.exec("ALTER TABLE hosted_jobs_away RENAME TO hosted_jobs")
+ r.exec("ALTER TABLE hosted_limits RENAME TO hosted_limits_away")
+ try("limits")
+ r.exec("ALTER TABLE hosted_limits_away RENAME TO hosted_limits")
+ r.exec("ALTER TABLE members RENAME TO members_away")
+ try("roster")
+ r.exec("ALTER TABLE members_away RENAME TO members")
+ r.exec("UPDATE members SET active=0 WHERE address=?", hkOwner)
+ try("removed")
+ r.exec("UPDATE members SET active=1 WHERE address=?", hkOwner)
+ r.exec("UPDATE hosted_jobs SET hold_seconds_json = '{\"bad\": 1}'")
+ try("hold")
+ r.exec("UPDATE hosted_jobs SET hold_seconds_json = '{\"2026-11-08\": 6000}'")
+ r.mustAdmit("st-z", isolatedjob.SizeLarge, at(8, 10, 0))
+ r.must(r.hosted(func(t *txn) error {
+ for _, bad := range []struct {
+ size isolatedjob.Size
+ life time.Duration
+ }{{"medium", HostedChecksLifetime}, {isolatedjob.SizeLarge, 0}, {isolatedjob.SizeLarge, 25 * time.Hour}} {
+ if ok, _, err := t.hostedAdmit(hkOwner, bad.size, bad.life, at(8, 10, 0)); ok || !errors.Is(err, ErrInvalid) {
+ return fmt.Errorf("admitted %v: %t %v", bad, ok, err)
+ }
+ }
+ return nil
+ }))
+}
+
+// TestOwnerRaisesLimit: only a current owner sets a current member's
+// limits, at the revision they saw, audited in the same transaction; a
+// person with no row has the defaults.
+func TestOwnerRaisesLimit(t *testing.T) {
+ r, fail := rosterRig(t)
+ r.task("tkh", "Hosted", hkOwner)
+ r.exec("CREATE TABLE audit_probe (detail text)")
+ var audits []string
+ auditFails := false
+ r.s.authority.Audit = func(tx *gorm.DB, actor, kind, detail string) error {
+ if _, inTx := tx.Statement.ConnPool.(gorm.TxCommitter); !inTx {
+ return errors.New("audit outside the transaction")
+ }
+ if kind != "hosted.limits" {
+ return nil
+ }
+ if auditFails {
+ return errors.New("audit failed")
+ }
+ audits = append(audits, actor+" "+kind+" "+detail)
+ return tx.Exec("INSERT INTO audit_probe(detail) VALUES (?)", detail).Error
+ }
+ limits := func() (HostedLimits, int64) {
+ t.Helper()
+ var l HostedLimits
+ var rev int64
+ r.must(r.tx(func(t *txn) error {
+ var err error
+ l, rev, err = t.hostedLimits(hkOwner)
+ return err
+ }))
+ return l, rev
+ }
+ if l, rev := limits(); l != DefaultHostedLimits || rev != 0 {
+ t.Fatalf("no row: %+v %d", l, rev)
+ }
+ admit := func(step string) string {
+ t.Helper()
+ r.hostedStep(step)
+ var reason string
+ r.must(r.tx(func(t *txn) error {
+ ok, why, err := t.hostedAdmit(hkOwner, isolatedjob.SizeLarge, HostedChecksLifetime, r.now)
+ if err != nil || !ok {
+ reason = why
+ return err
+ }
+ hold, err := hostedHoldFor(isolatedjob.SizeLarge, HostedChecksLifetime, r.now)
+ if err != nil {
+ return err
+ }
+ _, err = t.newHostedJob(hostedJobSpec{Step: step, Size: isolatedjob.SizeLarge, Hold: hold, At: r.now})
+ reason = "admitted"
+ return err
+ }))
+ return reason
+ }
+ if admit("st-1") != "admitted" || admit("st-2") != "admitted" || admit("st-3") != "running" {
+ t.Fatal("defaults not applied")
+ }
+ three := HostedLimits{Running: 3, DailySeconds: 8 * 3600, MonthlyMicros: 50_000_000}
+ r.exec("UPDATE members SET role='member' WHERE address=?", hkMember)
+ if err := r.s.SetHostedLimits(r.ctx, hkMember, hkOwner, three, 0); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("a member set limits: %v", err)
+ }
+ if err := r.s.SetHostedLimits(r.ctx, hkOwner, "stranger@example.com", three, 0); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("limits for someone not on the roster: %v", err)
+ }
+ for _, bad := range []HostedLimits{{Running: -1, DailySeconds: 1, MonthlyMicros: 1}, {Running: 1, DailySeconds: -1, MonthlyMicros: 1}, {Running: 1, DailySeconds: 1, MonthlyMicros: -1}, {Running: 1001, DailySeconds: 1, MonthlyMicros: 1}} {
+ if err := r.s.SetHostedLimits(r.ctx, hkOwner, hkOwner, bad, 0); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("limits %+v: %v", bad, err)
+ }
+ }
+ if err := r.s.SetHostedLimits(r.ctx, hkOwner, hkOwner, three, 1); !errors.Is(err, ErrCardConflict) {
+ t.Fatalf("a stale revision: %v", err)
+ }
+ *fail = true
+ if err := r.s.SetHostedLimits(r.ctx, hkOwner, hkOwner, three, 0); err == nil {
+ t.Fatal("set with the roster unavailable")
+ }
+ *fail = false
+ auditFails = true
+ if err := r.s.SetHostedLimits(r.ctx, hkOwner, hkOwner, three, 0); err == nil {
+ t.Fatal("set with a failing audit")
+ }
+ auditFails = false
+ if l, rev := limits(); l != DefaultHostedLimits || rev != 0 || len(audits) != 0 {
+ t.Fatalf("a refused write took effect: %+v %d %v", l, rev, audits)
+ }
+ r.must(r.s.SetHostedLimits(r.ctx, hkOwner, hkOwner, three, 0))
+ if l, rev := limits(); l != three || rev != 1 {
+ t.Fatalf("after the raise: %+v %d", l, rev)
+ }
+ if want := []string{"owner@example.com hosted.limits owner@example.com/revision:1/running:3/daily_seconds:28800/monthly_micros:50000000"}; !reflect.DeepEqual(audits, want) {
+ t.Fatalf("audits %q", audits)
+ }
+ var probes int64
+ r.must(r.s.db.G.Raw("SELECT count(*) FROM audit_probe").Scan(&probes).Error)
+ if probes != 1 {
+ t.Fatalf("audit rows %d", probes)
+ }
+ if admit("st-4") != "admitted" || admit("st-5") != "running" {
+ t.Fatal("the raised limit not applied")
+ }
+ if err := r.s.SetHostedLimits(r.ctx, hkOwner, hkOwner, DefaultHostedLimits, 0); !errors.Is(err, ErrCardConflict) {
+ t.Fatalf("a second write at revision 0: %v", err)
+ }
+ r.exec("UPDATE members SET active=0 WHERE address=?", hkOwner)
+ if err := r.s.SetHostedLimits(r.ctx, hkOwner, hkMember, three, 0); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("a removed owner set limits: %v", err)
+ }
+}
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go
index b970b156..d01c7557 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{}, &notificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &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...)
+var Models = append([]any{&changeDiffRecord{}, &notificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, &copyAttemptRecord{}, &copyReviewRecord{}, &copyFeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, &notebookRecord{}, &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{}, &hostedLimitRecord{}, &hostedAdmitLock{}}, push.Models...)
type turnRecord struct {
CreateRepo string
diff --git a/internal/equipo/migrations/0127_hosted_limits.sql b/internal/equipo/migrations/0127_hosted_limits.sql
new file mode 100644
index 00000000..964a48e7
--- /dev/null
+++ b/internal/equipo/migrations/0127_hosted_limits.sql
@@ -0,0 +1,8 @@
+-- Hosted runners slice 2 (Task 20): per-person hosted limits (decision
+-- S2-9). hosted_limits is a person's limits as an owner set them, at the
+-- revision a write must name; a person with no row has the defaults.
+-- hosted_admit_locks is the row each admission writes first, so its
+-- counts and its job's insert hold the write. New tables only; no
+-- existing row changes.
+CREATE TABLE hosted_limits (person text, running integer, daily_seconds integer, monthly_micros integer, owner text, revision integer, updated_at datetime, PRIMARY KEY (person));
+CREATE TABLE hosted_admit_locks (person text, admissions integer, PRIMARY KEY (person));
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index e451eb7f..ae93a386 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -938,3 +938,12 @@ 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);
+
+-- Hosted runners slice 2 (Task 20): per-person hosted limits (decision
+-- S2-9). hosted_limits is a person's limits as an owner set them, at the
+-- revision a write must name; a person with no row has the defaults.
+-- hosted_admit_locks is the row each admission writes first, so its
+-- counts and its job's insert hold the write. New tables only; no
+-- existing row changes.
+CREATE TABLE hosted_limits (person text, running integer, daily_seconds integer, monthly_micros integer, owner text, revision integer, updated_at datetime, PRIMARY KEY (person));
+CREATE TABLE hosted_admit_locks (person text, admissions integer, PRIMARY KEY (person));