oficina / equipo Public

feat: serve scoped runner assignments and fenced reports

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 34ac5e93f72cdd87a632f27df157964f58ea9ece parent 7a5ca9b
28 files changed, +3,348 −60
  • .rastrillo/budgets.txt +4 −1
  • internal/equipo/app.go +1 −0
  • internal/equipo/authority.go +7 −2
  • internal/equipo/connection_models.go +4 −19
  • internal/equipo/connection_selection.go +3 −0
  • internal/equipo/execution.go +12 −11
  • internal/equipo/migrations/0013_runner_assignments.sql +21 −0
  • internal/equipo/migrations/schema.sql +22 −0
  • internal/equipo/models.go +1 −1
  • internal/equipo/runner_api.go +215 −0
  • internal/equipo/runner_execution.go +499 −0
  • internal/equipo/runner_execution_models.go +81 −0
  • internal/equipo/runner_handlers.go +2 −2
  • internal/equipo/runner_mutations.go +322 −0
  • internal/equipo/runner_provenance.go +121 −0
  • internal/equipo/runner_rotation.go +154 −0
  • internal/equipo/team/admission.go +208 −0
  • internal/equipo/team/admit_retry_test.go +198 −0
  • internal/equipo/team/scheduler.go +4 −2
  • internal/equipo/team/shared.go +4 −0
  • internal/equipo/team/stop.go +4 −2
  • internal/equipo/team/store.go +14 −2
  • internal/equipotest/execution_schema_test.go +16 −12
  • internal/equipotest/runner_api_test.go +988 −0
  • internal/runnerproto/journal.go +143 −0
  • internal/runnerproto/types.go +115 −1
  • internal/runnerproto/validate.go +7 −5
  • internal/runnerproto/wire.go +178 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 0022aae2..9f56bd1f 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -9,7 +9,10 @@
# time <dir> <duration> <reason>
# perf <METHOD> <path> <duration>|skip <reason>
# boot <duration> <reason>
-size internal/equipo/team 7600 - Preserve the plan-mandated core layout; Tasks 2-4 add recovery, subscription accounting, Git candidate identity, repository checks and observed isolation provenance to the copied transactional core.
+size internal/equipo/team 7900 - Preserve the plan-mandated core layout; Tasks 2-4 add recovery and evidence checks, and Task 8 adds atomic admission tickets and shared transaction composition.
perf GET /* skip Unknown private paths render 404; this fallback contains no screens.
time internal/equipo/team 15s Copied core crash, recovery and concurrency tests take about 7.7s idle and 13.6s on the loaded shared machine.
time internal/equipotest 25s Task 6 keeps the mandated connections tests in this package; its focused authority, isolation, atomic-write and real-session checks took 15.5s on the shared machine, above the prior 15s allowance.
+
+size internal/equipo 6500 - Task 8 keeps the mandated runner API, assignment, credential rotation and provenance adapters in the app package alongside the shared transaction and roster checks.
+size internal/equipotest - 8300 Task 8 keeps the mandated runner_api_test.go route, ticket, containment, provenance and failure tests beside the existing activation database fixtures; they add coverage across all runner endpoints and cross-job concurrency.
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 24a668e3..10e6a230 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -93,6 +93,7 @@ func Router(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logger) (chi.
a.Use(csrf.Protect(cfg.Origin, csrf.Exempt("/api/enrolments", "/api/enrolments/token")))
a.Post("/api/enrolments", a.beginEnrolment)
a.Post("/api/enrolments/token", a.exchangeEnrolment)
+ a.Mount("/api/runner/v1", a.store.RunnerHandler())
a.Get("/signin", func(w http.ResponseWriter, r *http.Request) { renderSignin(a.auth, w, r) })
a.Post("/auth/begin", a.auth.Begin)
a.Get("/auth/callback", a.auth.Callback)
diff --git a/internal/equipo/authority.go b/internal/equipo/authority.go
index 6dafe67a..08130ec8 100644
--- a/internal/equipo/authority.go
+++ b/internal/equipo/authority.go
@@ -82,7 +82,7 @@ func (a *RosterAuthority) Introspect(ctx context.Context, req team.AdmissionRequ
return team.Admission{}, team.ErrGrantRevoked
}
var admission team.Admission
- err = a.store.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(func(tx *gorm.DB) error {
+ check := func(tx *gorm.DB) error {
var instance Team
if err := tx.First(&instance).Error; err != nil {
return err
@@ -132,7 +132,12 @@ func (a *RosterAuthority) Introspect(ctx context.Context, req team.AdmissionRequ
now := a.clock.Now()
admission = team.Admission{Grant: req.Grant, Version: project.GrantVersion, Epoch: instance.RosterEpoch, IssuedAt: now, ExpiresAt: now.Add(5 * time.Second)}
return nil
- }, &sql.TxOptions{ReadOnly: true})
+ }
+ if tx, ok := ctx.Value(runnerTxKey{}).(*gorm.DB); ok {
+ err = check(tx)
+ } else {
+ err = a.store.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(check, &sql.TxOptions{ReadOnly: true})
+ }
if err != nil {
if errors.Is(err, team.ErrGrantRevoked) || errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, ErrNotFound) {
return team.Admission{}, team.ErrGrantRevoked
diff --git a/internal/equipo/connection_models.go b/internal/equipo/connection_models.go
index f8f58de6..63e4a7ec 100644
--- a/internal/equipo/connection_models.go
+++ b/internal/equipo/connection_models.go
@@ -5,22 +5,15 @@ import (
"time"
"amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
)
// ConnectionRouting is an assertion by the authenticated runner about its
// operator-managed binding file and supported provider routing. It contains
// opaque account identity and a home hash, never credentials or home paths.
-type ConnectionRouting struct {
- BindingID, AccountID, ObservedAccountID, CredentialHomeHash string
- AccountPinned, NoFailover, TimelineRecovery, ProcessOwnership bool
-}
+type ConnectionRouting = runnerproto.ConnectionRouting
-type ConnectionReport struct {
- LocalID, Provider, ProviderVersion, PaseoVersion, Family, Model, AccountLabel, Kind, UnavailableReason, IsolationConfigHash string
- Available, ReadIsolation, AllowanceKnown bool
- AllowanceRemaining int64
- Routing ConnectionRouting
-}
+type ConnectionReport = runnerproto.ConnectionReport
type Connection struct {
ID string `gorm:"primaryKey"`
@@ -82,15 +75,7 @@ type ConnectionInvalidation struct {
At time.Time
}
-type Selection struct {
- ConnectionID, RunnerID, Person, Provider, Family, Model, AccountLabel, AccountID string
- Revision, ChoiceRevision, SpecialistRevision int64
- Reason string
- MaxConcurrent int
- AllowanceKnown bool
- AllowanceRemaining int64
- Isolation team.IsolationSnapshot
-}
+type Selection = runnerproto.Selection
// WithVerifiedIsolationTuples captures a copy at construction. Reports cannot
// extend this release-owned list. The production default is empty.
diff --git a/internal/equipo/connection_selection.go b/internal/equipo/connection_selection.go
index 410673aa..6a704115 100644
--- a/internal/equipo/connection_selection.go
+++ b/internal/equipo/connection_selection.go
@@ -58,6 +58,9 @@ func specialistAt(tx *gorm.DB, key string) (Specialist, error) {
if key == "engineering" {
capabilities = []string{"reproduce", "implement", "reconcile"}
}
+ if key == "review" {
+ capabilities = []string{"review", "verify"}
+ }
var live int64
if err := tx.Table("attempts").Joins("JOIN steps ON steps.id = attempts.step_id").Where("attempts.containment = ? AND steps.capability IN ?", "pending", capabilities).Count(&live).Error; err != nil {
return sp, storeError(err)
diff --git a/internal/equipo/execution.go b/internal/equipo/execution.go
index fccb0328..320ec292 100644
--- a/internal/equipo/execution.go
+++ b/internal/equipo/execution.go
@@ -2,19 +2,19 @@ package equipo
import (
"context"
- "database/sql"
"encoding/json"
"errors"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/rastrillo/rastrillo/db"
"gorm.io/gorm"
- "gorm.io/plugin/dbresolver"
)
type Execution struct {
- Core *team.Store
- db *db.DB
+ Core *team.Store
+ store *Store
+ validators RunnerValidators
+ db *db.DB
}
// AttachExecution is a startup operation, before serving requests.
@@ -26,11 +26,13 @@ func (s *Store) AttachExecution(ctx context.Context, path string, options team.O
if s.execution != nil {
return nil, ErrConflict
}
+ original := options.Provenance
+ options.Provenance = s.runnerProvenance(original)
core, err := team.OpenShared(ctx, s.db.Writer(), path, options)
if err != nil {
return nil, err
}
- x := &Execution{Core: core, db: s.db}
+ x := &Execution{Core: core, db: s.db, store: s}
if err := x.Write(ctx, func(tx *gorm.DB) error {
var instance Team
if err := tx.First(&instance).Error; err != nil {
@@ -72,11 +74,10 @@ func (e *Execution) Write(ctx context.Context, fn func(*gorm.DB) error) error {
if e == nil || e.Core == nil || e.db == nil {
return ErrUnavailable
}
- return e.Core.WithTransaction(ctx, func(tx *sql.Tx) error {
- g := e.db.G.Session(&gorm.Session{NewDB: true, Context: ctx, SkipDefaultTransaction: true, DisableNestedTransaction: true}).Clauses(dbresolver.Write)
- g.Statement.ConnPool = tx
- g.ConnPool = tx
- // A fresh statement prevents an earlier query error leaking into the next.
- return fn(g.Session(&gorm.Session{NewDB: true}))
+ return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ if err := fn(tx); err != nil {
+ return err
+ }
+ return e.syncExposure(ctx, tx)
})
}
diff --git a/internal/equipo/migrations/0013_runner_assignments.sql b/internal/equipo/migrations/0013_runner_assignments.sql
new file mode 100644
index 00000000..e68794d7
--- /dev/null
+++ b/internal/equipo/migrations/0013_runner_assignments.sql
@@ -0,0 +1,21 @@
+
+CREATE TABLE admission_tickets (
+ action_id INTEGER PRIMARY KEY REFERENCES actions(id),
+ job_id INTEGER NOT NULL REFERENCES jobs(id),
+ request_id TEXT NOT NULL,
+ attempt_id INTEGER NOT NULL REFERENCES attempts(id),
+ fence INTEGER NOT NULL,
+ runner TEXT NOT NULL,
+ dispatch TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ incarnation INTEGER NOT NULL,
+ UNIQUE(job_id, request_id)
+);
+UPDATE service SET schema_version=7 WHERE id=1;
+
+CREATE TABLE runner_assignments (id text, task_id text, step_key text, workspace_key text, team_id text, runner_id text, person text, selection text, isolation text, kind text, state text, revision integer, job_id integer, attempt_id integer, fence integer, claim_request text, brief text, lease_deadline datetime, invalidation_id integer, PRIMARY KEY (id));
+CREATE UNIQUE INDEX runner_assignment_step ON runner_assignments(task_id, step_key, revision);
+CREATE TABLE runner_cleanups (id text, assignment_id text, runner_id text, person text, machine_key_hash text, instance_id text, audience text, token_hash text, fence integer, attempt_id integer, expires_at datetime, PRIMARY KEY(id));
+CREATE UNIQUE INDEX runner_cleanup_token ON runner_cleanups(token_hash);
+CREATE TABLE runner_observations (assignment_id text, request_id text, operation text, payload_hash text, payload text, at datetime, PRIMARY KEY(assignment_id, request_id));
+CREATE TABLE runner_rotations (runner_id text, assignment_id text, request_id text, state text, credential_id text, PRIMARY KEY(runner_id));
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 470c4afe..243d843c 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -308,3 +308,25 @@ CREATE TABLE tasks (id text, requester text, description text, request_id text,
CREATE UNIQUE INDEX task_request ON tasks(requester, request_id);
CREATE TABLE task_outboxes (task_id text, state text, project_revision integer, budget_revision integer, engineering text, review text, prepared text, job_spec text, PRIMARY KEY (task_id));
CREATE UNIQUE INDEX jobs_request ON jobs(account, requester, request_key) WHERE request_key <> '';
+
+
+CREATE TABLE admission_tickets (
+ action_id INTEGER PRIMARY KEY REFERENCES actions(id),
+ job_id INTEGER NOT NULL REFERENCES jobs(id),
+ request_id TEXT NOT NULL,
+ attempt_id INTEGER NOT NULL REFERENCES attempts(id),
+ fence INTEGER NOT NULL,
+ runner TEXT NOT NULL,
+ dispatch TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ incarnation INTEGER NOT NULL,
+ UNIQUE(job_id, request_id)
+);
+
+
+CREATE TABLE runner_assignments (id text, task_id text, step_key text, workspace_key text, team_id text, runner_id text, person text, selection text, isolation text, kind text, state text, revision integer, job_id integer, attempt_id integer, fence integer, claim_request text, brief text, lease_deadline datetime, invalidation_id integer, PRIMARY KEY (id));
+CREATE UNIQUE INDEX runner_assignment_step ON runner_assignments(task_id, step_key, revision);
+CREATE TABLE runner_cleanups (id text, assignment_id text, runner_id text, person text, machine_key_hash text, instance_id text, audience text, token_hash text, fence integer, attempt_id integer, expires_at datetime, PRIMARY KEY(id));
+CREATE UNIQUE INDEX runner_cleanup_token ON runner_cleanups(token_hash);
+CREATE TABLE runner_observations (assignment_id text, request_id text, operation text, payload_hash text, payload text, at datetime, PRIMARY KEY(assignment_id, request_id));
+CREATE TABLE runner_rotations (runner_id text, assignment_id text, request_id text, state text, credential_id text, PRIMARY KEY(runner_id));
diff --git a/internal/equipo/models.go b/internal/equipo/models.go
index ded2f4b1..13b55b62 100644
--- a/internal/equipo/models.go
+++ b/internal/equipo/models.go
@@ -2,7 +2,7 @@ package equipo
import "time"
-var Models = append([]any{&Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
+var Models = append([]any{&runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...)
type Role string
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go
new file mode 100644
index 00000000..dcdd7ed1
--- /dev/null
+++ b/internal/equipo/runner_api.go
@@ -0,0 +1,215 @@
+package equipo
+
+import (
+ "mime"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "github.com/go-chi/chi/v5"
+)
+
+// RunnerHandler exposes only outbound runner protocol endpoints. Normal app
+// construction leaves execution unattached and these endpoints fail closed.
+func (s *Store) RunnerHandler() http.Handler {
+ r := chi.NewRouter()
+ r.Post("/poll", s.runnerPoll)
+ r.Post("/claim", s.runnerClaim)
+ for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ r.Post("/"+op, s.runnerMutation(op))
+ }
+ r.Post("/connections", s.runnerConnections)
+ r.Post("/heartbeat", s.runnerConnections)
+ r.Get("/artifacts/{assignment}/{artifact}", s.runnerArtifact)
+ return r
+}
+func runnerBody(w http.ResponseWriter, r *http.Request, v any, limit int64) bool {
+ content, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || content != "application/json" || runnerproto.DecodeLimit(r.Body, v, limit) != nil {
+ runnerFailure(w, ErrInvalid)
+ return false
+ }
+ return true
+}
+func (s *Store) runnerBearer(w http.ResponseWriter, r *http.Request) (RunnerPrincipal, string, bool) {
+ w.Header().Set("Cache-Control", "no-store")
+ values := r.Header.Values("Authorization")
+ if len(r.Header.Values("Cookie")) != 0 || len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") {
+ runnerFailure(w, ErrForbidden)
+ return RunnerPrincipal{}, "", false
+ }
+ token := strings.TrimPrefix(values[0], "Bearer ")
+ p, err := s.AuthenticateRunner(r.Context(), token)
+ if err != nil {
+ runnerFailure(w, err)
+ return p, "", false
+ }
+ return p, token, true
+}
+func (s *Store) runnerPoll(w http.ResponseWriter, r *http.Request) {
+ p, _, ok := s.runnerBearer(w, r)
+ if !ok {
+ return
+ }
+ var q runnerproto.PollRequest
+ if !runnerBody(w, r, &q, 8192) {
+ return
+ }
+ if q.Version != 1 {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ if s.execution == nil {
+ runnerFailure(w, ErrUnavailable)
+ return
+ }
+ if err := s.execution.Sync(r.Context()); err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ value, err := s.execution.Poll(r.Context(), p, q.After)
+ if err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: value})
+}
+func (s *Store) runnerClaim(w http.ResponseWriter, r *http.Request) {
+ p, _, ok := s.runnerBearer(w, r)
+ if !ok {
+ return
+ }
+ var q ClaimRequest
+ if !runnerBody(w, r, &q, 8192) {
+ return
+ }
+ if s.execution == nil {
+ runnerFailure(w, ErrUnavailable)
+ return
+ }
+ value, err := s.execution.Claim(r.Context(), p, q)
+ if err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: value})
+}
+func (s *Store) runnerMutation(op string) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if s.execution == nil {
+ runnerFailure(w, ErrUnavailable)
+ return
+ }
+ var q RunnerRequest
+ limit := int64(runnerproto.MaxActionBytes)
+ if op == "artifacts" {
+ limit = 2 * runnerproto.MaxArtifactBytes
+ }
+ if op == "events" {
+ limit = runnerproto.MaxEventBytes + 4096
+ }
+ if !runnerBody(w, r, &q, limit) {
+ return
+ }
+ var value any
+ var err error
+ if strings.HasPrefix(r.Header.Get("Authorization"), "Cleanup ") {
+ if len(r.Header.Values("Authorization")) != 1 || len(r.Header.Values("Cookie")) != 0 {
+ runnerFailure(w, ErrForbidden)
+ return
+ }
+ value, err = s.execution.Cleanup(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Cleanup "), op, q)
+ } else {
+ p, _, ok := s.runnerBearer(w, r)
+ if !ok {
+ return
+ }
+ value, err = s.execution.Mutate(r.Context(), p, op, q)
+ }
+ if err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: value})
+ }
+}
+func (s *Store) runnerConnections(w http.ResponseWriter, r *http.Request) {
+ p, _, ok := s.runnerBearer(w, r)
+ if !ok {
+ return
+ }
+ var q runnerproto.HeartbeatRequest
+ if !runnerBody(w, r, &q, runnerproto.MaxActionBytes) {
+ return
+ }
+ if q.Version != 1 || q.RequestID == "" || len(q.RequestID) > 256 {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ if q.RotationRequestID != "" {
+ if s.execution == nil {
+ runnerFailure(w, ErrUnavailable)
+ return
+ }
+ if err := s.execution.AcknowledgeRotation(r.Context(), p, q.RotationRequestID); err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ }
+ if len(q.Reports) > 0 {
+ var reports []ConnectionReport
+ if runnerproto.DecodeLimit(strings.NewReader(string(q.Reports)), &reports, runnerproto.MaxActionBytes) != nil {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ if err := s.ReportConnections(r.Context(), p, reports); err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ }
+ runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: struct{}{}})
+}
+func (s *Store) runnerArtifact(w http.ResponseWriter, r *http.Request) {
+ p, _, ok := s.runnerBearer(w, r)
+ if !ok {
+ return
+ }
+ if s.execution == nil {
+ runnerFailure(w, ErrUnavailable)
+ return
+ }
+ id, err := strconv.ParseInt(chi.URLParam(r, "artifact"), 10, 64)
+ if err != nil {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ q := r.URL.Query()
+ if q.Get("version") != "1" {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ attempt, err := strconv.ParseInt(q.Get("attempt"), 10, 64)
+ if err != nil {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ fence, err := strconv.ParseInt(q.Get("fence"), 10, 64)
+ if err != nil {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ job, err := strconv.ParseInt(q.Get("job"), 10, 64)
+ if err != nil {
+ runnerFailure(w, ErrInvalid)
+ return
+ }
+ request := RunnerRequest{Version: 1, AssignmentID: chi.URLParam(r, "assignment"), RequestID: q.Get("request_id"), Scope: Scope{Account: team.AccountID(q.Get("account")), Job: team.JobID(job)}, Handle: team.Handle{Attempt: team.AttemptID(attempt), Fence: fence, Runner: p.RunnerID}}
+ value, err := s.execution.ReadArtifact(r.Context(), p, request, team.ArtifactID(id))
+ if err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: value})
+}
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go
new file mode 100644
index 00000000..9f63cd76
--- /dev/null
+++ b/internal/equipo/runner_execution.go
@@ -0,0 +1,499 @@
+package equipo
+
+import (
+ "context"
+ "crypto/rand"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "gorm.io/gorm"
+ "gorm.io/plugin/dbresolver"
+)
+
+type runnerTxKey struct{}
+
+func (e *Execution) gormTx(ctx context.Context, tx *sql.Tx) *gorm.DB {
+ g := e.db.G.Session(&gorm.Session{NewDB: true, Context: ctx, SkipDefaultTransaction: true, DisableNestedTransaction: true}).Clauses(dbresolver.Write)
+ g.Statement.ConnPool = tx
+ g.ConnPool = tx
+ return g.Session(&gorm.Session{NewDB: true})
+}
+func (e *Execution) atomic(ctx context.Context, fn func(context.Context, *gorm.DB) error) error {
+ return e.Core.Atomic(ctx, func(ctx context.Context, raw *sql.Tx) error {
+ tx := e.gormTx(ctx, raw)
+ ctx = context.WithValue(ctx, runnerTxKey{}, tx)
+ return fn(ctx, tx.WithContext(ctx))
+ })
+}
+func assignmentValue(a runnerAssignment) (Assignment, error) {
+ var sel Selection
+ if err := json.Unmarshal([]byte(a.Selection), &sel); err != nil {
+ return Assignment{}, err
+ }
+ var iso team.IsolationSnapshot
+ if err := json.Unmarshal([]byte(a.Isolation), &iso); err != nil {
+ return Assignment{}, err
+ }
+ sel.Isolation = iso
+ return Assignment{ID: a.ID, TaskID: a.TaskID, StepKey: a.StepKey, WorkspaceKey: a.WorkspaceKey, Scope: Scope{Account: team.AccountID(a.TeamID), Job: team.JobID(a.JobID)}, Selection: sel, Revision: a.Revision, Kind: a.Kind}, nil
+}
+func specialistFor(step string) string {
+ switch step {
+ case "review", "verify":
+ return "review"
+ default:
+ return "engineering"
+ }
+}
+func mergeIsolation(a, b team.IsolationSnapshot) team.IsolationSnapshot {
+ if b.Status == "unconfined" {
+ a.Status = "unconfined"
+ }
+ a.RunnerTainted = a.RunnerTainted || b.RunnerTainted
+ for _, id := range b.AcknowledgementIDs {
+ if !slices.Contains(a.AcknowledgementIDs, id) {
+ a.AcknowledgementIDs = append(a.AcknowledgementIDs, id)
+ }
+ }
+ for _, tuple := range b.ObservedTuples {
+ if !slices.Contains(a.ObservedTuples, tuple) {
+ a.ObservedTuples = append(a.ObservedTuples, tuple)
+ }
+ }
+ return a
+}
+func (s *Store) selectionCurrent(tx *gorm.DB, task Task, step string, sel Selection) (Selection, error) {
+ if _, err := bugAuthority(tx, Actor{Address: task.Requester}, task.ProjectID); err != nil {
+ return sel, err
+ }
+ if sel.Person != task.Requester {
+ return sel, ErrForbidden
+ }
+ choice, ids, err := choiceAt(tx, task.Requester, task.ProjectID)
+ if err != nil {
+ return sel, err
+ }
+ if !slices.Contains(ids, sel.ConnectionID) || (choice.Revision != sel.ChoiceRevision && choice.PinnedID != "" && choice.PinnedID != sel.ConnectionID && specialistFor(step) != "review") {
+ return sel, ErrConflict
+ }
+ var sp Specialist
+ if err := tx.First(&sp, "key=?", specialistFor(step)).Error; err != nil {
+ return sel, storeError(err)
+ }
+ if sp.Revision != sel.SpecialistRevision {
+ return sel, ErrConflict
+ }
+ var c connectionRecord
+ if err := tx.First(&c, "id=?", sel.ConnectionID).Error; err != nil {
+ return sel, storeError(err)
+ }
+ if c.Person != sel.Person || c.RunnerID != sel.RunnerID || c.Revision != sel.Revision {
+ return sel, ErrConflict
+ }
+ if err := decodeConnection(&c); err != nil {
+ return sel, err
+ }
+ for _, r := range c.Reports {
+ if r.Model != sel.Model || r.Provider != sel.Provider || r.Family != sel.Family || r.Routing.AccountID != sel.AccountID {
+ continue
+ }
+ ok, _, err := s.eligible(tx, c, r, s.runnerClock.Now().UTC())
+ if err != nil {
+ return sel, err
+ }
+ if !ok {
+ return sel, ErrForbidden
+ }
+ iso, err := s.isolationSnapshot(tx, c, r)
+ if err != nil {
+ return sel, err
+ }
+ sel.Isolation = mergeIsolation(sel.Isolation, iso)
+ return sel, nil
+ }
+ return sel, ErrForbidden
+}
+func (e *Execution) assignmentCurrent(ctx context.Context, tx *gorm.DB, p RunnerPrincipal, a runnerAssignment) (Assignment, error) {
+ if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil {
+ return Assignment{}, err
+ }
+ if a.RunnerID != p.RunnerID || a.Person != p.Person {
+ return Assignment{}, ErrForbidden
+ }
+ var rotation runnerRotation
+ err := tx.First(&rotation, "runner_id=?", p.RunnerID).Error
+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return Assignment{}, storeError(err)
+ }
+ if err == nil && rotation.State != "ready" {
+ return Assignment{}, ErrUnavailable
+ }
+ value, err := assignmentValue(a)
+ if err != nil {
+ return value, err
+ }
+ var task Task
+ if err := tx.First(&task, "id=?", a.TaskID).Error; err != nil {
+ return value, storeError(err)
+ }
+ if task.TeamID != a.TeamID || int64(task.JobID) != a.JobID || task.Requester != a.Person {
+ return value, ErrForbidden
+ }
+ sel, err := e.store.selectionCurrent(tx, task, a.StepKey, value.Selection)
+ if err != nil {
+ return value, err
+ }
+ // Both families must still be available before any provider spending.
+ if specialistFor(a.StepKey) == "engineering" {
+ var out taskOutbox
+ if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil {
+ return value, storeError(err)
+ }
+ var rev Selection
+ if err := json.Unmarshal([]byte(out.Review), &rev); err != nil {
+ return value, err
+ }
+ if rev.Family == sel.Family || rev.RunnerID != sel.RunnerID {
+ return value, ErrForbidden
+ }
+ if _, err := e.store.selectionCurrent(tx, task, "review", rev); err != nil {
+ return value, err
+ }
+ }
+ value.Selection = sel
+ iso, _ := json.Marshal(sel.Isolation)
+ if err := tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("Isolation").Updates(&runnerAssignment{Isolation: string(iso)}).Error; err != nil {
+ return value, storeError(err)
+ }
+ return value, nil
+}
+func (e *Execution) Sync(ctx context.Context) error {
+ return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ // Preserve exposure on all existing work, including evidence already registered.
+ if err := e.syncExposure(ctx, tx); err != nil {
+ return err
+ }
+ var recovered []runnerAssignment
+ if err := tx.Where("attempt_id IN (SELECT id FROM attempts WHERE containment='contained') AND state NOT IN ?", []string{"contained", "reconcile"}).Find(&recovered).Error; err != nil {
+ return storeError(err)
+ }
+ for _, a := range recovered {
+ value, err := assignmentValue(a)
+ if err != nil {
+ return err
+ }
+ state := "contained"
+ if value.Selection.Isolation.RunnerTainted || value.Selection.Isolation.Status == "unconfined" {
+ state = "reconcile"
+ if err := tx.Exec("INSERT INTO runner_rotations(runner_id,assignment_id,request_id,state,credential_id) VALUES(?,?,?,'reconcile','') ON CONFLICT(runner_id) DO UPDATE SET state='reconcile'", a.RunnerID, a.ID, "").Error; err != nil {
+ return storeError(err)
+ }
+ }
+ if err := tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: state}).Error; err != nil {
+ return storeError(err)
+ }
+ }
+ var prepared []Task
+ if err := tx.Where("state=?", "prepared").Find(&prepared).Error; err != nil {
+ return storeError(err)
+ }
+ for _, task := range prepared {
+ var out taskOutbox
+ if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil {
+ return storeError(err)
+ }
+ var sel Selection
+ if err := json.Unmarshal([]byte(out.Engineering), &sel); err != nil {
+ return err
+ }
+ var credential runnerCredentialRecord
+ err := tx.Where("runner_id=? AND revoked_at IS NULL AND expires_at>?", sel.RunnerID, e.store.runnerClock.Now().UTC()).First(&credential).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ continue
+ }
+ if err != nil {
+ return storeError(err)
+ }
+ if _, err := e.store.StartBug(ctx, RunnerPrincipal{RunnerID: sel.RunnerID, Person: task.Requester, CredentialID: credential.ID}, task.ID, task.Revision); err != nil {
+ return err
+ }
+ }
+ var tasks []Task
+ if err := tx.Where("state IN ?", []string{"preparing", "queued"}).Find(&tasks).Error; err != nil {
+ return storeError(err)
+ }
+ for _, task := range tasks {
+ var out taskOutbox
+ if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil {
+ return storeError(err)
+ }
+ var eng, rev Selection
+ if json.Unmarshal([]byte(out.Engineering), &eng) != nil || json.Unmarshal([]byte(out.Review), &rev) != nil {
+ return ErrUnavailable
+ }
+ keys := []string{"prepare"}
+ if task.JobID != 0 {
+ job, err := e.Core.GetJob(ctx, Scope{Account: team.AccountID(task.TeamID), Job: task.JobID})
+ if err != nil {
+ return err
+ }
+ if job.State.Terminal() {
+ continue
+ }
+ keys = nil
+ steps, err := e.Core.Steps(ctx, Scope{Account: team.AccountID(task.TeamID), Job: task.JobID})
+ if err != nil {
+ return err
+ }
+ for _, st := range steps {
+ if st.State != team.StepPending {
+ continue
+ }
+ ready := true
+ for _, dep := range st.DependsOn {
+ for _, other := range steps {
+ if other.Key == dep && other.State != team.StepSucceeded {
+ ready = false
+ }
+ }
+ }
+ if ready {
+ keys = append(keys, st.Key)
+ }
+ }
+ }
+ for _, key := range keys {
+ var count int64
+ if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND step_key=? AND state!=?", task.ID, key, "contained").Count(&count).Error; err != nil {
+ return storeError(err)
+ }
+ if count > 0 {
+ continue
+ }
+ sel := eng
+ if specialistFor(key) == "review" {
+ sel = rev
+ }
+ raw, _ := json.Marshal(sel)
+ iso, _ := json.Marshal(sel.Isolation)
+ kind := "step"
+ if key == "prepare" {
+ kind = "prepare"
+ }
+ var revision int64
+ if err := tx.Raw("SELECT COALESCE(MAX(revision),0)+1 FROM runner_assignments WHERE task_id=? AND step_key=?", task.ID, key).Scan(&revision).Error; err != nil {
+ return storeError(err)
+ }
+ var sequence int64
+ if err := tx.Raw("SELECT COALESCE(MAX(CAST(id AS INTEGER)),0)+1 FROM runner_assignments").Scan(&sequence).Error; err != nil {
+ return storeError(err)
+ }
+ a := runnerAssignment{ID: fmt.Sprintf("%020d", sequence), TaskID: task.ID, StepKey: key, WorkspaceKey: rand.Text(), TeamID: task.TeamID, RunnerID: sel.RunnerID, Person: task.Requester, Selection: string(raw), Isolation: string(iso), Kind: kind, State: "pending", Revision: revision, JobID: int64(task.JobID)}
+ if err := tx.Create(&a).Error; err != nil {
+ return storeError(err)
+ }
+ }
+ }
+ return nil
+ })
+}
+func (e *Execution) Poll(ctx context.Context, p RunnerPrincipal, after string) ([]Assignment, error) {
+ parent := ctx
+ ctx, cancel := context.WithTimeout(ctx, runnerproto.LongPollSeconds*time.Second)
+ defer cancel()
+ deadline := time.NewTimer(runnerproto.LongPollSeconds * time.Second)
+ defer deadline.Stop()
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ var values []Assignment
+ err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ if err := e.Core.AdmissionAvailable(ctx); err != nil {
+ return err
+ }
+ var rows []runnerAssignment
+ if err := tx.Where("runner_id=? AND person=? AND state=? AND id>?", p.RunnerID, p.Person, "pending", after).Order("id").Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ for _, a := range rows {
+ value, err := e.assignmentCurrent(ctx, tx, p, a)
+ if err != nil {
+ return err
+ }
+ values = append(values, value)
+ }
+ return nil
+ })
+ if err != nil {
+ if errors.Is(err, context.DeadlineExceeded) && parent.Err() == nil {
+ return []Assignment{}, nil
+ }
+ return nil, err
+ }
+ if len(values) > 0 {
+ return values, nil
+ }
+ select {
+ case <-ctx.Done():
+ if errors.Is(ctx.Err(), context.DeadlineExceeded) && parent.Err() == nil {
+ return []Assignment{}, nil
+ }
+ return nil, ctx.Err()
+ case <-deadline.C:
+ return []Assignment{}, nil
+ case <-tick.C:
+ }
+ }
+}
+func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest) (ClaimResponse, error) {
+ if q.Version != 1 || q.AssignmentID == "" || q.RequestID == "" || len(q.RequestID) > 256 {
+ return ClaimResponse{}, ErrInvalid
+ }
+ var result ClaimResponse
+ err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ if err := e.Core.AdmissionAvailable(ctx); err != nil {
+ return err
+ }
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ value, err := e.assignmentCurrent(ctx, tx, p, a)
+ if err != nil {
+ return err
+ }
+ if a.Revision != q.Revision {
+ return ErrConflict
+ }
+ if a.State == "claimed" && a.ClaimRequest == q.RequestID {
+ h := team.Handle{Attempt: team.AttemptID(a.AttemptID), Fence: a.Fence, Runner: a.RunnerID}
+ if a.Kind == "step" {
+ if err := e.Core.ValidateHandle(ctx, value.Scope, h); err != nil {
+ return err
+ }
+ job, err := e.Core.GetJob(ctx, value.Scope)
+ if err != nil {
+ return err
+ }
+ h.Revision = job.Revision
+ }
+ if !e.store.runnerClock.Now().Before(a.LeaseDeadline) {
+ return ErrForbidden
+ }
+ var brief RunnerBrief
+ if err := json.Unmarshal([]byte(a.Brief), &brief); err != nil {
+ return err
+ }
+ brief.Selection = value.Selection
+ var c runnerCleanup
+ if err := tx.First(&c, "assignment_id=?", a.ID).Error; err != nil {
+ return storeError(err)
+ }
+ token := runnerSecret()
+ if err := tx.Model(&runnerCleanup{}).Where("id=?", c.ID).Select("TokenHash").Updates(&runnerCleanup{TokenHash: runnerHash(runnerproto.CleanupAudience, token)}).Error; err != nil {
+ return storeError(err)
+ }
+ result = ClaimResponse{Scope: value.Scope, Handle: h, Brief: brief, LeaseDeadline: a.LeaseDeadline, CleanupToken: token, CleanupExpiresAt: c.ExpiresAt, RenewSeconds: 15}
+ return nil
+ }
+ if a.State != "pending" {
+ return ErrConflict
+ }
+ var task Task
+ if err := tx.First(&task, "id=?", a.TaskID).Error; err != nil {
+ return storeError(err)
+ }
+ if _, err := specialistAt(tx, specialistFor(a.StepKey)); err != nil {
+ return err
+ }
+ // Preparation occupies the same specialist slot before it has a core attempt.
+ var preparing int64
+ if err := tx.Model(&runnerAssignment{}).Where("kind='prepare' AND state='claimed'").Count(&preparing).Error; err != nil {
+ return storeError(err)
+ }
+ if preparing > 0 {
+ return ErrUnavailable
+ }
+ var project Project
+ if err := tx.First(&project, task.ProjectID).Error; err != nil {
+ return storeError(err)
+ }
+ var sp Specialist
+ if err := tx.First(&sp, "key=?", specialistFor(a.StepKey)).Error; err != nil {
+ return storeError(err)
+ }
+ policy, err := bugPolicy(tx, task)
+ if err != nil {
+ return err
+ }
+ brief := RunnerBrief{Policy: policy, Target: team.TargetBinding{Kind: team.TargetRepository, Repository: project.Repository, DefaultRef: project.DefaultBranch, Ref: task.ReviewRef, BaseRevision: task.BaseCommit}, Instructions: task.Description, StandingInstructions: sp.StandingInstructions, ConfirmedPreferences: []string{}, Selection: value.Selection, ArtifactHashes: []string{}}
+ if task.CheckDefinitionHash != "" {
+ brief.ArtifactHashes = append(brief.ArtifactHashes, task.CheckDefinitionHash)
+ }
+ deadline := e.store.runnerClock.Now().UTC().Add(30 * time.Second)
+ h := team.Handle{Revision: task.Revision, Fence: a.Revision, Runner: p.RunnerID}
+ if a.Kind == "step" {
+ h, err = e.Core.Claim(ctx, value.Scope, a.StepKey, p.RunnerID, a.WorkspaceKey)
+ if err != nil {
+ return err
+ }
+ job, err := e.Core.GetJob(ctx, value.Scope)
+ if err != nil {
+ return err
+ }
+ brief.Policy = job.Policy
+ brief.Target = job.Target
+ attempts, err := e.Core.Attempts(ctx, value.Scope)
+ if err != nil {
+ return err
+ }
+ for _, att := range attempts {
+ if att.ID == h.Attempt {
+ deadline = att.LeaseDeadline
+ }
+ }
+ artifacts, err := e.Core.Artifacts(ctx, value.Scope)
+ if err != nil {
+ return err
+ }
+ for _, art := range artifacts {
+ brief.ArtifactHashes = append(brief.ArtifactHashes, art.Hash)
+ }
+ }
+ runner, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC())
+ if err != nil {
+ return err
+ }
+ token := runnerSecret()
+ now := e.store.runnerClock.Now().UTC()
+ cleanup := runnerCleanup{ID: rand.Text(), AssignmentID: a.ID, RunnerID: runner.ID, Person: runner.Person, MachineKeyHash: runner.MachineKeyHash, InstanceID: runner.InstanceID, Audience: runnerproto.CleanupAudience, TokenHash: runnerHash(runnerproto.CleanupAudience, token), AttemptID: int64(h.Attempt), Fence: h.Fence, ExpiresAt: now.Add(30 * 24 * time.Hour)}
+ if err := tx.Create(&cleanup).Error; err != nil {
+ return storeError(err)
+ }
+ raw, _ := json.Marshal(brief)
+ a.Brief = string(raw)
+ a.AttemptID = int64(h.Attempt)
+ a.Fence = h.Fence
+ a.LeaseDeadline = deadline
+ a.State = "claimed"
+ a.ClaimRequest = q.RequestID
+ if err := tx.Model(&runnerAssignment{}).Where("id=? AND state='pending'", a.ID).Select("Brief", "AttemptID", "Fence", "LeaseDeadline", "State", "ClaimRequest").Updates(&a).Error; err != nil {
+ return storeError(err)
+ }
+ result = ClaimResponse{Scope: value.Scope, Handle: h, Brief: brief, LeaseDeadline: deadline, CleanupToken: token, CleanupExpiresAt: cleanup.ExpiresAt, RenewSeconds: 15}
+ return appendAudit(tx, Actor{Address: p.Person}, "runner.claim", a.ID)
+ })
+ if err != nil {
+ return ClaimResponse{}, err
+ }
+ return result, nil
+}
diff --git a/internal/equipo/runner_execution_models.go b/internal/equipo/runner_execution_models.go
new file mode 100644
index 00000000..b201eaee
--- /dev/null
+++ b/internal/equipo/runner_execution_models.go
@@ -0,0 +1,81 @@
+package equipo
+
+import (
+ "context"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type Scope = team.Scope
+type ClaimRequest = runnerproto.ClaimRequest
+type RunnerRequest = runnerproto.RunnerRequest
+
+type Assignment = runnerproto.Assignment
+type RunnerBrief = runnerproto.RunnerBrief
+type ClaimResponse = runnerproto.ClaimResponse
+type runnerAssignment struct {
+ ID string `gorm:"primaryKey"`
+ TaskID string `gorm:"uniqueIndex:runner_assignment_step"`
+ StepKey string `gorm:"uniqueIndex:runner_assignment_step"`
+ WorkspaceKey, TeamID, RunnerID, Person, Selection, Isolation, Kind, State string
+ Revision int64 `gorm:"uniqueIndex:runner_assignment_step"`
+ JobID, AttemptID, Fence int64
+ ClaimRequest, Brief string
+ LeaseDeadline time.Time
+ InvalidationID int64
+}
+
+func (runnerAssignment) TableName() string { return "runner_assignments" }
+
+type runnerCleanup struct {
+ ID string `gorm:"primaryKey"`
+ AssignmentID, RunnerID, Person, MachineKeyHash, InstanceID, Audience string
+ TokenHash string `gorm:"uniqueIndex:runner_cleanup_token"`
+ Fence, AttemptID int64
+ ExpiresAt time.Time
+}
+
+func (runnerCleanup) TableName() string { return "runner_cleanups" }
+
+type runnerObservation struct {
+ AssignmentID string `gorm:"primaryKey"`
+ RequestID string `gorm:"primaryKey"`
+ Operation, PayloadHash, Payload string
+ At time.Time
+}
+
+func (runnerObservation) TableName() string { return "runner_observations" }
+
+type runnerRotation struct {
+ RunnerID string `gorm:"primaryKey"`
+ AssignmentID, RequestID, State, CredentialID string
+}
+
+func (runnerRotation) TableName() string { return "runner_rotations" }
+
+type executionAdmissionTicket struct {
+ ActionID int64 `gorm:"primaryKey;autoIncrement:false"`
+ JobID int64 `gorm:"not null"`
+ RequestID string `gorm:"not null"`
+ AttemptID int64 `gorm:"not null"`
+ Fence int64 `gorm:"not null"`
+ Runner, Dispatch, ExpiresAt string `gorm:"not null"`
+ Incarnation int64 `gorm:"not null"`
+}
+
+func (executionAdmissionTicket) TableName() string { return "admission_tickets" }
+
+type RunnerValidators struct {
+ Receipt func(context.Context, Assignment, RunnerRequest) (team.Receipt, error)
+ Containment func(context.Context, Assignment, RunnerRequest) error
+ Prepare func(context.Context, Assignment, RunnerRequest) (PreparedBug, error)
+ Events func(context.Context, Assignment, RunnerRequest) error
+ Artifact func(context.Context, Assignment, RunnerRequest) error
+}
+
+// SetRunnerValidators is a startup-only dependency injection seam.
+func (e *Execution) SetRunnerValidators(v RunnerValidators) { e.validators = v }
+
+type CredentialRotation = runnerproto.CredentialRotation
diff --git a/internal/equipo/runner_handlers.go b/internal/equipo/runner_handlers.go
index ba39574a..b3c66c72 100644
--- a/internal/equipo/runner_handlers.go
+++ b/internal/equipo/runner_handlers.go
@@ -2,7 +2,6 @@ package equipo
import (
"context"
- "encoding/json"
"errors"
"mime"
"net/http"
@@ -25,7 +24,8 @@ func runnerJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
- _ = json.NewEncoder(w).Encode(value)
+ data, _ := runnerproto.Marshal(value)
+ _, _ = w.Write(append(data, '\n'))
}
func runnerFailure(w http.ResponseWriter, err error) {
status, key := 503, "service.unavailable"
diff --git a/internal/equipo/runner_mutations.go b/internal/equipo/runner_mutations.go
new file mode 100644
index 00000000..4a1ef392
--- /dev/null
+++ b/internal/equipo/runner_mutations.go
@@ -0,0 +1,322 @@
+package equipo
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "gorm.io/gorm"
+)
+
+func requestValid(q RunnerRequest) bool {
+ return q.Version == 1 && q.RequestID != "" && len(q.RequestID) <= 256 && q.AssignmentID != ""
+}
+func binding(a runnerAssignment, q RunnerRequest) bool {
+ return a.TeamID == string(q.Scope.Account) && a.JobID == int64(q.Scope.Job) && a.AttemptID == int64(q.Handle.Attempt) && a.Fence == q.Handle.Fence && a.RunnerID == q.Handle.Runner
+}
+func (e *Execution) Mutate(ctx context.Context, p RunnerPrincipal, op string, q RunnerRequest) (any, error) {
+ if !requestValid(q) {
+ return nil, ErrInvalid
+ }
+ if op == "contained" {
+ if err := e.containmentBarrier(ctx, p, "", q); err != nil {
+ return nil, err
+ }
+ }
+ var result any
+ err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ if err := e.syncExposure(ctx, tx); err != nil {
+ return err
+ }
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ if !binding(a, q) {
+ return ErrForbidden
+ }
+ historical := op == "receipts" || op == "lost" || op == "contained"
+ value, err := assignmentValue(a)
+ if err != nil {
+ return err
+ }
+ if historical {
+ if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ if a.RunnerID != p.RunnerID || a.Person != p.Person {
+ return ErrForbidden
+ }
+ } else {
+ value, err = e.assignmentCurrent(ctx, tx, p, a)
+ if err != nil {
+ return err
+ }
+ }
+ if !historical {
+ if err := e.Core.AdmissionAvailable(ctx); err != nil {
+ return err
+ }
+ if a.State != "claimed" {
+ return ErrForbidden
+ }
+ if a.Kind == "step" {
+ if err := e.Core.ValidateHandle(ctx, q.Scope, q.Handle); err != nil {
+ return err
+ }
+ } else if !e.store.runnerClock.Now().Before(a.LeaseDeadline) {
+ return ErrForbidden
+ }
+ }
+ result, err = e.mutateAt(ctx, tx, a, value, op, q, false)
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+func (e *Execution) Cleanup(ctx context.Context, token, op string, q RunnerRequest) (any, error) {
+ if !requestValid(q) || (op != "receipts" && op != "lost" && op != "contained") {
+ return nil, ErrForbidden
+ }
+ if op == "contained" {
+ if err := e.containmentBarrier(ctx, RunnerPrincipal{}, token, q); err != nil {
+ return nil, err
+ }
+ }
+ var result any
+ err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ var cleanup runnerCleanup
+ if err := tx.First(&cleanup, "token_hash=?", runnerHash(runnerproto.CleanupAudience, token)).Error; err != nil {
+ return storeError(err)
+ }
+ now := e.store.runnerClock.Now().UTC()
+ if cleanup.Audience != runnerproto.CleanupAudience || !now.Before(cleanup.ExpiresAt) || cleanup.AssignmentID != q.AssignmentID || cleanup.AttemptID != int64(q.Handle.Attempt) || cleanup.Fence != q.Handle.Fence {
+ return ErrForbidden
+ }
+ var runner runnerRecord
+ if err := tx.First(&runner, "id=?", cleanup.RunnerID).Error; err != nil {
+ return storeError(err)
+ }
+ instance, err := runnerInstance(tx)
+ if err != nil {
+ return err
+ }
+ if cleanup.InstanceID != instance || runner.InstanceID != instance || runner.Person != cleanup.Person || runner.MachineKeyHash != cleanup.MachineKeyHash {
+ return ErrForbidden
+ }
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ if !binding(a, q) || a.RunnerID != runner.ID || a.Person != runner.Person {
+ return ErrForbidden
+ }
+ value, err := assignmentValue(a)
+ if err != nil {
+ return err
+ }
+ result, err = e.mutateAt(ctx, tx, a, value, op, q, true)
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+func observeRunner(tx *gorm.DB, a runnerAssignment, op string, q RunnerRequest, now time.Time) (bool, error) {
+ raw, err := json.Marshal(q)
+ if err != nil {
+ return false, err
+ }
+ sum := sha256.Sum256(raw)
+ hash := hex.EncodeToString(sum[:])
+ var old runnerObservation
+ err = tx.First(&old, "assignment_id=? AND request_id=?", a.ID, q.RequestID).Error
+ if err == nil {
+ if old.Operation != op || old.PayloadHash != hash {
+ return false, ErrConflict
+ }
+ return true, nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return false, storeError(err)
+ }
+ return false, storeError(tx.Create(&runnerObservation{AssignmentID: a.ID, RequestID: q.RequestID, Operation: op, PayloadHash: hash, Payload: string(raw), At: now}).Error)
+}
+func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, op string, q RunnerRequest, cleanup bool) (any, error) {
+ now := e.store.runnerClock.Now().UTC()
+ switch op {
+ case "renew":
+ deadline := now.Add(30 * time.Second)
+ if a.Kind == "step" {
+ var err error
+ deadline, err = e.Core.Renew(ctx, q.Scope, q.Handle)
+ if err != nil {
+ return nil, err
+ }
+ }
+ return deadline, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("LeaseDeadline").Updates(&runnerAssignment{LeaseDeadline: deadline}).Error)
+ case "intend":
+ if a.Kind != "step" || q.Intent == nil {
+ return nil, ErrInvalid
+ }
+ raw, _ := json.Marshal(q.Intent)
+ if len(raw) > runnerproto.MaxActionBytes {
+ return nil, ErrInvalid
+ }
+ return e.Core.Intend(ctx, q.Scope, q.Handle, *q.Intent)
+ case "admit":
+ if a.Kind != "step" {
+ return nil, ErrInvalid
+ }
+ return e.Core.AdmitOnce(ctx, q.Scope, q.Handle, q.ActionID, q.RequestID)
+ case "receipts", "lost":
+ // Authenticated runners and cleanup holders report observations, not trusted
+ // billing receipts. Reconciliation validators perform settlement later.
+ action, err := e.Core.GetAction(ctx, q.Scope, q.ActionID)
+ if err != nil {
+ return nil, err
+ }
+ if action.Attempt != q.Handle.Attempt || action.Fence != q.Handle.Fence {
+ return nil, ErrForbidden
+ }
+ if op == "receipts" && q.Receipt == nil {
+ return nil, ErrInvalid
+ }
+ _, err = observeRunner(tx, a, op, q, now)
+ if err != nil {
+ return nil, err
+ }
+ if !cleanup && op == "receipts" && e.validators.Receipt != nil {
+ receipt, err := e.validators.Receipt(ctx, value, q)
+ if err != nil {
+ return nil, err
+ }
+ return nil, e.Core.Record(ctx, q.Scope, q.ActionID, receipt)
+ }
+ return nil, nil
+ case "contained":
+ if e.validators.Containment == nil {
+ return nil, ErrUnavailable
+ }
+ retry, err := observeRunner(tx, a, op, q, now)
+ if err != nil {
+ return nil, err
+ }
+ if retry || a.State == "contained" {
+ return CredentialRotation{}, nil
+ }
+ if err := e.validators.Containment(ctx, value, q); err != nil {
+ return nil, err
+ }
+ if a.Kind == "step" {
+ if err := e.Core.ContainUntrusted(ctx, q.Scope, q.Handle); err != nil {
+ return nil, err
+ }
+ }
+ if err := tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "contained"}).Error; err != nil {
+ return nil, storeError(err)
+ }
+ if value.Selection.Isolation.RunnerTainted || value.Selection.Isolation.Status == "unconfined" {
+ return e.rotateContained(tx, a, q, now)
+ }
+ return CredentialRotation{}, nil
+ case "stop":
+ if a.Kind == "step" {
+ return nil, e.Core.StopAttempt(ctx, q.Scope, q.Handle, "runner_stop")
+ }
+ return nil, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error)
+ case "release":
+ if a.Kind != "step" {
+ return nil, ErrInvalid
+ }
+ return nil, e.Core.Release(ctx, q.Scope, q.Handle, q.Reason, "runner_release")
+ case "complete":
+ if a.Kind != "step" || q.Result == nil {
+ return nil, ErrInvalid
+ }
+ return nil, e.Core.Complete(ctx, q.Scope, q.Handle, *q.Result)
+ case "prepare":
+ if a.Kind != "prepare" || e.validators.Prepare == nil {
+ return nil, ErrUnavailable
+ }
+ prepared, err := e.validators.Prepare(ctx, value, q)
+ if err != nil {
+ return nil, err
+ }
+ var task Task
+ if err := tx.First(&task, "id=?", a.TaskID).Error; err != nil {
+ return nil, storeError(err)
+ }
+ // The validated payload is applied through Task 7's transaction checks.
+ var credential runnerCredentialRecord
+ if err := tx.Where("runner_id=? AND revoked_at IS NULL AND expires_at>?", a.RunnerID, now).First(&credential).Error; err != nil {
+ return nil, storeError(err)
+ }
+ task, err = e.store.PrepareBug(ctx, RunnerPrincipal{a.RunnerID, a.Person, credential.ID}, task.ID, task.Revision, prepared)
+ if err != nil {
+ return nil, err
+ }
+ return task, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "prepared"}).Error)
+ case "events":
+ if len(q.Event) == 0 || len(q.Event) > runnerproto.MaxEventBytes {
+ return nil, ErrInvalid
+ }
+ if e.validators.Events == nil {
+ return nil, ErrUnavailable
+ }
+ if err := e.validators.Events(ctx, value, q); err != nil {
+ return nil, err
+ }
+ _, err := observeRunner(tx, a, op, q, now)
+ return nil, err
+ case "artifacts":
+ if a.Kind != "step" || q.Artifact == nil || len(q.Artifact.Payload) > runnerproto.MaxArtifactBytes {
+ return nil, ErrInvalid
+ }
+ if e.validators.Artifact == nil {
+ return nil, ErrUnavailable
+ }
+ if err := e.validators.Artifact(ctx, value, q); err != nil {
+ return nil, err
+ }
+ return e.Core.Register(ctx, q.Scope, q.Handle, *q.Artifact)
+ }
+ return nil, ErrInvalid
+}
+
+func (e *Execution) ReadArtifact(ctx context.Context, p RunnerPrincipal, q RunnerRequest, id team.ArtifactID) (team.Artifact, error) {
+ if !requestValid(q) {
+ return team.Artifact{}, ErrInvalid
+ }
+ var result team.Artifact
+ err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ if !binding(a, q) || a.State != "claimed" {
+ return ErrForbidden
+ }
+ if _, err := e.assignmentCurrent(ctx, tx, p, a); err != nil {
+ return err
+ }
+ if err := e.Core.ValidateHandle(ctx, q.Scope, q.Handle); err != nil {
+ return err
+ }
+ var err error
+ result, err = e.Core.Artifact(ctx, q.Scope, id)
+ return err
+ })
+ if err != nil {
+ return team.Artifact{}, err
+ }
+ return result, nil
+}
diff --git a/internal/equipo/runner_provenance.go b/internal/equipo/runner_provenance.go
new file mode 100644
index 00000000..34c1bfac
--- /dev/null
+++ b/internal/equipo/runner_provenance.go
@@ -0,0 +1,121 @@
+package equipo
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "gorm.io/gorm"
+)
+
+func (s *Store) runnerProvenance(observe team.ProvenanceResolver) team.ProvenanceResolver {
+ return func(ctx context.Context, raw *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) {
+ if s.execution == nil {
+ return team.Provenance{}, ErrUnavailable
+ }
+ tx := s.execution.gormTx(ctx, raw)
+ var a runnerAssignment
+ if err := tx.First(&a, "team_id=? AND job_id=? AND attempt_id=? AND fence=? AND runner_id=?", scope.Account, scope.Job, h.Attempt, h.Fence, h.Runner).Error; err != nil {
+ return team.Provenance{}, storeError(err)
+ }
+ value, err := assignmentValue(a)
+ if err != nil {
+ return team.Provenance{}, err
+ }
+ // Session/producer identity must come from a validator, never agent JSON.
+ if observe == nil {
+ return team.Provenance{}, ErrUnavailable
+ }
+ p, err := observe(ctx, raw, scope, h)
+ if err != nil {
+ return p, err
+ }
+ if p.Provider != value.Selection.Provider || p.ModelFamily != value.Selection.Family {
+ return p, ErrForbidden
+ }
+ p.Isolation = value.Selection.Isolation
+ return p, nil
+ }
+}
+func (e *Execution) syncExposure(ctx context.Context, tx *gorm.DB) error {
+ var rows []runnerAssignment
+ if err := tx.Where("state != ?", "contained").Find(&rows).Error; err != nil {
+ return storeError(err)
+ }
+ for _, a := range rows {
+ value, err := assignmentValue(a)
+ if err != nil {
+ return err
+ }
+ var c connectionRecord
+ if err := tx.First(&c, "id=?", value.Selection.ConnectionID).Error; err != nil {
+ return storeError(err)
+ }
+ if err := decodeConnection(&c); err != nil {
+ return err
+ }
+ if len(c.Reports) == 0 {
+ return ErrUnavailable
+ }
+ iso, err := e.store.isolationSnapshot(tx, c, c.Reports[0])
+ if err != nil {
+ return err
+ }
+ iso = mergeIsolation(value.Selection.Isolation, iso)
+ raw, _ := json.Marshal(iso)
+ var changes []ConnectionInvalidation
+ if err := tx.Where("id>? AND connection_id IN (SELECT id FROM connections WHERE runner_id=?)", a.InvalidationID, a.RunnerID).Order("id").Find(&changes).Error; err != nil {
+ return storeError(err)
+ }
+ for _, change := range changes {
+ a.InvalidationID = change.ID
+ // Acknowledging exposure propagates labels. Other security changes fence
+ // only work whose saved connection/choice is no longer eligible.
+ if change.Reason == "isolation_acknowledged" {
+ continue
+ }
+ var task Task
+ if err := tx.First(&task, "id=?", a.TaskID).Error; err != nil {
+ return storeError(err)
+ }
+ _, err := e.store.selectionCurrent(tx, task, a.StepKey, value.Selection)
+ if err != nil {
+ if !errors.Is(err, ErrForbidden) && !errors.Is(err, ErrConflict) {
+ return err
+ }
+ if a.State == "pending" || a.State == "claimed" {
+ a.State = "fenced"
+ if a.AttemptID != 0 {
+ if err := e.Core.StopAttempt(ctx, value.Scope, team.Handle{Attempt: team.AttemptID(a.AttemptID), Fence: a.Fence, Runner: a.RunnerID}, "connection_changed"); err != nil && !errors.Is(err, team.ErrFence) {
+ return err
+ }
+ }
+ }
+ }
+ }
+ a.Isolation = string(raw)
+ if err := tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("Isolation", "InvalidationID", "State").Updates(&a).Error; err != nil {
+ return storeError(err)
+ }
+ if iso.RunnerTainted || iso.Status == "unconfined" {
+ var artifacts []executionArtifacts
+ if err := tx.Where("attempt_id=? AND job_id=?", a.AttemptID, a.JobID).Find(&artifacts).Error; err != nil {
+ return storeError(err)
+ }
+ for _, art := range artifacts {
+ var p team.Provenance
+ if err := json.Unmarshal([]byte(art.Provenance), &p); err != nil {
+ return err
+ }
+ p.Isolation = mergeIsolation(p.Isolation, iso)
+ raw, _ := json.Marshal(p)
+ if err := tx.Model(&executionArtifacts{}).Where("id=?", art.ID).Select("Provenance").Updates(&executionArtifacts{Provenance: string(raw)}).Error; err != nil {
+ return storeError(err)
+ }
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/runner_rotation.go b/internal/equipo/runner_rotation.go
new file mode 100644
index 00000000..758545af
--- /dev/null
+++ b/internal/equipo/runner_rotation.go
@@ -0,0 +1,154 @@
+package equipo
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+func (e *Execution) rotateContained(tx *gorm.DB, a runnerAssignment, q RunnerRequest, now time.Time) (CredentialRotation, error) {
+ result := CredentialRotation{CleanupTokens: map[string]string{}}
+ var runner runnerRecord
+ if err := tx.First(&runner, "id=?", a.RunnerID).Error; err != nil {
+ return result, storeError(err)
+ }
+ var credentials []runnerCredentialRecord
+ if err := tx.Where("runner_id=? AND revoked_at IS NULL AND expires_at>?", a.RunnerID, now).Find(&credentials).Error; err != nil {
+ return result, storeError(err)
+ }
+ live := runner.RevokedAt == nil && len(credentials) > 0
+ if _, err := currentRunnerMember(tx, runner.Person); err != nil {
+ if !errors.Is(err, ErrForbidden) && !errors.Is(err, ErrNotFound) {
+ return result, err
+ }
+ live = false
+ }
+ if err := tx.Model(&runnerCredentialRecord{}).Where("runner_id=? AND revoked_at IS NULL", a.RunnerID).Select("RevokedAt").Updates(&runnerCredentialRecord{RevokedAt: &now}).Error; err != nil {
+ return result, storeError(err)
+ }
+ rotation := runnerRotation{RunnerID: a.RunnerID, AssignmentID: a.ID, RequestID: q.RequestID, State: "cleanup_only"}
+ if live {
+ credential, err := mintRunnerCredential(tx, runner, now)
+ if err != nil {
+ return result, err
+ }
+ // Rotation cannot extend the predecessor's remaining authority.
+ expiry := credentials[0].ExpiresAt
+ for _, c := range credentials {
+ if c.ExpiresAt.Before(expiry) {
+ expiry = c.ExpiresAt
+ }
+ }
+ credential.ExpiresAt = expiry
+ if err := tx.Model(&runnerCredentialRecord{}).Where("id=?", credential.CredentialID).Select("ExpiresAt").Updates(&runnerCredentialRecord{ExpiresAt: expiry}).Error; err != nil {
+ return result, storeError(err)
+ }
+ result.Bearer = credential
+ rotation.State = "pending"
+ rotation.CredentialID = credential.CredentialID
+ }
+ var cleanups []runnerCleanup
+ if err := tx.Where("runner_id=?", a.RunnerID).Find(&cleanups).Error; err != nil {
+ return result, storeError(err)
+ }
+ for _, c := range cleanups {
+ token := runnerSecret()
+ if err := tx.Model(&runnerCleanup{}).Where("id=?", c.ID).Select("TokenHash").Updates(&runnerCleanup{TokenHash: runnerHash(runnerproto.CleanupAudience, token)}).Error; err != nil {
+ return result, storeError(err)
+ }
+ if now.Before(c.ExpiresAt) {
+ result.CleanupTokens[c.AssignmentID] = token
+ }
+ }
+ if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "runner_id"}}, DoUpdates: clause.AssignmentColumns([]string{"assignment_id", "request_id", "state", "credential_id"})}).Create(&rotation).Error; err != nil {
+ return result, storeError(err)
+ }
+ return result, appendAudit(tx, Actor{Address: a.Person}, "runner.containment.rotate", a.ID)
+}
+
+// AcknowledgeRotation is called only after the runner durably journals all of
+// the replacement credentials. Until this acknowledgement admission is closed.
+func (e *Execution) AcknowledgeRotation(ctx context.Context, p RunnerPrincipal, requestID string) error {
+ return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ var rotation runnerRotation
+ if err := tx.First(&rotation, "runner_id=?", p.RunnerID).Error; err != nil {
+ return storeError(err)
+ }
+ if rotation.CredentialID != p.CredentialID || rotation.RequestID != requestID || (rotation.State != "pending" && rotation.State != "ready") {
+ return ErrForbidden
+ }
+ return storeError(tx.Model(&runnerRotation{}).Where("runner_id=?", p.RunnerID).Select("State").Updates(&runnerRotation{State: "ready"}).Error)
+ })
+}
+
+// Commit the admission barrier before changing credentials. If the second
+// transaction fails, the runner remains blocked and can retry containment.
+func (e *Execution) containmentBarrier(ctx context.Context, p RunnerPrincipal, token string, q RunnerRequest) error {
+ if e.validators.Containment == nil {
+ return ErrUnavailable
+ }
+ return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ if !binding(a, q) {
+ return ErrForbidden
+ }
+ now := e.store.runnerClock.Now().UTC()
+ if token == "" {
+ if _, err := runnerPrincipalAt(tx, p, now); err != nil {
+ return err
+ }
+ if a.RunnerID != p.RunnerID || a.Person != p.Person {
+ return ErrForbidden
+ }
+ } else {
+ var c runnerCleanup
+ if err := tx.First(&c, "token_hash=?", runnerHash(runnerproto.CleanupAudience, token)).Error; err != nil {
+ return storeError(err)
+ }
+ instance, err := runnerInstance(tx)
+ if err != nil {
+ return err
+ }
+ var r runnerRecord
+ if err := tx.First(&r, "id=?", a.RunnerID).Error; err != nil {
+ return storeError(err)
+ }
+ if c.AssignmentID != a.ID || c.RunnerID != a.RunnerID || c.Person != a.Person || c.Audience != runnerproto.CleanupAudience || c.InstanceID != instance || r.InstanceID != instance || c.MachineKeyHash != r.MachineKeyHash || c.AttemptID != a.AttemptID || c.Fence != a.Fence || !now.Before(c.ExpiresAt) {
+ return ErrForbidden
+ }
+ }
+ var prior runnerObservation
+ err := tx.First(&prior, "assignment_id=? AND request_id=?", a.ID, q.RequestID).Error
+ if err == nil || a.State == "contained" {
+ return nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return storeError(err)
+ }
+ value, err := assignmentValue(a)
+ if err != nil {
+ return err
+ }
+ if err := e.validators.Containment(ctx, value, q); err != nil {
+ return err
+ }
+ if !value.Selection.Isolation.RunnerTainted && value.Selection.Isolation.Status != "unconfined" {
+ return nil
+ }
+ rotation := runnerRotation{RunnerID: a.RunnerID, AssignmentID: a.ID, RequestID: q.RequestID, State: "containing"}
+ if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "runner_id"}}, DoUpdates: clause.AssignmentColumns([]string{"assignment_id", "request_id", "state", "credential_id"})}).Create(&rotation).Error; err != nil {
+ return storeError(err)
+ }
+ return appendAudit(tx, Actor{Address: a.Person}, "runner.containment.pending", a.ID)
+ })
+}
diff --git a/internal/equipo/team/admission.go b/internal/equipo/team/admission.go
new file mode 100644
index 00000000..cfa03195
--- /dev/null
+++ b/internal/equipo/team/admission.go
@@ -0,0 +1,208 @@
+package team
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "time"
+)
+
+const admissionSchema = `
+CREATE TABLE admission_tickets (
+ action_id INTEGER PRIMARY KEY REFERENCES actions(id),
+ job_id INTEGER NOT NULL REFERENCES jobs(id),
+ request_id TEXT NOT NULL,
+ attempt_id INTEGER NOT NULL REFERENCES attempts(id),
+ fence INTEGER NOT NULL,
+ runner TEXT NOT NULL,
+ dispatch TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ incarnation INTEGER NOT NULL,
+ UNIQUE(job_id, request_id)
+);
+UPDATE service SET schema_version=7 WHERE id=1;
+`
+
+type AdmissionTicket struct {
+ Dispatch Dispatch `json:"dispatch"`
+ ExpiresAt time.Time `json:"expires_at"`
+ Incarnation int64 `json:"incarnation"`
+}
+
+type transactionBinding struct {
+ store *Store
+ tx *sql.Tx
+}
+type transactionKey struct{}
+
+func (s *Store) bound(ctx context.Context) *sql.Tx {
+ b, _ := ctx.Value(transactionKey{}).(transactionBinding)
+ if b.store == s {
+ return b.tx
+ }
+ return nil
+}
+
+// Atomic binds nested core operations to one guarded commit. Callbacks must not
+// retain the context or start goroutines with it.
+func (s *Store) Atomic(ctx context.Context, fn func(context.Context, *sql.Tx) error) error {
+ if tx := s.bound(ctx); tx != nil {
+ return fn(ctx, tx)
+ }
+ return s.WithTransaction(ctx, func(tx *sql.Tx) error {
+ return fn(context.WithValue(ctx, transactionKey{}, transactionBinding{s, tx}), tx)
+ })
+}
+
+func (s *Store) AdmitOnce(ctx context.Context, scope Scope, h Handle, id ActionID, requestID string) (AdmissionTicket, error) {
+ if requestID == "" || len(requestID) > 256 {
+ return AdmissionTicket{}, ErrInvalid
+ }
+ var ticket AdmissionTicket
+ err := s.Atomic(ctx, func(ctx context.Context, tx *sql.Tx) error {
+ if err := admissionOpen(ctx, tx); err != nil {
+ return err
+ }
+ hd, err := current(ctx, tx, scope, h, s.clock.Now())
+ if err != nil {
+ return err
+ }
+ a, err := loadAction(ctx, tx, scope.Job, id)
+ if err != nil {
+ return err
+ }
+ if a.Attempt != h.Attempt || a.Fence != h.Fence {
+ return ErrFence
+ }
+ var request, runner, raw, expiry string
+ var attempt AttemptID
+ var fence, inc int64
+ err = tx.QueryRowContext(ctx, `SELECT request_id,attempt_id,fence,runner,dispatch,expires_at,incarnation FROM admission_tickets WHERE action_id=?`, id).Scan(&request, &attempt, &fence, &runner, &raw, &expiry, &inc)
+ if errors.Is(err, sql.ErrNoRows) {
+ var other int
+ if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM admission_tickets WHERE job_id=? AND request_id=?`, scope.Job, requestID).Scan(&other); err != nil {
+ return err
+ }
+ if other != 0 {
+ return ErrConflict
+ }
+ dispatch, err := s.Admit(ctx, scope, id)
+ if err != nil {
+ return err
+ }
+ a, err = loadAction(ctx, tx, scope.Job, id)
+ if err != nil {
+ return err
+ }
+ deadline := a.AdmissionEnds
+ if max := s.clock.Now().Add(5 * time.Second); deadline.After(max) {
+ deadline = max
+ }
+ ticket = AdmissionTicket{dispatch, deadline, s.incarnation}
+ data, err := json.Marshal(dispatch)
+ if err != nil {
+ return err
+ }
+ _, err = tx.ExecContext(ctx, `INSERT INTO admission_tickets(action_id,job_id,request_id,attempt_id,fence,runner,dispatch,expires_at,incarnation) VALUES(?,?,?,?,?,?,?,?,?)`, id, scope.Job, requestID, h.Attempt, h.Fence, h.Runner, string(data), ts(deadline), s.incarnation)
+ return err
+ }
+ if err != nil {
+ return err
+ }
+ if request != requestID || attempt != h.Attempt || fence != h.Fence || runner != h.Runner {
+ return ErrConflict
+ }
+ if inc != s.incarnation {
+ return ErrStaleStore
+ }
+ if !s.clock.Now().Before(parseTS(expiry)) {
+ return ErrAdmissionExpired
+ }
+ if a.State != ActionDispatching || hd.job.State != JobRunning {
+ return ErrState
+ }
+ adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: hd.job.Grant.Ref, Account: hd.job.Account, Project: hd.job.Project, Target: hd.job.Target, Operation: a.Operation})
+ if err != nil {
+ return err
+ }
+ if err := checkAdmission(hd.job, adm, s.clock.Now()); err != nil {
+ return err
+ }
+ if err := checkBudget(ctx, tx, hd.job, Usage{}, s.clock.Now()); err != nil {
+ return err
+ }
+ r, err := loadReservation(ctx, tx, a.Reservation)
+ if err != nil {
+ return err
+ }
+ if r.State != ReservationOpen {
+ return ErrState
+ }
+ if err = json.Unmarshal([]byte(raw), &ticket.Dispatch); err != nil {
+ return err
+ }
+ if ticket.Dispatch.Hash != a.PayloadHash || ticket.Dispatch.Operation != a.Operation || string(ticket.Dispatch.Payload) != string(a.Payload) {
+ return ErrConflict
+ }
+ if a.Operation == OpForgePublish {
+ if err := checkPublication(ctx, tx, hd.job, a.Payload); err != nil {
+ return err
+ }
+ if hd.job.Policy.Version == 2 {
+ observed, err := s.observedProvenance(ctx, tx, scope, h)
+ if err != nil {
+ return err
+ }
+ var p publication
+ if strictJSON(a.Payload, &p) != nil || !isolationContains(p.Isolation, observed.Isolation) {
+ return ErrEvidence
+ }
+ }
+ }
+ ticket.ExpiresAt = parseTS(expiry)
+ ticket.Incarnation = inc
+ return nil
+ })
+ if err != nil {
+ return AdmissionTicket{}, err
+ }
+ return ticket, nil
+}
+
+// ValidateHandle checks current authority without renewing the lease.
+func (s *Store) ValidateHandle(ctx context.Context, scope Scope, h Handle) error {
+ return s.read(ctx, func(tx *sql.Tx) error { _, err := current(ctx, tx, scope, h, s.clock.Now()); return err })
+}
+
+// ContainUntrusted releases process capacity but retains the time reservation.
+func (s *Store) ContainUntrusted(ctx context.Context, scope Scope, h Handle) error {
+ return s.Atomic(ctx, func(ctx context.Context, tx *sql.Tx) error {
+ a, err := loadAttempt(ctx, tx, scope.Job, h.Attempt)
+ if err != nil {
+ return err
+ }
+ if a.Fence != h.Fence || a.Runner != h.Runner {
+ return ErrFence
+ }
+ if a.Containment == ContainmentContained {
+ return nil
+ }
+ if a.State == AttemptActive {
+ if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='stopping',stop_requested=? WHERE id=?`, ts(s.clock.Now()), a.ID); err != nil {
+ return err
+ }
+ if _, err := tx.ExecContext(ctx, `UPDATE steps SET fence=fence+1 WHERE id=? AND holder=? AND fence=?`, a.Step, a.ID, a.Fence); err != nil {
+ return err
+ }
+ }
+ if _, err := tx.ExecContext(ctx, `UPDATE time_reservations SET elapsed_unknown=1 WHERE attempt_id=?`, h.Attempt); err != nil {
+ return err
+ }
+ return s.Contain(ctx, scope, h.Attempt, "runner-validator")
+ })
+}
+
+func (s *Store) AdmissionAvailable(ctx context.Context) error {
+ return s.read(ctx, func(tx *sql.Tx) error { return admissionOpen(ctx, tx) })
+}
diff --git a/internal/equipo/team/admit_retry_test.go b/internal/equipo/team/admit_retry_test.go
new file mode 100644
index 00000000..5fc191d1
--- /dev/null
+++ b/internal/equipo/team/admit_retry_test.go
@@ -0,0 +1,198 @@
+package team
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func admissionFixture(t *testing.T) (*env, Scope, Handle, ActionID) {
+ e := newEnv(t)
+ _, sc := e.createJob(softwareSpec(SoftwareSteps(false)))
+ h := e.claim(sc, "reproduce", "runner-a", "ws-1")
+ id, err := e.store.Intend(e.ctx, sc, h, IntentSpec{Key: "turn", Operation: OpProviderCall, Payload: []byte(`{"task":"implement"}`), Reserve: Usage{InputTokens: 10, OutputTokens: 10}})
+ must(t, err)
+ return e, sc, h, id
+}
+func TestAdmitLostReplyRetry(t *testing.T) {
+ e, sc, h, id := admissionFixture(t)
+ first, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request-1")
+ must(t, err)
+ before, _ := e.store.Reservations(e.ctx, sc)
+ e.clock.Advance(time.Second)
+ again, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request-1")
+ must(t, err)
+ after, _ := e.store.Reservations(e.ctx, sc)
+ if !reflect.DeepEqual(first, again) || !reflect.DeepEqual(before, after) {
+ t.Fatal("retry changed ticket or charge")
+ }
+ var n int
+ must(t, e.store.db.QueryRow(`SELECT count(*) FROM events WHERE type='action.dispatching'`).Scan(&n))
+ if n != 1 {
+ t.Fatal("retry duplicated event")
+ }
+ if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "different"); err == nil {
+ t.Fatal("changed request accepted")
+ }
+ h.Fence++
+ if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "request-1"); err == nil {
+ t.Fatal("changed handle accepted")
+ }
+}
+func TestDispatchAdmissionExpires(t *testing.T) {
+ e, sc, h, id := admissionFixture(t)
+ ticket, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request")
+ must(t, err)
+ if ticket.ExpiresAt.Sub(e.clock.Now()) != 5*time.Second {
+ t.Fatal("wrong ticket lifetime")
+ }
+ e.clock.Advance(5 * time.Second)
+ if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "request"); err == nil {
+ t.Fatal("expired ticket replayed")
+ }
+}
+
+func TestAdmitLostReplyRetryDenied(t *testing.T) {
+ for _, kind := range []string{"cancelled", "revoked", "grant", "budget", "incarnation", "payload", "authority", "reservation"} {
+ t.Run(kind, func(t *testing.T) {
+ e, sc, h, id := admissionFixture(t)
+ _, err := e.store.AdmitOnce(e.ctx, sc, h, id, "request")
+ must(t, err)
+ switch kind {
+ case "cancelled":
+ _, err = e.store.Cancel(e.ctx, sc, "owner", "cancel")
+ must(t, err)
+ case "revoked":
+ e.auth.Revoke(grant)
+ case "grant":
+ e.auth.Amend(grant)
+ case "budget":
+ _, err = e.store.db.Exec(`UPDATE jobs SET policy=json_set(policy,'$.job.input_tokens',9,'$.per_call.input_tokens',9)`)
+ must(t, err)
+ case "incarnation":
+ _, err = e.store.db.Exec(`UPDATE admission_tickets SET incarnation=incarnation+1`)
+ must(t, err)
+ case "payload":
+ _, err = e.store.db.Exec(`UPDATE actions SET payload='{}' WHERE id=?`, id)
+ must(t, err)
+ case "authority":
+ e.auth.SetUnavailable(true)
+ case "reservation":
+ _, err = e.store.db.Exec(`UPDATE reservations SET state='settled'`)
+ must(t, err)
+ }
+ if _, err = e.store.AdmitOnce(e.ctx, sc, h, id, "request"); err == nil {
+ t.Fatal("unsafe replay accepted", kind)
+ }
+ })
+ }
+}
+
+func TestAdmitLostReplyRetryCrashHelper(t *testing.T) {
+ path := os.Getenv("EQUIPO_ADMIT_CRASH")
+ if path == "" {
+ return
+ }
+ clock := NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC))
+ auth := NewFakeAuthority(clock, 5*time.Second)
+ auth.Issue(grant, Grant{Account: acctA, Operations: map[Operation]bool{OpJobContinue: true, OpAttemptContinue: true, OpProviderCall: true}})
+ s, err := Open(context.Background(), path, Options{Clock: clock, Authority: auth, Adapters: map[Operation]Adapter{OpProviderCall: NewFakeProvider("fake", "model", nil)}})
+ must(t, err)
+ _, err = s.Resume(context.Background())
+ must(t, err)
+ job, err := s.CreateJob(context.Background(), softwareSpec(SoftwareSteps(false)))
+ must(t, err)
+ sc := Scope{Account: job.Account, Job: job.ID}
+ h, err := s.Claim(context.Background(), sc, "reproduce", "runner", "workspace")
+ must(t, err)
+ id, err := s.Intend(context.Background(), sc, h, IntentSpec{Key: "turn", Operation: OpProviderCall, Payload: []byte(`{}`), Reserve: Usage{InputTokens: 10, OutputTokens: 10}})
+ must(t, err)
+ s.commitHook = func(stage string) error {
+ if stage == os.Getenv("EQUIPO_ADMIT_STAGE") {
+ os.Exit(73)
+ }
+ return nil
+ }
+ _, err = s.AdmitOnce(context.Background(), sc, h, id, "durable-request")
+ t.Fatalf("did not crash: %v", err)
+}
+func TestAdmitLostReplyRetryCrash(t *testing.T) {
+ for _, stage := range []string{"before_commit", "after_commit"} {
+ t.Run(stage, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "crash.db")
+ exe, err := os.Executable()
+ must(t, err)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, exe, "-test.run=^TestAdmitLostReplyRetryCrashHelper$")
+ cmd.Env = append(os.Environ(), "EQUIPO_ADMIT_CRASH="+path, "EQUIPO_ADMIT_STAGE="+stage)
+ output, err := cmd.CombinedOutput()
+ if status, ok := err.(*exec.ExitError); !ok || status.ExitCode() != 73 {
+ t.Fatalf("crash not reached: %v %s", err, output)
+ }
+ raw, err := sql.Open("sqlite", path)
+ must(t, err)
+ defer raw.Close()
+ var n int
+ must(t, raw.QueryRow("SELECT count(*) FROM admission_tickets").Scan(&n))
+ if stage == "before_commit" {
+ if n != 0 {
+ t.Fatal("ticket escaped rollback")
+ }
+ return
+ }
+ if n != 1 {
+ t.Fatal("committed ticket missing")
+ }
+ var dispatch, expiry, request, state string
+ var inc int64
+ must(t, raw.QueryRow("SELECT dispatch,expires_at,request_id,incarnation FROM admission_tickets").Scan(&dispatch, &expiry, &request, &inc))
+ var d Dispatch
+ must(t, json.Unmarshal([]byte(dispatch), &d))
+ must(t, raw.QueryRow("SELECT state FROM actions").Scan(&state))
+ if d.Action != 1 || request != "durable-request" || parseTS(expiry).IsZero() || inc == 0 || state != "dispatching" {
+ t.Fatal("partial admission commit")
+ }
+ must(t, raw.QueryRow("SELECT count(*) FROM events WHERE type='action.dispatching'").Scan(&n))
+ if n != 1 {
+ t.Fatal("dispatch event missing")
+ }
+ clock := NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC))
+ auth := NewFakeAuthority(clock, 5*time.Second)
+ auth.Issue(grant, Grant{Account: acctA, Operations: map[Operation]bool{OpJobContinue: true, OpAttemptContinue: true, OpProviderCall: true}})
+ s, err := Open(ctx, path, Options{Clock: clock, Authority: auth})
+ must(t, err)
+ defer s.Close()
+ if _, err = s.AdmitOnce(ctx, Scope{Account: acctA, Job: 1}, Handle{Attempt: 1, Fence: 1, Runner: "runner"}, 1, "durable-request"); err == nil {
+ t.Fatal("crash replay dispatched in new incarnation")
+ }
+ var saved string
+ must(t, raw.QueryRow("SELECT dispatch FROM admission_tickets").Scan(&saved))
+ if saved != dispatch {
+ t.Fatal("reopen changed stored ticket")
+ }
+ })
+ }
+}
+
+func TestAdmitLostReplyRetryPublicationExposure(t *testing.T) {
+ g := newGitEnv(t)
+ g.build()
+ g.review()
+ g.verify(true)
+ h := g.claimStep("publish")
+ id, err := g.store.Intend(g.ctx, g.scope, h, IntentSpec{Key: "publish", Operation: OpForgePublish, Payload: mustJSON(g.publication())})
+ must(t, err)
+ _, err = g.store.AdmitOnce(g.ctx, g.scope, h, id, "publication")
+ must(t, err)
+ g.observed.Isolation.AcknowledgementIDs = append(g.observed.Isolation.AcknowledgementIDs, "new-exposure")
+ if _, err = g.store.AdmitOnce(g.ctx, g.scope, h, id, "publication"); err == nil {
+ t.Fatal("publication ticket replay ignored new runner exposure")
+ }
+}
diff --git a/internal/equipo/team/scheduler.go b/internal/equipo/team/scheduler.go
index 434bfcba..9a9d62f7 100644
--- a/internal/equipo/team/scheduler.go
+++ b/internal/equipo/team/scheduler.go
@@ -392,8 +392,10 @@ func revokeIntents(ctx context.Context, tx *sql.Tx, attempt AttemptID, now time.
// expired or finished attempt and, for an expired or stopped attempt on a
// still-pending step, clears the holder so a fresh claim may follow.
func (s *Store) Contain(ctx context.Context, scope Scope, id AttemptID, supervisor string) error {
- s.recoveryMu.Lock()
- defer s.recoveryMu.Unlock()
+ if s.bound(ctx) == nil {
+ s.recoveryMu.Lock()
+ defer s.recoveryMu.Unlock()
+ }
return s.tx(ctx, func(tx *sql.Tx) error {
now := s.clock.Now()
j, err := loadJob(ctx, tx, scope)
diff --git a/internal/equipo/team/shared.go b/internal/equipo/team/shared.go
index db2bb668..ac6852ac 100644
--- a/internal/equipo/team/shared.go
+++ b/internal/equipo/team/shared.go
@@ -39,6 +39,9 @@ func OpenShared(ctx context.Context, writer *sql.DB, path string, o Options) (*S
// WithTransaction keeps SQL commit and witness publication under the core guard.
// Use the supplied transaction throughout; do not call Store methods inside fn.
func (s *Store) WithTransaction(ctx context.Context, fn func(*sql.Tx) error) error {
+ if tx := s.bound(ctx); tx != nil {
+ return fn(tx)
+ }
s.recoveryMu.Lock()
defer s.recoveryMu.Unlock()
return s.tx(ctx, fn)
@@ -109,6 +112,7 @@ func (s *Store) checkSharedSchema(ctx context.Context) error {
}
var sharedSchemaQueries = []string{
+ `SELECT action_id,job_id,request_id,attempt_id,fence,runner,dispatch,expires_at,incarnation FROM admission_tickets LIMIT 0`,
`SELECT release_required,recovery_revision,reconciled_revision,clock_high_water FROM service LIMIT 0`,
`SELECT grant_stale,request_key,request_hash FROM jobs LIMIT 0`,
`SELECT elapsed_unknown FROM time_reservations LIMIT 0`,
diff --git a/internal/equipo/team/stop.go b/internal/equipo/team/stop.go
index 4c69ad07..a9a432b1 100644
--- a/internal/equipo/team/stop.go
+++ b/internal/equipo/team/stop.go
@@ -19,8 +19,10 @@ func (s *Store) StopAttempt(ctx context.Context, scope Scope, h Handle, reason s
if strings.TrimSpace(reason) == "" {
return fail(CodeInvalid, "stop needs a reason")
}
- s.recoveryMu.Lock()
- defer s.recoveryMu.Unlock()
+ if s.bound(ctx) == nil {
+ s.recoveryMu.Lock()
+ defer s.recoveryMu.Unlock()
+ }
return s.tx(ctx, func(tx *sql.Tx) error {
if _, err := loadJob(ctx, tx, scope); err != nil {
return err
diff --git a/internal/equipo/team/store.go b/internal/equipo/team/store.go
index 850818e0..5ca61f36 100644
--- a/internal/equipo/team/store.go
+++ b/internal/equipo/team/store.go
@@ -19,7 +19,7 @@ import (
// SchemaVersion is the one schema this binary writes. A database with a
// newer version is refused (ErrStaleStore): the binary would not know the
// rows it was reading.
-const SchemaVersion = 6
+const SchemaVersion = 7
// Adapter executes one operation class against an external system. Execute
// runs an admitted dispatch and returns its receipt; an error from Execute
@@ -314,7 +314,7 @@ func (s *Store) migrate(ctx context.Context) error {
return err
}
v = 2
- case v != 2 && v != 3 && v != 4 && v != 5 && v != SchemaVersion:
+ case v != 2 && v != 3 && v != 4 && v != 5 && v != 6 && v != SchemaVersion:
return fail(CodeStaleStore, "unsupported schema %d", v)
}
rows, err := tx.QueryContext(ctx, `PRAGMA table_info(jobs)`)
@@ -375,6 +375,12 @@ func (s *Store) migrate(ctx context.Context) error {
if v < 6 {
_, err = tx.ExecContext(ctx, jobRequestSchema)
}
+ if err != nil {
+ return err
+ }
+ if v < 7 {
+ _, err = tx.ExecContext(ctx, admissionSchema)
+ }
return err
})
}
@@ -513,6 +519,9 @@ func writeMarker(path string, inc, revision int64, clean bool) error {
// unpublished commit; start repairs that gap before advancing again.
// Reads also advance the position in this bounded prototype.
func (s *Store) tx(ctx context.Context, fn func(*sql.Tx) error) error {
+ if tx := s.bound(ctx); tx != nil {
+ return fn(tx)
+ }
return s.transact(ctx, false, func(tx *sql.Tx) error {
if s.incarnation != 0 {
if err := s.observeClock(ctx, tx); err != nil {
@@ -524,6 +533,9 @@ func (s *Store) tx(ctx context.Context, fn func(*sql.Tx) error) error {
}
func (s *Store) read(ctx context.Context, fn func(*sql.Tx) error) error {
+ if tx := s.bound(ctx); tx != nil {
+ return fn(tx)
+ }
return s.transact(ctx, false, fn)
}
diff --git a/internal/equipotest/execution_schema_test.go b/internal/equipotest/execution_schema_test.go
index 9d6c2267..f2e1690f 100644
--- a/internal/equipotest/execution_schema_test.go
+++ b/internal/equipotest/execution_schema_test.go
@@ -145,7 +145,7 @@ func TestExecutionSchemaParity(t *testing.T) {
defer old.Close()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0012_tasks" && m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
+ if m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
before.Add(m)
}
}
@@ -154,7 +154,7 @@ func TestExecutionSchemaParity(t *testing.T) {
executionMust(t, old.G.Create(&equipo.Account{Label: "existing account"}).Error)
result, err := migrate.Apply(ctx, old, equipo.BootSchema)
executionMust(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments"}) {
t.Fatalf("upgrade migrations: %v", result.Applied)
}
var account equipo.Account
@@ -174,7 +174,7 @@ func TestExecutionSchemaParity(t *testing.T) {
defer old.Close()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0012_tasks" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
+ if m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" {
before.Add(m)
}
}
@@ -185,7 +185,7 @@ func TestExecutionSchemaParity(t *testing.T) {
executionMust(t, err)
result, err := migrate.Apply(ctx, old, equipo.BootSchema)
executionMust(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments"}) {
t.Fatalf("task one upgrade migrations: %v", result.Applied)
}
var evidence string
@@ -207,7 +207,7 @@ func TestExecutionSchemaParity(t *testing.T) {
defer old.Close()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0012_tasks" && m.ID != "equipo/0009_runner_policy" {
+ if m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0009_runner_policy" {
before.Add(m)
}
}
@@ -233,7 +233,7 @@ func TestExecutionSchemaParity(t *testing.T) {
return
}
executionMust(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0009_runner_policy", "equipo/0012_tasks"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments"}) {
t.Fatal("wrong task two upgrade", result.Applied)
}
var project, input, cost int
@@ -256,7 +256,7 @@ func TestExecutionSchemaParity(t *testing.T) {
defer old.Close()
before := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0012_tasks" {
+ if m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" {
before.Add(m)
}
}
@@ -265,7 +265,7 @@ func TestExecutionSchemaParity(t *testing.T) {
executionMust(t, seedExecutionJob(old.Writer()))
result, err := migrate.Apply(ctx, old, equipo.BootSchema)
executionMust(t, err)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0012_tasks"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0012_tasks", "equipo/0013_runner_assignments"}) {
t.Fatal("task six upgrade migrations", result.Applied)
}
var key, hash string
@@ -273,8 +273,8 @@ func TestExecutionSchemaParity(t *testing.T) {
if key != "" || hash != "" {
t.Fatal("legacy request identity invented")
}
- if scalar(t, old, "SELECT schema_version FROM service") != 6 {
- t.Fatal("core version not six")
+ if scalar(t, old, "SELECT schema_version FROM service") != 7 {
+ t.Fatal("core version not seven")
}
for i := 0; i < 2; i++ {
result, err = migrate.Apply(ctx, old, equipo.BootSchema)
@@ -285,7 +285,7 @@ func TestExecutionSchemaParity(t *testing.T) {
}
})
- coreNames := map[string]bool{"grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true}
+ coreNames := map[string]bool{"admission_tickets": true, "grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true}
var appCore migrate.Snapshot
for _, table := range expected.Tables {
if coreNames[table.Name] {
@@ -295,7 +295,7 @@ func TestExecutionSchemaParity(t *testing.T) {
if len(appCore.Tables) != len(coreNames) {
t.Fatalf("execution tables = %d, want %d", len(appCore.Tables), len(coreNames))
}
- for _, version := range []int{1, 2, 3, 4, 5, 6} {
+ for _, version := range []int{1, 2, 3, 4, 5, 6, 7} {
t.Run(fmt.Sprint(version), func(t *testing.T) {
standalonePath := filepath.Join(t.TempDir(), "core.db")
core, err := team.Open(ctx, standalonePath, executionOptions())
@@ -306,6 +306,10 @@ func TestExecutionSchemaParity(t *testing.T) {
defer raw.Close()
raw.SetMaxOpenConns(1)
executionMust(t, seedExecutionJob(raw))
+ if version < 7 {
+ _, err = raw.Exec("DROP TABLE admission_tickets")
+ executionMust(t, err)
+ }
if version < 6 {
for _, q := range []string{"DROP INDEX jobs_request", "ALTER TABLE jobs DROP COLUMN request_key", "ALTER TABLE jobs DROP COLUMN request_hash"} {
_, err = raw.Exec(q)
diff --git a/internal/equipotest/runner_api_test.go b/internal/equipotest/runner_api_test.go
new file mode 100644
index 00000000..1a03c36f
--- /dev/null
+++ b/internal/equipotest/runner_api_test.go
@@ -0,0 +1,988 @@
+package equipotest
+
+import (
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "gorm.io/gorm"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+)
+
+type runnerFixture struct {
+ connectionFixture
+ x *equipo.Execution
+ a equipo.Assignment
+ claim equipo.ClaimResponse
+}
+
+func runnerFixtureNew(t *testing.T, claim bool) runnerFixture {
+ t.Helper()
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ task, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f))
+ executionMust(t, err)
+ var path string
+ executionMust(t, f.d.Writer().QueryRow(`SELECT file FROM pragma_database_list WHERE name='main'`).Scan(&path))
+ x, err := f.s.AttachExecution(connectionContext, filepath.Clean(path), team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock), Provenance: func(ctx context.Context, tx *sql.Tx, _ team.Scope, h team.Handle) (team.Provenance, error) {
+ var raw string
+ if err := tx.QueryRowContext(ctx, "SELECT selection FROM runner_assignments WHERE attempt_id=?", h.Attempt).Scan(&raw); err != nil {
+ return team.Provenance{}, err
+ }
+ var sel equipo.Selection
+ if err := json.Unmarshal([]byte(raw), &sel); err != nil {
+ return team.Provenance{}, err
+ }
+ return team.Provenance{Provider: sel.Provider, ModelFamily: sel.Family, Producer: "observed", Context: fmt.Sprint(h.Attempt)}, nil
+ }, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("claude", "sonnet", nil)}})
+ executionMust(t, err)
+ t.Cleanup(func() { x.Core.Close() })
+ _, err = x.Core.Resume(connectionContext)
+ executionMust(t, err)
+ _, err = f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision)
+ executionMust(t, err)
+ executionMust(t, x.Sync(connectionContext))
+ aa, err := x.Poll(connectionContext, f.principal, "")
+ executionMust(t, err)
+ if len(aa) != 1 {
+ t.Fatalf("assignments %v", aa)
+ }
+ out := runnerFixture{connectionFixture: f, x: x, a: aa[0]}
+ if claim {
+ out.claim, err = x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: aa[0].ID, Revision: aa[0].Revision, RequestID: "claim"})
+ executionMust(t, err)
+ }
+ return out
+}
+func (f runnerFixture) request() equipo.RunnerRequest {
+ return equipo.RunnerRequest{Version: 1, AssignmentID: f.a.ID, Scope: f.claim.Scope, Handle: f.claim.Handle, RequestID: "request"}
+}
+func TestRunnerCannotClaimOthersWork(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ for _, field := range []string{"person", "runner", "credential"} {
+ t.Run(field, func(t *testing.T) {
+ p := f.principal
+ switch field {
+ case "person":
+ p.Person = "other@example.com"
+ case "runner":
+ p.RunnerID = "other"
+ case "credential":
+ p.CredentialID = "other"
+ }
+ if _, err := f.x.Claim(connectionContext, p, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
+ t.Fatal("foreign claim accepted")
+ }
+ })
+ }
+}
+func TestRunnerFenceEveryMutation(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ t.Run(op, func(t *testing.T) {
+ q := f.request()
+ q.Handle.Fence++
+ if _, err := f.x.Mutate(connectionContext, f.principal, op, q); err == nil {
+ t.Fatal("wrong fence accepted", op)
+ }
+ })
+ }
+}
+func TestRunnerLongPollRechecksRoster(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ ctx, cancel := context.WithTimeout(connectionContext, time.Second)
+ defer cancel()
+ done := make(chan error, 1)
+ go func() { _, err := f.x.Poll(ctx, f.principal, f.a.ID); done <- err }()
+ time.Sleep(30 * time.Millisecond)
+ executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1))
+ if err := <-done; err == nil {
+ t.Fatal("revoked poll succeeded")
+ }
+}
+func TestSpecialistConcurrency(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ var n int
+ executionMust(t, f.d.Writer().QueryRow(`SELECT count(*) FROM attempts WHERE containment='pending'`).Scan(&n))
+ if n != 1 {
+ t.Fatal("missing claim")
+ }
+ if _, err := f.s.SelectConnection(connectionContext, ownerAddress, f.project.ID, "engineering", ""); err == nil {
+ t.Fatal("specialist slot not occupied")
+ }
+ if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "other"}); err == nil {
+ t.Fatal("second handle issued")
+ }
+}
+func TestRevokedCleanupCannotRefund(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) {
+ t.Fatal("cleanup reached trusted receipt validator")
+ return team.Receipt{}, nil
+ }})
+ q := f.request()
+ q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{"task":"implement"}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}}
+ result, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
+ executionMust(t, err)
+ id := result.(team.ActionID)
+ q.Intent = nil
+ q.ActionID = id
+ q.RequestID = "admit"
+ _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
+ executionMust(t, err)
+ executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1))
+ q.RequestID = "receipt"
+ q.Receipt = &team.Receipt{ID: "forged", Outcome: team.OutcomeSuccess, Usage: &team.Usage{}}
+ _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "receipts", q)
+ executionMust(t, err)
+ reservations, err := f.x.Core.Reservations(connectionContext, q.Scope)
+ executionMust(t, err)
+ if len(reservations) != 1 || reservations[0].State != team.ReservationOpen {
+ t.Fatal("cleanup refunded charge")
+ }
+ if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "intend", q); err == nil {
+ t.Fatal("cleanup admitted work")
+ }
+}
+func TestTaintedRunnerProvenance(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ executionMust(t, f.x.Sync(connectionContext))
+ if !f.claim.Brief.Selection.Isolation.RunnerTainted {
+ t.Fatal("confined task lost runner taint")
+ }
+ var raw string
+ executionMust(t, f.d.Writer().QueryRow(`SELECT isolation FROM runner_assignments WHERE id=?`, f.a.ID).Scan(&raw))
+ var iso team.IsolationSnapshot
+ executionMust(t, json.Unmarshal([]byte(raw), &iso))
+ if !iso.RunnerTainted {
+ t.Fatal("historical taint missing")
+ }
+}
+func TestUnconfinedContainmentRotatesTokens(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ oldBearer := runnerBearerFor(t, f)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ q := f.request()
+ q.RequestID = "stop"
+ _, err := f.x.Mutate(connectionContext, f.principal, "stop", q)
+ executionMust(t, err)
+ q.RequestID = "contained"
+ result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ rotation := result.(equipo.CredentialRotation)
+ if _, err := f.s.AuthenticateRunner(connectionContext, oldBearer); err == nil {
+ t.Fatal("old bearer survived containment")
+ }
+ if rotation.Bearer.Token == "" || len(rotation.CleanupTokens) != 1 {
+ t.Fatal("missing replacement credentials")
+ }
+ if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
+ t.Fatal("old cleanup token survived")
+ }
+ if _, err = f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = f.x.Mutate(connectionContext, f.principal, "renew", q); err == nil {
+ t.Fatal("old bearer principal survived")
+ }
+}
+
+func runnerBearerFor(t *testing.T, f runnerFixture) string {
+ t.Helper()
+ token := strings.Repeat("A", 43)
+ // Test credentials are seeded by hash; no real machine is enrolled.
+ sum := sha256.Sum256([]byte(runnerproto.RunnerAudience + "\x00" + token))
+ mustSQL(t, f.d, "UPDATE runner_credentials SET token_hash=? WHERE id=?", fmt.Sprintf("%x", sum), f.principal.CredentialID)
+ return token
+}
+func runnerHTTP(t *testing.T, f runnerFixture, op, token string, value any) int {
+ t.Helper()
+ raw, err := runnerproto.Marshal(value)
+ executionMust(t, err)
+ req := httptest.NewRequest("POST", "/"+op, bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ f.s.RunnerHandler().ServeHTTP(w, req)
+ return w.Code
+}
+func TestRunnerFenceHTTPBindings(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ token := runnerBearerFor(t, f)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ for _, field := range []string{"scope", "job", "attempt", "runner", "fence", "assignment", "version"} {
+ t.Run(op+"/"+field, func(t *testing.T) {
+ q := f.request()
+ q.Event = json.RawMessage(`{"kind":"progress"}`)
+ switch field {
+ case "scope":
+ q.Scope.Account = "other"
+ case "job":
+ q.Scope.Job++
+ case "attempt":
+ q.Handle.Attempt++
+ case "runner":
+ q.Handle.Runner = "other"
+ case "fence":
+ q.Handle.Fence++
+ case "assignment":
+ q.AssignmentID = "other"
+ case "version":
+ q.Version = 2
+ }
+ if status := runnerHTTP(t, f, op, token, q); status < 400 {
+ t.Fatal("HTTP binding accepted", status)
+ }
+ })
+ }
+ }
+ q := f.request()
+ q.Event = json.RawMessage(`{"kind":"progress"}`)
+ if status := runnerHTTP(t, f, "events", token, q); status != 200 {
+ t.Fatal("valid event denied", status)
+ }
+ if status := runnerHTTP(t, f, "renew", token, q); status != 200 {
+ t.Fatal("valid renew denied", status)
+ }
+ raw, err := runnerproto.Marshal(q)
+ executionMust(t, err)
+ req := httptest.NewRequest("POST", "/events", bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Cookie", "session=browser")
+ req.Header.Set("Content-Type", "application/json")
+ response := httptest.NewRecorder()
+ f.s.RunnerHandler().ServeHTTP(response, req)
+ if response.Code != 403 {
+ t.Fatal("runner accepted browser cookie", response.Code)
+ }
+ for _, op := range []string{"connections", "heartbeat"} {
+ if status := runnerHTTP(t, f, op, token, runnerproto.HeartbeatRequest{Version: 2}); status < 400 {
+ t.Fatal("version accepted", op)
+ }
+ }
+}
+func TestRunnerClaimRetryAndRace(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ q := equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}
+ var wg sync.WaitGroup
+ results := make(chan equipo.ClaimResponse, 2)
+ for i := 0; i < 2; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ r, err := f.x.Claim(connectionContext, f.principal, q)
+ if err == nil {
+ results <- r
+ }
+ }()
+ }
+ wg.Wait()
+ close(results)
+ var attempt team.AttemptID
+ for r := range results {
+ if attempt != 0 && attempt != r.Handle.Attempt {
+ t.Fatal("race issued two handles")
+ }
+ attempt = r.Handle.Attempt
+ }
+ if attempt == 0 || scalar(t, f.d, "SELECT count(*) FROM attempts") != 1 {
+ t.Fatal("claim race lost or duplicated attempt")
+ }
+ before := scalar(t, f.d, "SELECT count(*) FROM events")
+ r, err := f.x.Claim(connectionContext, f.principal, q)
+ executionMust(t, err)
+ if r.Handle.Attempt != attempt || scalar(t, f.d, "SELECT count(*) FROM events") != before {
+ t.Fatal("claim recovery added effects")
+ }
+}
+func TestIsolationAcknowledgementLapsesRunnerTickets(t *testing.T) {
+ for _, change := range []string{"removed", "demoted", "provider", "paseo", "configuration"} {
+ t.Run(change, func(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ q := f.request()
+ q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}}
+ id, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
+ executionMust(t, err)
+ q.Intent = nil
+ q.ActionID = id.(team.ActionID)
+ q.RequestID = "admit"
+ _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
+ executionMust(t, err)
+ switch change {
+ case "removed":
+ mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", ownerAddress)
+ case "demoted":
+ mustSQL(t, f.d, "UPDATE members SET role='member' WHERE address=?", ownerAddress)
+ default:
+ reports := append([]equipo.ConnectionReport(nil), f.reports...)
+ switch change {
+ case "provider":
+ reports[1].ProviderVersion = "next"
+ case "paseo":
+ reports[1].PaseoVersion = "next"
+ case "configuration":
+ reports[1].IsolationConfigHash = strings.Repeat("c", 64)
+ }
+ executionMust(t, f.s.ReportConnections(connectionContext, f.principal, reports))
+ }
+ if _, err = f.x.Mutate(connectionContext, f.principal, "admit", q); err == nil {
+ t.Fatal("stale admission accepted", change)
+ }
+ if _, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
+ t.Fatal("stale claim accepted", change)
+ }
+ })
+ }
+}
+func TestRunnerAuthorityDatabaseFailure(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ executionMust(t, f.d.G.Callback().Query().Before("gorm:query").Register("task8_failure", func(tx *gorm.DB) {
+ if tx.Statement.Table == "members" {
+ tx.AddError(errors.New("injected lookup error"))
+ }
+ }))
+ defer f.d.G.Callback().Query().Remove("task8_failure")
+ if out, err := f.x.Poll(connectionContext, f.principal, ""); err == nil || len(out) != 0 {
+ t.Fatal("database error became assignment")
+ }
+ if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
+ t.Fatal("database error became claim")
+ }
+}
+func TestUnconfinedContainmentRotatesTokensFailure(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ q := f.request()
+ q.RequestID = "stop"
+ _, err := f.x.Mutate(connectionContext, f.principal, "stop", q)
+ executionMust(t, err)
+ q.RequestID = "contained"
+ executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("rotation_fail", func(tx *gorm.DB) {
+ if tx.Statement.Table == "runner_credentials" {
+ tx.AddError(errors.New("rotation unavailable"))
+ }
+ }))
+ if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
+ t.Fatal("rotation failure hidden")
+ }
+ executionMust(t, f.d.G.Callback().Create().Remove("rotation_fail"))
+ var state string
+ executionMust(t, f.d.Writer().QueryRow("SELECT state FROM runner_rotations WHERE runner_id=?", f.principal.RunnerID).Scan(&state))
+ if state != "containing" {
+ t.Fatal("failed rotation reopened admission", state)
+ }
+ if _, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
+ t.Fatal("failed rotation admitted claim")
+ }
+ result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ rotation := result.(equipo.CredentialRotation)
+ p, err := f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token)
+ executionMust(t, err)
+ executionMust(t, f.x.AcknowledgeRotation(connectionContext, p, q.RequestID))
+ before := scalar(t, f.d, "SELECT count(*) FROM runner_credentials")
+ _, err = f.x.Cleanup(connectionContext, rotation.CleanupTokens[f.a.ID], "contained", q)
+ executionMust(t, err)
+ if scalar(t, f.d, "SELECT count(*) FROM runner_credentials") != before {
+ t.Fatal("containment retry rotated twice")
+ }
+}
+
+func runnerSecond(t *testing.T, f runnerFixture) equipo.Assignment {
+ t.Helper()
+ task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "another bug", "request-2")
+ executionMust(t, err)
+ task, err = f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f.connectionFixture))
+ executionMust(t, err)
+ _, err = f.s.StartBug(connectionContext, f.principal, task.ID, task.Revision)
+ executionMust(t, err)
+ executionMust(t, f.x.Sync(connectionContext))
+ aa, err := f.x.Poll(connectionContext, f.principal, "")
+ executionMust(t, err)
+ for _, a := range aa {
+ if a.ID != f.a.ID {
+ return a
+ }
+ }
+ t.Fatal("second assignment missing")
+ return equipo.Assignment{}
+}
+func TestSpecialistConcurrencyAcrossJobs(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ second := runnerSecond(t, f)
+ var wg sync.WaitGroup
+ won := make(chan bool, 2)
+ for _, a := range []equipo.Assignment{f.a, second} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: a.ID, Revision: a.Revision, RequestID: "claim"})
+ won <- err == nil
+ }()
+ }
+ wg.Wait()
+ close(won)
+ n := 0
+ for ok := range won {
+ if ok {
+ n++
+ }
+ }
+ if n != 1 {
+ t.Fatal("specialist concurrency exceeded one", n)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM attempts WHERE containment='pending'") != 1 {
+ t.Fatal("two jobs claimed specialist")
+ }
+}
+func runnerConcurrent(t *testing.T) (runnerFixture, runnerFixture) {
+ t.Helper()
+ f := runnerFixtureNew(t, false)
+ second := runnerSecond(t, f)
+ // Seed two active assignments to exercise exposure and rotation across jobs.
+ mustSQL(t, f.d, "UPDATE specialists SET max_concurrent=2 WHERE key='engineering'")
+ var err error
+ f.claim, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"})
+ executionMust(t, err)
+ g := f
+ g.a = second
+ g.claim, err = f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: second.ID, Revision: second.Revision, RequestID: "claim"})
+ executionMust(t, err)
+ return f, g
+}
+func TestTaintedRunnerProvenanceAlreadyRunning(t *testing.T) {
+ f, g := runnerConcurrent(t)
+ confined := team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{connectionTuple(f.reports[0])}}
+ iso, _ := json.Marshal(confined)
+ mustSQL(t, f.d, "DELETE FROM isolation_acknowledgements")
+ mustSQL(t, f.d, "UPDATE runner_assignments SET isolation=?", string(iso))
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ for _, fixture := range []runnerFixture{f, g} {
+ q := fixture.request()
+ q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro"), Provenance: team.Provenance{Isolation: confined}}
+ // Seed earlier validated evidence, before enabling the unconfined connection.
+ art, err := f.x.Core.Register(connectionContext, q.Scope, q.Handle, *q.Artifact)
+ executionMust(t, err)
+ if art.Provenance.Isolation.RunnerTainted {
+ t.Fatal("seed was already tainted")
+ }
+ }
+ codex := g.a.Selection
+ codex.ConnectionID = f.ids["codex"]
+ codex.Provider = "codex"
+ codex.Family = "gpt"
+ codex.Model = "gpt-5"
+ codex.AccountID = "opaque-codex"
+ codex.Isolation.Status = "unconfined"
+ raw, _ := json.Marshal(codex)
+ mustSQL(t, f.d, "UPDATE runner_assignments SET selection=? WHERE id=?", string(raw), g.a.ID)
+ review := f.a.Selection
+ raw, _ = json.Marshal(review)
+ mustSQL(t, f.d, "UPDATE task_outboxes SET review=? WHERE task_id=?", string(raw), g.a.TaskID)
+ f.ack(t)
+ for _, fixture := range []runnerFixture{f, g} {
+ artifacts, err := f.x.Core.Artifacts(connectionContext, fixture.claim.Scope)
+ executionMust(t, err)
+ if len(artifacts) != 1 || !artifacts[0].Provenance.Isolation.RunnerTainted {
+ t.Fatal("already registered evidence lost taint")
+ }
+ var saved string
+ executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_assignments WHERE id=?", fixture.a.ID).Scan(&saved))
+ var snapshot team.IsolationSnapshot
+ executionMust(t, json.Unmarshal([]byte(saved), &snapshot))
+ if !snapshot.RunnerTainted {
+ t.Fatal("already running step lost taint")
+ }
+ q := fixture.request()
+ q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro"), Provenance: team.Provenance{Isolation: confined}}
+ value, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q)
+ executionMust(t, err)
+ if !value.(team.Artifact).Provenance.Isolation.RunnerTainted {
+ t.Fatal("submitted confined provenance won")
+ }
+ }
+ executionMust(t, f.s.RevokeIsolationAcknowledgement(connectionContext, ownerActor, f.ids["codex"], 1))
+ artifacts, err := f.x.Core.Artifacts(connectionContext, f.claim.Scope)
+ executionMust(t, err)
+ if !artifacts[0].Provenance.Isolation.RunnerTainted {
+ t.Fatal("ack expiry erased historical exposure")
+ }
+}
+func TestUnconfinedContainmentRotatesTokensConcurrent(t *testing.T) {
+ for _, revoked := range []bool{false, true} {
+ t.Run(fmt.Sprint(revoked), func(t *testing.T) {
+ f, g := runnerConcurrent(t)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ if revoked {
+ executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1))
+ }
+ q := f.request()
+ q.RequestID = "contained"
+ result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ rotation := result.(equipo.CredentialRotation)
+ if len(rotation.CleanupTokens) != 2 {
+ t.Fatal("concurrent cleanup token not replaced")
+ }
+ if revoked && rotation.Bearer.Token != "" {
+ t.Fatal("revoked runner revived")
+ }
+ if _, err = f.x.Cleanup(connectionContext, g.claim.CleanupToken, "contained", g.request()); err == nil {
+ t.Fatal("concurrent old cleanup survived")
+ }
+ if !revoked {
+ principal, err := f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token)
+ executionMust(t, err)
+ active := g.request()
+ active.Intent = &team.IntentSpec{Key: "after-rotation", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
+ if _, err := f.x.Mutate(connectionContext, principal, "intend", active); err == nil {
+ t.Fatal("rotation admitted before durable acknowledgement")
+ }
+ executionMust(t, f.x.AcknowledgeRotation(connectionContext, principal, q.RequestID))
+ _, err = f.x.Mutate(connectionContext, principal, "intend", active)
+ executionMust(t, err)
+ }
+ q2 := g.request()
+ q2.RequestID = "second-contained"
+ result, err = f.x.Cleanup(connectionContext, rotation.CleanupTokens[g.a.ID], "contained", q2)
+ executionMust(t, err)
+ next := result.(equipo.CredentialRotation)
+ if revoked && next.Bearer.Token != "" {
+ t.Fatal("second containment revived runner")
+ }
+ before := scalar(t, f.d, "SELECT count(*) FROM runner_credentials")
+ q2.RequestID = "different-retry"
+ _, err = f.x.Cleanup(connectionContext, next.CleanupTokens[g.a.ID], "contained", q2)
+ executionMust(t, err)
+ if scalar(t, f.d, "SELECT count(*) FROM runner_credentials") != before {
+ t.Fatal("same attempt rotated twice")
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM time_reservations WHERE state='open'") != 2 {
+ t.Fatal("containment refunded time")
+ }
+ })
+ }
+}
+
+func TestRunnerEndpointSuccess(t *testing.T) {
+ for _, op := range []string{"artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ t.Run(op, func(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ token := runnerBearerFor(t, f)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ q := f.request()
+ switch op {
+ case "artifacts":
+ q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro")}
+ case "intend":
+ q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
+ case "admit", "receipts", "lost":
+ in := q
+ in.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}}
+ id, err := f.x.Mutate(connectionContext, f.principal, "intend", in)
+ executionMust(t, err)
+ q.ActionID = id.(team.ActionID)
+ if op != "admit" {
+ _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
+ executionMust(t, err)
+ q.RequestID = "report"
+ q.Receipt = &team.Receipt{ID: "observation", Outcome: team.OutcomeSuccess}
+ }
+ case "complete":
+ q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure}
+ case "release":
+ q.Reason = team.WaitRunnerUnavailable
+ }
+ if status := runnerHTTP(t, f, op, token, q); status != 200 {
+ t.Fatal("valid endpoint refused", status)
+ }
+ })
+ }
+}
+func TestRunnerWireAndJournal(t *testing.T) {
+ q := equipo.RunnerRequest{Version: 1, AssignmentID: "assignment", RequestID: "request", Scope: team.Scope{Account: "account", Job: 1}, Handle: team.Handle{Attempt: 2, Fence: 3, Runner: "runner"}, Intent: &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 1}}}
+ raw, err := runnerproto.Marshal(q)
+ executionMust(t, err)
+ if bytes.Contains(raw, []byte("InputTokens")) || !bytes.Contains(raw, []byte("input_tokens")) {
+ t.Fatal("wire is not snake case")
+ }
+ var round equipo.RunnerRequest
+ executionMust(t, runnerproto.DecodeLimit(bytes.NewReader(raw), &round, 65536))
+ if round.Intent.Reserve.InputTokens != 1 {
+ t.Fatal("wire lost reservation")
+ }
+ for _, bad := range []string{`{"version":1,"version":1}`, `{"Version":1}`, `{"version":2,"unknown":true}`} {
+ if runnerproto.DecodeLimit(strings.NewReader(bad), &round, 65536) == nil {
+ t.Fatal("invalid JSON accepted", bad)
+ }
+ }
+ now := time.Now().UTC()
+ ticket := team.AdmissionTicket{Dispatch: team.Dispatch{Action: 1}, Incarnation: 3, ExpiresAt: now.Add(5 * time.Second)}
+ dir := t.TempDir()
+ q.Intent = nil
+ q.ActionID = 1
+ executionMust(t, runnerproto.JournalAdmission(dir, q))
+ executionMust(t, runnerproto.JournalAdmission(dir, q))
+ changed := q
+ changed.Handle.Fence++
+ if runnerproto.JournalAdmission(dir, changed) == nil {
+ t.Fatal("journal accepted changed request binding")
+ }
+ executionMust(t, runnerproto.ConsumeTicket(dir, "request", ticket, now, 3))
+ q.RequestID = "different"
+ executionMust(t, runnerproto.JournalAdmission(dir, q))
+ if runnerproto.ConsumeTicket(dir, "different", ticket, now, 3) == nil {
+ t.Fatal("same ticket consumed twice")
+ }
+ ticket.Dispatch.Action = 2
+ q.ActionID = 2
+ q.RequestID = "late"
+ executionMust(t, runnerproto.JournalAdmission(dir, q))
+ if runnerproto.ConsumeTicket(dir, "late", ticket, now.Add(5*time.Second), 3) == nil {
+ t.Fatal("stale ticket consumed")
+ }
+ q.RequestID = "other"
+ executionMust(t, runnerproto.JournalAdmission(dir, q))
+ if runnerproto.ConsumeTicket(dir, "other", ticket, now, 4) == nil {
+ t.Fatal("wrong incarnation consumed")
+ }
+ path := filepath.Join(dir, "credentials.json")
+ executionMust(t, runnerproto.JournalCredentials(path, map[string]string{"bearer": "replacement"}))
+ info, err := os.Stat(path)
+ executionMust(t, err)
+ if info.Mode().Perm() != 0600 {
+ t.Fatal("journal permissions")
+ }
+}
+
+func TestRunnerPrepareOutbox(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ var path string
+ executionMust(t, f.d.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path))
+ x, err := f.s.AttachExecution(connectionContext, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)})
+ executionMust(t, err)
+ t.Cleanup(func() { x.Core.Close() })
+ _, err = x.Core.Resume(connectionContext)
+ executionMust(t, err)
+ executionMust(t, x.Sync(connectionContext))
+ aa, err := x.Poll(connectionContext, f.principal, "")
+ executionMust(t, err)
+ if len(aa) != 1 || aa[0].Kind != "prepare" {
+ t.Fatal("preparation assignment missing")
+ }
+ claim, err := x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: aa[0].ID, Revision: aa[0].Revision, RequestID: "claim"})
+ executionMust(t, err)
+ rf := runnerFixture{connectionFixture: f, x: x, a: aa[0], claim: claim}
+ token := runnerBearerFor(t, rf)
+ x.SetRunnerValidators(equipo.RunnerValidators{Prepare: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (equipo.PreparedBug, error) {
+ return bugPrepared(f), nil
+ }})
+ if status := runnerHTTP(t, rf, "prepare", token, rf.request()); status != 200 {
+ t.Fatal("prepare HTTP failed", status)
+ }
+ executionMust(t, x.Sync(connectionContext))
+ task, err = f.s.Task(connectionContext, ownerActor, task.ID)
+ executionMust(t, err)
+ if task.JobID == 0 || task.State != "queued" {
+ t.Fatal("prepared outbox not linked")
+ }
+ executionMust(t, x.Sync(connectionContext))
+ if scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 {
+ t.Fatal("preparation retry duplicated job")
+ }
+}
+
+func TestRunnerEndpointForeignPrincipal(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ code, key := beginDevice(t, f.s)
+ approveDevice(t, f.s, code, "member@example.com")
+ credential := claimDevice(t, f.s, code, key)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ t.Run(op, func(t *testing.T) {
+ if status := runnerHTTP(t, f, op, credential.Token, f.request()); status != 403 {
+ t.Fatal("foreign principal did not fail the binding guard", status)
+ }
+ })
+ }
+ if status := runnerHTTP(t, f, "claim", credential.Token, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); status != 403 {
+ t.Fatal("foreign claim did not fail binding", status)
+ }
+}
+func TestRunnerBoundsAndArtifactScope(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ q := f.request()
+ q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro")}
+ value, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q)
+ executionMust(t, err)
+ art := value.(team.Artifact)
+ token := runnerBearerFor(t, f)
+ url := fmt.Sprintf("/artifacts/%s/%d?version=1&request_id=read&account=%s&job=%d&attempt=%d&fence=%d", f.a.ID, art.ID, q.Scope.Account, q.Scope.Job, q.Handle.Attempt, q.Handle.Fence)
+ for _, bad := range []bool{false, true} {
+ u := url
+ if bad {
+ u = strings.Replace(u, "account="+string(q.Scope.Account), "account=other", 1)
+ }
+ r := httptest.NewRequest("GET", u, nil)
+ r.Header.Set("Authorization", "Bearer "+token)
+ w := httptest.NewRecorder()
+ f.s.RunnerHandler().ServeHTTP(w, r)
+ if (!bad && w.Code != 200) || (bad && w.Code < 400) {
+ t.Fatal("artifact scope", bad, w.Code)
+ }
+ }
+ for _, op := range []string{"events", "artifacts", "intend"} {
+ t.Run(op, func(t *testing.T) {
+ q := f.request()
+ switch op {
+ case "events":
+ q.Event = json.RawMessage(`{"text":"` + strings.Repeat("a", runnerproto.MaxEventBytes) + `"}`)
+ case "artifacts":
+ q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: bytes.Repeat([]byte("a"), runnerproto.MaxArtifactBytes+1)}
+ case "intend":
+ q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{"text":"` + strings.Repeat("a", runnerproto.MaxActionBytes) + `"}`)}
+ }
+ if _, err := f.x.Mutate(connectionContext, f.principal, op, q); err == nil {
+ t.Fatal("oversized payload accepted")
+ }
+ })
+ }
+}
+func TestRunnerClaimAtomicRollback(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("claim_fail", func(tx *gorm.DB) {
+ if tx.Statement.Table == "audit_events" {
+ if event, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && event.Kind == "runner.claim" {
+ tx.AddError(errors.New("claim audit unavailable"))
+ }
+ }
+ }))
+ q := equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}
+ if response, err := f.x.Claim(connectionContext, f.principal, q); err == nil || response.CleanupToken != "" {
+ t.Fatal("failed claim returned authority")
+ }
+ executionMust(t, f.d.G.Callback().Create().Remove("claim_fail"))
+ if scalar(t, f.d, "SELECT count(*) FROM attempts") != 0 || scalar(t, f.d, "SELECT count(*) FROM runner_cleanups") != 0 {
+ t.Fatal("claim partially committed")
+ }
+ _, err := f.x.Claim(connectionContext, f.principal, q)
+ executionMust(t, err)
+}
+
+func TestRunnerSelectionGuards(t *testing.T) {
+ for _, kind := range []string{"connection_revision", "connection_person", "connection_runner", "account", "stale", "specialist", "choice", "paused"} {
+ t.Run(kind, func(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ switch kind {
+ case "connection_revision":
+ mustSQL(t, f.d, "UPDATE connections SET revision=revision+1 WHERE id=?", f.a.Selection.ConnectionID)
+ case "connection_person":
+ mustSQL(t, f.d, "UPDATE connections SET person='other@example.com' WHERE id=?", f.a.Selection.ConnectionID)
+ case "connection_runner":
+ code, key := beginDevice(t, f.s)
+ approveDevice(t, f.s, code, ownerAddress)
+ credential := claimDevice(t, f.s, code, key)
+ mustSQL(t, f.d, "UPDATE connections SET runner_id=? WHERE id=?", credential.RunnerID, f.a.Selection.ConnectionID)
+ case "account":
+ sel := f.a.Selection
+ sel.AccountID = "other"
+ raw, _ := json.Marshal(sel)
+ mustSQL(t, f.d, "UPDATE runner_assignments SET selection=? WHERE id=?", string(raw), f.a.ID)
+ case "stale":
+ f.clock.Advance(90 * time.Second)
+ case "specialist":
+ mustSQL(t, f.d, "UPDATE specialists SET revision=revision+1 WHERE key='engineering'")
+ case "choice":
+ mustSQL(t, f.d, "UPDATE connection_choices SET connection_ids_json='[]'")
+ case "paused":
+ executionMust(t, f.x.Write(connectionContext, func(tx *gorm.DB) error { return tx.Exec("UPDATE service SET admission_paused=1").Error }))
+ }
+ if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); err == nil {
+ t.Fatal("claim guard bypassed", kind)
+ }
+ })
+ }
+}
+func TestRevokedCleanupBindingGuards(t *testing.T) {
+ for _, field := range []string{"audience", "expiry", "instance", "machine", "person", "attempt", "fence"} {
+ t.Run(field, func(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ q := f.request()
+ q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`)}
+ id, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
+ executionMust(t, err)
+ q.Intent = nil
+ q.ActionID = id.(team.ActionID)
+ q.Receipt = &team.Receipt{ID: "observation", Outcome: team.OutcomeSuccess}
+ switch field {
+ case "audience":
+ mustSQL(t, f.d, "UPDATE runner_cleanups SET audience='other'")
+ case "expiry":
+ mustSQL(t, f.d, "UPDATE runner_cleanups SET expires_at=?", f.clock.Now().Add(-time.Second))
+ case "instance":
+ mustSQL(t, f.d, "UPDATE runner_cleanups SET instance_id='other'")
+ case "machine":
+ mustSQL(t, f.d, "UPDATE runner_cleanups SET machine_key_hash='other'")
+ case "person":
+ mustSQL(t, f.d, "UPDATE runner_cleanups SET person='other'")
+ case "attempt":
+ mustSQL(t, f.d, "UPDATE runner_cleanups SET attempt_id=attempt_id+1")
+ case "fence":
+ mustSQL(t, f.d, "UPDATE runner_cleanups SET fence=fence+1")
+ }
+ if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "receipts", q); err == nil {
+ t.Fatal("cleanup binding bypassed", field)
+ }
+ })
+ }
+}
+
+func TestUnconfinedContainmentProofRequired(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return equipo.ErrForbidden }})
+ q := f.request()
+ if _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
+ t.Fatal("unverified containment accepted")
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM attempts WHERE containment='contained'") != 0 {
+ t.Fatal("invalid proof freed capacity")
+ }
+}
+
+func TestSpecialistConcurrencyReview(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ mustSQL(t, f.d, "UPDATE steps SET capability='verify' WHERE id=(SELECT step_id FROM attempts WHERE id=?)", f.claim.Handle.Attempt)
+ if _, err := f.s.SelectConnection(connectionContext, ownerAddress, f.project.ID, "review", "claude"); err == nil {
+ t.Fatal("verification did not occupy review specialist")
+ }
+}
+
+func TestRunnerAssignmentRetryPreservesCleanup(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ q := f.request()
+ q.Intent = &team.IntentSpec{Key: "old-turn", Operation: team.OpProviderCall, Payload: []byte(`{}`)}
+ id, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
+ executionMust(t, err)
+ q.Intent = nil
+ q.ActionID = id.(team.ActionID)
+ q.RequestID = "release"
+ q.Reason = team.WaitRunnerUnavailable
+ _, err = f.x.Mutate(connectionContext, f.principal, "release", q)
+ executionMust(t, err)
+ q.RequestID = "contained"
+ result, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ rotation := result.(equipo.CredentialRotation)
+ principal, err := f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token)
+ executionMust(t, err)
+ executionMust(t, f.x.AcknowledgeRotation(connectionContext, principal, q.RequestID))
+ executionMust(t, f.x.Sync(connectionContext))
+ ctx, cancel := context.WithTimeout(connectionContext, 100*time.Millisecond)
+ defer cancel()
+ aa, err := f.x.Poll(ctx, principal, f.a.ID)
+ if err != nil || len(aa) != 1 {
+ t.Fatal("contained retry assignment missing", err)
+ }
+ if aa[0].ID == f.a.ID || aa[0].Revision <= f.a.Revision {
+ t.Fatal("retry reused assignment binding")
+ }
+ _, err = f.x.Claim(connectionContext, principal, equipo.ClaimRequest{Version: 1, AssignmentID: aa[0].ID, Revision: aa[0].Revision, RequestID: "new-claim"})
+ executionMust(t, err)
+ q.RequestID = "late"
+ q.Receipt = &team.Receipt{ID: "old-observation", Outcome: team.OutcomeSuccess}
+ _, err = f.x.Cleanup(connectionContext, rotation.CleanupTokens[f.a.ID], "receipts", q)
+ executionMust(t, err)
+}
+
+func TestRunnerCannotUseAnotherMachine(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ code, key := beginDevice(t, f.s)
+ approveDevice(t, f.s, code, ownerAddress)
+ credential := claimDevice(t, f.s, code, key)
+ q := f.request()
+ q.Event = json.RawMessage(`{"kind":"progress"}`)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ if status := runnerHTTP(t, f, "events", credential.Token, q); status != 403 {
+ t.Fatal("same person used another machine's assignment", status)
+ }
+ if status := runnerHTTP(t, f, "claim", credential.Token, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}); status != 403 {
+ t.Fatal("same person claimed another machine's work", status)
+ }
+}
+func TestRunnerClaimRevision(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ if _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision + 1, RequestID: "claim"}); err == nil {
+ t.Fatal("stale assignment revision claimed")
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM attempts") != 0 {
+ t.Fatal("stale claim created attempt")
+ }
+}
+func TestRunnerHeartbeatAndValidatedReceipt(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ token := runnerBearerFor(t, f)
+ reports, err := runnerproto.Marshal(f.reports)
+ executionMust(t, err)
+ for _, op := range []string{"heartbeat", "connections"} {
+ if status := runnerHTTP(t, f, op, token, runnerproto.HeartbeatRequest{Version: 1, RequestID: op, Reports: reports}); status != 200 {
+ t.Fatal("valid machine report denied", op, status)
+ }
+ }
+ q := f.request()
+ q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: []byte(`{}`)}
+ result, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
+ executionMust(t, err)
+ q.Intent = nil
+ q.ActionID = result.(team.ActionID)
+ q.RequestID = "admit"
+ _, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
+ executionMust(t, err)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) {
+ return team.Receipt{ID: "verified", Outcome: team.OutcomeSuccess}, nil
+ }})
+ q.RequestID = "receipt"
+ q.Receipt = &team.Receipt{ID: "reported", Outcome: team.OutcomeSuccess}
+ if status := runnerHTTP(t, f, "receipts", token, q); status != 200 {
+ t.Fatal("validated receipt refused", status)
+ }
+ action, err := f.x.Core.GetAction(connectionContext, q.Scope, q.ActionID)
+ executionMust(t, err)
+ if action.Receipt == nil || action.Receipt.ID != "verified" {
+ t.Fatal("reported receipt bypassed validator")
+ }
+}
+
+func TestRevokedCleanupContainmentPreservesIntentCharge(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ q := f.request()
+ q.Intent = &team.IntentSpec{Key: "reserved", Operation: team.OpProviderCall, Payload: []byte(`{}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}}
+ _, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
+ executionMust(t, err)
+ q.Intent = nil
+ q.RequestID = "contained"
+ _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ reservations, err := f.x.Core.Reservations(connectionContext, q.Scope)
+ executionMust(t, err)
+ if len(reservations) != 1 || reservations[0].State != team.ReservationOpen {
+ t.Fatal("cleanup containment refunded an intent reservation")
+ }
+}
diff --git a/internal/runnerproto/journal.go b/internal/runnerproto/journal.go
new file mode 100644
index 00000000..3525b2c9
--- /dev/null
+++ b/internal/runnerproto/journal.go
@@ -0,0 +1,143 @@
+package runnerproto
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+)
+
+// ConsumeTicket durably records consumption before the caller executes an
+// effect. A crash after consumption is uncertain and must never redispatch.
+func ConsumeTicket(dir, requestID string, ticket team.AdmissionTicket, now time.Time, incarnation int64) error {
+ if requestID == "" || incarnation <= 0 || ticket.Dispatch.Action <= 0 || incarnation != ticket.Incarnation || !now.Before(ticket.ExpiresAt) || ticket.ExpiresAt.Sub(now) > 5*time.Second {
+ return ErrInvalid
+ }
+ rawRequest, err := os.ReadFile(admissionPath(dir, requestID))
+ if err != nil {
+ return err
+ }
+ var request RunnerRequest
+ if json.Unmarshal(rawRequest, &request) != nil || request.RequestID != requestID || request.ActionID != ticket.Dispatch.Action {
+ return ErrInvalid
+ }
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return err
+ }
+ hash := sha256.Sum256([]byte(fmt.Sprintf("%d/%d", ticket.Incarnation, ticket.Dispatch.Action)))
+ path := filepath.Join(dir, hex.EncodeToString(hash[:])+".consumed")
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ return err
+ }
+ raw, err := json.Marshal(struct {
+ RequestID string
+ Ticket team.AdmissionTicket
+ }{requestID, ticket})
+ if err == nil {
+ _, err = f.Write(raw)
+ }
+ if err == nil {
+ err = f.Sync()
+ }
+ closeErr := f.Close()
+ if err != nil {
+ return err
+ }
+ if closeErr != nil {
+ return closeErr
+ }
+ return syncDirectory(dir)
+}
+
+// JournalCredentials atomically replaces the local credential bundle before
+// the caller acknowledges rotation. The directory is trusted runner state.
+func JournalCredentials(path string, value any) error {
+ raw, err := json.Marshal(value)
+ if err != nil {
+ return err
+ }
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return err
+ }
+ f, err := os.CreateTemp(dir, ".rotation-")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(f.Name())
+ if _, err = f.Write(raw); err == nil {
+ err = f.Sync()
+ }
+ closeErr := f.Close()
+ if err != nil {
+ return err
+ }
+ if closeErr != nil {
+ return closeErr
+ }
+ if err = os.Rename(f.Name(), path); err != nil {
+ return err
+ }
+ return syncDirectory(dir)
+}
+func syncDirectory(path string) error {
+ d, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer d.Close()
+ return d.Sync()
+}
+
+func admissionPath(dir, requestID string) string {
+ hash := sha256.Sum256([]byte(requestID))
+ return filepath.Join(dir, hex.EncodeToString(hash[:])+".request")
+}
+
+// JournalAdmission saves the exact request before the HTTP call. Retrying a
+// request ID with another action or fence is refused, including after restart.
+func JournalAdmission(dir string, request RunnerRequest) error {
+ if request.Version != Version || request.RequestID == "" || len(request.RequestID) > 256 || request.ActionID <= 0 || request.Scope.Account == "" || request.Scope.Job <= 0 || request.Handle.Attempt <= 0 || request.Handle.Fence <= 0 || request.Handle.Runner == "" {
+ return ErrInvalid
+ }
+ raw, err := json.Marshal(request)
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return err
+ }
+ path := admissionPath(dir, request.RequestID)
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if os.IsExist(err) {
+ saved, readErr := os.ReadFile(path)
+ if readErr != nil {
+ return readErr
+ }
+ if !bytes.Equal(saved, raw) {
+ return ErrInvalid
+ }
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if _, err = f.Write(raw); err == nil {
+ err = f.Sync()
+ }
+ closeErr := f.Close()
+ if err != nil {
+ return err
+ }
+ if closeErr != nil {
+ return closeErr
+ }
+ return syncDirectory(dir)
+}
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go
index ff3362e7..56bd3388 100644
--- a/internal/runnerproto/types.go
+++ b/internal/runnerproto/types.go
@@ -1,6 +1,10 @@
package runnerproto
-import "time"
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "encoding/json"
+ "time"
+)
const (
Version = 1
@@ -54,3 +58,113 @@ type ErrorResponse struct {
Version int `json:"version"`
Error string `json:"error"`
}
+
+const (
+ CleanupAudience = "cleanup"
+ LongPollSeconds = 25
+ RenewSeconds = 15
+ MaxActionBytes = 64 << 10
+ MaxEventBytes = 16 << 10
+ MaxArtifactBytes = 1 << 20
+)
+
+type ClaimRequest struct {
+ Version int `json:"version"`
+ AssignmentID string `json:"assignment_id"`
+ Revision int64 `json:"revision"`
+ RequestID string `json:"request_id"`
+}
+type PollRequest struct {
+ Version int `json:"version"`
+ After string `json:"after"`
+}
+type RunnerRequest struct {
+ Version int `json:"version"`
+ AssignmentID string `json:"assignment_id"`
+ Scope team.Scope `json:"scope"`
+ Handle team.Handle `json:"handle"`
+ RequestID string `json:"request_id"`
+ ActionID team.ActionID `json:"action_id,omitempty"`
+ Intent *team.IntentSpec `json:"intent,omitempty"`
+ Receipt *team.Receipt `json:"receipt,omitempty"`
+ Artifact *team.ArtifactSpec `json:"artifact,omitempty"`
+ Event json.RawMessage `json:"event,omitempty"`
+ Prepared json.RawMessage `json:"prepared,omitempty"`
+ Proof json.RawMessage `json:"proof,omitempty"`
+ Result *team.AttemptResult `json:"result,omitempty"`
+ Reason team.WaitReason `json:"reason,omitempty"`
+}
+type WorkResponse struct {
+ Version int `json:"version"`
+ Result any `json:"result"`
+}
+type HeartbeatRequest struct {
+ RequestID string `json:"request_id"`
+ Version int `json:"version"`
+ Reports json.RawMessage `json:"reports"`
+ RotationRequestID string `json:"rotation_request_id,omitempty"`
+}
+type Delivery struct {
+ Ticket team.AdmissionTicket `json:"ticket"`
+ ReceivedAt time.Time `json:"received_at"`
+}
+
+type ConnectionRouting struct {
+ BindingID, AccountID, ObservedAccountID, CredentialHomeHash string
+ AccountPinned, NoFailover, TimelineRecovery, ProcessOwnership bool
+}
+
+type ConnectionReport struct {
+ LocalID, Provider, ProviderVersion, PaseoVersion, Family, Model, AccountLabel, Kind, UnavailableReason, IsolationConfigHash string
+ Available, ReadIsolation, AllowanceKnown bool
+ AllowanceRemaining int64
+ Routing ConnectionRouting
+}
+
+type Selection struct {
+ ConnectionID, RunnerID, Person, Provider, Family, Model, AccountLabel, AccountID string
+ Revision, ChoiceRevision, SpecialistRevision int64
+ Reason string
+ MaxConcurrent int
+ AllowanceKnown bool
+ AllowanceRemaining int64
+ Isolation team.IsolationSnapshot
+}
+
+type Assignment struct {
+ ID string `json:"id"`
+ TaskID string `json:"task_id"`
+ StepKey string `json:"step_key"`
+ WorkspaceKey string `json:"workspace_key"`
+ Scope Scope `json:"scope"`
+ Selection Selection `json:"selection"`
+ Revision int64 `json:"revision"`
+ Kind string `json:"kind"`
+}
+
+type RunnerBrief struct {
+ Target team.TargetBinding `json:"target"`
+ Instructions string `json:"instructions"`
+ StandingInstructions string `json:"standing_instructions"`
+ ConfirmedPreferences []string `json:"confirmed_preferences"`
+ Selection Selection `json:"selection"`
+ Policy team.Policy `json:"policy"`
+ ArtifactHashes []string `json:"artifact_hashes"`
+}
+
+type ClaimResponse struct {
+ Scope Scope `json:"scope"`
+ Handle team.Handle `json:"handle"`
+ Brief RunnerBrief `json:"brief"`
+ LeaseDeadline time.Time `json:"lease_deadline"`
+ CleanupToken string `json:"cleanup_token"`
+ CleanupExpiresAt time.Time `json:"cleanup_expires_at"`
+ RenewSeconds int `json:"renew_seconds"`
+}
+
+type CredentialRotation struct {
+ Bearer RunnerCredential `json:"bearer"`
+ CleanupTokens map[string]string `json:"cleanup_tokens"`
+}
+
+type Scope = team.Scope
diff --git a/internal/runnerproto/validate.go b/internal/runnerproto/validate.go
index 4f593d36..ad9a5c1a 100644
--- a/internal/runnerproto/validate.go
+++ b/internal/runnerproto/validate.go
@@ -17,8 +17,12 @@ import (
var ErrInvalid = errors.New("runner.invalid")
func Decode(r io.Reader, value any) error {
- data, err := io.ReadAll(io.LimitReader(r, 8193))
- if err != nil || len(data) > 8192 {
+ return DecodeLimit(r, value, 8192)
+}
+
+func DecodeLimit(r io.Reader, value any, limit int64) error {
+ data, err := io.ReadAll(io.LimitReader(r, limit+1))
+ if err != nil || int64(len(data)) > limit {
return ErrInvalid
}
dec := json.NewDecoder(bytes.NewReader(data))
@@ -28,9 +32,7 @@ func Decode(r io.Reader, value any) error {
if _, err = dec.Token(); err != io.EOF {
return ErrInvalid
}
- dec = json.NewDecoder(bytes.NewReader(data))
- dec.DisallowUnknownFields()
- if dec.Decode(value) != nil {
+ if decodeWire(data, value) != nil {
return ErrInvalid
}
return nil
diff --git a/internal/runnerproto/wire.go b/internal/runnerproto/wire.go
new file mode 100644
index 00000000..5a725520
--- /dev/null
+++ b/internal/runnerproto/wire.go
@@ -0,0 +1,178 @@
+package runnerproto
+
+import (
+ "bytes"
+ "encoding/json"
+ "reflect"
+ "strings"
+ "unicode"
+)
+
+// Wire adapts legacy core DTO field names without changing their persisted JSON.
+func snake(s string) string {
+ r := []rune(s)
+ var out []rune
+ for i, c := range r {
+ if unicode.IsUpper(c) {
+ if i > 0 && (unicode.IsLower(r[i-1]) || unicode.IsDigit(r[i-1]) || (i+1 < len(r) && unicode.IsLower(r[i+1]))) {
+ out = append(out, '_')
+ }
+ c = unicode.ToLower(c)
+ }
+ out = append(out, c)
+ }
+ return string(out)
+}
+func fieldNames(f reflect.StructField) (string, string) {
+ tag := strings.Split(f.Tag.Get("json"), ",")[0]
+ if tag != "" {
+ return tag, tag
+ }
+ return snake(f.Name), f.Name
+}
+
+var unmarshalerType = reflect.TypeFor[json.Unmarshaler]()
+
+func incoming(value any, t reflect.Type) (any, error) {
+ for t.Kind() == reflect.Pointer {
+ t = t.Elem()
+ }
+ if reflect.PointerTo(t).Implements(unmarshalerType) {
+ return value, nil
+ }
+ switch t.Kind() {
+ case reflect.Struct:
+ fields, ok := value.(map[string]any)
+ if !ok {
+ return value, nil
+ }
+ out := map[string]any{}
+ for name, v := range fields {
+ found := false
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ if !f.IsExported() {
+ continue
+ }
+ wire, stored := fieldNames(f)
+ if wire == name {
+ normalized, err := incoming(v, f.Type)
+ if err != nil {
+ return nil, err
+ }
+ out[stored] = normalized
+ found = true
+ break
+ }
+ }
+ if !found {
+ return nil, ErrInvalid
+ }
+ }
+ return out, nil
+ case reflect.Slice, reflect.Array:
+ if values, ok := value.([]any); ok {
+ for i, v := range values {
+ n, err := incoming(v, t.Elem())
+ if err != nil {
+ return nil, err
+ }
+ values[i] = n
+ }
+ return values, nil
+ }
+ case reflect.Map:
+ if values, ok := value.(map[string]any); ok {
+ for k, v := range values {
+ n, err := incoming(v, t.Elem())
+ if err != nil {
+ return nil, err
+ }
+ values[k] = n
+ }
+ return values, nil
+ }
+ }
+ return value, nil
+}
+func decodeWire(data []byte, value any) error {
+ typ := reflect.TypeOf(value)
+ if typ == nil || typ.Kind() != reflect.Pointer {
+ return ErrInvalid
+ }
+ var raw any
+ d := json.NewDecoder(bytes.NewReader(data))
+ d.UseNumber()
+ if d.Decode(&raw) != nil {
+ return ErrInvalid
+ }
+ normalized, err := incoming(raw, typ)
+ if err != nil {
+ return err
+ }
+ data, err = json.Marshal(normalized)
+ if err != nil {
+ return err
+ }
+ d = json.NewDecoder(bytes.NewReader(data))
+ d.DisallowUnknownFields()
+ return d.Decode(value)
+}
+func outgoing(v reflect.Value) any {
+ if !v.IsValid() {
+ return nil
+ }
+ if v.Kind() == reflect.Interface || v.Kind() == reflect.Pointer {
+ if v.IsNil() {
+ return nil
+ }
+ return outgoing(v.Elem())
+ }
+ if _, ok := v.Interface().(json.Marshaler); ok {
+ return v.Interface()
+ }
+ switch v.Kind() {
+ case reflect.Struct:
+ out := map[string]any{}
+ t := v.Type()
+ for i := 0; i < v.NumField(); i++ {
+ f := t.Field(i)
+ if !f.IsExported() {
+ continue
+ }
+ name, _ := fieldNames(f)
+ if name == "-" {
+ continue
+ }
+ if strings.Contains(f.Tag.Get("json"), "omitempty") && v.Field(i).IsZero() {
+ continue
+ }
+ out[name] = outgoing(v.Field(i))
+ }
+ return out
+ case reflect.Slice, reflect.Array:
+ if v.Type().Elem().Kind() == reflect.Uint8 {
+ return v.Interface()
+ }
+ if v.Kind() == reflect.Slice && v.IsNil() {
+ return nil
+ }
+ out := make([]any, v.Len())
+ for i := range out {
+ out[i] = outgoing(v.Index(i))
+ }
+ return out
+ case reflect.Map:
+ if v.Type().Key().Kind() != reflect.String {
+ return v.Interface()
+ }
+ out := map[string]any{}
+ iter := v.MapRange()
+ for iter.Next() {
+ out[iter.Key().String()] = outgoing(iter.Value())
+ }
+ return out
+ }
+ return v.Interface()
+}
+func Marshal(value any) ([]byte, error) { return json.Marshal(outgoing(reflect.ValueOf(value))) }