fix: prove containment by start time and survive restarts
34 files changed,
+2,396
−317
internal/equipo/runner_handlers.go+2 −1internal/equipo/runner_report_validation.go+189 −0internal/equipo/runner_supervision.go+11 −11internal/equipotest/cancel_test.go+39 −8internal/equipotest/preparation_integration_test.go+191 −45internal/runner/checks/attestation_r1_test.go+69 −0internal/runner/checks/executor.go+30 −10internal/runner/checks/executor_test.go+1 −0internal/runner/checks/sandbox.go+18 −2internal/runner/containment_r1_test.go+575 −0internal/runner/creation_recovery.go+86 −0internal/runner/http.go+14 −2internal/runner/lease_check_r1_test.go+105 −0internal/runner/lease_linux.go+27 −0internal/runner/paseo/client.go+36 −2internal/runner/paseo/types.go+2 −0internal/runner/process_linux.go+284 −131internal/runner/process_linux_test.go+31 −20internal/runner/questions.go+3 −2internal/runner/retry.go+43 −0internal/runner/service.go+24 −2internal/runner/supervisor.go+78 −15internal/runner/supervisor_r1_test.go+310 −0internal/runner/supervisor_test.go+6 −4internal/runner/tool_journal.go+44 −0internal/runner/witness.go+16 −17internal/runner/workflow.go+37 −10internal/runner/workflow_integration_test.go+35 −7internal/runner/workflow_turn.go+14 −19internal/runner/workspace/workspace.go+1 −1internal/runnerproto/ownership.go+14 −0internal/runnerproto/types.go+2 −1runner/paseo/bridge.mjs+39 −7runner/paseo/bridge.test.mjs+20 −0
CI failed — run details
diff --git a/internal/equipo/runner_handlers.go b/internal/equipo/runner_handlers.go| index c1469628..f1d22a58 100644 |
| --- a/internal/equipo/runner_handlers.go |
| +++ b/internal/equipo/runner_handlers.go |
| @@ -8,6 +8,7 @@ import ( |
| "strconv" |
| "strings" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "amadan.net/rastrillo/rastrillo/auth" |
| "github.com/go-chi/chi/v5" |
| @@ -37,7 +38,7 @@ func runnerFailure(w http.ResponseWriter, err error) { |
| status, key = 409, "runner.pending" |
| case errors.Is(err, ErrInvalid): |
| status, key = 422, "form.invalid" |
| - case errors.Is(err, ErrForbidden), errors.Is(err, ErrNotFound): |
| + case errors.Is(err, ErrForbidden), errors.Is(err, ErrNotFound), errors.Is(err, team.ErrScope), errors.Is(err, team.ErrFence), errors.Is(err, team.ErrLeaseExpired), errors.Is(err, team.ErrAdmissionExpired), errors.Is(err, team.ErrGrantRevoked), errors.Is(err, team.ErrGrantStale): |
| status, key = 403, "form.forbidden" |
| case errors.Is(err, ErrConflict): |
| status, key = 409, "form.conflict" |
diff --git a/internal/equipo/runner_report_validation.go b/internal/equipo/runner_report_validation.go| new file mode 100644 |
| index 00000000..7571c3d4 |
| --- /dev/null |
| +++ b/internal/equipo/runner_report_validation.go |
| @@ -0,0 +1,189 @@ |
| +package equipo |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| + "slices" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func instanceValidators() RunnerValidators { |
| + return RunnerValidators{ |
| + Artifact: func(_ context.Context, a Assignment, q RunnerRequest) error { |
| + if a.ID != q.AssignmentID || q.Artifact == nil || len(q.Artifact.Payload) == 0 || !json.Valid(q.Artifact.Payload) { |
| + return ErrInvalid |
| + } |
| + return nil |
| + }, |
| + Prepare: func(_ context.Context, a Assignment, q RunnerRequest) (runnerproto.PreparedBug, error) { |
| + var p runnerproto.PreparedBug |
| + if a.ID != q.AssignmentID || a.Kind != "prepare" || json.Unmarshal(q.Prepared, &p) != nil || team.ContentDigest(p.CheckDefinition) != p.CheckDefinitionHash { |
| + return p, ErrInvalid |
| + } |
| + return p, nil |
| + }, |
| + Events: func(_ context.Context, a Assignment, q RunnerRequest) error { |
| + var event runnerproto.Event |
| + if runnerproto.DecodeLimit(bytes.NewReader(q.Event), &event, runnerproto.MaxEventBytes+4096) != nil || event.Validate() != nil || event.AssignmentID != a.ID || event.Scope != q.Scope || event.Handle != q.Handle || event.ActionID != q.ActionID { |
| + return ErrInvalid |
| + } |
| + return nil |
| + }, |
| + Question: func(ctx context.Context, a Assignment, q RunnerRequest) error { |
| + if q.Question == nil || q.Question.Validate() != nil || q.Question.AssignmentID != a.ID || q.Question.TaskID != a.TaskID || q.Question.Attempt != int64(q.Handle.Attempt) || q.Question.Fence != q.Handle.Fence { |
| + return ErrInvalid |
| + } |
| + tx, ok := ctx.Value(runnerTxKey{}).(*gorm.DB) |
| + if !ok { |
| + return ErrUnavailable |
| + } |
| + var events []runnerEvent |
| + if err := tx.Where("assignment_id=?", a.ID).Find(&events).Error; err != nil { |
| + return storeError(err) |
| + } |
| + for _, row := range events { |
| + var event runnerproto.Event |
| + if json.Unmarshal([]byte(row.Body), &event) != nil { |
| + return ErrInvalid |
| + } |
| + if event.ServerID == q.Question.ServerID && event.AgentID == q.Question.AgentID && event.SessionID == q.Question.SessionID { |
| + return nil |
| + } |
| + } |
| + return ErrForbidden |
| + }, |
| + Receipt: func(_ context.Context, a Assignment, q RunnerRequest) (team.Receipt, error) { |
| + if a.ID != q.AssignmentID { |
| + return team.Receipt{}, ErrForbidden |
| + } |
| + if q.Receipt != nil { |
| + return *q.Receipt, nil |
| + } |
| + var event runnerproto.Event |
| + if runnerproto.DecodeLimit(bytes.NewReader(q.Event), &event, runnerproto.MaxEventBytes+4096) != nil || event.Validate() != nil || (event.Kind != "turn_completed" && event.Kind != "turn_failed") { |
| + return team.Receipt{}, ErrInvalid |
| + } |
| + outcome := team.OutcomeSuccess |
| + if event.Kind == "turn_failed" { |
| + outcome = team.OutcomeFailure |
| + } |
| + // Without a separate authenticated usage receipt, completion remains unmeasured. |
| + return team.Receipt{ID: event.TurnID, Outcome: outcome, Provider: a.Selection.Provider, Model: a.Selection.Model}, nil |
| + }, |
| + Containment: func(_ context.Context, a Assignment, q RunnerRequest) error { |
| + var p runnerproto.ContainmentProof |
| + if a.ID != q.AssignmentID || json.Unmarshal(q.Proof, &p) != nil || !p.Empty || p.Scope != q.Scope || p.Handle != q.Handle || p.Owner.Attempt != q.Handle.Attempt || p.Owner.Fence != q.Handle.Fence || p.Inventory.BootID == "" || p.Inventory.CheckedAt.IsZero() || !p.Inventory.CoverageKnown || len(p.Inventory.Processes) != 0 || len(p.Inventory.TerminalIDs) != 0 { |
| + return ErrInvalid |
| + } |
| + marker := runnerproto.EventHash([]any{q.Scope, q.Handle.Attempt, q.Handle.Fence, q.Handle.Runner}) |
| + if a.Kind == "prepare" { |
| + marker = a.ID |
| + } |
| + if p.Owner.Marker != marker || (a.Kind == "prepare" && !p.Owner.LocalOnly) { |
| + return ErrForbidden |
| + } |
| + if !p.Owner.LocalOnly && (p.Owner.Workspace.ServerID == "" || p.Owner.Workspace.WorkspaceID == "") { |
| + return ErrInvalid |
| + } |
| + return nil |
| + }, |
| + } |
| +} |
| + |
| +func (s *Store) supervisedAssignment(ctx context.Context, raw *sql.Tx, scope team.Scope, h team.Handle) (runnerAssignment, Assignment, error) { |
| + var a runnerAssignment |
| + if s.execution == nil { |
| + return a, Assignment{}, ErrUnavailable |
| + } |
| + tx := s.execution.gormTx(ctx, raw) |
| + 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 a, Assignment{}, storeError(err) |
| + } |
| + value, err := assignmentValue(a) |
| + return a, value, err |
| +} |
| +func (s *Store) supervisedProvenance(ctx context.Context, raw *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) { |
| + a, value, err := s.supervisedAssignment(ctx, raw, scope, h) |
| + if err != nil { |
| + return team.Provenance{}, err |
| + } |
| + p := team.Provenance{Producer: "equipo-runner", Provider: value.Selection.Provider, ModelFamily: value.Selection.Family, Context: runnerproto.EventHash([]any{scope, h.Attempt, h.Fence, h.Runner})} |
| + if a.StepKey == "verify" || a.StepKey == "publish" { |
| + return p, nil |
| + } |
| + var rows []runnerEvent |
| + if err = s.execution.gormTx(ctx, raw).Where("assignment_id=? AND kind=?", a.ID, "timeline_ready").Find(&rows).Error; err != nil { |
| + return p, storeError(err) |
| + } |
| + if len(rows) == 0 { |
| + return p, ErrForbidden |
| + } |
| + for i, row := range rows { |
| + var event runnerproto.Event |
| + if json.Unmarshal([]byte(row.Body), &event) != nil || event.Scope != scope || event.Handle.Attempt != h.Attempt || event.Handle.Fence != h.Fence || event.Handle.Runner != h.Runner { |
| + return p, ErrForbidden |
| + } |
| + if i > 0 && (p.Producer != event.AgentID || p.Context != event.SessionID) { |
| + return p, ErrConflict |
| + } |
| + p.Producer = event.AgentID |
| + p.Context = event.SessionID |
| + } |
| + return p, nil |
| +} |
| +func (s *Store) supervisedExecutorEvidence(ctx context.Context, raw *sql.Tx, scope team.Scope, h team.Handle, spec team.ArtifactSpec) (team.Provenance, error) { |
| + a, value, err := s.supervisedAssignment(ctx, raw, scope, h) |
| + if err != nil { |
| + return team.Provenance{}, err |
| + } |
| + var iso team.IsolationSnapshot |
| + switch spec.Role { |
| + case team.RoleBaseResult, team.RoleCandidateResult: |
| + var r team.CheckResult |
| + if json.Unmarshal(spec.Payload, &r) != nil { |
| + return team.Provenance{}, ErrInvalid |
| + } |
| + iso = r.Isolation |
| + if (spec.Role == team.RoleBaseResult && a.StepKey != "reproduce") || (spec.Role == team.RoleCandidateResult && a.StepKey != "verify") { |
| + return team.Provenance{}, ErrForbidden |
| + } |
| + case team.RoleRepositoryChecks: |
| + var r team.RepositoryCheckResult |
| + if a.StepKey != "verify" || json.Unmarshal(spec.Payload, &r) != nil { |
| + return team.Provenance{}, ErrInvalid |
| + } |
| + iso = r.Isolation |
| + default: |
| + return team.Provenance{}, ErrForbidden |
| + } |
| + expectedIsolation := value.Selection.Isolation |
| + if expectedIsolation.RunnerTainted { |
| + expectedIsolation.Status = "unconfined" |
| + } |
| + reported := canonicalReportIsolation(iso) |
| + expected := canonicalReportIsolation(expectedIsolation) |
| + if !bytes.Equal(reported, expected) { |
| + return team.Provenance{}, ErrForbidden |
| + } |
| + return team.Provenance{Producer: "equipo-checks", Provider: "executor", Context: h.Runner, ConnectionID: value.Selection.ConnectionID, Isolation: value.Selection.Isolation}, nil |
| +} |
| + |
| +func canonicalReportIsolation(iso team.IsolationSnapshot) []byte { |
| + iso.AcknowledgementIDs = slices.Clone(iso.AcknowledgementIDs) |
| + slices.Sort(iso.AcknowledgementIDs) |
| + iso.AcknowledgementIDs = slices.Compact(iso.AcknowledgementIDs) |
| + iso.ObservedTuples = slices.Clone(iso.ObservedTuples) |
| + slices.SortFunc(iso.ObservedTuples, func(a, b team.IsolationTuple) int { |
| + x, _ := json.Marshal(a) |
| + y, _ := json.Marshal(b) |
| + return bytes.Compare(x, y) |
| + }) |
| + iso.ObservedTuples = slices.Compact(iso.ObservedTuples) |
| + raw, _ := json.Marshal(iso) |
| + return raw |
| +} |
diff --git a/internal/equipo/runner_supervision.go b/internal/equipo/runner_supervision.go| index 7a839db6..c84d4516 100644 |
| --- a/internal/equipo/runner_supervision.go |
| +++ b/internal/equipo/runner_supervision.go |
| @@ -2,27 +2,23 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| - "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "context" |
| "encoding/json" |
| "gorm.io/gorm" |
| ) |
| -// AttachSupervisedExecution installs the real journal, executor and question |
| -// validators as one startup operation. Ordinary construction remains closed. |
| -func (s *Store) AttachSupervisedExecution(ctx context.Context, path string, options team.Options, w *runner.Witness) (*Execution, error) { |
| - if w == nil { |
| - return nil, ErrInvalid |
| - } |
| - options.Provenance = w.Provenance |
| - options.ExecutorEvidence = w.ExecutorEvidence |
| +// AttachSupervisedExecution installs instance-side validators. The runner |
| +// verifies its local observations before submitting authenticated reports. |
| +func (s *Store) AttachSupervisedExecution(ctx context.Context, path string, options team.Options) (*Execution, error) { |
| + options.Provenance = s.supervisedProvenance |
| + options.ExecutorEvidence = s.supervisedExecutorEvidence |
| options.Adapters = map[team.Operation]team.Adapter{team.OpProviderCall: s.RunnerAdapter(team.OpProviderCall), team.OpForgePublish: s.RunnerAdapter(team.OpForgePublish)} |
| e, err := s.AttachExecution(ctx, path, options) |
| if err != nil { |
| return nil, err |
| } |
| - e.SetRunnerValidators(RunnerValidators{Question: w.Question, Receipt: w.Receipt, Containment: w.Containment, Prepare: w.Prepare, Events: w.Events, Artifact: w.Artifact}) |
| + e.SetRunnerValidators(instanceValidators()) |
| return e, nil |
| } |
| func (e *Execution) concludeAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, q RunnerRequest) (any, error) { |
| @@ -65,9 +61,13 @@ func (e *Execution) RecoverClaim(ctx context.Context, p RunnerPrincipal, q Claim |
| if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil { |
| return storeError(err) |
| } |
| - if a.RunnerID != p.RunnerID || a.Person != p.Person || a.ClaimRequest != q.RequestID || a.Revision != q.Revision || a.State == "pending" { |
| + if a.RunnerID != p.RunnerID || a.Person != p.Person { |
| return ErrForbidden |
| } |
| + if a.ClaimRequest != q.RequestID || a.Revision != q.Revision || a.State == "pending" { |
| + result.NotClaimed = true |
| + return nil |
| + } |
| var cleanup runnerCleanup |
| if err := tx.First(&cleanup, "assignment_id=?", a.ID).Error; err != nil { |
| return storeError(err) |
diff --git a/internal/equipotest/cancel_test.go b/internal/equipotest/cancel_test.go| index 3cdb9768..863f460b 100644 |
| --- a/internal/equipotest/cancel_test.go |
| +++ b/internal/equipotest/cancel_test.go |
| @@ -4,8 +4,10 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "context" |
| + "errors" |
| "net/http/httptest" |
| "os" |
| "path/filepath" |
| @@ -32,12 +34,6 @@ func TestCancelTaskFencesBeforeAcknowledgement(t *testing.T) { |
| t.Fatal("stranger cancelled") |
| } |
| } |
| -func TestBugPreparationIntegration(t *testing.T) { |
| - f := runnerFixtureNew(t, true) |
| - if len(f.claim.Brief.CheckDefinition) == 0 { |
| - t.Fatal("immutable check definition missing from runner claim") |
| - } |
| -} |
| func TestRunnerBugFailureEndsFixedRun(t *testing.T) { |
| f := runnerFixtureNew(t, true) |
| @@ -134,7 +130,42 @@ func TestRunnerRestartLostClaimReply(t *testing.T) { |
| t.Fatal("recovery restored dispatch authority") |
| } |
| q.RequestID = "other" |
| - if _, err = f.x.RecoverClaim(connectionContext, f.principal, q); err == nil { |
| - t.Fatal("foreign claim request recovered") |
| + if reply, e := f.x.RecoverClaim(connectionContext, f.principal, q); e != nil || !reply.NotClaimed || reply.CleanupToken != "" { |
| + t.Fatal("foreign claim request recovered authority") |
| + } |
| +} |
| + |
| +func TestRunnerHTTPExpiredLeaseDefinitive(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + token := runnerBearerFor(t, f) |
| + server := httptest.NewServer(f.s.RunnerHandler()) |
| + defer server.Close() |
| + dir := t.TempDir() |
| + executionMust(t, os.Chmod(dir, 0700)) |
| + journal, err := runner.OpenJournal(connectionContext, filepath.Join(dir, "journal.db")) |
| + executionMust(t, err) |
| + defer journal.Close() |
| + api, err := runner.NewHTTPInstance(server.URL, journal, runnerproto.RunnerCredential{Token: token, ExpiresAt: time.Now().Add(time.Hour)}) |
| + executionMust(t, err) |
| + f.clock.Advance(61 * time.Second) |
| + if err = api.Call(connectionContext, "validate", f.request(), nil); !errors.Is(err, paseo.ErrIdentity) { |
| + t.Fatal("expired lease was not a definitive denial", err) |
| + } |
| +} |
| +func TestRunnerHTTPNeverAppliedClaim(t *testing.T) { |
| + f := runnerFixtureNew(t, false) |
| + token := runnerBearerFor(t, f) |
| + server := httptest.NewServer(f.s.RunnerHandler()) |
| + defer server.Close() |
| + dir := t.TempDir() |
| + executionMust(t, os.Chmod(dir, 0700)) |
| + journal, err := runner.OpenJournal(connectionContext, filepath.Join(dir, "journal.db")) |
| + executionMust(t, err) |
| + defer journal.Close() |
| + api, err := runner.NewHTTPInstance(server.URL, journal, runnerproto.RunnerCredential{Token: token, ExpiresAt: time.Now().Add(time.Hour)}) |
| + executionMust(t, err) |
| + _, err = api.RecoverClaim(connectionContext, runnerproto.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "never-sent"}) |
| + if !errors.Is(err, runner.ErrNotClaimed) { |
| + t.Fatal("never-applied claim not distinguished", err) |
| } |
| } |
diff --git a/internal/equipotest/preparation_integration_test.go b/internal/equipotest/preparation_integration_test.go| index fffdd619..41626183 100644 |
| --- a/internal/equipotest/preparation_integration_test.go |
| +++ b/internal/equipotest/preparation_integration_test.go |
| @@ -1,7 +1,6 @@ |
| package equipotest |
| import ( |
| - "bytes" |
| "context" |
| "crypto/sha256" |
| "encoding/json" |
| @@ -11,7 +10,6 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| - "runtime" |
| "strings" |
| "testing" |
| "time" |
| @@ -20,6 +18,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| "amadan.net/oficina/equipo/internal/runner/paseo" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| @@ -31,7 +30,12 @@ type preparationRemote struct{ path string } |
| func (r preparationRemote) Resolve(context.Context, string) (workspace.Remote, error) { |
| return workspace.Remote{URL: r.path}, nil |
| } |
| -func TestBugPreparationCrashRealProtocolLocalGit(t *testing.T) { |
| +func TestBugPreparationCrashRealProtocolLocalGit(t *testing.T) { runPreparationSupervisor(t, true) } |
| +func TestBugPreparationIntegration(t *testing.T) { runPreparationSupervisor(t, false) } |
| +func runPreparationSupervisor(t *testing.T, crash bool) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| f := bugFixture(t) |
| task := bugTask(t, f) |
| ctx := connectionContext |
| @@ -45,7 +49,7 @@ func TestBugPreparationCrashRealProtocolLocalGit(t *testing.T) { |
| 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.AttachSupervisedExecution(ctx, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)}, w) |
| + x, err := f.s.AttachSupervisedExecution(ctx, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)}) |
| executionMust(t, err) |
| defer x.Core.Close() |
| _, err = x.Core.Resume(ctx) |
| @@ -92,12 +96,20 @@ func TestBugPreparationCrashRealProtocolLocalGit(t *testing.T) { |
| policy := paseo.ReadPolicy{ConfigHash: strings.Repeat("a", 64), DeniedPaths: []string{state, private}} |
| binary, err := exec.LookPath("codex") |
| executionMust(t, err) |
| - sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: binary, ScratchRoot: scratch, GoRoot: runtime.GOROOT(), GoBinary: filepath.Join(runtime.GOROOT(), "bin/go"), Protected: protected}) |
| + goBinary, err := exec.LookPath("go") |
| + executionMust(t, err) |
| + goBinary, err = filepath.EvalSymlinks(goBinary) |
| executionMust(t, err) |
| + goRoot := filepath.Dir(filepath.Dir(goBinary)) |
| + sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: binary, ScratchRoot: scratch, GoRoot: goRoot, GoBinary: filepath.Join(goRoot, "bin/go"), Protected: protected}) |
| + executionMust(t, err) |
| + localRepo := "" |
| + client := &paseo.Client{} |
| m, err := workspace.New(workspace.Config{PrivateRoot: private, WorkspaceRoot: filepath.Join(root, "work"), GitPath: "/usr/bin/git", Forge: preparationRemote{remote}, Protected: protected, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Definitions: func(ctx context.Context, target team.TargetBinding, repo string) (runnerproto.PreparedBug, error) { |
| + localRepo = repo |
| d, err := checks.LoadBaseDefinition(ctx, repo, target.Repository, target.BaseRevision, scratch) |
| if err != nil { |
| - return runnerproto.PreparedBug{}, err |
| + return runnerproto.PreparedBug{}, fmt.Errorf("preparation definition/baseline: %w", err) |
| } |
| e, err := checks.New(checks.Config{ScratchRoot: scratch, Deadline: time.Now().Add(2 * time.Minute), Policy: policy, Export: func(ctx context.Context, commit, dest string) error { |
| return checks.ExportBase(ctx, repo, commit, dest) |
| @@ -107,64 +119,78 @@ func TestBugPreparationCrashRealProtocolLocalGit(t *testing.T) { |
| return checks.Reproduction{}, paseo.ErrIdentity |
| }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return a.Selection.Isolation, nil }}, sandbox) |
| if err != nil { |
| - return runnerproto.PreparedBug{}, err |
| + return runnerproto.PreparedBug{}, fmt.Errorf("preparation definition/baseline: %w", err) |
| } |
| d.Baseline, err = e.CaptureBaseline(ctx, d) |
| if err != nil { |
| - return runnerproto.PreparedBug{}, err |
| + return runnerproto.PreparedBug{}, fmt.Errorf("preparation definition/baseline: %w", err) |
| } |
| b, _ := json.Marshal(d) |
| return runnerproto.PreparedBug{CheckDefinition: b, CheckDefinitionHash: checks.Digest(b), BaselineTestSetHash: d.Baseline.Hash}, nil |
| - }}, &paseo.Client{}) |
| - executionMust(t, err) |
| - prepared, err := w.PrepareBug(ctx, m, a, claim.Brief.Target) |
| + }}, client) |
| executionMust(t, err) |
| - if prepared.BaseCommit != base { |
| - t.Fatal("preparation did not pin Git base") |
| - } |
| + |
| token := strings.Repeat("A", 43) |
| 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) |
| - q := runnerproto.RunnerRequest{Version: 1, AssignmentID: a.ID, Scope: claim.Scope, Handle: claim.Handle, RequestID: "prepared"} |
| - q.Prepared, _ = json.Marshal(prepared) |
| - send := func() int { |
| - raw, err := runnerproto.Marshal(q) |
| - executionMust(t, err) |
| - req := httptest.NewRequest("POST", "/prepare", bytes.NewReader(raw)) |
| - req.Header.Set("Content-Type", "application/json") |
| - req.Header.Set("Authorization", "Bearer "+token) |
| - rec := httptest.NewRecorder() |
| - f.s.RunnerHandler().ServeHTTP(rec, req) |
| - return rec.Code |
| - } |
| - injected := false |
| - executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task15_prepare_crash", func(tx *gorm.DB) { |
| - if event, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && event.Kind == "task.prepare" { |
| - injected = true |
| - tx.AddError(errors.New("crash before acknowledgement")) |
| + server := httptest.NewServer(f.s.RunnerHandler()) |
| + defer server.Close() |
| + api, err := runner.NewHTTPInstance(server.URL, journal, runnerproto.RunnerCredential{Token: token, ExpiresAt: time.Now().Add(time.Hour)}) |
| + executionMust(t, err) |
| + // Recover the exact already-issued claim over HTTP, then use its original live lease. |
| + recovered, err := api.RecoverClaim(ctx, runnerproto.ClaimRequest{Version: 1, AssignmentID: a.ID, Revision: a.Revision, RequestID: "prepare-claim"}) |
| + executionMust(t, err) |
| + claim.CleanupToken = recovered.CleanupToken |
| + // Fixture clocks are fixed; the runner's Linux clock needs live deadlines. |
| + claim.LeaseDeadline = time.Now().Add(time.Minute) |
| + claim.AttemptDeadline = time.Now().Add(10 * time.Minute) |
| + wf, err := runner.NewBugWorkflow(runner.BugWorkflowConfig{Workspaces: m, Client: client, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Executor: func(context.Context, runner.RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error) { |
| + return nil, paseo.ErrContract |
| + }, Publisher: &forge.Publisher{}, StateDir: state, Executable: "/bin/false", InstanceID: "fixture"}) |
| + executionMust(t, err) |
| + inspector, err := runner.NewLinuxProcessInspector("/proc", client, journal) |
| + executionMust(t, err) |
| + transport := &preparationTransport{api: api, crash: crash} |
| + config := runner.SupervisorConfig{Journal: journal, Client: client, Inspector: inspector, API: transport, Workflow: wf, CredentialsPath: filepath.Join(state, "credentials"), InstallCredentials: api.InstallCredentials} |
| + supervisor, err := runner.NewSupervisor(config) |
| + executionMust(t, err) |
| + executionMust(t, supervisor.Recover(ctx)) |
| + err = supervisor.Run(ctx, runner.RunClaim{Assignment: a, ClaimResponse: claim}) |
| + if crash { |
| + if err == nil || !transport.interrupted { |
| + t.Fatal("containment crash not observed", err) |
| } |
| - })) |
| - if code := send(); code < 400 || !injected { |
| - t.Fatal("crash accepted", code) |
| + executionMust(t, x.Sync(ctx)) |
| + if scalar(t, f.d, "SELECT count(*) FROM jobs") != 0 { |
| + t.Fatal("StartBug ran before containment") |
| + } |
| + inspector, err = runner.NewLinuxProcessInspector("/proc", client, journal) |
| + executionMust(t, err) |
| + transport.crash = false |
| + config.Inspector = inspector |
| + supervisor, err = runner.NewSupervisor(config) |
| + executionMust(t, err) |
| + executionMust(t, supervisor.Recover(ctx)) |
| + } else { |
| + executionMust(t, err) |
| } |
| - executionMust(t, f.d.G.Callback().Create().Remove("task15_prepare_crash")) |
| - if code := send(); code != 200 { |
| - t.Fatal("real protocol preparation failed", code) |
| + savedPreparation, err := f.s.Task(ctx, ownerActor, task.ID) |
| + executionMust(t, err) |
| + if savedPreparation.BaseCommit != base { |
| + t.Fatal("preparation did not pin immutable Git base") |
| } |
| - executionMust(t, x.Sync(ctx)) |
| - if scalar(t, f.d, "SELECT count(*) FROM jobs") != 0 { |
| - t.Fatal("StartBug ran before preparation containment") |
| + if scalar(t, f.d, "SELECT count(*) FROM runner_assignments WHERE state='contained'") != 1 { |
| + t.Fatal("supervisor did not prove preparation containment") |
| } |
| - // No process or workspace was created by this metadata-only fixture after baseline capture. |
| - // The separate supervisor tests prove the real containment validator and cleanup ordering. |
| - mustSQL(t, f.d, "UPDATE runner_assignments SET state='contained' WHERE id=?", a.ID) |
| + injected := false |
| executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task15_link_crash", func(tx *gorm.DB) { |
| if event, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && event.Kind == "task.link" { |
| + injected = true |
| tx.AddError(errors.New("crash before link acknowledgement")) |
| } |
| })) |
| - if err = x.Sync(ctx); err == nil { |
| - t.Fatal("link crash not observed") |
| + if err = x.Sync(ctx); err == nil || !injected { |
| + t.Fatal("link crash not observed", err) |
| } |
| executionMust(t, f.d.G.Callback().Create().Remove("task15_link_crash")) |
| executionMust(t, x.Sync(ctx)) |
| @@ -174,4 +200,124 @@ func TestBugPreparationCrashRealProtocolLocalGit(t *testing.T) { |
| if saved.JobID == 0 || scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 { |
| t.Fatal("preparation duplicated job") |
| } |
| + if !crash { |
| + exerciseHTTPExecutor(t, api, journal, sandbox, policy, localRepo, scratch) |
| + } |
| +} |
| + |
| +type preparationTransport struct { |
| + api *runner.HTTPInstance |
| + crash, interrupted bool |
| +} |
| + |
| +func (p *preparationTransport) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| + if op == "contained" && p.crash { |
| + p.interrupted = true |
| + return runner.ErrTransient |
| + } |
| + return p.api.Call(ctx, op, q, out) |
| +} |
| +func (p *preparationTransport) RestoreClaim(c runner.RunClaim) error { return p.api.RestoreClaim(c) } |
| + |
| +// privateProcTest runs the test with a real kernel proc mount and an init |
| +// process distinct from the runner. Every process in this namespace is ours. |
| +func privateProcTest(t *testing.T) bool { |
| + t.Helper() |
| + if os.Getenv("EQUIPO_PRIVATE_PROC_TEST") == "1" { |
| + return false |
| + } |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command("unshare", "--user", "--map-root-user", "--pid", "--mount", "--fork", "--mount-proc", "/bin/sh", "-c", `"$1" -test.run "^$2$" -test.count=1 -test.v; result=$?; exit "$result"`, "sh", exe, t.Name()) |
| + cmd.Env = append(os.Environ(), "EQUIPO_PRIVATE_PROC_TEST=1") |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("private /proc test: %v\n%s", err, out) |
| + } |
| + t.Log(string(out)) |
| + return true |
| +} |
| + |
| +func exerciseHTTPExecutor(t *testing.T, api *runner.HTTPInstance, journal *runner.Journal, sandbox *checks.CodexSandbox, policy paseo.ReadPolicy, repo, scratch string) { |
| + ctx := context.Background() |
| + assignments, err := api.Poll(ctx) |
| + executionMust(t, err) |
| + if len(assignments) != 1 || assignments[0].StepKey != "reproduce" { |
| + t.Fatal("dependent assignment missing", assignments) |
| + } |
| + a := assignments[0] |
| + claim, err := api.Claim(ctx, runnerproto.ClaimRequest{Version: 1, AssignmentID: a.ID, Revision: a.Revision, RequestID: "reproduction-claim"}) |
| + executionMust(t, err) |
| + q := runnerproto.RunnerRequest{Version: 1, AssignmentID: a.ID, Scope: claim.Scope, Handle: claim.Handle, RequestID: "ready"} |
| + event := runnerproto.Event{Version: 1, ID: q.RequestID, TaskID: a.TaskID, AssignmentID: a.ID, Scope: q.Scope, Handle: q.Handle, ServerID: "server", AgentID: "observed-agent", SessionID: "observed-session", Epoch: "epoch", Kind: "timeline_ready", Payload: []byte(`{}`), SourceTime: time.Now().UTC()} |
| + // The instance derives exposure from its assignment even if a runner omits it. |
| + q.Event, err = runnerproto.Marshal(event) |
| + executionMust(t, err) |
| + executionMust(t, api.Call(ctx, "events", q, nil)) |
| + q.Event = nil |
| + reproduction := checks.Reproduction{ExpectedSymptom: "reproduced", Files: []checks.File{{Path: "bug_test.go", Bytes: []byte("package prepfixture\nimport \"testing\"\nfunc TestBug(t *testing.T){t.Fatal(\"reproduced\")}\n")}}, TestNames: []checks.TestIdentity{{Package: "prepfixture", Name: "TestBug"}}} |
| + raw, err := json.Marshal(reproduction) |
| + executionMust(t, err) |
| + q.RequestID = "reproduction" |
| + q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "application/json", Payload: raw} |
| + var art team.Artifact |
| + executionMust(t, api.Call(ctx, "artifacts", q, &art)) |
| + if art.Provenance.Producer != "observed-agent" || !art.Provenance.Isolation.RunnerTainted { |
| + t.Fatal("instance did not derive producer and taint", art.Provenance) |
| + } |
| + q.RequestID = "freeze" |
| + q.Artifact = nil |
| + q.Prepared, _ = json.Marshal(runnerproto.FreezeRequest{ExpectedSymptom: reproduction.ExpectedSymptom, DefinitionHash: checks.Digest(claim.Brief.CheckDefinition), ReproductionHash: art.Hash}) |
| + executionMust(t, api.Call(ctx, "freeze", q, nil)) |
| + q.Prepared = nil |
| + var definition checks.Definition |
| + executionMust(t, json.Unmarshal(claim.Brief.CheckDefinition, &definition)) |
| + executor, err := checks.New(checks.Config{ScratchRoot: scratch, Scope: claim.Scope, Handle: claim.Handle, Deadline: time.Now().Add(2 * time.Minute), Policy: policy, DefinitionHash: checks.Digest(claim.Brief.CheckDefinition), ReproductionHash: art.Hash, Export: func(ctx context.Context, commit, dest string) error { |
| + return checks.ExportBase(ctx, repo, commit, dest) |
| + }, ResolveCandidate: func(context.Context, string) (team.GitCandidate, error) { |
| + return team.GitCandidate{}, paseo.ErrIdentity |
| + }, Reproduction: func(context.Context, string) (checks.Reproduction, error) { return reproduction, nil }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return a.Selection.Isolation, nil }}, sandbox) |
| + executionMust(t, err) |
| + witness, err := runner.NewWitness(journal) |
| + executionMust(t, err) |
| + executor.SetAttestationStore(witness) |
| + result, err := executor.Reproduce(ctx, definition, reproduction, definition.Base, "") |
| + executionMust(t, err) |
| + payload, err := json.Marshal(result) |
| + executionMust(t, err) |
| + spec := team.ArtifactSpec{Role: team.RoleBaseResult, MediaType: "application/json", Payload: payload} |
| + // A new Witness has no executor pointer or in-memory attestation map. |
| + restarted, err := runner.NewWitness(journal) |
| + executionMust(t, err) |
| + _, err = restarted.ExecutorEvidence(ctx, nil, claim.Scope, claim.Handle, spec) |
| + executionMust(t, err) |
| + q.RequestID = "base" |
| + q.Artifact = &spec |
| + for _, change := range []string{"fence", "taint", "definition"} { |
| + bad := q |
| + copySpec := spec |
| + bad.Artifact = ©Spec |
| + bad.RequestID = "bad-" + change |
| + changed := result |
| + switch change { |
| + case "fence": |
| + bad.Handle.Fence++ |
| + case "taint": |
| + changed.Isolation.RunnerTainted = false |
| + case "definition": |
| + changed.CheckDefinitionHash = strings.Repeat("b", 64) |
| + } |
| + if change != "fence" { |
| + copySpec.Payload, _ = json.Marshal(changed) |
| + } |
| + if err = api.Call(ctx, "artifacts", bad, nil); err == nil { |
| + t.Fatal("unbound HTTP evidence accepted", change) |
| + } |
| + } |
| + executionMust(t, api.Call(ctx, "artifacts", q, &art)) |
| + if art.Provenance.Provider != "executor" || !art.Provenance.Isolation.RunnerTainted { |
| + t.Fatal("executor exposure lost", art.Provenance) |
| + } |
| } |
diff --git a/internal/runner/checks/attestation_r1_test.go b/internal/runner/checks/attestation_r1_test.go| new file mode 100644 |
| index 00000000..faaadb3a |
| --- /dev/null |
| +++ b/internal/runner/checks/attestation_r1_test.go |
| @@ -0,0 +1,69 @@ |
| +package checks |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "errors" |
| + "io" |
| + "os/exec" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| +) |
| + |
| +type durableFixture map[string]team.Provenance |
| + |
| +func (d durableFixture) SaveAttestation(_ context.Context, k string, p team.Provenance) error { |
| + d[k] = p |
| + return nil |
| +} |
| +func (d durableFixture) LoadAttestation(_ context.Context, k string) (team.Provenance, error) { |
| + return d[k], nil |
| +} |
| +func TestExecutorAttestationSurvivesReconstruction(t *testing.T) { |
| + f := newFixture(t) |
| + ctx := context.Background() |
| + store := durableFixture{} |
| + f.e.SetAttestationStore(store) |
| + result, err := f.e.Reproduce(ctx, f.d, f.r, baseID, "") |
| + must(t, err) |
| + fresh, err := newExecutor(f.e.cfg, localSandbox{}) |
| + must(t, err) |
| + fresh.SetAttestationStore(store) |
| + spec := team.ArtifactSpec{Role: team.RoleBaseResult, Payload: raw(result)} |
| + if _, err = fresh.ValidateEvidence(ctx, nil, f.e.cfg.Scope, f.e.cfg.Handle, spec); err != nil { |
| + t.Fatal("durable attestation lost", err) |
| + } |
| + spec.Payload = append(spec.Payload, ' ') |
| + if _, err = fresh.ValidateEvidence(ctx, nil, f.e.cfg.Scope, f.e.cfg.Handle, spec); err == nil { |
| + t.Fatal("changed payload accepted") |
| + } |
| +} |
| + |
| +func TestExecutorRequiresAttestationStore(t *testing.T) { |
| + f := newFixture(t) |
| + f.e.SetAttestationStore(nil) |
| + if _, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, ""); err == nil { |
| + t.Fatal("executor returned unattested result without durable store") |
| + } |
| +} |
| + |
| +func TestCheckSandboxSupervisedCleanup(t *testing.T) { |
| + binary, err := exec.LookPath("codex") |
| + must(t, err) |
| + config := testSandboxConfig(t, binary, t.TempDir()) |
| + sandbox, err := NewCodexSandbox(context.Background(), config) |
| + must(t, err) |
| + work := t.TempDir() |
| + policy := paseo.ReadPolicy{ConfigHash: "hash", DeniedPaths: []string{config.Protected.RunnerState}} |
| + for _, script := range []string{"true", "exit 3"} { |
| + ended := 0 |
| + ctx := runnerproto.WithProcessOwnership(context.Background(), "attempt", func(context.Context, int) error { return nil }) |
| + ctx = runnerproto.WithCommandOwnership(ctx, func(context.Context, int, string) error { return nil }, func(context.Context, string) error { ended++; return paseo.ErrUncertain }) |
| + _, err := sandbox.Run(ctx, Command{Argv: []string{"sh", "-c", script}, Dir: ".", TimeoutSeconds: 5}, work, policy, io.Discard, io.Discard) |
| + if !errors.Is(err, paseo.ErrUncertain) || ended != 1 { |
| + t.Fatal("next command could proceed without confirmed cleanup", script, ended, err) |
| + } |
| + } |
| +} |
diff --git a/internal/runner/checks/executor.go b/internal/runner/checks/executor.go| index d0548084..7f8129c2 100644 |
| --- a/internal/runner/checks/executor.go |
| +++ b/internal/runner/checks/executor.go |
| @@ -13,6 +13,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| type CommandSandbox interface { |
| @@ -30,13 +31,27 @@ type Config struct { |
| Export func(context.Context, string, string) error |
| Isolation func(context.Context) (team.IsolationSnapshot, error) |
| } |
| +type AttestationStore interface { |
| + SaveAttestation(context.Context, string, team.Provenance) error |
| + LoadAttestation(context.Context, string) (team.Provenance, error) |
| +} |
| + |
| +func AttestationKey(scope team.Scope, h team.Handle, spec team.ArtifactSpec) string { |
| + return runnerproto.EventHash([]any{scope, h.Attempt, h.Fence, h.Runner, spec.Role, Digest(spec.Payload)}) |
| +} |
| +func (e *Executor) SetAttestationStore(store AttestationStore) { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + e.store = store |
| +} |
| + |
| type Executor struct { |
| + store AttestationStore |
| exposure team.IsolationSnapshot |
| logs map[string][]byte |
| cfg Config |
| sandbox CommandSandbox |
| mu sync.Mutex |
| - attested map[string]team.Provenance |
| binary, version string |
| } |
| @@ -55,7 +70,7 @@ func newExecutor(cfg Config, sandbox CommandSandbox) (*Executor, error) { |
| if sandbox == nil || cfg.Export == nil || cfg.ResolveCandidate == nil || cfg.Reproduction == nil || cfg.Isolation == nil || !filepath.IsAbs(cfg.ScratchRoot) || cfg.Policy.ConfigHash == "" || len(cfg.Policy.DeniedPaths) == 0 || cfg.Deadline.IsZero() { |
| return nil, paseo.ErrContract |
| } |
| - return &Executor{cfg: cfg, sandbox: sandbox, attested: map[string]team.Provenance{}, logs: map[string][]byte{}}, nil |
| + return &Executor{cfg: cfg, sandbox: sandbox, logs: map[string][]byte{}}, nil |
| } |
| func (e *Executor) scratch(ctx context.Context, commit string) (string, func(), error) { |
| root, err := os.MkdirTemp(e.cfg.ScratchRoot, "checks-") |
| @@ -279,10 +294,14 @@ func canonicalIsolation(iso team.IsolationSnapshot) team.IsolationSnapshot { |
| iso.ObservedTuples = slices.Compact(iso.ObservedTuples) |
| return iso |
| } |
| -func (e *Executor) attest(role team.Role, value any, iso team.IsolationSnapshot) { |
| +func (e *Executor) attest(ctx context.Context, role team.Role, value any, iso team.IsolationSnapshot) error { |
| e.mu.Lock() |
| defer e.mu.Unlock() |
| - e.attested[string(role)+Digest(encode(value))] = team.Provenance{Producer: "equipo-checks", Provider: "executor", Context: string(e.cfg.Handle.Runner), Isolation: iso} |
| + p := team.Provenance{Producer: "equipo-checks", Provider: "executor", Context: string(e.cfg.Handle.Runner), Isolation: iso} |
| + if e.store != nil { |
| + return e.store.SaveAttestation(ctx, AttestationKey(e.cfg.Scope, e.cfg.Handle, team.ArtifactSpec{Role: role, Payload: encode(value)}), p) |
| + } |
| + return paseo.ErrContract |
| } |
| func (e *Executor) ValidateEvidence(ctx context.Context, _ *sql.Tx, scope team.Scope, h team.Handle, spec team.ArtifactSpec) (team.Provenance, error) { |
| current, err := e.isolation(ctx) |
| @@ -297,8 +316,11 @@ func (e *Executor) ValidateEvidence(ctx context.Context, _ *sql.Tx, scope team.S |
| if scope.Account == "" || scope.Job <= 0 || h.Attempt <= 0 || h.Fence <= 0 || scope != e.cfg.Scope || h.Attempt != e.cfg.Handle.Attempt || h.Fence != e.cfg.Handle.Fence || h.Runner != e.cfg.Handle.Runner { |
| return team.Provenance{}, paseo.ErrIdentity |
| } |
| - p, ok := e.attested[string(spec.Role)+Digest(spec.Payload)] |
| - if !ok || !bytes.Equal(encode(p.Isolation), encode(current)) { |
| + if e.store == nil { |
| + return team.Provenance{}, paseo.ErrContract |
| + } |
| + p, err := e.store.LoadAttestation(ctx, AttestationKey(scope, h, spec)) |
| + if err != nil || p.Producer != "equipo-checks" || p.Provider != "executor" || p.Context != h.Runner || !bytes.Equal(encode(p.Isolation), encode(current)) { |
| return p, paseo.ErrIdentity |
| } |
| return p, nil |
| @@ -369,8 +391,7 @@ func (e *Executor) Reproduce(ctx context.Context, d Definition, r Reproduction, |
| if outcome == team.CheckFail { |
| result.FailureMessage = r.ExpectedSymptom |
| } |
| - e.attest(role, result, iso) |
| - return result, nil |
| + return result, e.attest(ctx, role, result, iso) |
| } |
| func (e *Executor) RepositoryChecks(ctx context.Context, d Definition, candidate team.GitCandidate, candidateHash string) (team.RepositoryCheckResult, error) { |
| result := team.RepositoryCheckResult{} |
| @@ -417,8 +438,7 @@ func (e *Executor) RepositoryChecks(ctx context.Context, d Definition, candidate |
| return result, err |
| } |
| result = team.RepositoryCheckResult{CandidateHash: candidateHash, Commit: candidate.Commit, CheckDefinitionHash: e.cfg.DefinitionHash, BaselineTestSetHash: d.Baseline.Hash, ObservedTestSetHash: setHash(names), Outcome: team.CheckPass, TestsRun: count, LogHash: e.saveLog(encode(logs)), ObservedNames: namesSorted(names), Isolation: iso, ExecutorBinary: e.binary, ExecutorVersion: e.version} |
| - e.attest(team.RoleRepositoryChecks, result, iso) |
| - return result, nil |
| + return result, e.attest(ctx, team.RoleRepositoryChecks, result, iso) |
| } |
| func (e *Executor) freshRun(ctx context.Context, d Definition, r *Reproduction, commit string, c Command) (*goResults, int, string, error) { |
diff --git a/internal/runner/checks/executor_test.go b/internal/runner/checks/executor_test.go| index 35ee5a7c..f8e8f339 100644 |
| --- a/internal/runner/checks/executor_test.go |
| +++ b/internal/runner/checks/executor_test.go |
| @@ -101,6 +101,7 @@ func newFixture(t *testing.T) fixture { |
| }} |
| e, err := newExecutor(cfg, localSandbox{}) |
| must(t, err) |
| + e.SetAttestationStore(durableFixture{}) |
| baseline, err := e.CaptureBaseline(context.Background(), d) |
| must(t, err) |
| d.Baseline = baseline |
diff --git a/internal/runner/checks/sandbox.go b/internal/runner/checks/sandbox.go| index eab95e00..e1279117 100644 |
| --- a/internal/runner/checks/sandbox.go |
| +++ b/internal/runner/checks/sandbox.go |
| @@ -2,6 +2,7 @@ package checks |
| import ( |
| "context" |
| + "crypto/rand" |
| "encoding/json" |
| "errors" |
| "io" |
| @@ -107,7 +108,7 @@ func canonicalPath(path string) (string, error) { |
| func within(root, path string) bool { |
| return root == path || strings.HasPrefix(path, root+string(filepath.Separator)) |
| } |
| -func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy paseo.ReadPolicy, stdout, stderr io.Writer) (int, error) { |
| +func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy paseo.ReadPolicy, stdout, stderr io.Writer) (code int, resultErr error) { |
| if policy.ConfigHash == "" || len(policy.DeniedPaths) == 0 || len(c.Argv) == 0 || c.TimeoutSeconds < 1 || c.TimeoutSeconds > 1200 { |
| return -1, paseo.ErrPolicy |
| } |
| @@ -193,6 +194,14 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p |
| cmd.Dir = control |
| cmd.Env = []string{"PATH=" + filepath.Join(s.goRoot, "bin") + ":/usr/bin:/bin", "HOME=" + s.home, "CODEX_HOME=" + cfgHome, "TMPDIR=" + temp, "GOCACHE=" + cache, "GOTMPDIR=" + goTemp, "GOROOT=" + s.goRoot, "CGO_ENABLED=0", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=", "GOPROXY=off", "GOSUMDB=off", "LANG=C", "LC_ALL=C"} |
| marker, track := runnerproto.ProcessOwnership(ctx) |
| + begin, end := runnerproto.CommandOwnership(ctx) |
| + command := rand.Text() |
| + if track != nil && (begin == nil || end == nil) { |
| + return -1, paseo.ErrContract |
| + } |
| + if begin != nil { |
| + cmd.Env = append(cmd.Env, "EQUIPO_COMMAND_MARKER="+command) |
| + } |
| if marker != "" { |
| cmd.Env = append(cmd.Env, "EQUIPO_ATTEMPT_MARKER="+marker) |
| } |
| @@ -216,12 +225,19 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p |
| defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) |
| } |
| if track != nil { |
| - if err = track(ctx, cmd.Process.Pid); err != nil { |
| + if err = begin(ctx, cmd.Process.Pid, command); err != nil { |
| _ = cmd.Cancel() |
| _ = cmd.Wait() |
| return -1, err |
| } |
| } |
| + if end != nil { |
| + defer func() { |
| + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) |
| + defer cancel() |
| + resultErr = errors.Join(resultErr, end(cleanup, command)) |
| + }() |
| + } |
| err = cmd.Wait() |
| if ctx.Err() != nil { |
| return -1, ctx.Err() |
diff --git a/internal/runner/containment_r1_test.go b/internal/runner/containment_r1_test.go| new file mode 100644 |
| index 00000000..e7d56c94 |
| --- /dev/null |
| +++ b/internal/runner/containment_r1_test.go |
| @@ -0,0 +1,575 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "runtime" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +func realInspector(t *testing.T) (*LinuxProcessInspector, ProcessOwner) { |
| + t.Helper() |
| + p, o := processFixture(t) |
| + p.root = "/proc" |
| + return p, o |
| +} |
| + |
| +func escapedChild(t *testing.T, o ProcessOwner) int { |
| + t.Helper() |
| + c := exec.Command("/bin/sh", "-c", "cd /; env -i /usr/bin/setsid /bin/sleep 60 >/dev/null 2>&1 & echo $!") |
| + c.Dir = o.Workspace.Path |
| + c.Env = []string{"PATH=/usr/bin:/bin", "EQUIPO_ATTEMPT_MARKER=" + o.Marker} |
| + raw, err := c.Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pid, err := strconv.Atoi(strings.TrimSpace(string(raw))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fd, err := unix.PidfdOpen(pid, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); unix.Close(fd) }) |
| + for i := 0; i < 100; i++ { |
| + env, e := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/environ") |
| + cwd, c := os.Readlink("/proc/" + strconv.Itoa(pid) + "/cwd") |
| + if e == nil && c == nil && len(env) == 0 && cwd == "/" { |
| + return pid |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + t.Fatal("owned fixture did not finish stripping its environment") |
| + return pid |
| +} |
| + |
| +func TestLinuxInspectorRealEscapedOrphan(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + pid := escapedChild(t, o) |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if inv.CoverageKnown { |
| + e, _ := p.entry(pid) |
| + t.Fatalf("escaped orphan produced known coverage: %+v entry=%+v runner=%d track=%d", inv, e, os.Getpid(), p.records[ownerKey(o)].TrackTicks) |
| + } |
| + id, err := p.identity(pid) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if p.Stop(ctx, id) == nil { |
| + t.Fatal("unattributed orphan was signalled") |
| + } |
| + s, r, _, _ := cleanupFixture(t) |
| + s.inspector = p |
| + r.Owner = o |
| + if proof, err := s.cleanup(ctx, r); err == nil || proof.Empty { |
| + t.Fatal("escaped orphan allowed containment") |
| + } |
| +} |
| + |
| +func TestLinuxInspectorRealRestart(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + for _, survivor := range []string{"none", "owned", "unknown"} { |
| + t.Run(survivor, func(t *testing.T) { |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + if survivor == "owned" { |
| + childProcess(t, o.Workspace.Path, o.Marker) |
| + } |
| + if survivor == "unknown" { |
| + escapedChild(t, o) |
| + } |
| + restarted, err := NewLinuxProcessInspector("/proc", p.client, p.journal) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + inv, err := restarted.Remaining(ctx, o) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + switch survivor { |
| + case "none": |
| + if !inv.CoverageKnown || len(inv.Processes) != 0 { |
| + t.Fatalf("restart could not prove empty: %+v", inv) |
| + } |
| + case "owned": |
| + if len(inv.Processes) == 0 { |
| + t.Fatal("restart lost owned survivor") |
| + } |
| + case "unknown": |
| + if inv.CoverageKnown { |
| + t.Fatal("restart forgot unknown survivor") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestLinuxInspectorRealRunnerControlAndOtherAttempt(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + control := exec.Command("/usr/bin/git", "hash-object", "--stdin") |
| + control.Dir = "/" |
| + control.Env = []string{"PATH=/usr/bin:/bin", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"} |
| + input, err := control.StdinPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = control.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { input.Close(); control.Process.Kill(); control.Wait() }) |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 { |
| + t.Fatalf("runner child not excluded: %+v %v", inv, err) |
| + } |
| + other := o |
| + other.Attempt++ |
| + other.Marker += "-other" |
| + other.Workspace.Path = t.TempDir() |
| + if err = p.Track(ctx, other); err != nil { |
| + t.Fatal(err) |
| + } |
| + child := childProcess(t, other.Workspace.Path, other.Marker) |
| + // Attribution must work even if this attempt is scanned first. |
| + inv, err = p.Remaining(ctx, o) |
| + if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 { |
| + t.Fatalf("other attempt contaminated inventory: %+v %v", inv, err) |
| + } |
| + if len(p.records[ownerKey(other)].Known) != 1 { |
| + t.Fatal("other attempt attribution was not retained") |
| + } |
| + inv, err = p.Remaining(ctx, other) |
| + if err != nil || len(inv.Processes) != 1 || inv.Processes[0].PID != child.Process.Pid { |
| + t.Fatalf("other attempt lost child: %+v %v", inv, err) |
| + } |
| + if err = control.Process.Signal(unix.Signal(0)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestProcessIdentityOwnedPIDReuse(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := childProcess(t, o.Workspace.Path, o.Marker) |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil || len(inv.Processes) == 0 { |
| + t.Fatal(inv, err) |
| + } |
| + stale := inv.Processes[0] |
| + stale.StartTicks-- |
| + // The journal remembers an owned identity, but its PID is now a different lifetime. |
| + p.records[ownerKey(o)].Known = []ProcessIdentity{stale} |
| + if p.Stop(ctx, stale) == nil { |
| + t.Fatal("owned reused PID was signalled") |
| + } |
| + if c.Process.Signal(unix.Signal(0)) != nil { |
| + t.Fatal("replacement process killed") |
| + } |
| +} |
| + |
| +func TestLinuxInspectorPreexistingUnreadable(t *testing.T) { |
| + p, o := processFixture(t) |
| + pid := os.Getpid() |
| + dir := p.root + "/" + strconv.Itoa(pid) |
| + if err := os.Mkdir(dir, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink("/proc/self/stat", dir+"/stat"); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + if err := p.Track(context.Background(), o); err != nil { |
| + t.Fatalf("preexisting unreadable process blocks Track: %v", err) |
| + } |
| +} |
| + |
| +func TestRunnerRestartRealInspectorRecovery(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, r, _, _ := cleanupFixture(t) |
| + s.journal = p.journal |
| + r.Owner = o |
| + r.Phase = "completed" |
| + if err := s.save(ctx, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + restarted, err := NewLinuxProcessInspector("/proc", p.client, p.journal) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.inspector = restarted |
| + if err = s.Recover(ctx); err != nil { |
| + t.Fatal("restart cleanup failed", err) |
| + } |
| + if !s.ready || s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)].Phase != "contained" { |
| + t.Fatal("restart did not contain") |
| + } |
| +} |
| + |
| +func TestLinuxInspectorReboot(t *testing.T) { |
| + p, o := processFixture(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.records[ownerKey(o)].TrackBoot = "previous-boot" |
| + c := childProcess(t, o.Workspace.Path, o.Marker) |
| + linkProcess(t, p.root, c.Process.Pid) |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 { |
| + t.Fatalf("reboot retained old process authority: %+v %v", inv, err) |
| + } |
| + if p.Stop(ctx, ProcessIdentity{PID: c.Process.Pid, StartTicks: 1, BootID: "previous-boot"}) == nil { |
| + t.Fatal("previous boot identity signalled") |
| + } |
| +} |
| + |
| +// privateProcTest runs the test with a real kernel proc mount and an init |
| +// process distinct from the runner. Every process in this namespace is ours. |
| +func privateProcTest(t *testing.T) bool { |
| + t.Helper() |
| + if os.Getenv("EQUIPO_PRIVATE_PROC_TEST") == "1" { |
| + return false |
| + } |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command("unshare", "--user", "--map-root-user", "--pid", "--mount", "--fork", "--mount-proc", "/bin/sh", "-c", `"$1" -test.run "^$2$" -test.count=1 -test.v; result=$?; exit "$result"`, "sh", exe, t.Name()) |
| + cmd.Env = append(os.Environ(), "EQUIPO_PRIVATE_PROC_TEST=1") |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("private /proc test: %v\n%s", err, out) |
| + } |
| + t.Log(string(out)) |
| + return true |
| +} |
| + |
| +func TestLinuxInspectorCommandLeftovers(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + control := childProcess(t, o.Workspace.Path, o.Marker) |
| + cmd := exec.Command("/bin/sh", "-c", "/bin/sleep 60 & echo $!; wait") |
| + cmd.Dir = o.Workspace.Path |
| + cmd.Env = []string{"EQUIPO_ATTEMPT_MARKER=" + o.Marker, "EQUIPO_COMMAND_MARKER=command"} |
| + pipe, err := cmd.StdoutPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) |
| + var pid int |
| + if _, err = fmt.Fscanln(pipe, &pid); err != nil { |
| + t.Fatal(err) |
| + } |
| + fd, err := unix.PidfdOpen(pid, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); unix.Close(fd) }) |
| + if err = p.BeginCommand(ctx, o, cmd.Process.Pid, "command"); err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd.Process.Kill() |
| + cmd.Wait() |
| + if err = p.EndCommand(ctx, o, "command"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n, _ := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, 0); n != 1 { |
| + t.Fatal("next command could start with a surviving predecessor child") |
| + } |
| + if err = control.Process.Signal(unix.Signal(0)); err != nil { |
| + t.Fatal("unrelated attempt process stopped", err) |
| + } |
| +} |
| + |
| +type slowArchiveClient struct { |
| + *cleanupClient |
| + during func() |
| +} |
| + |
| +func (c *slowArchiveClient) Archive(context.Context, paseo.Agent) error { c.during(); return nil } |
| +func TestLinuxInspectorMonitorsThroughCleanup(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, r, _, _ := cleanupFixture(t) |
| + s.inspector = p |
| + r.Owner = o |
| + var childFD int = -1 |
| + s.client = &slowArchiveClient{cleanupClient: s.client.(*cleanupClient), during: func() { |
| + cmd := exec.Command("/bin/sh", "-c", `/usr/bin/setsid /bin/sh -c 'sleep 0.5; cd /; exec env -i /bin/sleep 60' >/dev/null 2>&1 & echo $!`) |
| + cmd.Dir = o.Workspace.Path |
| + cmd.Env = []string{"PATH=/usr/bin:/bin", "EQUIPO_ATTEMPT_MARKER=" + o.Marker} |
| + raw, err := cmd.Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pid, err := strconv.Atoi(strings.TrimSpace(string(raw))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + childFD, err = unix.PidfdOpen(pid, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { unix.PidfdSendSignal(childFD, unix.SIGKILL, nil, 0); unix.Close(childFD) }) |
| + time.Sleep(2500 * time.Millisecond) |
| + }} |
| + proof, err := s.cleanup(ctx, r) |
| + if err != nil || !proof.Empty { |
| + t.Fatal("cleanup lost monitoring attribution", proof, err) |
| + } |
| + if n, _ := unix.Poll([]unix.PollFd{{Fd: int32(childFD), Events: unix.POLLIN}}, 0); n != 1 { |
| + t.Fatal("cleanup acknowledged a live child") |
| + } |
| +} |
| + |
| +type duringTerminalList struct { |
| + terminalFixture |
| + after func() |
| +} |
| + |
| +func (c *duringTerminalList) ListTerminals(context.Context, paseo.Workspace) ([]string, error) { |
| + if c.after != nil { |
| + fn := c.after |
| + c.after = nil |
| + fn() |
| + } |
| + return nil, nil |
| +} |
| +func TestLinuxInspectorProcessBornDuringTerminalRPC(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + client := &duringTerminalList{} |
| + p.client = client |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + client.after = func() { escapedChild(t, o) } |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if inv.CoverageKnown && len(inv.Processes) == 0 { |
| + t.Fatal("process born during terminal RPC yielded empty proof") |
| + } |
| +} |
| + |
| +func TestLinuxInspectorOtherAttemptMarkerWinsSharedPreparationPath(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + o.LocalOnly = true |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + other := o |
| + other.Attempt++ |
| + other.Marker += "-other" |
| + if err := p.Track(ctx, other); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := childProcess(t, o.Workspace.Path, other.Marker) |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 { |
| + t.Fatal("other marker attributed to shared path", inv, err) |
| + } |
| + inv, err = p.Remaining(ctx, other) |
| + if err != nil || !inv.CoverageKnown || len(inv.Processes) != 1 || inv.Processes[0].PID != c.Process.Pid { |
| + t.Fatal("other attempt lost shared-path child", inv, err) |
| + } |
| +} |
| + |
| +func TestRunnerRestartUnknownProcessBlocksUntilExit(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + pid := escapedChild(t, o) |
| + s, r, _, order := cleanupFixture(t) |
| + s.journal = p.journal |
| + r.Owner = o |
| + r.Phase = "completed" |
| + if err := s.save(ctx, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + restarted, err := NewLinuxProcessInspector("/proc", p.client, p.journal) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.inspector = restarted |
| + if err = s.Recover(ctx); err == nil || s.ready { |
| + t.Fatal("restart contained unknown live process") |
| + } |
| + for _, op := range *order { |
| + if op == "contained" { |
| + t.Fatal("unknown process was acknowledged") |
| + } |
| + } |
| + // Only the fixture creator can stop this unattributed process. |
| + fd, err := unix.PidfdOpen(pid, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer unix.Close(fd) |
| + if err = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, 1000); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.Recover(ctx); err != nil || !s.ready { |
| + t.Fatal("exited unknown process permanently blocked recovery", err) |
| + } |
| +} |
| + |
| +func TestLinuxInspectorUndumpableHelper(t *testing.T) { |
| + if os.Getenv("EQUIPO_UNDUMPABLE_HELPER") != "1" { |
| + return |
| + } |
| + if err := unix.Prctl(unix.PR_SET_DUMPABLE, 0, 0, 0, 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(os.Getenv("EQUIPO_UNDUMPABLE_READY"), []byte("ready"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(time.Minute) |
| +} |
| +func TestLinuxInspectorRealUnreadableStartBoundary(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + runtime.LockOSThread() |
| + defer runtime.UnlockOSThread() |
| + for _, before := range []bool{true, false} { |
| + t.Run(strconv.FormatBool(before), func(t *testing.T) { |
| + p, o := realInspector(t) |
| + ctx := context.Background() |
| + if !before { |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + ready := filepath.Join(t.TempDir(), "ready") |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command("/bin/sh", "-c", `"$1" -test.run '^TestLinuxInspectorUndumpableHelper$' >/dev/null 2>&1 & echo $!`, "sh", exe) |
| + cmd.Env = append(os.Environ(), "EQUIPO_UNDUMPABLE_HELPER=1", "EQUIPO_UNDUMPABLE_READY="+ready) |
| + raw, err := cmd.Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pid, err := strconv.Atoi(strings.TrimSpace(string(raw))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fd, err := unix.PidfdOpen(pid, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer unix.Close(fd) |
| + defer unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) |
| + for i := 0; i < 100; i++ { |
| + if _, err = os.Stat(ready); err == nil { |
| + break |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + if err != nil { |
| + t.Fatal("undumpable helper did not start", err) |
| + } |
| + // Remove namespace capabilities so root cannot override the proc access check. |
| + runtime.LockOSThread() |
| + defer runtime.UnlockOSThread() |
| + header := unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3} |
| + data := [2]unix.CapUserData{} |
| + if err = unix.Capset(&header, &data[0]); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = os.ReadFile("/proc/" + strconv.Itoa(pid) + "/environ"); !os.IsPermission(err) { |
| + t.Fatal("fixture environ is not inaccessible", err) |
| + } |
| + if before { |
| + time.Sleep(20 * time.Millisecond) |
| + if err = p.Track(ctx, o); err != nil { |
| + t.Fatal("preexisting unreadable process blocked Track", err) |
| + } |
| + } |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if inv.CoverageKnown != before || len(inv.Processes) != 0 { |
| + t.Fatal("unreadable process classified without start boundary", before, inv) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/creation_recovery.go b/internal/runner/creation_recovery.go| new file mode 100644 |
| index 00000000..eaf4a4d7 |
| --- /dev/null |
| +++ b/internal/runner/creation_recovery.go |
| @@ -0,0 +1,86 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func (j *Journal) creationIntent(ctx context.Context, kind, key string, out any) (bool, error) { |
| + var raw []byte |
| + err := j.db.QueryRowContext(ctx, "SELECT body FROM journal_intents WHERE intent_key=?", runnerproto.EventHash([]string{kind, key})).Scan(&raw) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + var intent paseo.Intent |
| + if json.Unmarshal(raw, &intent) != nil || intent.Kind != kind || intent.Key != key { |
| + return false, paseo.ErrIdentity |
| + } |
| + return true, json.Unmarshal(intent.Request, out) |
| +} |
| +func (s *Supervisor) recoverCreation(ctx context.Context, r *attemptState) error { |
| + if r.Claim.Assignment.Kind == "prepare" { |
| + return nil |
| + } |
| + changed := false |
| + if r.Owner.Workspace.WorkspaceID == "" { |
| + var request paseo.WorkspaceRequest |
| + found, err := s.journal.creationIntent(ctx, "workspace", r.Claim.Assignment.WorkspaceKey, &request) |
| + if err != nil { |
| + return err |
| + } |
| + if found { |
| + client, ok := s.client.(interface { |
| + RecoverWorkspace(context.Context, paseo.WorkspaceRequest) (paseo.Workspace, error) |
| + }) |
| + if !ok { |
| + return paseo.ErrUncertain |
| + } |
| + ws, err := client.RecoverWorkspace(ctx, request) |
| + if err != nil { |
| + return err |
| + } |
| + r.Owner.Workspace = ws |
| + r.Owner.LocalOnly = false |
| + changed = true |
| + if err = s.save(ctx, r); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + if r.Agent.AgentID == "" { |
| + var request paseo.AgentRequest |
| + found, err := s.journal.creationIntent(ctx, "agent", r.request("agent").RequestID, &request) |
| + if err != nil { |
| + return err |
| + } |
| + if found { |
| + client, ok := s.client.(interface { |
| + RecoverAgent(context.Context, paseo.AgentRequest) (paseo.Agent, error) |
| + }) |
| + if !ok { |
| + return paseo.ErrUncertain |
| + } |
| + r.Agent, err = client.RecoverAgent(ctx, request) |
| + if err != nil { |
| + return err |
| + } |
| + r.Owner.AgentID = r.Agent.AgentID |
| + changed = true |
| + if err = s.save(ctx, r); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + if changed { |
| + return s.inspector.Track(ctx, r.Owner) |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/http.go b/internal/runner/http.go| index 5fbec762..7156be75 100644 |
| --- a/internal/runner/http.go |
| +++ b/internal/runner/http.go |
| @@ -44,11 +44,20 @@ func (c *HTTPInstance) post(ctx context.Context, op string, body any, token stri |
| req.Header.Set("Content-Type", "application/json") |
| response, err := c.client.Do(req) |
| if err != nil { |
| - return paseo.ErrUncertain |
| + return ErrTransient |
| } |
| defer response.Body.Close() |
| if response.StatusCode != http.StatusOK { |
| - return paseo.ErrUncertain |
| + if op == "claim" && (response.StatusCode == http.StatusConflict || response.StatusCode == http.StatusServiceUnavailable) { |
| + return ErrClaimRefused |
| + } |
| + if response.StatusCode == http.StatusForbidden || response.StatusCode == http.StatusUnauthorized { |
| + return paseo.ErrIdentity |
| + } |
| + if response.StatusCode >= 500 || response.StatusCode == http.StatusTooManyRequests { |
| + return ErrTransient |
| + } |
| + return paseo.ErrContract |
| } |
| var envelope struct { |
| Version int `json:"version"` |
| @@ -108,6 +117,9 @@ func (c *HTTPInstance) claim(ctx context.Context, op string, q runnerproto.Claim |
| if err = c.post(ctx, op, q, token, &claim); err != nil { |
| return claim, err |
| } |
| + if claim.NotClaimed { |
| + return claim, ErrNotClaimed |
| + } |
| if claim.CleanupToken == "" || claim.Handle.Runner == "" { |
| return runnerproto.ClaimResponse{}, paseo.ErrIdentity |
| } |
diff --git a/internal/runner/lease_check_r1_test.go b/internal/runner/lease_check_r1_test.go| new file mode 100644 |
| index 00000000..df6a2c0a |
| --- /dev/null |
| +++ b/internal/runner/lease_check_r1_test.go |
| @@ -0,0 +1,105 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type renewingCheckAPI struct{ renewals atomic.Int32 } |
| + |
| +func (a *renewingCheckAPI) Call(_ context.Context, op string, _ runnerproto.RunnerRequest, out any) error { |
| + if op != "renew" { |
| + return paseo.ErrContract |
| + } |
| + a.renewals.Add(1) |
| + *(out.(*time.Time)) = time.Now().Add(time.Minute) |
| + return nil |
| +} |
| +func TestRunnerLeaseLongCheck(t *testing.T) { |
| + if privateProcTest(t) { |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 110*time.Second) |
| + defer cancel() |
| + root := t.TempDir() |
| + state := filepath.Join(root, "state") |
| + wfMust(t, os.Mkdir(state, 0700)) |
| + protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: state + "/config", Journal: state + "/journal", Bearer: state + "/bearer", Cleanup: state + "/cleanup", ForgeCredential: state + "/forge", PaseoHome: state + "/paseo", ProviderHomes: []string{state + "/provider"}, SSH: state + "/ssh"} |
| + binary, err := exec.LookPath("codex") |
| + wfMust(t, err) |
| + goBinary, err := exec.LookPath("go") |
| + wfMust(t, err) |
| + goBinary, err = filepath.EvalSymlinks(goBinary) |
| + wfMust(t, err) |
| + sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: binary, ScratchRoot: root, GoRoot: filepath.Dir(filepath.Dir(goBinary)), GoBinary: goBinary, Protected: protected}) |
| + wfMust(t, err) |
| + policy := paseo.ReadPolicy{ConfigHash: strings.Repeat("a", 64), DeniedPaths: []string{state}} |
| + source := filepath.Join(root, "source") |
| + wfMust(t, os.Mkdir(source, 0700)) |
| + files := map[string]string{"go.mod": "module longcheck\n\ngo 1.26.0\n", "long_test.go": "package longcheck\nimport(\"testing\";\"time\")\nfunc TestLong(t *testing.T){time.Sleep(61*time.Second)}\n"} |
| + for name, value := range files { |
| + wfMust(t, os.WriteFile(filepath.Join(source, name), []byte(value), 0600)) |
| + } |
| + command := checks.Command{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 100} |
| + d, err := checks.ParseDefinition(ctx, marshal(checks.Definition{Version: 1, Repository: "amadan.net/test/long", Base: strings.Repeat("a", 40), Commands: []checks.Command{command}, Reproduction: command}), "amadan.net/test/long", strings.Repeat("a", 40)) |
| + wfMust(t, err) |
| + d, err = checks.FreezeMaterial(ctx, d, source) |
| + wfMust(t, err) |
| + s, r, _, _ := cleanupFixture(t) |
| + api := &renewingCheckAPI{} |
| + s.api = api |
| + now, err := s.clock.Read() |
| + wfMust(t, err) |
| + r.Claim.LeaseDeadline = now.Wall.Add(time.Minute) |
| + r.Claim.AttemptDeadline = now.Wall.Add(105 * time.Second) |
| + l, err := newLease(now, r.Claim.LeaseDeadline, r.Claim.AttemptDeadline) |
| + wfMust(t, err) |
| + done := make(chan struct{}) |
| + go s.watchLease(ctx, cancel, r, l, done) |
| + defer func() { cancel(); <-done }() |
| + var validations atomic.Int32 |
| + s.mu.Lock() |
| + s.activeCurrent = func(context.Context) error { validations.Add(1); return nil } |
| + s.mu.Unlock() |
| + e, err := checks.New(checks.Config{ScratchRoot: root, Scope: r.Claim.Scope, Handle: r.Claim.Handle, Deadline: r.Claim.AttemptDeadline, Policy: policy, Export: func(_ context.Context, _ string, dest string) error { |
| + if err := os.Mkdir(dest, 0700); err != nil { |
| + return err |
| + } |
| + for name, value := range files { |
| + if err := os.WriteFile(filepath.Join(dest, name), []byte(value), 0600); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { |
| + return team.IsolationSnapshot{Status: "confined"}, nil |
| + }, ResolveCandidate: func(context.Context, string) (team.GitCandidate, error) { |
| + return team.GitCandidate{}, paseo.ErrIdentity |
| + }, Reproduction: func(context.Context, string) (checks.Reproduction, error) { |
| + return checks.Reproduction{}, paseo.ErrIdentity |
| + }}, sandbox) |
| + wfMust(t, err) |
| + p, o := realInspector(t) |
| + o.LocalOnly = true |
| + wfMust(t, p.Track(ctx, o)) |
| + ctx = checks.WithProcessOwnership(ctx, o.Marker, func(ctx context.Context, pid int) error { return p.TrackPID(ctx, o, pid) }) |
| + ctx = runnerproto.WithCommandOwnership(ctx, func(ctx context.Context, pid int, key string) error { return p.BeginCommand(ctx, o, pid, key) }, func(ctx context.Context, key string) error { return p.EndCommand(ctx, o, key) }) |
| + started := time.Now() |
| + baseline, err := e.CaptureBaseline(ctx, d) |
| + wfMust(t, err) |
| + if time.Since(started) < time.Minute || len(baseline.Names) == 0 || api.renewals.Load() < 4 || validations.Load() < 4 { |
| + t.Fatal("check did not outlive renewed lease", api.renewals.Load(), validations.Load()) |
| + } |
| +} |
diff --git a/internal/runner/lease_linux.go b/internal/runner/lease_linux.go| index a829d92d..08970466 100644 |
| --- a/internal/runner/lease_linux.go |
| +++ b/internal/runner/lease_linux.go |
| @@ -83,3 +83,30 @@ func (l *leaseGuard) renew(now ClockReading, deadline time.Time) error { |
| return nil |
| } |
| func (l *leaseGuard) bound() time.Time { l.mu.Lock(); defer l.mu.Unlock(); return l.deadline } |
| + |
| +func (l *leaseGuard) renewReply(sent, received ClockReading, deadline time.Time) error { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + if err := l.checkLocked(received); err != nil { |
| + return err |
| + } |
| + if sent.BootID != received.BootID || sent.Elapsed > received.Elapsed || received.Wall.Before(sent.Wall) { |
| + l.expired = true |
| + return paseo.ErrUncertain |
| + } |
| + remaining := deadline.Sub(sent.Wall) |
| + if remaining > 60*time.Second { |
| + remaining = 60 * time.Second |
| + } |
| + end := sent.Elapsed + remaining - 10*time.Second |
| + if end > l.attemptEnd { |
| + end = l.attemptEnd |
| + } |
| + if received.Elapsed >= end { |
| + l.expired = true |
| + return paseo.ErrUncertain |
| + } |
| + l.end = end |
| + l.deadline = received.Wall.Add(end - received.Elapsed) |
| + return nil |
| +} |
diff --git a/internal/runner/paseo/client.go b/internal/runner/paseo/client.go| index 620129d8..de8bce9c 100644 |
| --- a/internal/runner/paseo/client.go |
| +++ b/internal/runner/paseo/client.go |
| @@ -7,6 +7,7 @@ import ( |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| + "fmt" |
| "io" |
| "net" |
| "os" |
| @@ -414,7 +415,7 @@ func (c *Client) CreateWorkspace(ctx context.Context, r WorkspaceRequest) (Works |
| if err := c.call(ctx, "create_workspace", r, &w); err != nil { |
| return w, err |
| } |
| - if w.ServerID != c.cfg.ServerID || w.ProjectID != r.ProjectID || w.WorkspaceID == "" || !pathAllowed(w.Path, r.ReadPolicy) { |
| + if (r.ResourceID != "" && w.WorkspaceID != r.ResourceID) || w.ServerID != c.cfg.ServerID || w.ProjectID != r.ProjectID || w.WorkspaceID == "" || !pathAllowed(w.Path, r.ReadPolicy) { |
| return w, ErrUncertain |
| } |
| return w, nil |
| @@ -439,7 +440,7 @@ func (c *Client) CreateAgent(ctx context.Context, r AgentRequest) (Agent, error) |
| if err := c.call(ctx, "create_agent", r, &a); err != nil { |
| return a, err |
| } |
| - if a.ServerID != c.cfg.ServerID || a.WorkspaceID != r.Workspace.WorkspaceID || a.AgentID == "" || a.ProviderSessionID == "" || a.AccountID != caps.ObservedAccount || a.Provider != r.Selection.Provider || a.Model != r.Selection.Model || a.Family != r.Selection.Family { |
| + if (r.ResourceID != "" && a.AgentID != r.ResourceID) || a.ServerID != c.cfg.ServerID || a.WorkspaceID != r.Workspace.WorkspaceID || a.AgentID == "" || a.ProviderSessionID == "" || a.AccountID != caps.ObservedAccount || a.Provider != r.Selection.Provider || a.Model != r.Selection.Model || a.Family != r.Selection.Family { |
| return a, ErrUncertain |
| } |
| // Retain our own copy so caller mutations cannot change the policy of a turn. |
| @@ -679,3 +680,36 @@ func (c *Client) ProviderPolicy(ctx context.Context, s Selection, p ReadPolicy) |
| } |
| return result, nil |
| } |
| + |
| +func CreationID(kind, key string) string { |
| + sum := sha256.Sum256([]byte(kind + "\x00" + key)) |
| + sum[6] = (sum[6] & 15) | 80 |
| + sum[8] = (sum[8] & 63) | 128 |
| + return fmt.Sprintf("%x-%x-%x-%x-%x", sum[:4], sum[4:6], sum[6:8], sum[8:10], sum[10:16]) |
| +} |
| +func (c *Client) RecoverWorkspace(ctx context.Context, r WorkspaceRequest) (Workspace, error) { |
| + var w Workspace |
| + if r.ResourceID == "" { |
| + return w, ErrUncertain |
| + } |
| + if err := c.call(ctx, "recover_workspace", r, &w); err != nil { |
| + return w, err |
| + } |
| + if w.ServerID != c.cfg.ServerID || w.WorkspaceID != r.ResourceID || w.ProjectID != r.ProjectID || !pathAllowed(w.Path, r.ReadPolicy) { |
| + return Workspace{}, ErrIdentity |
| + } |
| + return w, nil |
| +} |
| +func (c *Client) RecoverAgent(ctx context.Context, r AgentRequest) (Agent, error) { |
| + var a Agent |
| + if r.ResourceID == "" { |
| + return a, ErrUncertain |
| + } |
| + if err := c.call(ctx, "recover_agent", r, &a); err != nil { |
| + return a, err |
| + } |
| + if a.ServerID != c.cfg.ServerID || a.AgentID != r.ResourceID || a.WorkspaceID != r.Workspace.WorkspaceID || a.Provider != r.Selection.Provider || a.Model != r.Selection.Model { |
| + return Agent{}, ErrIdentity |
| + } |
| + return a, nil |
| +} |
diff --git a/internal/runner/paseo/types.go b/internal/runner/paseo/types.go| index b5177643..19c4a753 100644 |
| --- a/internal/runner/paseo/types.go |
| +++ b/internal/runner/paseo/types.go |
| @@ -77,6 +77,7 @@ type Agent struct { |
| Family string `json:"family"` |
| } |
| type WorkspaceRequest struct { |
| + ResourceID string `json:"resource_id,omitempty"` |
| Isolation string `json:"isolation"` |
| ProjectID string `json:"project_id"` |
| Path string `json:"path"` |
| @@ -93,6 +94,7 @@ type MCPServer struct { |
| Env map[string]string `json:"env"` |
| } |
| type AgentRequest struct { |
| + ResourceID string `json:"resource_id,omitempty"` |
| Workspace Workspace `json:"workspace"` |
| Selection Selection `json:"selection"` |
| IdempotencyKey string `json:"idempotency_key"` |
diff --git a/internal/runner/process_linux.go b/internal/runner/process_linux.go| index 9bb88c20..fc28178d 100644 |
| --- a/internal/runner/process_linux.go |
| +++ b/internal/runner/process_linux.go |
| @@ -3,6 +3,7 @@ package runner |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| "os" |
| "path/filepath" |
| @@ -31,14 +32,11 @@ type TerminalClient interface { |
| KillTerminal(context.Context, paseo.Workspace, string) error |
| } |
| type processRecord struct { |
| - LastScanElapsed time.Duration |
| - Owner ProcessOwner |
| - Known []ProcessIdentity |
| - Baseline []ProcessIdentity |
| - Started bool |
| - Unknown bool |
| - UnknownStage int |
| - UnknownPID int |
| + Owner ProcessOwner |
| + Known []ProcessIdentity |
| + Commands map[string][]ProcessIdentity |
| + TrackTicks uint64 |
| + TrackBoot string |
| } |
| type LinuxProcessInspector struct { |
| root, boot string |
| @@ -46,7 +44,6 @@ type LinuxProcessInspector struct { |
| journal *Journal |
| mu sync.Mutex |
| records map[string]*processRecord |
| - stopped map[int]ProcessIdentity |
| beforeTrackPID func(int) |
| } |
| @@ -58,21 +55,20 @@ func NewLinuxProcessInspector(procRoot string, client TerminalClient, journal *J |
| if err != nil || strings.TrimSpace(string(b)) == "" { |
| return nil, paseo.ErrUncertain |
| } |
| - p := &LinuxProcessInspector{root: procRoot, boot: strings.TrimSpace(string(b)), client: client, journal: journal, records: map[string]*processRecord{}, stopped: map[int]ProcessIdentity{}} |
| - // A restarted monitor cannot assert uninterrupted ownership coverage. |
| + p := &LinuxProcessInspector{root: procRoot, boot: strings.TrimSpace(string(b)), client: client, journal: journal, records: map[string]*processRecord{}} |
| + // The durable Track boundary remains valid across sampling gaps and restarts. |
| var records []processRecord |
| if err := journal.readStates(context.Background(), "process", &records); err != nil { |
| return nil, err |
| } |
| for i := range records { |
| r := records[i] |
| - r.Unknown = true |
| p.records[ownerKey(r.Owner)] = &r |
| } |
| return p, nil |
| } |
| func ownerKey(o ProcessOwner) string { |
| - return runnerproto.EventHash([]any{o.Attempt, o.Fence, o.Marker, o.Workspace}) |
| + return runnerproto.EventHash([]any{o.Attempt, o.Fence, o.Marker}) |
| } |
| func validOwner(o ProcessOwner) bool { |
| return (o.Attempt > 0 || o.LocalOnly && o.Attempt == 0) && o.Fence > 0 && o.Marker != "" && (o.LocalOnly || o.Workspace.ServerID != "" && o.Workspace.WorkspaceID != "") && filepath.IsAbs(o.Workspace.Path) && filepath.Clean(o.Workspace.Path) == o.Workspace.Path && o.Workspace.Path != "/" |
| @@ -89,14 +85,19 @@ func (p *LinuxProcessInspector) Track(ctx context.Context, o ProcessOwner) error |
| } |
| key := ownerKey(o) |
| if p.records[key] == nil { |
| - p.records[key] = &processRecord{Owner: o} |
| + reading, err := (linuxClock{}).Read() |
| + if err != nil || reading.BootID != p.boot { |
| + return paseo.ErrUncertain |
| + } |
| + // Linux exposes stat starttime in USER_HZ (100 ticks per second). |
| + p.records[key] = &processRecord{Owner: o, TrackTicks: uint64(reading.Elapsed / (10 * time.Millisecond)), TrackBoot: p.boot} |
| } else { |
| p.records[key].Owner = o |
| } |
| if err = p.save(ctx, p.records[key]); err != nil { |
| return err |
| } |
| - inv, err := p.scan(ctx, p.records[key]) |
| + inv, err := p.scan(ctx, p.records[key], true) |
| if err != nil { |
| return err |
| } |
| @@ -115,7 +116,7 @@ func (p *LinuxProcessInspector) Remaining(ctx context.Context, o ProcessOwner) ( |
| if r == nil { |
| return ProcessInventory{}, paseo.ErrIdentity |
| } |
| - return p.scan(ctx, r) |
| + return p.scan(ctx, r, true) |
| } |
| type procEntry struct { |
| @@ -166,40 +167,30 @@ func (p *LinuxProcessInspector) identity(pid int) (ProcessIdentity, error) { |
| func identityKey(id ProcessIdentity) string { |
| return fmt.Sprintf("%s/%d/%d", id.BootID, id.PID, id.StartTicks) |
| } |
| -func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord) (ProcessInventory, error) { |
| - inv := ProcessInventory{BootID: p.boot, CoverageKnown: !r.Unknown, CheckedAt: time.Now().UTC()} |
| - stage, pidAt := 0, 0 |
| - unknown := func() { r.Unknown = true; r.UnknownStage = stage; r.UnknownPID = pidAt; inv.CoverageKnown = false } |
| - reading, clockErr := (linuxClock{}).Read() |
| - if clockErr != nil || reading.BootID != p.boot || r.LastScanElapsed > 0 && (reading.Elapsed < r.LastScanElapsed || reading.Elapsed-r.LastScanElapsed > 2*time.Second) { |
| +func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, terminals bool) (ProcessInventory, error) { |
| + inv := ProcessInventory{BootID: p.boot, CoverageKnown: r.TrackTicks > 0 && r.TrackBoot != "", CheckedAt: time.Now().UTC()} |
| + unknown := func() { inv.CoverageKnown = false } |
| + boot, err := os.ReadFile(filepath.Join(p.root, "sys/kernel/random/boot_id")) |
| + if err != nil || strings.TrimSpace(string(boot)) != p.boot { |
| unknown() |
| } |
| - r.LastScanElapsed = reading.Elapsed |
| - |
| entries, err := os.ReadDir(p.root) |
| if err != nil { |
| unknown() |
| - _ = p.save(context.WithoutCancel(ctx), r) |
| - return inv, err |
| - } |
| - boot, err := os.ReadFile(filepath.Join(p.root, "sys/kernel/random/boot_id")) |
| - if err != nil || strings.TrimSpace(string(boot)) != p.boot { |
| - unknown() |
| + return inv, errors.Join(err, p.save(context.WithoutCancel(ctx), r)) |
| } |
| - known := map[string]bool{} |
| - knownPID := map[int]bool{} |
| - for _, id := range r.Known { |
| - known[identityKey(id)] = true |
| - knownPID[id.PID] = true |
| - } |
| - for _, record := range p.records { |
| + all := map[int]procEntry{} |
| + attributed := map[int]string{} |
| + known := map[string]string{} |
| + for key, record := range p.records { |
| for _, id := range record.Known { |
| - knownPID[id.PID] = true |
| + known[identityKey(id)] = key |
| } |
| } |
| - all := map[int]procEntry{} |
| - owned := map[int]bool{} |
| for _, d := range entries { |
| + if r.TrackBoot != "" && r.TrackBoot != p.boot { |
| + break |
| + } |
| if ctx.Err() != nil { |
| unknown() |
| break |
| @@ -208,119 +199,171 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord) (Pro |
| if err != nil || pid <= 0 { |
| continue |
| } |
| - pidAt = pid |
| - stage = 1 |
| var st unix.Stat_t |
| if err = unix.Stat(filepath.Join(p.root, d.Name()), &st); err != nil { |
| - if os.IsNotExist(err) && (p.stopped[pid].PID == pid || knownPID[pid]) { |
| - continue |
| + if !os.IsNotExist(err) { |
| + unknown() |
| } |
| - unknown() |
| continue |
| } |
| if st.Uid != uint32(os.Getuid()) { |
| continue |
| } |
| - stage = 2 |
| e, err := p.entry(pid) |
| if err != nil { |
| - if os.IsNotExist(err) && (p.stopped[pid].PID == pid || knownPID[pid]) { |
| - continue |
| + if !os.IsNotExist(err) { |
| + unknown() |
| } |
| - unknown() |
| continue |
| } |
| if e.dead { |
| continue |
| } |
| - stage = 3 |
| + all[pid] = e |
| + if key := known[identityKey(e.id)]; key != "" { |
| + attributed[pid] = key |
| + } |
| + if r.TrackBoot != p.boot && r.TrackBoot != "" { |
| + continue |
| + } |
| + if e.id.StartTicks < r.TrackTicks { |
| + continue |
| + } |
| env, envErr := os.ReadFile(filepath.Join(p.root, d.Name(), "environ")) |
| cwd, cwdErr := os.Readlink(filepath.Join(p.root, d.Name(), "cwd")) |
| - if envErr != nil || cwdErr != nil { |
| - after, e2 := p.entry(pid) |
| - if (e2 == nil && after.id == e.id && after.dead) || (os.IsNotExist(e2) && (p.stopped[pid] == e.id || known[identityKey(e.id)])) { |
| - continue |
| - } |
| - unknown() |
| + after, err := p.entry(pid) |
| + if os.IsNotExist(err) || err == nil && after.dead { |
| + delete(all, pid) |
| continue |
| } |
| - // Check identity after collecting attributes; a recycled or vanished PID is not a coherent observation. |
| - stage = 4 |
| - after, err := p.identity(pid) |
| - if err != nil || after != e.id { |
| - if os.IsNotExist(err) && (p.stopped[pid] == e.id || known[identityKey(e.id)]) { |
| - continue |
| - } |
| + if err != nil || after.id != e.id { |
| + delete(all, pid) |
| unknown() |
| continue |
| } |
| - e.cwd = cwd |
| e.env = string(env) |
| + e.cwd = cwd |
| all[pid] = e |
| - marker := false |
| - for _, v := range strings.Split(e.env, "\x00") { |
| - marker = marker || v == "EQUIPO_ATTEMPT_MARKER="+r.Owner.Marker |
| + if key := known[identityKey(e.id)]; key != "" { |
| + attributed[pid] = key |
| + continue |
| } |
| - path := e.cwd == r.Owner.Workspace.Path || strings.HasPrefix(e.cwd, r.Owner.Workspace.Path+"/") |
| - if known[identityKey(e.id)] || marker || path { |
| - owned[pid] = true |
| + var markers, paths []string |
| + for key, record := range p.records { |
| + if record.TrackBoot != p.boot || e.id.StartTicks < record.TrackTicks { |
| + continue |
| + } |
| + marker := false |
| + if envErr == nil { |
| + for _, v := range strings.Split(e.env, "\x00") { |
| + marker = marker || v == "EQUIPO_ATTEMPT_MARKER="+record.Owner.Marker |
| + } |
| + } |
| + path := cwdErr == nil && (cwd == record.Owner.Workspace.Path || strings.HasPrefix(cwd, record.Owner.Workspace.Path+"/")) |
| + if marker { |
| + markers = append(markers, key) |
| + } |
| + if path { |
| + paths = append(paths, key) |
| + } |
| } |
| - for _, id := range r.Owner.ExecutorGroups { |
| - if id == e.id { |
| - owned[pid] = true |
| + if len(markers) == 1 { |
| + attributed[pid] = markers[0] |
| + } else if len(markers) > 1 { |
| + unknown() |
| + } else if len(paths) == 1 { |
| + attributed[pid] = paths[0] |
| + } else if len(paths) > 1 { |
| + unknown() |
| + } |
| + |
| + } |
| + // Propagate only ancestry observed live in this scan, with coherent lifetimes. |
| + for changed := true; changed; { |
| + changed = false |
| + for pid, e := range all { |
| + parent, ok := all[e.parent] |
| + if attributed[pid] == "" && ok && attributed[e.parent] != "" && parent.id.StartTicks <= e.id.StartTicks { |
| + attributed[pid] = attributed[e.parent] |
| + changed = true |
| } |
| } |
| } |
| + controls := map[int]bool{} |
| + host := &LinuxProcessInspector{root: "/proc", boot: p.boot} |
| + runnerID, runnerErr := host.identity(os.Getpid()) |
| + if e, ok := all[os.Getpid()]; runnerErr == nil && ok && e.id == runnerID { |
| + controls[os.Getpid()] = true |
| + } |
| for changed := true; changed; { |
| changed = false |
| for pid, e := range all { |
| - if !owned[pid] && owned[e.parent] && all[e.parent].id.StartTicks <= e.id.StartTicks { |
| - owned[pid] = true |
| + if !controls[pid] && attributed[pid] == "" && controls[e.parent] && all[e.parent].id.StartTicks <= e.id.StartTicks { |
| + controls[pid] = true |
| changed = true |
| } |
| } |
| } |
| - stage = 5 |
| - if r.Started { |
| - unrelated := map[int]bool{} |
| - for _, id := range r.Baseline { |
| - if e, ok := all[id.PID]; ok && e.id == id && !owned[id.PID] { |
| - unrelated[id.PID] = true |
| + for pid, e := range all { |
| + if r.TrackBoot != p.boot && r.TrackBoot != "" { |
| + continue |
| + } |
| + if e.id.StartTicks < r.TrackTicks { |
| + continue |
| + } |
| + key := attributed[pid] |
| + if key != "" { |
| + record := p.records[key] |
| + if known[identityKey(e.id)] == "" { |
| + record.Known = append(record.Known, e.id) |
| + known[identityKey(e.id)] = key |
| + } |
| + if key == ownerKey(r.Owner) { |
| + inv.Processes = append(inv.Processes, e.id) |
| } |
| + } else if !controls[pid] { |
| + unknown() |
| } |
| - for changed := true; changed; { |
| - changed = false |
| + } |
| + for _, record := range p.records { |
| + for command, ids := range record.Commands { |
| + members := map[int]bool{} |
| + for _, id := range ids { |
| + if e, ok := all[id.PID]; ok && e.id == id { |
| + members[id.PID] = true |
| + } |
| + } |
| for pid, e := range all { |
| - if !owned[pid] && !unrelated[pid] && unrelated[e.parent] { |
| - unrelated[pid] = true |
| - changed = true |
| + for _, v := range strings.Split(e.env, "\x00") { |
| + if v == "EQUIPO_COMMAND_MARKER="+command && attributed[pid] == ownerKey(record.Owner) { |
| + members[pid] = true |
| + } |
| } |
| } |
| - } |
| - for pid := range all { |
| - if !owned[pid] && !unrelated[pid] { |
| - unknown() |
| + for changed := true; changed; { |
| + changed = false |
| + for pid, e := range all { |
| + if !members[pid] && members[e.parent] && all[e.parent].id.StartTicks <= e.id.StartTicks { |
| + members[pid] = true |
| + changed = true |
| + } |
| + } |
| } |
| - } |
| - } else { |
| - for pid, e := range all { |
| - if !owned[pid] { |
| - r.Baseline = append(r.Baseline, e.id) |
| + saved := map[string]bool{} |
| + for _, id := range ids { |
| + saved[identityKey(id)] = true |
| + } |
| + for pid := range members { |
| + id := all[pid].id |
| + if !saved[identityKey(id)] { |
| + record.Commands[command] = append(record.Commands[command], id) |
| + } |
| } |
| - } |
| - r.Started = true |
| - } |
| - for pid := range owned { |
| - id := all[pid].id |
| - inv.Processes = append(inv.Processes, id) |
| - if !known[identityKey(id)] { |
| - r.Known = append(r.Known, id) |
| - known[identityKey(id)] = true |
| } |
| } |
| + |
| sort.Slice(inv.Processes, func(i, j int) bool { return inv.Processes[i].PID < inv.Processes[j].PID }) |
| - stage = 6 |
| - if !r.Owner.LocalOnly { |
| + if terminals && !r.Owner.LocalOnly { |
| ids, err := p.client.ListTerminals(ctx, r.Owner.Workspace) |
| if err != nil { |
| unknown() |
| @@ -328,15 +371,48 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord) (Pro |
| inv.TerminalIDs = ids |
| } |
| } |
| + if terminals && inv.CoverageKnown && len(inv.Processes) == 0 && r.TrackBoot == p.boot { |
| + // A terminal RPC can outlast a process lifetime. Close the scan after it. |
| + closing, err := os.ReadDir(p.root) |
| + if err != nil { |
| + unknown() |
| + } else { |
| + for _, d := range closing { |
| + pid, e := strconv.Atoi(d.Name()) |
| + if e != nil { |
| + continue |
| + } |
| + var st unix.Stat_t |
| + if e = unix.Stat(filepath.Join(p.root, d.Name()), &st); e != nil { |
| + if !os.IsNotExist(e) { |
| + unknown() |
| + } |
| + continue |
| + } |
| + if st.Uid != uint32(os.Getuid()) { |
| + continue |
| + } |
| + entry, e := p.entry(pid) |
| + if e != nil { |
| + if !os.IsNotExist(e) { |
| + unknown() |
| + } |
| + continue |
| + } |
| + if !entry.dead && entry.id.StartTicks >= r.TrackTicks && all[pid].id != entry.id { |
| + unknown() |
| + } |
| + } |
| + } |
| + } |
| inv.Observed = append([]ProcessIdentity(nil), r.Known...) |
| inv.ExecutorGroups = append([]ProcessIdentity(nil), r.Owner.ExecutorGroups...) |
| - if err := p.save(context.WithoutCancel(ctx), r); err != nil { |
| - return ProcessInventory{}, err |
| - } |
| - if ctx.Err() != nil { |
| - return inv, ctx.Err() |
| + for _, record := range p.records { |
| + if err := p.save(context.WithoutCancel(ctx), record); err != nil { |
| + return inv, err |
| + } |
| } |
| - return inv, nil |
| + return inv, ctx.Err() |
| } |
| func (p *LinuxProcessInspector) Stop(ctx context.Context, id ProcessIdentity) error { |
| p.mu.Lock() |
| @@ -362,6 +438,9 @@ func (p *LinuxProcessInspector) Stop(ctx context.Context, id ProcessIdentity) er |
| return paseo.ErrIdentity |
| } |
| status, err := os.ReadFile(filepath.Join(p.root, strconv.Itoa(id.PID), "status")) |
| + if os.IsNotExist(err) { |
| + return nil |
| + } |
| if err != nil { |
| return err |
| } |
| @@ -369,7 +448,7 @@ func (p *LinuxProcessInspector) Stop(ctx context.Context, id ProcessIdentity) er |
| for _, line := range strings.Split(string(status), "\n") { |
| if strings.HasPrefix(line, "NSpid:") { |
| f := strings.Fields(line) |
| - host = len(f) == 2 && f[1] == strconv.Itoa(id.PID) |
| + host = len(f) >= 2 && f[1] == strconv.Itoa(id.PID) |
| } |
| } |
| if !host { |
| @@ -380,12 +459,18 @@ func (p *LinuxProcessInspector) Stop(ctx context.Context, id ProcessIdentity) er |
| return paseo.ErrIdentity |
| } |
| fd, err := unix.PidfdOpen(id.PID, 0) |
| + if err == unix.ESRCH { |
| + return nil |
| + } |
| if err != nil { |
| return err |
| } |
| defer unix.Close(fd) |
| hostInspector := &LinuxProcessInspector{root: "/proc", boot: p.boot} |
| current, err := hostInspector.identity(id.PID) |
| + if os.IsNotExist(err) { |
| + return nil |
| + } |
| if err != nil || current != id { |
| return paseo.ErrIdentity |
| } |
| @@ -393,13 +478,15 @@ func (p *LinuxProcessInspector) Stop(ctx context.Context, id ProcessIdentity) er |
| return err |
| } |
| current, err = hostInspector.identity(id.PID) |
| + if os.IsNotExist(err) { |
| + return nil |
| + } |
| if err != nil || current != id { |
| return paseo.ErrIdentity |
| } |
| if err = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); err != nil { |
| return err |
| } |
| - p.stopped[id.PID] = id |
| fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} |
| n, err := unix.Poll(fds, 1000) |
| if err != nil || n != 1 { |
| @@ -440,7 +527,10 @@ func (j *Journal) readStates(ctx context.Context, kind string, out any) error { |
| if err = rows.Err(); err != nil { |
| return err |
| } |
| - raw, _ := json.Marshal(list) |
| + raw, err := json.Marshal(list) |
| + if err != nil { |
| + return err |
| + } |
| return json.Unmarshal(raw, out) |
| } |
| @@ -476,6 +566,8 @@ func (p *LinuxProcessInspector) InspectProcesses(ctx context.Context, _ paseo.Se |
| if err != nil { |
| return false, err |
| } |
| + // Before Track all existing processes are pre-existing. Only stat/UID |
| + // access is needed; unreadable environments do not prevent preflight. |
| for _, d := range entries { |
| if ctx.Err() != nil { |
| return false, ctx.Err() |
| @@ -485,29 +577,90 @@ func (p *LinuxProcessInspector) InspectProcesses(ctx context.Context, _ paseo.Se |
| continue |
| } |
| var st unix.Stat_t |
| - if unix.Stat(filepath.Join(p.root, d.Name()), &st) != nil { |
| - return false, paseo.ErrUncertain |
| - } |
| - if st.Uid != uint32(os.Getuid()) { |
| - continue |
| - } |
| - e, err := p.entry(pid) |
| - if err != nil { |
| + if err = unix.Stat(filepath.Join(p.root, d.Name()), &st); err != nil { |
| + if os.IsNotExist(err) { |
| + continue |
| + } |
| return false, err |
| } |
| - if e.dead { |
| + if st.Uid != uint32(os.Getuid()) { |
| continue |
| } |
| - if _, err = os.ReadFile(filepath.Join(p.root, d.Name(), "environ")); err != nil { |
| + if _, err = p.entry(pid); err != nil && !os.IsNotExist(err) { |
| return false, err |
| } |
| - if _, err = os.Readlink(filepath.Join(p.root, d.Name(), "cwd")); err != nil { |
| - return false, err |
| + } |
| + |
| + return true, nil |
| +} |
| + |
| +func (p *LinuxProcessInspector) observe(ctx context.Context, o ProcessOwner) (ProcessInventory, error) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + r := p.records[ownerKey(o)] |
| + if r == nil { |
| + return ProcessInventory{}, paseo.ErrIdentity |
| + } |
| + return p.scan(ctx, r, false) |
| +} |
| + |
| +func (p *LinuxProcessInspector) BeginCommand(ctx context.Context, o ProcessOwner, pid int, command string) error { |
| + if command == "" { |
| + return paseo.ErrIdentity |
| + } |
| + if err := p.TrackPID(ctx, o, pid); err != nil { |
| + return err |
| + } |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + r := p.records[ownerKey(o)] |
| + id, err := p.identity(pid) |
| + if err != nil { |
| + return err |
| + } |
| + if r.Commands == nil { |
| + r.Commands = map[string][]ProcessIdentity{} |
| + } |
| + if _, ok := r.Commands[command]; ok { |
| + return paseo.ErrIdentity |
| + } |
| + r.Commands[command] = []ProcessIdentity{id} |
| + return p.save(ctx, r) |
| +} |
| +func (p *LinuxProcessInspector) EndCommand(ctx context.Context, o ProcessOwner, command string) error { |
| + inv, err := p.Remaining(ctx, o) |
| + if err != nil { |
| + return err |
| + } |
| + p.mu.Lock() |
| + r := p.records[ownerKey(o)] |
| + ids, ok := r.Commands[command] |
| + ids = append([]ProcessIdentity(nil), ids...) |
| + p.mu.Unlock() |
| + if !ok { |
| + return paseo.ErrIdentity |
| + } |
| + live := map[ProcessIdentity]bool{} |
| + for _, id := range inv.Processes { |
| + live[id] = true |
| + } |
| + var failures error |
| + for _, id := range ids { |
| + if live[id] { |
| + failures = errors.Join(failures, p.Stop(ctx, id)) |
| } |
| - id, err := p.identity(pid) |
| - if err != nil || id != e.id { |
| - return false, paseo.ErrUncertain |
| + } |
| + inv, err = p.Remaining(ctx, o) |
| + failures = errors.Join(failures, err) |
| + if !inv.CoverageKnown { |
| + failures = errors.Join(failures, paseo.ErrUncertain) |
| + } |
| + for _, id := range inv.Processes { |
| + for _, owned := range ids { |
| + if id == owned { |
| + failures = errors.Join(failures, paseo.ErrUncertain) |
| + } |
| } |
| } |
| - return true, nil |
| + return failures |
| } |
diff --git a/internal/runner/process_linux_test.go b/internal/runner/process_linux_test.go| index a5eca4a7..b47753f4 100644 |
| --- a/internal/runner/process_linux_test.go |
| +++ b/internal/runner/process_linux_test.go |
| @@ -61,7 +61,10 @@ func childProcess(t *testing.T, dir, marker string) *exec.Cmd { |
| return c |
| } |
| func TestLinuxInspectorEnvironmentStrippedChild(t *testing.T) { |
| - p, o := processFixture(t) |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| ctx := context.Background() |
| if err := p.Track(ctx, o); err != nil { |
| t.Fatal(err) |
| @@ -78,12 +81,15 @@ func TestLinuxInspectorEnvironmentStrippedChild(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - linkProcess(t, p.root, pid) |
| childID, err := p.identity(pid) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - t.Cleanup(func() { _ = p.Stop(context.Background(), childID) }) |
| + fd, err := unix.PidfdOpen(childID.PID, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); unix.Close(fd) }) |
| inv, err := p.Remaining(ctx, o) |
| if err != nil { |
| t.Fatal(err) |
| @@ -142,12 +148,15 @@ func TestLinuxInspectorUnknownCoverage(t *testing.T) { |
| cancel() |
| _, _ = p.Remaining(cancelled, o) |
| inv, _ := p.Remaining(ctx, o) |
| - if inv.CoverageKnown { |
| - t.Fatal("interrupted inventory became known") |
| + if !inv.CoverageKnown { |
| + t.Fatal("full rescan did not restore coverage") |
| } |
| } |
| func TestLinuxInspectorTrackedChildChangesCWD(t *testing.T) { |
| - p, o := processFixture(t) |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| ctx := context.Background() |
| if err := p.Track(ctx, o); err != nil { |
| t.Fatal(err) |
| @@ -160,7 +169,6 @@ func TestLinuxInspectorTrackedChildChangesCWD(t *testing.T) { |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { c.Process.Kill(); c.Wait() }) |
| - linkProcess(t, p.root, c.Process.Pid) |
| inv, err := p.Remaining(ctx, o) |
| if err != nil || len(inv.Processes) == 0 { |
| t.Fatalf("not tracked: %+v %v", inv, err) |
| @@ -244,34 +252,40 @@ func TestLinuxInspectorUnreadableSameUser(t *testing.T) { |
| if err = os.Symlink(o.Workspace.Path, filepath.Join(dir, "cwd")); err != nil { |
| t.Fatal(err) |
| } |
| - if err = p.Track(context.Background(), o); err == nil { |
| - t.Fatal("unreadable same-user process admitted") |
| + if err = p.Track(context.Background(), o); err != nil { |
| + t.Fatal("preexisting unreadable process blocked admission") |
| } |
| inv, _ := p.Remaining(context.Background(), o) |
| - if inv.CoverageKnown { |
| - t.Fatal("unreadable inventory acknowledged") |
| + if !inv.CoverageKnown { |
| + t.Fatal("preexisting unreadable inventory blocked") |
| } |
| } |
| func TestLinuxInspectorMonitoringGap(t *testing.T) { |
| - p, o := processFixture(t) |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| ctx := context.Background() |
| if err := p.Track(ctx, o); err != nil { |
| t.Fatal(err) |
| } |
| - p.records[ownerKey(o)].LastScanElapsed -= 3 * time.Second |
| + time.Sleep(2100 * time.Millisecond) |
| inv, err := p.Remaining(ctx, o) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if inv.CoverageKnown { |
| - t.Fatal("monitoring gap accepted as coverage") |
| + if !inv.CoverageKnown { |
| + t.Fatal("monitoring gap prevented full rescan") |
| } |
| } |
| func TestProcessIdentityNamespacePID(t *testing.T) { |
| p, o := processFixture(t) |
| ctx := context.Background() |
| + if err := p.Track(ctx, o); err != nil { |
| + t.Fatal(err) |
| + } |
| control := childProcess(t, o.Workspace.Path, o.Marker) |
| pid := control.Process.Pid |
| dir := filepath.Join(p.root, strconv.Itoa(pid)) |
| @@ -293,10 +307,7 @@ func TestProcessIdentityNamespacePID(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if err = p.Stop(ctx, id); err == nil { |
| - t.Fatal("namespace PID signalled host control") |
| - } |
| - if err = control.Process.Signal(unix.Signal(0)); err != nil { |
| - t.Fatal("host control did not survive", err) |
| + if err = p.Stop(ctx, id); err != nil { |
| + t.Fatal("host PID in nested namespace refused", err) |
| } |
| } |
diff --git a/internal/runner/questions.go b/internal/runner/questions.go| index 7fd37fbf..a5312cce 100644 |
| --- a/internal/runner/questions.go |
| +++ b/internal/runner/questions.go |
| @@ -159,7 +159,7 @@ func (r *QuestionRelay) Wait(ctx context.Context, q runnerproto.Question, poll f |
| } |
| timer := time.NewTimer(time.Until(q.ExpiresAt)) |
| defer timer.Stop() |
| - tick := time.NewTicker(100 * time.Millisecond) |
| + tick := time.NewTicker(time.Duration(runnerproto.LongPollSeconds) * time.Second) |
| defer tick.Stop() |
| for { |
| deadline, err := r.Current(ctx, q) |
| @@ -172,7 +172,8 @@ func (r *QuestionRelay) Wait(ctx context.Context, q runnerproto.Question, poll f |
| } |
| timer.Reset(time.Until(q.ExpiresAt)) |
| pollCtx, cancel := context.WithDeadline(ctx, q.ExpiresAt) |
| - answer, err := poll(pollCtx) |
| + var answer *runnerproto.QuestionAnswer |
| + err = retryAuthority(pollCtx, func() error { var e error; answer, e = poll(pollCtx); return e }) |
| cancel() |
| if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil && !time.Now().Before(q.ExpiresAt) { |
| continue |
diff --git a/internal/runner/retry.go b/internal/runner/retry.go| new file mode 100644 |
| index 00000000..057d90d9 |
| --- /dev/null |
| +++ b/internal/runner/retry.go |
| @@ -0,0 +1,43 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| +) |
| + |
| +var ErrTransient = errors.New("runner_transient") |
| +var ErrNotClaimed = errors.New("runner_not_claimed") |
| +var ErrClaimRefused = errors.New("runner_claim_refused") |
| + |
| +func retryAuthority(ctx context.Context, call func() error) error { |
| + delay := 200 * time.Millisecond |
| + for { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + err := call() |
| + if !errors.Is(err, ErrTransient) && !errors.Is(err, paseo.ErrClosed) { |
| + return err |
| + } |
| + timer := time.NewTimer(delay) |
| + select { |
| + case <-ctx.Done(): |
| + timer.Stop() |
| + return ctx.Err() |
| + case <-timer.C: |
| + } |
| + if delay < 2*time.Second { |
| + delay *= 2 |
| + } |
| + } |
| +} |
| + |
| +func remoteError(err error) error { |
| + if errors.Is(err, paseo.ErrUncertain) { |
| + return ErrTransient |
| + } |
| + return err |
| +} |
diff --git a/internal/runner/service.go b/internal/runner/service.go| index 3658a556..8ce1a190 100644 |
| --- a/internal/runner/service.go |
| +++ b/internal/runner/service.go |
| @@ -44,7 +44,14 @@ func (s *Service) Run(ctx context.Context) error { |
| if err = s.Supervisor.journal.saveState(ctx, "claim", a.ID, request); err != nil { |
| return err |
| } |
| - claim, err := s.Source.Claim(ctx, request) |
| + var claim runnerproto.ClaimResponse |
| + err = retryAuthority(ctx, func() error { var e error; claim, e = s.Source.Claim(ctx, request); return e }) |
| + if errors.Is(err, ErrClaimRefused) || errors.Is(err, paseo.ErrIdentity) { |
| + if err = s.clearClaim(ctx, request); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| if err != nil { |
| return err |
| } |
| @@ -78,7 +85,14 @@ func (s *Service) recoverClaims(ctx context.Context) error { |
| if !ok || s.Supervisor.workflow == nil { |
| return paseo.ErrUncertain |
| } |
| - reply, err := source.RecoverClaim(ctx, q) |
| + var reply runnerproto.ClaimResponse |
| + err := retryAuthority(ctx, func() error { var e error; reply, e = source.RecoverClaim(ctx, q); return e }) |
| + if errors.Is(err, ErrNotClaimed) { |
| + if err = s.clearClaim(ctx, q); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| if err != nil { |
| return err |
| } |
| @@ -94,6 +108,9 @@ func (s *Service) recoverClaims(ctx context.Context) error { |
| return paseo.ErrIdentity |
| } |
| record := &attemptState{Claim: RunClaim{Assignment: assignment, ClaimResponse: reply}, Phase: "recovering", Owner: ProcessOwner{LocalOnly: true, Attempt: reply.Handle.Attempt, Fence: reply.Handle.Fence, Marker: assignment.ID, Workspace: paseo.Workspace{Path: s.Supervisor.workflow.cfg.Workspaces.PreparationDirectory()}}} |
| + if assignment.Kind != "prepare" { |
| + record.Owner.Marker = attemptKey(reply.Scope, reply.Handle) |
| + } |
| if err = s.Supervisor.save(ctx, record); err != nil { |
| return err |
| } |
| @@ -103,3 +120,8 @@ func (s *Service) recoverClaims(ctx context.Context) error { |
| } |
| return nil |
| } |
| + |
| +func (s *Service) clearClaim(ctx context.Context, q runnerproto.ClaimRequest) error { |
| + _, err := s.Supervisor.journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='claim' AND state_key=?", q.AssignmentID) |
| + return err |
| +} |
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go| index 1c9597e4..12fa589f 100644 |
| --- a/internal/runner/supervisor.go |
| +++ b/internal/runner/supervisor.go |
| @@ -34,6 +34,7 @@ type attemptState struct { |
| Agent paseo.Agent |
| Phase string |
| FailurePhase string |
| + StopError string |
| SocketPath, CapabilityPath string |
| Proof *ContainmentProof |
| Rotation *runnerproto.CredentialRotation |
| @@ -62,6 +63,8 @@ type Supervisor struct { |
| activeKey string |
| activeCancel context.CancelFunc |
| activeSocket *AttemptSocket |
| + activeCurrent func(context.Context) error |
| + monitorStop func() |
| activeStop runnerproto.RunnerRequest |
| states map[string]*attemptState |
| ready bool |
| @@ -113,7 +116,6 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| return err |
| } |
| r := &attemptState{Claim: claim, Phase: "claimed"} |
| - s.states[key] = r |
| raw, err := json.Marshal(r) |
| if err != nil { |
| return err |
| @@ -121,14 +123,28 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| if _, err = s.journal.db.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES('attempt',?,?)", key, raw); err != nil { |
| return paseo.ErrUncertain |
| } |
| + s.states[key] = r |
| active, cancel := context.WithCancel(ctx) |
| defer cancel() |
| + defer func() { |
| + if s.monitorStop != nil { |
| + s.monitorStop() |
| + s.monitorStop = nil |
| + } |
| + }() |
| s.mu.Lock() |
| s.activeKey = key |
| s.activeCancel = cancel |
| s.activeStop = r.request("stop") |
| s.mu.Unlock() |
| - defer func() { s.mu.Lock(); s.activeKey = ""; s.activeCancel = nil; s.activeSocket = nil; s.mu.Unlock() }() |
| + defer func() { |
| + s.mu.Lock() |
| + s.activeKey = "" |
| + s.activeCancel = nil |
| + s.activeSocket = nil |
| + s.activeCurrent = nil |
| + s.mu.Unlock() |
| + }() |
| done := make(chan struct{}) |
| go s.watchLease(active, cancel, r, lease, done) |
| err = s.workflow.run(active, s, r, lease) |
| @@ -139,10 +155,15 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| <-done |
| cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) |
| defer cleanupCancel() |
| + outcome := "accepted" |
| + if err != nil { |
| + outcome = "rejected" |
| + } |
| + err = errors.Join(err, s.journal.finishTools(cleanupCtx, r.Claim, outcome)) |
| if err != nil { |
| q := r.request("failed") |
| q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure} |
| - _ = s.api.Call(cleanupCtx, "complete", q, nil) |
| + err = errors.Join(err, s.api.Call(cleanupCtx, "complete", q, nil)) |
| } |
| _, cleanupErr := s.cleanup(cleanupCtx, r) |
| if err == nil && cleanupErr == nil && r.Claim.Assignment.StepKey == "publish" { |
| @@ -176,14 +197,27 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, |
| // A blocked renewal never pauses the local lease watchdog. |
| reply := make(chan error, 1) |
| go func() { |
| - var deadline time.Time |
| - err := s.api.Call(ctx, "renew", r.request("renew"), &deadline) |
| - if err == nil { |
| - n, e := s.clock.Read() |
| + err := retryAuthority(ctx, func() error { |
| + sent, e := s.clock.Read() |
| if e != nil { |
| - err = e |
| - } else { |
| - err = l.renew(n, deadline) |
| + return e |
| + } |
| + var deadline time.Time |
| + if e = s.api.Call(ctx, "renew", r.request("renew"), &deadline); e != nil { |
| + return e |
| + } |
| + received, e := s.clock.Read() |
| + if e != nil { |
| + return e |
| + } |
| + return l.renewReply(sent, received, deadline) |
| + }) |
| + if err == nil { |
| + s.mu.Lock() |
| + current := s.activeCurrent |
| + s.mu.Unlock() |
| + if current != nil { |
| + err = current(ctx) |
| } |
| } |
| reply <- err |
| @@ -227,8 +261,9 @@ func (s *Supervisor) Cancel(ctx context.Context, scope team.Scope, h team.Handle |
| cancel := s.activeCancel |
| stop := s.activeStop |
| s.mu.Unlock() |
| + var stopErr error |
| if active { |
| - _ = s.api.Call(ctx, "stop", stop, nil) |
| + stopErr = s.api.Call(ctx, "stop", stop, nil) |
| cancel() |
| } |
| s.runMu.Lock() |
| @@ -239,9 +274,10 @@ func (s *Supervisor) Cancel(ctx context.Context, scope team.Scope, h team.Handle |
| } |
| // Instance fences first; failure never prevents local stopping. |
| if !active { |
| - _ = s.api.Call(ctx, "stop", r.request("stop"), nil) |
| + stopErr = s.api.Call(ctx, "stop", r.request("stop"), nil) |
| } |
| - return s.cleanup(ctx, r) |
| + proof, err := s.cleanup(ctx, r) |
| + return proof, errors.Join(stopErr, err) |
| } |
| func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentProof, error) { |
| proof := ContainmentProof{Scope: r.Claim.Scope, Handle: r.Claim.Handle, Owner: r.Owner} |
| @@ -254,6 +290,10 @@ func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentP |
| if r.Phase == "verified" && r.Proof != nil { |
| return s.reportContainment(ctx, r) |
| } |
| + if err := s.recoverCreation(ctx, r); err != nil { |
| + return proof, err |
| + } |
| + proof.Owner = r.Owner |
| r.Phase = "stopping" |
| if err := s.save(ctx, r); err != nil { |
| return proof, err |
| @@ -261,6 +301,12 @@ func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentP |
| if !validOwner(r.Owner) { |
| return proof, paseo.ErrUncertain |
| } |
| + if s.monitorStop == nil { |
| + if _, ok := s.inspector.(*LinuxProcessInspector); ok { |
| + _, stop := monitorOwnership(context.WithoutCancel(ctx), s.inspector, r.Owner) |
| + defer stop() |
| + } |
| + } |
| var failures error |
| if r.Agent.AgentID != "" { |
| failures = errors.Join(failures, s.client.Stop(ctx, r.Agent)) |
| @@ -309,6 +355,11 @@ func (s *Supervisor) reportContainment(ctx context.Context, r *attemptState) (Co |
| return *r.Proof, err |
| } |
| q.Proof = raw |
| + if s.workflow != nil && s.workflow.cfg.Witness != nil { |
| + if err = s.workflow.cfg.Witness.Containment(ctx, r.Claim.Assignment, q); err != nil { |
| + return *r.Proof, err |
| + } |
| + } |
| var rotation runnerproto.CredentialRotation |
| if err = s.api.Call(ctx, "contained", q, &rotation); err != nil { |
| return *r.Proof, err |
| @@ -348,12 +399,19 @@ func (s *Supervisor) Recover(ctx context.Context) error { |
| var failures error |
| for i := range states { |
| r := &states[i] |
| + failures = errors.Join(failures, s.journal.finishTools(ctx, r.Claim, "interrupted")) |
| s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)] = r |
| if restore, ok := s.api.(interface{ RestoreClaim(RunClaim) error }); ok { |
| failures = errors.Join(failures, restore.RestoreClaim(r.Claim)) |
| } |
| if r.Phase != "contained" { |
| - _ = s.api.Call(ctx, "stop", r.request("stop"), nil) |
| + if r.Phase != "completed" && r.Phase != "prepared" && r.Phase != "verified" { |
| + stopErr := s.api.Call(ctx, "stop", r.request("stop"), nil) |
| + if stopErr != nil { |
| + r.StopError = stopErr.Error() |
| + failures = errors.Join(failures, s.save(ctx, r)) |
| + } |
| + } |
| if _, err := s.cleanup(ctx, r); err != nil { |
| failures = errors.Join(failures, err) |
| continue |
| @@ -374,7 +432,12 @@ func (s *Supervisor) Recover(ctx context.Context) error { |
| } |
| var batchErr error |
| for _, e := range pending { |
| - q := runnerproto.RunnerRequest{Version: 1, AssignmentID: e.AssignmentID, Scope: e.Scope, Handle: e.Handle, RequestID: e.ID, ActionID: e.ActionID, Event: marshal(e)} |
| + raw, err := runnerproto.Marshal(e) |
| + if err != nil { |
| + batchErr = errors.Join(batchErr, err) |
| + continue |
| + } |
| + q := runnerproto.RunnerRequest{Version: 1, AssignmentID: e.AssignmentID, Scope: e.Scope, Handle: e.Handle, RequestID: e.ID, ActionID: e.ActionID, Event: raw} |
| if err := s.api.Call(ctx, "events", q, nil); err != nil { |
| batchErr = errors.Join(batchErr, err) |
| continue |
diff --git a/internal/runner/supervisor_r1_test.go b/internal/runner/supervisor_r1_test.go| new file mode 100644 |
| index 00000000..765d0cda |
| --- /dev/null |
| +++ b/internal/runner/supervisor_r1_test.go |
| @@ -0,0 +1,310 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type claimSourceR1 struct { |
| + calls []runnerproto.ClaimRequest |
| + err error |
| + recovery error |
| +} |
| + |
| +func (s *claimSourceR1) Poll(context.Context) ([]runnerproto.Assignment, error) { |
| + return nil, context.Canceled |
| +} |
| +func (s *claimSourceR1) Claim(_ context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| + s.calls = append(s.calls, q) |
| + return runnerproto.ClaimResponse{}, s.err |
| +} |
| +func (s *claimSourceR1) RecoverClaim(_ context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| + s.calls = append(s.calls, q) |
| + return runnerproto.ClaimResponse{}, s.recovery |
| +} |
| + |
| +func TestRunnerRestartNeverAppliedClaim(t *testing.T) { |
| + s, _, _, _ := cleanupFixture(t) |
| + s.workflow = &BugWorkflow{} |
| + q := runnerproto.ClaimRequest{Version: 1, AssignmentID: "refused", RequestID: "exact-request", Revision: 3} |
| + if err := s.journal.saveState(context.Background(), "claim", q.AssignmentID, q); err != nil { |
| + t.Fatal(err) |
| + } |
| + source := &claimSourceR1{recovery: ErrNotClaimed} |
| + service := Service{Supervisor: s, Source: source} |
| + if err := service.recoverClaims(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + var pending []runnerproto.ClaimRequest |
| + if err := s.journal.readStates(context.Background(), "claim", &pending); err != nil || len(pending) != 0 { |
| + t.Fatal("refused claim still blocks restart", pending, err) |
| + } |
| + if len(source.calls) != 1 || source.calls[0] != q { |
| + t.Fatal("recovery changed request") |
| + } |
| +} |
| + |
| +func TestRunnerLeaseRenewMeasuredAtSend(t *testing.T) { |
| + start := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"} |
| + l, err := newLease(start, start.Wall.Add(time.Minute), start.Wall.Add(10*time.Minute)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := start |
| + sent.Elapsed += 15 * time.Second |
| + sent.Wall = sent.Wall.Add(15 * time.Second) |
| + received := sent |
| + received.Elapsed += 20 * time.Second |
| + received.Wall = received.Wall.Add(20 * time.Second) |
| + if err = l.renewReply(sent, received, received.Wall.Add(time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if l.end != sent.Elapsed+50*time.Second { |
| + t.Fatalf("reply delay extended authority: %v", l.end-sent.Elapsed) |
| + } |
| +} |
| + |
| +func TestRunnerFailedInsertDoesNotBlock(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + s.states = map[string]*attemptState{} |
| + s.ready = true |
| + r.Claim.LeaseDeadline = time.Now().Add(time.Minute) |
| + r.Claim.AttemptDeadline = time.Now().Add(time.Hour) |
| + if err := s.Run(context.Background(), r.Claim); err == nil { |
| + t.Fatal("duplicate insert succeeded") |
| + } |
| + if len(s.states) != 0 { |
| + t.Fatal("failed INSERT poisoned in-memory states") |
| + } |
| +} |
| + |
| +func TestRunnerTransientRetryAndDenial(t *testing.T) { |
| + for _, denied := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "outage", true: "revoked"}[denied], func(t *testing.T) { |
| + calls := 0 |
| + err := retryAuthority(context.Background(), func() error { |
| + calls++ |
| + if denied { |
| + return paseo.ErrIdentity |
| + } |
| + if calls < 3 { |
| + return ErrTransient |
| + } |
| + return nil |
| + }) |
| + if denied { |
| + if !errors.Is(err, paseo.ErrIdentity) || calls != 1 { |
| + t.Fatal("denial retried", calls, err) |
| + } |
| + } else if err != nil || calls != 3 { |
| + t.Fatal("outage aborted", calls, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRunnerRejectedToolsDrainWindow(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + ctx := context.Background() |
| + r.Claim.Assignment.TaskID = "task" |
| + for i := 0; i < 128; i++ { |
| + submission := ToolSubmission{InstanceID: "instance", TaskID: "task", Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, RequestID: fmt.Sprint(i), Name: "submit_review", Arguments: []byte(`{"decision":"reject"}`), Agent: r.Agent} |
| + if err := s.journal.appendTool(ctx, submission, fmt.Sprint(i)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := s.journal.finishTools(ctx, r.Claim, "rejected"); err != nil { |
| + t.Fatal(err) |
| + } |
| + pending, err := s.journal.ToolSubmissions(ctx, 128) |
| + if err != nil || len(pending) != 0 { |
| + t.Fatal("terminal failure left tool window full", len(pending), err) |
| + } |
| + var count int |
| + if err = s.journal.db.QueryRow("SELECT count(*) FROM journal_supervisor WHERE kind='tool-outcome'").Scan(&count); err != nil || count != 128 { |
| + t.Fatal("rejections not recorded", count, err) |
| + } |
| +} |
| + |
| +type creationRecoveryClient struct { |
| + *cleanupClient |
| + workspace paseo.Workspace |
| + agent paseo.Agent |
| + lookups int |
| +} |
| + |
| +func (c *creationRecoveryClient) RecoverWorkspace(context.Context, paseo.WorkspaceRequest) (paseo.Workspace, error) { |
| + c.lookups++ |
| + return c.workspace, nil |
| +} |
| +func (c *creationRecoveryClient) RecoverAgent(context.Context, paseo.AgentRequest) (paseo.Agent, error) { |
| + c.lookups++ |
| + return c.agent, nil |
| +} |
| +func TestRunnerRestartCreationIntents(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + ctx := context.Background() |
| + r.Phase = "creating-workspace" |
| + r.Claim.Assignment.WorkspaceKey = "workspace-key" |
| + ws := r.Owner.Workspace |
| + agent := r.Agent |
| + agent.ProviderSessionID = "session" |
| + agent.WorkspaceID = ws.WorkspaceID |
| + c := &creationRecoveryClient{cleanupClient: s.client.(*cleanupClient), workspace: ws, agent: agent} |
| + s.client = c |
| + r.Owner.LocalOnly = true |
| + r.Owner.Workspace = paseo.Workspace{Path: ws.Path} |
| + r.Agent = paseo.Agent{} |
| + if err := s.save(ctx, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + requests := []paseo.Intent{ |
| + {Kind: "workspace", Key: r.Claim.Assignment.WorkspaceKey, RequestHash: "hash", Request: marshal(paseo.WorkspaceRequest{ResourceID: ws.WorkspaceID, IdempotencyKey: r.Claim.Assignment.WorkspaceKey})}, |
| + {Kind: "agent", Key: r.request("agent").RequestID, RequestHash: "hash", Request: marshal(paseo.AgentRequest{ResourceID: agent.AgentID, Workspace: ws, IdempotencyKey: r.request("agent").RequestID})}, |
| + } |
| + for _, i := range requests { |
| + if err := s.journal.RecordIntent(ctx, i); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := s.Recover(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + saved := s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)] |
| + if c.lookups != 2 || saved.Agent != agent || saved.Owner.Workspace != ws || saved.Owner.LocalOnly { |
| + t.Fatal("creation intent not recovered before cleanup", c.lookups, saved.Owner, saved.Agent) |
| + } |
| +} |
| + |
| +type personWaitAPI struct { |
| + question runnerproto.Question |
| + answers int |
| + denied bool |
| +} |
| + |
| +func (a *personWaitAPI) Call(_ context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| + switch op { |
| + case "questions": |
| + a.question = *q.Question |
| + *(out.(*runnerproto.Question)) = a.question |
| + case "answers": |
| + a.answers++ |
| + if a.denied { |
| + return paseo.ErrIdentity |
| + } |
| + if a.answers < 3 { |
| + return ErrTransient |
| + } |
| + value := a.question |
| + value.Answer = &runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: []byte(`{"answers":{"answer":"The first case"}}`)} |
| + *(out.(*[]runnerproto.Question)) = []runnerproto.Question{value} |
| + case "question_resolved": |
| + default: |
| + return paseo.ErrContract |
| + } |
| + return nil |
| +} |
| +func TestRunnerPersonWaitTransientAndRevoked(t *testing.T) { |
| + for _, denied := range []bool{false, true} { |
| + t.Run(fmt.Sprint(denied), func(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + ctx := context.Background() |
| + r.Claim.Assignment.TaskID = "task" |
| + r.Agent.ProviderSessionID = "session" |
| + v := ToolSubmission{InstanceID: "instance", TaskID: "task", Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, RequestID: "ask", Name: "ask_person", Arguments: []byte(`{"question":"Which case?"}`), Agent: r.Agent} |
| + if err := s.journal.appendTool(ctx, v, "hash"); err != nil { |
| + t.Fatal(err) |
| + } |
| + witness, err := NewWitness(s.journal) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := &BugWorkflow{cfg: BugWorkflowConfig{Witness: witness}} |
| + api := &personWaitAPI{denied: denied} |
| + s.api = api |
| + now, err := s.clock.Read() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + l, err := newLease(now, now.Wall.Add(time.Minute), now.Wall.Add(time.Hour)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + checks := 0 |
| + answer, asked, err := w.personFollowup(ctx, s, r, l, func(context.Context) error { checks++; return nil }) |
| + if denied { |
| + if !errors.Is(err, paseo.ErrIdentity) || api.answers != 1 { |
| + t.Fatal("revocation did not stop wait", err, api.answers) |
| + } |
| + } else if err != nil || !asked || answer != "The first case" || api.answers != 3 || checks != 1 { |
| + t.Fatal("transient outage ended person wait", answer, asked, err, api.answers, checks) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type refusedClaimSource struct { |
| + calls []runnerproto.ClaimRequest |
| + polls int |
| + transient bool |
| +} |
| + |
| +func (s *refusedClaimSource) Poll(context.Context) ([]runnerproto.Assignment, error) { |
| + s.polls++ |
| + if s.polls > 1 { |
| + return nil, context.Canceled |
| + } |
| + return []runnerproto.Assignment{{ID: "refused", Revision: 2}}, nil |
| +} |
| +func (s *refusedClaimSource) Claim(_ context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| + s.calls = append(s.calls, q) |
| + if s.transient && len(s.calls) == 1 { |
| + return runnerproto.ClaimResponse{}, ErrTransient |
| + } |
| + return runnerproto.ClaimResponse{}, ErrClaimRefused |
| +} |
| +func TestRunnerRefusedClaimClearedAndUnknownRetried(t *testing.T) { |
| + for _, transient := range []bool{false, true} { |
| + t.Run(fmt.Sprint(transient), func(t *testing.T) { |
| + s, _, _, _ := cleanupFixture(t) |
| + source := &refusedClaimSource{transient: transient} |
| + service := Service{Supervisor: s, Source: source} |
| + if err := service.Run(context.Background()); !errors.Is(err, context.Canceled) { |
| + t.Fatal(err) |
| + } |
| + var claims []runnerproto.ClaimRequest |
| + if err := s.journal.readStates(context.Background(), "claim", &claims); err != nil || len(claims) != 0 { |
| + t.Fatal("refusal persisted", claims, err) |
| + } |
| + if transient && (len(source.calls) != 2 || source.calls[0] != source.calls[1]) { |
| + t.Fatal("unknown claim changed request", source.calls) |
| + } |
| + if err := service.recoverClaims(context.Background()); err != nil { |
| + t.Fatal("refused claim blocked restart", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type stopErrorAPI struct{} |
| + |
| +func (stopErrorAPI) Call(_ context.Context, op string, _ runnerproto.RunnerRequest, _ any) error { |
| + if op == "stop" { |
| + return ErrTransient |
| + } |
| + return nil |
| +} |
| +func TestCancelReportsStopErrorAfterLocalCleanup(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + s.api = stopErrorAPI{} |
| + proof, err := s.Cancel(context.Background(), r.Claim.Scope, r.Claim.Handle) |
| + if !proof.Empty || !errors.Is(err, ErrTransient) { |
| + t.Fatal("stop error was swallowed or prevented local cleanup", proof.Empty, err) |
| + } |
| +} |
diff --git a/internal/runner/supervisor_test.go b/internal/runner/supervisor_test.go| index 1400d91b..501d5636 100644 |
| --- a/internal/runner/supervisor_test.go |
| +++ b/internal/runner/supervisor_test.go |
| @@ -279,17 +279,19 @@ func TestRunnerRestartCleansEveryAttempt(t *testing.T) { |
| } |
| func TestCancelSurvivingBackgroundChild(t *testing.T) { |
| - p, o := processFixture(t) |
| + if privateProcTest(t) { |
| + return |
| + } |
| + p, o := realInspector(t) |
| control := childProcess(t, t.TempDir(), "control") |
| - linkProcess(t, p.root, control.Process.Pid) |
| + time.Sleep(20 * time.Millisecond) |
| ctx := context.Background() |
| if err := p.Track(ctx, o); err != nil { |
| t.Fatal(err) |
| } |
| child := childProcess(t, o.Workspace.Path, "") |
| - linkProcess(t, p.root, child.Process.Pid) |
| inv, err := p.Remaining(ctx, o) |
| - if err != nil || !inv.CoverageKnown || len(inv.Processes) != 1 { |
| + if err != nil || !inv.CoverageKnown || len(inv.Processes) != 1 || inv.Processes[0].PID != child.Process.Pid { |
| t.Fatalf("child attribution: %+v %v", inv, err) |
| } |
| s, r, _, _ := cleanupFixture(t) |
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go| index 7cf9aaff..804e11d4 100644 |
| --- a/internal/runner/tool_journal.go |
| +++ b/internal/runner/tool_journal.go |
| @@ -104,3 +104,47 @@ func (j *Journal) AckTool(ctx context.Context, v ToolSubmission) error { |
| } |
| return nil |
| } |
| + |
| +func (j *Journal) finishTools(ctx context.Context, c RunClaim, outcome string) error { |
| + tx, err := j.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + rows, err := tx.QueryContext(ctx, `SELECT request_key FROM journal_tools WHERE acked=0 AND json_extract(body,'$.task_id')=? AND json_extract(body,'$.attempt')=? AND json_extract(body,'$.fence')=?`, c.Assignment.TaskID, c.Handle.Attempt, c.Handle.Fence) |
| + if err != nil { |
| + return err |
| + } |
| + var keys []string |
| + for rows.Next() { |
| + var key string |
| + if err = rows.Scan(&key); err != nil { |
| + rows.Close() |
| + return err |
| + } |
| + keys = append(keys, key) |
| + } |
| + err = rows.Err() |
| + closeErr := rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + if closeErr != nil { |
| + return closeErr |
| + } |
| + body, err := json.Marshal(struct { |
| + Outcome string `json:"outcome"` |
| + }{outcome}) |
| + if err != nil { |
| + return err |
| + } |
| + for _, key := range keys { |
| + if _, err = tx.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES('tool-outcome',?,?) ON CONFLICT(kind,state_key) DO NOTHING", key, body); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, "UPDATE journal_tools SET acked=1 WHERE request_key=?", key); err != nil { |
| + return err |
| + } |
| + } |
| + return tx.Commit() |
| +} |
diff --git a/internal/runner/witness.go b/internal/runner/witness.go| index eca0db4b..8c12d80f 100644 |
| --- a/internal/runner/witness.go |
| +++ b/internal/runner/witness.go |
| @@ -5,7 +5,6 @@ import ( |
| "context" |
| "database/sql" |
| "encoding/json" |
| - "sync" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runner/checks" |
| @@ -17,16 +16,14 @@ import ( |
| // Witness validates against supervisor observations, never submitted labels. |
| // Its journal must be provided by the trusted runner transport at startup. |
| type Witness struct { |
| - journal *Journal |
| - mu sync.Mutex |
| - executors map[string]*checks.Executor |
| + journal *Journal |
| } |
| func NewWitness(j *Journal) (*Witness, error) { |
| if j == nil { |
| return nil, paseo.ErrContract |
| } |
| - return &Witness{journal: j, executors: map[string]*checks.Executor{}}, nil |
| + return &Witness{journal: j}, nil |
| } |
| func (w *Witness) record(ctx context.Context, kind, key string, v any) error { |
| return w.journal.saveState(ctx, "witness-"+kind, key, v) |
| @@ -85,23 +82,25 @@ func (w *Witness) Provenance(ctx context.Context, _ *sql.Tx, scope team.Scope, h |
| } |
| return team.Provenance{Producer: a.AgentID, Provider: a.Provider, ModelFamily: a.Family, Context: a.ProviderSessionID}, nil |
| } |
| -func (w *Witness) installExecutor(c RunClaim, e *checks.Executor) { |
| - w.mu.Lock() |
| - defer w.mu.Unlock() |
| - w.executors[attemptKey(c.Scope, c.Handle)] = e |
| +func (w *Witness) installExecutor(_ RunClaim, e *checks.Executor) { e.SetAttestationStore(w) } |
| +func (w *Witness) SaveAttestation(ctx context.Context, key string, p team.Provenance) error { |
| + return w.record(ctx, "executor", key, p) |
| } |
| -func (w *Witness) ExecutorEvidence(ctx context.Context, tx *sql.Tx, scope team.Scope, h team.Handle, spec team.ArtifactSpec) (team.Provenance, error) { |
| - w.mu.Lock() |
| - e := w.executors[attemptKey(scope, h)] |
| - w.mu.Unlock() |
| - if e == nil { |
| - return team.Provenance{}, paseo.ErrUncertain |
| +func (w *Witness) LoadAttestation(ctx context.Context, key string) (team.Provenance, error) { |
| + var p team.Provenance |
| + err := w.read(ctx, "executor", key, &p) |
| + return p, err |
| +} |
| +func (w *Witness) ExecutorEvidence(ctx context.Context, _ *sql.Tx, scope team.Scope, h team.Handle, spec team.ArtifactSpec) (team.Provenance, error) { |
| + p, err := w.LoadAttestation(ctx, checks.AttestationKey(scope, h, spec)) |
| + if err != nil || p.Producer != "equipo-checks" || p.Provider != "executor" || p.Context != h.Runner { |
| + return team.Provenance{}, paseo.ErrIdentity |
| } |
| - return e.ValidateEvidence(ctx, tx, scope, h, spec) |
| + return p, nil |
| } |
| func (w *Witness) Events(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) error { |
| var e runnerproto.Event |
| - if json.Unmarshal(q.Event, &e) != nil || e.Validate() != nil || e.AssignmentID != a.ID { |
| + if runnerproto.DecodeLimit(bytes.NewReader(q.Event), &e, runnerproto.MaxEventBytes+4096) != nil || e.Validate() != nil || e.AssignmentID != a.ID { |
| return paseo.ErrIdentity |
| } |
| var raw []byte |
diff --git a/internal/runner/workflow.go b/internal/runner/workflow.go| index 66585891..5fdf3f73 100644 |
| --- a/internal/runner/workflow.go |
| +++ b/internal/runner/workflow.go |
| @@ -47,13 +47,16 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| return err |
| } |
| ctx, stopMonitoring := monitorOwnership(ctx, s.inspector, r.Owner) |
| - defer stopMonitoring() |
| + s.monitorStop = stopMonitoring |
| inspector, ok := s.inspector.(*LinuxProcessInspector) |
| if !ok { |
| return paseo.ErrContract |
| } |
| ctx = checks.WithProcessOwnership(ctx, r.Owner.Marker, func(ctx context.Context, pid int) error { return inspector.TrackPID(ctx, r.Owner, pid) }) |
| + ctx = runnerproto.WithCommandOwnership(ctx, func(ctx context.Context, pid int, command string) error { |
| + return inspector.BeginCommand(ctx, r.Owner, pid, command) |
| + }, func(ctx context.Context, command string) error { return inspector.EndCommand(ctx, r.Owner, command) }) |
| prepared, err := w.cfg.Witness.PrepareBug(ctx, w.cfg.Workspaces, r.Claim.Assignment, r.Claim.Brief.Target) |
| if err != nil { |
| return err |
| @@ -69,10 +72,14 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| r.Phase = "prepared" |
| return s.save(ctx, r) |
| } |
| + r.Owner = ProcessOwner{LocalOnly: true, Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: attemptKey(r.Claim.Scope, r.Claim.Handle), Workspace: paseo.Workspace{Path: w.cfg.Workspaces.PreparationDirectory()}} |
| r.Phase = "creating-workspace" |
| if err := s.save(ctx, r); err != nil { |
| return err |
| } |
| + if err := s.inspector.Track(ctx, r.Owner); err != nil { |
| + return err |
| + } |
| ws, err := w.cfg.Workspaces.Create(ctx, r.Claim.Assignment, r.Claim.Brief) |
| if err != nil { |
| return err |
| @@ -86,7 +93,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| return err |
| } |
| ctx, stopMonitoring := monitorOwnership(ctx, s.inspector, r.Owner) |
| - defer stopMonitoring() |
| + s.monitorStop = stopMonitoring |
| owner := r.Owner |
| policy, err := w.cfg.Policy(ctx, selection(r.Claim.Assignment)) |
| if err != nil { |
| @@ -101,10 +108,10 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if err = l.check(now); err != nil { |
| return err |
| } |
| - if err = w.cfg.Workspaces.ValidateTurn(ctx, r.Claim.Assignment, ws); err != nil { |
| + if err = retryAuthority(ctx, func() error { return remoteError(w.cfg.Workspaces.ValidateTurn(ctx, r.Claim.Assignment, ws)) }); err != nil { |
| return err |
| } |
| - if err = s.api.Call(ctx, "validate", r.request("validate"), nil); err != nil { |
| + if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "validate", r.request("validate"), nil) }); err != nil { |
| return err |
| } |
| if r.Agent.AgentID != "" { |
| @@ -121,6 +128,9 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| } |
| return nil |
| } |
| + s.mu.Lock() |
| + s.activeCurrent = current |
| + s.mu.Unlock() |
| step := r.Claim.Assignment.StepKey |
| var artifacts []team.Artifact |
| if err = s.api.Call(ctx, "evidence", r.request("evidence"), &artifacts); err != nil { |
| @@ -195,13 +205,16 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if err != nil { |
| return err |
| } |
| - agent, err := w.cfg.Client.CreateAgent(ctx, paseo.AgentRequest{ProviderOptions: options, Workspace: ws.Paseo, Selection: selection(r.Claim.Assignment), IdempotencyKey: r.request("agent").RequestID, ModeID: "default", ReadPolicy: policy, Env: env, MCPServers: map[string]paseo.MCPServer{"equipo": mcp}}) |
| + agent, err := w.cfg.Client.CreateAgent(ctx, paseo.AgentRequest{ResourceID: paseo.CreationID("agent", r.request("agent").RequestID), ProviderOptions: options, Workspace: ws.Paseo, Selection: selection(r.Claim.Assignment), IdempotencyKey: r.request("agent").RequestID, ModeID: "default", ReadPolicy: policy, Env: env, MCPServers: map[string]paseo.MCPServer{"equipo": mcp}}) |
| if err != nil { |
| return err |
| } |
| r.Agent = agent |
| r.Owner.AgentID = agent.AgentID |
| r.Phase = "tracking-agent" |
| + if err = s.save(ctx, r); err != nil { |
| + return err |
| + } |
| if err = s.inspector.Track(ctx, r.Owner); err != nil { |
| return err |
| } |
| @@ -230,6 +243,11 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| return team.Artifact{}, err |
| } |
| spec := team.ArtifactSpec{Role: role, MediaType: "application/json", Payload: raw} |
| + if role == team.RoleBaseResult || role == team.RoleCandidateResult || role == team.RoleRepositoryChecks { |
| + if _, err = w.cfg.Witness.ExecutorEvidence(ctx, nil, r.Claim.Scope, r.Claim.Handle, spec); err != nil { |
| + return team.Artifact{}, err |
| + } |
| + } |
| if role == team.RoleCandidate { |
| spec.MediaType = team.GitCandidateMediaType |
| } |
| @@ -318,7 +336,10 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| return paseo.ErrContract |
| } |
| ctx = checks.WithProcessOwnership(ctx, r.Owner.Marker, func(ctx context.Context, pid int) error { return inspector.TrackPID(ctx, r.Owner, pid) }) |
| - executor, err := w.cfg.Executor(ctx, r.Claim, definition, reproduction, l.bound()) |
| + ctx = runnerproto.WithCommandOwnership(ctx, func(ctx context.Context, pid int, command string) error { |
| + return inspector.BeginCommand(ctx, r.Owner, pid, command) |
| + }, func(ctx context.Context, command string) error { return inspector.EndCommand(ctx, r.Owner, command) }) |
| + executor, err := w.cfg.Executor(ctx, r.Claim, definition, reproduction, r.Claim.AttemptDeadline) |
| if err != nil { |
| return err |
| } |
| @@ -376,6 +397,7 @@ func reviewVerdict(decision string) team.Verdict { |
| func monitorOwnership(parent context.Context, inspector ProcessInspector, owner ProcessOwner) (context.Context, func()) { |
| ctx, cancel := context.WithCancel(parent) |
| + sampling, stop := context.WithCancel(context.WithoutCancel(parent)) |
| done := make(chan struct{}) |
| go func() { |
| defer close(done) |
| @@ -383,16 +405,21 @@ func monitorOwnership(parent context.Context, inspector ProcessInspector, owner |
| defer ticker.Stop() |
| for { |
| select { |
| - case <-ctx.Done(): |
| + case <-sampling.Done(): |
| return |
| case <-ticker.C: |
| - inv, err := inspector.Remaining(context.WithoutCancel(ctx), owner) |
| + var inv ProcessInventory |
| + var err error |
| + if local, ok := inspector.(*LinuxProcessInspector); ok { |
| + inv, err = local.observe(sampling, owner) |
| + } else { |
| + inv, err = inspector.Remaining(sampling, owner) |
| + } |
| if err != nil || !inv.CoverageKnown { |
| cancel() |
| - return |
| } |
| } |
| } |
| }() |
| - return ctx, func() { cancel(); <-done } |
| + return ctx, func() { stop(); cancel(); <-done } |
| } |
diff --git a/internal/runner/workflow_integration_test.go b/internal/runner/workflow_integration_test.go| index 3e22077a..04b8c730 100644 |
| --- a/internal/runner/workflow_integration_test.go |
| +++ b/internal/runner/workflow_integration_test.go |
| @@ -4,11 +4,11 @@ import ( |
| "context" |
| "database/sql" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| "os" |
| "os/exec" |
| "path/filepath" |
| - "runtime" |
| "strings" |
| "testing" |
| "time" |
| @@ -116,7 +116,7 @@ func (a *coreWorkflowAPI) Call(ctx context.Context, op string, q runnerproto.Run |
| err = a.w.Events(ctx, assignment, q) |
| if err == nil { |
| var e Event |
| - json.Unmarshal(q.Event, &e) |
| + runnerproto.DecodeLimit(strings.NewReader(string(q.Event)), &e, runnerproto.MaxEventBytes+4096) |
| if e.Kind == "turn_completed" || e.Kind == "turn_failed" { |
| var receipt team.Receipt |
| receipt, err = a.w.Receipt(ctx, assignment, q) |
| @@ -154,7 +154,9 @@ func (a *coreWorkflowAPI) Call(ctx context.Context, op string, q runnerproto.Run |
| } |
| return nil |
| } |
| -func TestRunnerBugWorkflow(t *testing.T) { |
| +func TestRunnerBugWorkflow(t *testing.T) { runBugWorkflow(t, false) } |
| +func TestRunnerBugWorkflowRejectedTools(t *testing.T) { runBugWorkflow(t, true) } |
| +func runBugWorkflow(t *testing.T, reject bool) { |
| ctx := context.Background() |
| root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-") |
| wfMust(t, err) |
| @@ -175,6 +177,9 @@ func TestRunnerBugWorkflow(t *testing.T) { |
| proc := isolatedProc(t) |
| bridge := filepath.Join(root, "bridge.mjs") |
| script := fmt.Sprintf(workflowBridge, proc) |
| + if reject { |
| + script = strings.Replace(script, "decision:'approve'", "decision:'changes_requested'", 1) |
| + } |
| wfMust(t, os.WriteFile(bridge, []byte(script), 0600)) |
| policy := paseo.ReadPolicy{ConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", DeniedPaths: []string{state, private}} |
| client, err := paseo.Start(ctx, paseo.Config{NodePath: "/usr/local/bin/node", BridgePath: bridge, DaemonHome: state, Endpoint: "127.0.0.1:1", ServerID: "server", RecordIntent: j.RecordIntent, InspectProcesses: func(context.Context, paseo.Selection) (bool, error) { return true, nil }, AuthorizeUnconfined: func(context.Context, paseo.Selection, paseo.Capabilities) error { return nil }, VerifiedTuples: []paseo.VerifiedTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", ConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}}) |
| @@ -195,7 +200,11 @@ func TestRunnerBugWorkflow(t *testing.T) { |
| protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: filepath.Join(state, "config"), Journal: filepath.Join(state, "j.db"), Bearer: filepath.Join(state, "bearer"), Cleanup: filepath.Join(state, "cleanup"), ForgeCredential: filepath.Join(state, "forge"), PaseoHome: filepath.Join(state, "paseo"), ProviderHomes: []string{filepath.Join(state, "provider")}, SSH: filepath.Join(state, "ssh")} |
| codex, err := exec.LookPath("codex") |
| wfMust(t, err) |
| - goRoot := runtime.GOROOT() |
| + goBinary, err := exec.LookPath("go") |
| + wfMust(t, err) |
| + goBinary, err = filepath.EvalSymlinks(goBinary) |
| + wfMust(t, err) |
| + goRoot := filepath.Dir(filepath.Dir(goBinary)) |
| sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: codex, ScratchRoot: scratch, GoRoot: goRoot, GoBinary: filepath.Join(goRoot, "bin/go"), Protected: protected}) |
| wfMust(t, err) |
| iso := team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", IsolationConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} |
| @@ -204,6 +213,9 @@ func TestRunnerBugWorkflow(t *testing.T) { |
| var pinned checks.Definition |
| var repo string |
| executor := func(ctx context.Context, c RunClaim, d checks.Definition, r checks.Reproduction, deadline time.Time) (*checks.Executor, error) { |
| + if c.Handle.Attempt > 0 && !deadline.Equal(c.AttemptDeadline) { |
| + return nil, fmt.Errorf("executor got lease snapshot instead of attempt deadline") |
| + } |
| return checks.New(checks.Config{ScratchRoot: scratch, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(r)), Reproduction: func(context.Context, string) (checks.Reproduction, error) { return r, nil }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return c.Brief.Selection.Isolation, nil }, ResolveCandidate: func(ctx context.Context, hash string) (team.GitCandidate, error) { |
| arts, err := apiArtifacts(ctx, w, c) |
| if err != nil { |
| @@ -337,13 +349,29 @@ func TestRunnerBugWorkflow(t *testing.T) { |
| } |
| claim := RunClaim{Assignment: a, ClaimResponse: runnerproto.ClaimResponse{Scope: scope, Handle: h, Brief: runnerproto.RunnerBrief{Target: target, Selection: sel, Policy: pol, CheckDefinition: marshal(pinned), ArtifactHashes: hashes}, AttemptDeadline: time.Now().Add(20 * time.Minute), LeaseDeadline: time.Now().Add(60 * time.Second)}} |
| if err = s.Run(ctx, claim); err != nil { |
| + if reject && step == "review" && errors.Is(err, team.ErrEvidence) { |
| + pending, e := j.ToolSubmissions(ctx, 128) |
| + wfMust(t, e) |
| + if len(pending) != 0 || s.states[attemptKey(scope, h)].Phase != "contained" { |
| + t.Fatal("rejected review was not drained and contained", len(pending)) |
| + } |
| + var outcomes int |
| + wfMust(t, j.db.QueryRow("SELECT count(*) FROM journal_supervisor WHERE kind='tool-outcome' AND json_extract(body,'$.outcome')='rejected'").Scan(&outcomes)) |
| + if outcomes != 1 { |
| + t.Fatal("review rejection not recorded", outcomes) |
| + } |
| + return |
| + } |
| for _, v := range inspector.records { |
| - t.Log("coverage", v.Owner.Attempt, v.Unknown, v.UnknownStage, v.UnknownPID) |
| + t.Log("coverage", v.Owner.Attempt, v.TrackTicks, v.TrackBoot) |
| } |
| b, _ := os.ReadFile(filepath.Join(proc, "failure")) |
| t.Fatalf("%s (%s): %v %s", step, s.states[attemptKey(scope, h)].FailurePhase, err, b) |
| } |
| } |
| + if reject { |
| + t.Fatal("rejected review published") |
| + } |
| entries, err := os.ReadDir(filepath.Join(state, "admissions")) |
| wfMust(t, err) |
| consumed := 0 |
| @@ -391,8 +419,8 @@ readline.createInterface({input:process.stdin}).on('line',async line=>{const q=J |
| case 'provider_policy':result={fixture:true};break; |
| case 'preflight':result={version:'0.14.0',server_id:'server',provider_version:p.selection.provider==='claude'?'2.1.312':'0.165.0',paseo_version:'0.14.0',account_pinning:true,observed_account:'account',no_failover:true,recoverable_timeline:true,process_ownership:true,mcp_at_create:true,read_isolation:true,isolation_config_hash:'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'};break; |
| case 'register_project':result={server_id:'server',project_id:p.path,path:p.path};break; |
| -case 'create_workspace':{const path=p.path+'-work';git(p.path,['worktree','add','-b',p.branch,path,p.base_commit]);result={server_id:'server',project_id:p.project_id,workspace_id:p.idempotency_key,path};break;} |
| -case 'create_agent':{if(!p.provider_options?.fixture) throw Error('missing creation policy');const a={server_id:'server',agent_id:'agent'+(++n),provider_session_id:'session'+n,workspace_id:p.workspace.workspace_id,account_id:'account',provider:p.selection.provider,family:p.selection.family,model:p.selection.model};const child=spawn('/bin/sleep',['60'],{cwd:p.workspace.path,env:p.env,stdio:'ignore'});fs.symlinkSync('/proc/'+child.pid,proc+'/'+child.pid);agents.set(a.agent_id,{request:p,child});result=a;break;} |
| +case 'create_workspace':{const path=p.path+'-work';git(p.path,['worktree','add','-b',p.branch,path,p.base_commit]);result={server_id:'server',project_id:p.project_id,workspace_id:p.resource_id||p.idempotency_key,path};break;} |
| +case 'create_agent':{if(!p.provider_options?.fixture) throw Error('missing creation policy');const a={server_id:'server',agent_id:p.resource_id||'agent'+n,provider_session_id:'session'+(++n),workspace_id:p.workspace.workspace_id,account_id:'account',provider:p.selection.provider,family:p.selection.family,model:p.selection.model};const child=spawn('/bin/sleep',['60'],{cwd:p.workspace.path,env:p.env,stdio:'ignore'});fs.symlinkSync('/proc/'+child.pid,proc+'/'+child.pid);agents.set(a.agent_id,{request:p,child});result=a;break;} |
| case 'subscribe':subs.set(p.agent.agent_id,p.subscription_id);event(p.agent,'timeline_replacement');break; |
| case 'send':{const a=p.agent,request=agents.get(a.agent_id).request,message=JSON.parse(p.message),step=message.Step;let name,args;++turn; |
| if(step==='reproduce'){name='submit_reproduction';args={expected_symptom:'wrong value',files:[{path:'bug_test.go',bytes:Buffer.from('package fixture\nimport "testing"\nfunc TestBug(t *testing.T){if Value()!=2 {t.Fatal("wrong value")}}\n').toString('base64')}],test_names:[{package:'fixture',name:'TestBug'}]};} |
diff --git a/internal/runner/workflow_turn.go b/internal/runner/workflow_turn.go| index 72e49b23..04a119e5 100644 |
| --- a/internal/runner/workflow_turn.go |
| +++ b/internal/runner/workflow_turn.go |
| @@ -33,7 +33,11 @@ func (w *BugWorkflow) modelTurn(ctx context.Context, s *Supervisor, r *attemptSt |
| pump := EventPump{Journal: s.journal, Upload: func(ctx context.Context, e Event) error { |
| q := r.request(e.ID) |
| q.RequestID = e.ID |
| - q.Event = marshal(e) |
| + var err error |
| + q.Event, err = runnerproto.Marshal(e) |
| + if err != nil { |
| + return err |
| + } |
| q.ActionID = e.ActionID |
| return s.api.Call(ctx, "events", q, nil) |
| }, Contain: func(context.Context) error { return paseo.ErrUncertain }} |
| @@ -141,7 +145,7 @@ drained: |
| q := r.request("turn-intent-" + suffix) |
| q.Intent = &team.IntentSpec{Key: q.RequestID, Operation: team.OpProviderCall, Payload: marshal(map[string]string{"provider": r.Agent.Provider, "model": r.Agent.Model, "prompt": message}), Reserve: team.Usage{Calls: 1, InputTokens: 32000, OutputTokens: 4000, CostUnavailable: true}} |
| var intent team.ActionID |
| - if err := s.api.Call(ctx, "intend", q, &intent); err != nil { |
| + if err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "intend", q, &intent) }); err != nil { |
| return err |
| } |
| action = intent |
| @@ -152,7 +156,7 @@ drained: |
| return err |
| } |
| var ticket team.AdmissionTicket |
| - if err := s.api.Call(ctx, "admit", q, &ticket); err != nil { |
| + if err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "admit", q, &ticket) }); err != nil { |
| return err |
| } |
| if err := current(ctx); err != nil { |
| @@ -161,24 +165,15 @@ drained: |
| if err := runnerproto.ConsumeTicket(dir, q.RequestID, ticket, time.Now().UTC(), ticket.Incarnation); err != nil { |
| return err |
| } |
| - return w.cfg.Client.Send(ctx, r.Agent, message, q.RequestID) |
| + return retryAuthority(ctx, func() error { return remoteError(w.cfg.Client.Send(ctx, r.Agent, message, q.RequestID)) }) |
| } |
| if err = dispatch(); err != nil { |
| return err |
| } |
| - refresh := time.NewTicker(100 * time.Millisecond) |
| - defer refresh.Stop() |
| for { |
| select { |
| case <-ctx.Done(): |
| return ctx.Err() |
| - case <-refresh.C: |
| - if err = current(ctx); err != nil { |
| - return err |
| - } |
| - if err = socket.RenewLease(ctx, l.bound()); err != nil { |
| - return err |
| - } |
| case e, ok := <-sub.Events: |
| if !ok { |
| return paseo.ErrUncertain |
| @@ -210,7 +205,7 @@ drained: |
| }} |
| if err = relay.Wait(ctx, saved, func(ctx context.Context) (*runnerproto.QuestionAnswer, error) { |
| var answers []runnerproto.Question |
| - err := s.api.Call(ctx, "answers", r.request("answers"), &answers) |
| + err := retryAuthority(ctx, func() error { return s.api.Call(ctx, "answers", r.request("answers"), &answers) }) |
| if err != nil { |
| return nil, err |
| } |
| @@ -326,20 +321,20 @@ func (w *BugWorkflow) personFollowup(ctx context.Context, s *Supervisor, r *atte |
| if err = s.api.Call(ctx, "questions", request, &saved); err != nil { |
| return "", true, err |
| } |
| - ticker := time.NewTicker(100 * time.Millisecond) |
| + ticker := time.NewTicker(time.Duration(runnerproto.LongPollSeconds) * time.Second) |
| defer ticker.Stop() |
| for { |
| - if err = current(ctx); err != nil { |
| - return "", true, err |
| - } |
| var answers []runnerproto.Question |
| - if err = s.api.Call(ctx, "answers", r.request("answers"), &answers); err != nil { |
| + if err = retryAuthority(ctx, func() error { return s.api.Call(ctx, "answers", r.request("answers"), &answers) }); err != nil { |
| return "", true, err |
| } |
| for _, answer := range answers { |
| if answer.ID != saved.ID || answer.Answer == nil { |
| continue |
| } |
| + if err = current(ctx); err != nil { |
| + return "", true, err |
| + } |
| if saved.ValidateAnswer(*answer.Answer) != nil || answer.Answer.Behavior != "allow" { |
| return "", true, paseo.ErrIdentity |
| } |
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go| index 2c90b209..7e8a5b55 100644 |
| --- a/internal/runner/workspace/workspace.go |
| +++ b/internal/runner/workspace/workspace.go |
| @@ -454,7 +454,7 @@ func (m *Manager) Create(ctx context.Context, a runnerproto.Assignment, brief ru |
| if project.ProjectID == "" || project.Path != source || project.ServerID == "" { |
| return zero, paseo.ErrUncertain |
| } |
| - at = attempt{AssignmentHash: digest(a), Hash: hash, Request: paseo.WorkspaceRequest{Isolation: "worktree", ProjectID: project.ProjectID, Path: source, BaseCommit: brief.Target.BaseRevision, Branch: brief.Target.Ref, IdempotencyKey: a.WorkspaceKey, Selection: selection(a), ReadPolicy: policy}, Target: brief.Target, ArtifactHashes: append([]string(nil), brief.ArtifactHashes...), Isolation: a.Selection.Isolation} |
| + at = attempt{AssignmentHash: digest(a), Hash: hash, Request: paseo.WorkspaceRequest{ResourceID: paseo.CreationID("workspace", a.WorkspaceKey), Isolation: "worktree", ProjectID: project.ProjectID, Path: source, BaseCommit: brief.Target.BaseRevision, Branch: brief.Target.Ref, IdempotencyKey: a.WorkspaceKey, Selection: selection(a), ReadPolicy: policy}, Target: brief.Target, ArtifactHashes: append([]string(nil), brief.ArtifactHashes...), Isolation: a.Selection.Isolation} |
| if e = save(record, at); e != nil { |
| return zero, e |
| } |
diff --git a/internal/runnerproto/ownership.go b/internal/runnerproto/ownership.go| index 35873f60..c52c3a90 100644 |
| --- a/internal/runnerproto/ownership.go |
| +++ b/internal/runnerproto/ownership.go |
| @@ -15,3 +15,17 @@ func ProcessOwnership(ctx context.Context) (string, func(context.Context, int) e |
| v, _ := ctx.Value(ownershipKey{}).(ownership) |
| return v.marker, v.track |
| } |
| + |
| +type commandOwnershipKey struct{} |
| +type commandOwnership struct { |
| + Begin func(context.Context, int, string) error |
| + End func(context.Context, string) error |
| +} |
| + |
| +func WithCommandOwnership(ctx context.Context, begin func(context.Context, int, string) error, end func(context.Context, string) error) context.Context { |
| + return context.WithValue(ctx, commandOwnershipKey{}, commandOwnership{begin, end}) |
| +} |
| +func CommandOwnership(ctx context.Context) (func(context.Context, int, string) error, func(context.Context, string) error) { |
| + v, _ := ctx.Value(commandOwnershipKey{}).(commandOwnership) |
| + return v.Begin, v.End |
| +} |
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go| index 9294bdba..fd9f75e5 100644 |
| --- a/internal/runnerproto/types.go |
| +++ b/internal/runnerproto/types.go |
| @@ -103,7 +103,7 @@ type WorkResponse struct { |
| type HeartbeatRequest struct { |
| RequestID string `json:"request_id"` |
| Version int `json:"version"` |
| - Reports json.RawMessage `json:"reports"` |
| + Reports json.RawMessage `json:"reports,omitempty"` |
| RotationRequestID string `json:"rotation_request_id,omitempty"` |
| } |
| type Delivery struct { |
| @@ -157,6 +157,7 @@ type RunnerBrief struct { |
| } |
| type ClaimResponse struct { |
| + NotClaimed bool `json:"not_claimed,omitempty"` |
| AttemptDeadline time.Time `json:"attempt_deadline"` |
| Scope Scope `json:"scope"` |
| Handle team.Handle `json:"handle"` |
diff --git a/runner/paseo/bridge.mjs b/runner/paseo/bridge.mjs| index 112ba55e..d728f555 100644 |
| --- a/runner/paseo/bridge.mjs |
| +++ b/runner/paseo/bridge.mjs |
| @@ -152,17 +152,17 @@ export class Bridge { |
| return { server_id: status.serverId, project_id: result.project.projectId, path: result.project.projectRootPath }; |
| } |
| async createWorkspace(r) { |
| - keys(r, ['project_id', 'path', 'base_commit', 'branch', 'idempotency_key', 'selection', 'read_policy', 'isolation']); |
| + keys(r, ['resource_id', 'project_id', 'path', 'base_commit', 'branch', 'idempotency_key', 'selection', 'read_policy', 'isolation']); |
| if (r.isolation !== 'worktree') fail('invalid_request'); |
| allowedPath(r.path, r.read_policy); |
| const status = await this.status(); |
| if (status.version !== VERSION) fail('unsupported_daemon_version'); |
| if (!text(r.project_id) || !text(r.idempotency_key) || !/^[a-f0-9]{40,64}$/.test(r.base_commit) || !text(r.branch)) fail('invalid_request'); |
| this.creationReceipts(); |
| - const result = await this.client.createWorkspace({ source: { kind: 'worktree', cwd: r.path, projectId: r.project_id, action: 'branch-off', refName: r.base_commit, branchName: r.branch }, idempotencyKey: r.idempotency_key }); |
| + const result = await this.client.createWorkspace({ workspaceId: r.resource_id, source: { kind: 'worktree', cwd: r.path, projectId: r.project_id, action: 'branch-off', refName: r.base_commit, branchName: r.branch }, idempotencyKey: r.idempotency_key }); |
| if (result.error || !result.workspace) fail('uncertain'); |
| const w = result.workspace; |
| - if (!text(w.id) || w.projectId !== r.project_id || !text(w.workspaceDirectory)) fail('identity_mismatch'); |
| + if ((r.resource_id && w.id !== r.resource_id) || !text(w.id) || w.projectId !== r.project_id || !text(w.workspaceDirectory)) fail('identity_mismatch'); |
| allowedPath(w.workspaceDirectory, r.read_policy); |
| return { server_id: status.serverId, project_id: w.projectId, workspace_id: w.id, path: w.workspaceDirectory }; |
| } |
| @@ -171,7 +171,7 @@ export class Bridge { |
| return providerPolicy(selection.provider, status.version, read_policy); |
| } |
| async createAgent(r) { |
| - keys(r, ['workspace', 'selection', 'idempotency_key', 'mode_id', 'read_policy', 'env', 'provider_options', 'mcp_servers']); |
| + keys(r, ['resource_id', 'workspace', 'selection', 'idempotency_key', 'mode_id', 'read_policy', 'env', 'provider_options', 'mcp_servers']); |
| const status = await this.status(r.workspace.server_id); |
| allowedPath(r.workspace.path, r.read_policy); |
| if (!text(r.workspace.workspace_id) || !text(r.idempotency_key) || r.mode_id !== 'default') fail('invalid_request'); |
| @@ -183,10 +183,42 @@ export class Bridge { |
| keys(server, ['type', 'command', 'args', 'env']); validateEnv(server.env ?? {}); |
| } |
| this.creationReceipts(); |
| - const a = await this.client.createAgent({ workspaceId: r.workspace.workspace_id, cwd: r.workspace.path, provider: r.selection.provider, model: r.selection.model, idempotencyKey: r.idempotency_key, modeId: r.mode_id, env: r.env ?? {}, providerOptions: r.provider_options, mcpServers: r.mcp_servers }); |
| - if (!text(a.id) || a.workspaceId !== r.workspace.workspace_id || a.cwd !== r.workspace.path || a.provider !== r.selection.provider || a.model !== r.selection.model) fail('identity_mismatch'); |
| + const a = await this.client.createAgent({ agentId: r.resource_id, workspaceId: r.workspace.workspace_id, cwd: r.workspace.path, provider: r.selection.provider, model: r.selection.model, idempotencyKey: r.idempotency_key, modeId: r.mode_id, env: r.env ?? {}, providerOptions: r.provider_options, mcpServers: r.mcp_servers }); |
| + if ((r.resource_id && a.id !== r.resource_id) || !text(a.id) || a.workspaceId !== r.workspace.workspace_id || a.cwd !== r.workspace.path || a.provider !== r.selection.provider || a.model !== r.selection.model) fail('identity_mismatch'); |
| return { server_id: status.serverId, agent_id: a.id, provider_session_id: a.runtimeInfo?.sessionId ?? a.persistence?.sessionId ?? '', workspace_id: a.workspaceId, account_id: '', provider: a.provider, model: a.model, family: r.selection.family }; |
| } |
| + async recoverWorkspace(r) { |
| + if (!text(r.resource_id)) fail('uncertain'); |
| + const status = await this.status(); |
| + const result = await this.client.fetchWorkspaces({ includeBackground: true, filter: { projectId: r.project_id, idPrefix: r.resource_id, includeInternal: true, includeBackground: true }, page: { limit: 10 } }); |
| + if (!Array.isArray(result.entries)) fail('uncertain'); |
| + const matches = result.entries.filter(w => w.id === r.resource_id); |
| + if (matches.length !== 1) fail('uncertain'); |
| + const w = matches[0]; |
| + if (w.projectId !== r.project_id || !text(w.workspaceDirectory)) fail('identity_mismatch'); |
| + allowedPath(w.workspaceDirectory, r.read_policy); |
| + return { server_id: status.serverId, project_id: w.projectId, workspace_id: w.id, path: w.workspaceDirectory }; |
| + } |
| + async recoverAgent(r) { |
| + if (!text(r.resource_id)) fail('uncertain'); |
| + const status = await this.status(r.workspace.server_id); |
| + let cursor; |
| + const seen = new Set(); |
| + for (let page = 0; page < 100; page++) { |
| + const result = await this.client.fetchAgents({ includeBackground: true, filter: { includeArchived: true, includeInternal: true, includeBackground: true }, page: { limit: 100, ...(cursor ? { cursor } : {}) } }); |
| + if (!Array.isArray(result.entries)) fail('uncertain'); |
| + const matches = result.entries.filter(e => e.agent?.id === r.resource_id); |
| + if (matches.length > 1) fail('identity_mismatch'); |
| + if (matches.length === 1) { |
| + const a = matches[0].agent; |
| + if (a.workspaceId !== r.workspace.workspace_id || a.cwd !== r.workspace.path || a.provider !== r.selection.provider || a.model !== r.selection.model) fail('identity_mismatch'); |
| + return { server_id: status.serverId, agent_id: a.id, provider_session_id: a.runtimeInfo?.sessionId ?? a.persistence?.sessionId ?? '', workspace_id: a.workspaceId, account_id: '', provider: a.provider, model: a.model, family: r.selection.family }; |
| + } |
| + if (!result.pageInfo?.hasMore || !text(result.pageInfo.nextCursor) || seen.has(result.pageInfo.nextCursor)) fail('uncertain'); |
| + cursor = result.pageInfo.nextCursor; seen.add(cursor); |
| + } |
| + fail('uncertain'); |
| + } |
| find(agent) { |
| const sub = [...this.subscriptions.values()].find(s => isDeepStrictEqual(s.agent, agent)); |
| if (!sub || !sub.ready || sub.closed) fail('subscription_not_ready'); |
| @@ -343,7 +375,7 @@ export async function run(input, output, diagnostic) { |
| bridge = new Bridge(await connectLocal(q.params, await loadSDK()), write); result = {}; |
| } else { |
| if (!bridge) fail('invalid_request'); |
| - const methods = { preflight: 'preflight', provider_policy: 'providerPolicy', register_project: 'registerProject', create_workspace: 'createWorkspace', create_agent: 'createAgent', subscribe: 'subscribe', unsubscribe: 'unsubscribe', send: 'send', respond: 'respond', stop: 'stop', archive: 'archive', archive_workspace: 'archiveWorkspace', list_terminals: 'listTerminals', kill_terminal: 'killTerminal' }; |
| + const methods = { preflight: 'preflight', provider_policy: 'providerPolicy', register_project: 'registerProject', create_workspace: 'createWorkspace', create_agent: 'createAgent', recover_workspace: 'recoverWorkspace', recover_agent: 'recoverAgent', subscribe: 'subscribe', unsubscribe: 'unsubscribe', send: 'send', respond: 'respond', stop: 'stop', archive: 'archive', archive_workspace: 'archiveWorkspace', list_terminals: 'listTerminals', kill_terminal: 'killTerminal' }; |
| if (!Object.hasOwn(methods, q.op)) fail('invalid_request'); |
| result = await bridge[methods[q.op]](q.params); |
| } |
diff --git a/runner/paseo/bridge.test.mjs b/runner/paseo/bridge.test.mjs| index 550f7afa..aec98259 100644 |
| --- a/runner/paseo/bridge.test.mjs |
| +++ b/runner/paseo/bridge.test.mjs |
| @@ -329,3 +329,23 @@ test('runner obtains the pinned creation policy before recording creation', asyn |
| f.daemon.getDaemonStatus = async () => ({ serverId: workspace.server_id, version: '0.15.0' }); |
| await assert.rejects(f.bridge.providerPolicy({ selection, read_policy: policy }), /unsupported_daemon_version/); |
| }); |
| + |
| +test('recovery looks up preassigned IDs without creating resources', async () => { |
| + const f = fake(); |
| + f.daemon.fetchWorkspaces = async () => ({ entries: [{ id: workspace.workspace_id, projectId: workspace.project_id, workspaceDirectory: workspace.path }], pageInfo: { hasMore: false } }); |
| + f.daemon.fetchAgents = async () => ({ entries: [{ agent: { id: agent.agent_id, workspaceId: workspace.workspace_id, cwd: workspace.path, provider: selection.provider, model: selection.model, persistence: { sessionId: agent.provider_session_id } } }], pageInfo: { hasMore: false } }); |
| + const w = await f.bridge.recoverWorkspace({ resource_id: workspace.workspace_id, project_id: workspace.project_id, read_policy: policy }); |
| + const a = await f.bridge.recoverAgent({ ...request(), resource_id: agent.agent_id }); |
| + assert.equal(w.workspace_id, workspace.workspace_id); |
| + assert.equal(a.agent_id, agent.agent_id); |
| + assert.equal(f.calls.filter(x => x[0] === 'create' || x[0] === 'workspace').length, 0); |
| + await assert.rejects(f.bridge.recoverWorkspace({ resource_id: 'other', project_id: workspace.project_id, read_policy: policy }), /uncertain/); |
| +}); |
| + |
| +test('creation sends preassigned resource IDs', async () => { |
| + const f = fake(); |
| + await f.bridge.createAgent({ ...request(), resource_id: agent.agent_id }); |
| + assert.equal(f.calls.find(x => x[0] === 'create')[1].agentId, agent.agent_id); |
| + await f.bridge.createWorkspace({ resource_id: workspace.workspace_id, project_id: workspace.project_id, path: workspace.path, base_commit: 'a'.repeat(40), branch: 'equipo/test', idempotency_key: 'workspace-intent', selection, read_policy: policy, isolation: 'worktree' }); |
| + assert.equal(f.calls.find(x => x[0] === 'workspace')[1].workspaceId, workspace.workspace_id); |
| +}); |