fix: keep live owners across partial scans and cancels
14 files changed,
+723
−79
internal/runner/containment_r3_test.go+331 −0internal/runner/journal.go+3 −0internal/runner/lease_check_r1_test.go+3 −1internal/runner/lease_linux.go+23 −0internal/runner/lease_r3_test.go+100 −0internal/runner/paseo/cancellation_r3_test.go+113 −0internal/runner/paseo/client.go+36 −32internal/runner/paseo/client_test.go+13 −3internal/runner/process_linux.go+32 −9internal/runner/supervisor.go+19 −20internal/runner/workflow.go+26 −9internal/runner/workflow_integration_test.go+1 −1runner/paseo/bridge.mjs+9 −3runner/paseo/bridge.test.mjs+14 −1
CI failed — run details
diff --git a/internal/runner/containment_r3_test.go b/internal/runner/containment_r3_test.go| new file mode 100644 |
| index 00000000..fff55f89 |
| --- /dev/null |
| +++ b/internal/runner/containment_r3_test.go |
| @@ -0,0 +1,331 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "errors" |
| + "golang.org/x/sys/unix" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| +) |
| + |
| +type partialScanContext struct { |
| + context.Context |
| + checks int |
| +} |
| + |
| +func (c *partialScanContext) Err() error { |
| + c.checks++ |
| + if c.checks >= 2 { |
| + return context.Canceled |
| + } |
| + return nil |
| +} |
| + |
| +func TestLinuxInspectorPartialScanKeepsOwners(t *testing.T) { |
| + for _, mode := range []string{"cancel", "stat-error", "missing-stat", "old-boot"} { |
| + t.Run(mode, func(t *testing.T) { |
| + p, o := processFixture(t) |
| + ctx := context.Background() |
| + wfMust(t, p.Track(ctx, o)) |
| + child := childProcess(t, t.TempDir(), "stripped") |
| + pid := child.Process.Pid |
| + linkProcess(t, p.root, pid) |
| + wfMust(t, p.BeginCommand(ctx, o, pid, "command")) |
| + id, err := p.identity(pid) |
| + wfMust(t, err) |
| + scanOwner := o |
| + scanCtx := ctx |
| + path := filepath.Join(p.root, strconv.Itoa(pid)) |
| + switch mode { |
| + case "cancel": |
| + // A lower numeric entry is visited before cancellation skips the survivor. |
| + wfMust(t, os.Mkdir(filepath.Join(p.root, "1"), 0700)) |
| + scanCtx = &partialScanContext{Context: ctx} |
| + case "stat-error", "missing-stat": |
| + wfMust(t, os.Remove(path)) |
| + wfMust(t, os.Mkdir(path, 0700)) |
| + if mode == "stat-error" { |
| + wfMust(t, os.Mkdir(filepath.Join(path, "stat"), 0700)) |
| + } |
| + case "old-boot": |
| + scanOwner.Attempt++ |
| + scanOwner.Marker += "-old" |
| + p.records[ownerKey(scanOwner)] = &processRecord{Owner: scanOwner, TrackTicks: 1, TrackBoot: "previous-boot"} |
| + } |
| + inv, err := p.Remaining(scanCtx, scanOwner) |
| + if mode == "cancel" && !errors.Is(err, context.Canceled) { |
| + t.Fatal("scan was not cancelled", err) |
| + } |
| + if mode != "old-boot" && inv.CoverageKnown { |
| + t.Fatal("partial scan claimed coverage") |
| + } |
| + // Verify the durable record before a successful rescan can repair attribution. |
| + restarted, err := NewLinuxProcessInspector(p.root, p.client, p.journal) |
| + wfMust(t, err) |
| + r := restarted.records[ownerKey(o)] |
| + for name, ids := range map[string][]ProcessIdentity{"known": r.Known, "executor": r.Owner.ExecutorGroups, "command": r.Commands["command"]} { |
| + if !slices.Contains(ids, id) { |
| + t.Errorf("partial scan forgot live %s identity", name) |
| + } |
| + } |
| + if t.Failed() { |
| + return |
| + } |
| + if mode == "stat-error" || mode == "missing-stat" { |
| + wfMust(t, os.RemoveAll(path)) |
| + linkProcess(t, p.root, pid) |
| + } |
| + if mode == "cancel" { |
| + wfMust(t, os.Remove(filepath.Join(p.root, "1"))) |
| + } |
| + wfMust(t, restarted.Stop(ctx, id)) |
| + _ = child.Wait() |
| + inv, err = restarted.Remaining(ctx, o) |
| + if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 { |
| + t.Fatal("survivor could not be contained", inv, err) |
| + } |
| + s, state, _, _ := cleanupFixture(t) |
| + s.journal, s.inspector, state.Owner = restarted.journal, restarted, o |
| + proof, err := s.cleanup(ctx, state) |
| + if err != nil || !proof.Empty { |
| + t.Fatal("cleanup did not reach empty", proof, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRunnerJournalCancelledStateWrite(t *testing.T) { |
| + for _, deadline := range []bool{false, true} { |
| + t.Run(strconv.FormatBool(deadline), func(t *testing.T) { |
| + s, _, _, _ := cleanupFixture(t) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + if deadline { |
| + ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) |
| + } |
| + cancel() |
| + err := s.journal.saveState(ctx, "fixture", "cancelled", struct{}{}) |
| + if !errors.Is(err, ctx.Err()) { |
| + t.Errorf("context error replaced with journal failure: %v", err) |
| + } |
| + if err := s.journal.AdmissionAllowed(context.Background()); err != nil { |
| + t.Fatal("cancelled write latched journal block", err) |
| + } |
| + wfMust(t, s.journal.Close()) |
| + j, err := OpenJournal(context.Background(), s.journal.path) |
| + wfMust(t, err) |
| + defer j.Close() |
| + wfMust(t, j.AdmissionAllowed(context.Background())) |
| + wfMust(t, j.saveState(context.Background(), "fixture", "retry", struct{}{})) |
| + }) |
| + } |
| + t.Run("storage-error", func(t *testing.T) { |
| + s, _, _, _ := cleanupFixture(t) |
| + _, err := s.journal.db.Exec("CREATE TRIGGER fail_state BEFORE INSERT ON journal_supervisor BEGIN SELECT RAISE(FAIL, 'storage failure'); END") |
| + wfMust(t, err) |
| + if !errors.Is(s.journal.saveState(context.Background(), "fixture", "broken", struct{}{}), ErrJournal) { |
| + t.Fatal("storage error not reported") |
| + } |
| + if s.journal.AdmissionAllowed(context.Background()) == nil { |
| + t.Fatal("storage error did not block journal") |
| + } |
| + }) |
| +} |
| + |
| +func TestRunnerCreationReissueClearsRefusal(t *testing.T) { |
| + for _, kind := range []string{"workspace", "agent"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s, _, _, _ := cleanupFixture(t) |
| + ctx := context.Background() |
| + i := paseo.Intent{Kind: kind, Key: "same-key", RequestHash: "same-hash", Request: []byte(`{}`)} |
| + wfMust(t, s.journal.RecordIntent(ctx, i)) |
| + wfMust(t, s.journal.RecordCreationRefusal(ctx, i)) |
| + wfMust(t, s.settleCreation(ctx, kind, i.Key, paseo.ErrCreationAbsent)) |
| + wfMust(t, s.journal.RecordIntent(ctx, i)) |
| + wfMust(t, s.journal.Close()) |
| + j, err := OpenJournal(ctx, s.journal.path) |
| + wfMust(t, err) |
| + defer j.Close() |
| + s.journal = j |
| + if err := s.settleCreation(ctx, kind, i.Key, paseo.ErrCreationAbsent); !errors.Is(err, paseo.ErrUncertain) { |
| + t.Fatal("reissued intent with lost reply settled by stale refusal", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRunnerMonitorCancellationCause(t *testing.T) { |
| + _, r, p, _ := cleanupFixture(t) |
| + p.unknown = true |
| + ctx, stop := monitorOwnership(context.Background(), p, r.Owner) |
| + defer stop() |
| + select { |
| + case <-ctx.Done(): |
| + case <-time.After(time.Second): |
| + t.Fatal("monitor did not cancel") |
| + } |
| + if !errors.Is(context.Cause(ctx), paseo.ErrUncertain) { |
| + t.Fatal("monitor lost cancellation cause", context.Cause(ctx)) |
| + } |
| +} |
| + |
| +type failingClockR3 struct{} |
| + |
| +func (failingClockR3) Read() (ClockReading, error) { return ClockReading{}, os.ErrPermission } |
| +func TestRunnerLeaseCancellationCause(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + s.clock = failingClockR3{} |
| + ctx, cancel := context.WithCancelCause(context.Background()) |
| + defer cancel(nil) |
| + done := make(chan struct{}) |
| + go s.watchLease(ctx, cancel, r, nil, done) |
| + <-done |
| + if !errors.Is(context.Cause(ctx), os.ErrPermission) { |
| + t.Fatal("lease watchdog lost cancellation cause", context.Cause(ctx)) |
| + } |
| +} |
| + |
| +type clockFuncR3 func() (ClockReading, error) |
| + |
| +func (f clockFuncR3) Read() (ClockReading, error) { return f() } |
| + |
| +type apiFuncR3 func(context.Context, string, runnerproto.RunnerRequest, any) error |
| + |
| +func (f apiFuncR3) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| + return f(ctx, op, q, out) |
| +} |
| + |
| +func TestRunnerLeaseWatchdogCauseSites(t *testing.T) { |
| + for _, mode := range []string{"check", "renew", "RenewLease", "checkRenewal"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + now := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"} |
| + l, err := newLease(now, now.Wall.Add(time.Minute), now.Wall.Add(5*time.Minute)) |
| + wfMust(t, err) |
| + var reads atomic.Int32 |
| + s.clock = clockFuncR3(func() (ClockReading, error) { |
| + n := reads.Add(1) |
| + elapsed := time.Duration(0) |
| + if n > 1 { |
| + elapsed = 15 * time.Second |
| + } |
| + if mode == "check" && n > 1 || mode == "checkRenewal" && n > 3 { |
| + elapsed = 51 * time.Second |
| + } |
| + return ClockReading{Wall: now.Wall.Add(elapsed), Elapsed: now.Elapsed + elapsed, BootID: now.BootID}, nil |
| + }) |
| + apiDone := make(chan struct{}) |
| + s.api = apiFuncR3(func(ctx context.Context, _ string, _ runnerproto.RunnerRequest, out any) error { |
| + defer close(apiDone) |
| + if mode == "renew" { |
| + return paseo.ErrPolicy |
| + } |
| + if mode == "checkRenewal" { |
| + <-ctx.Done() |
| + return ctx.Err() |
| + } |
| + *out.(*time.Time) = now.Wall.Add(time.Minute) |
| + return nil |
| + }) |
| + if mode == "RenewLease" { |
| + s.activeSocket = &AttemptSocket{invalid: true} |
| + } |
| + ctx, cancel := context.WithCancelCause(context.Background()) |
| + defer cancel(nil) |
| + done := make(chan struct{}) |
| + go s.watchLease(ctx, cancel, r, l, done) |
| + select { |
| + case <-done: |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("watchdog failed to stop") |
| + } |
| + if mode != "check" { |
| + <-apiDone |
| + } |
| + var cause attemptCancellation |
| + if !errors.As(context.Cause(ctx), &cause) || cause.operation != "watchLease."+mode { |
| + t.Fatal("watchdog lost source", mode, context.Cause(ctx)) |
| + } |
| + var want error = paseo.ErrUncertain |
| + if mode == "renew" { |
| + want = paseo.ErrPolicy |
| + } |
| + if mode == "RenewLease" { |
| + want = runnerproto.ErrInvalid |
| + } |
| + if !errors.Is(context.Cause(ctx), want) { |
| + t.Fatal("watchdog lost cause", context.Cause(ctx)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type cancelTrackR3 struct { |
| + *cleanupInspector |
| + cancel context.CancelCauseFunc |
| +} |
| + |
| +func (p cancelTrackR3) Track(context.Context, ProcessOwner) error { |
| + p.cancel(os.ErrPermission) |
| + return context.Canceled |
| +} |
| +func TestRunnerFailureDetailRetainsCause(t *testing.T) { |
| + s, r, p, _ := cleanupFixture(t) |
| + ctx, cancel := context.WithCancelCause(context.Background()) |
| + defer cancel(nil) |
| + s.inspector = cancelTrackR3{p, cancel} |
| + _, err := s.journal.db.Exec("DELETE FROM journal_supervisor WHERE kind='attempt'") |
| + wfMust(t, err) |
| + s.ready = true |
| + s.states = map[string]*attemptState{} |
| + s.workflow = &BugWorkflow{cfg: BugWorkflowConfig{Workspaces: &workspace.Manager{}}} |
| + claim := r.Claim |
| + claim.Assignment.Kind = "prepare" |
| + claim.LeaseDeadline = time.Now().Add(time.Minute) |
| + claim.AttemptDeadline = time.Now().Add(5 * time.Minute) |
| + if err := s.Run(ctx, claim); !errors.Is(err, os.ErrPermission) { |
| + t.Fatal("attempt lost cause", err) |
| + } |
| + var states []attemptState |
| + wfMust(t, s.journal.readStates(context.Background(), "attempt", &states)) |
| + if len(states) != 1 || !strings.Contains(states[0].FailureDetail, os.ErrPermission.Error()) { |
| + t.Fatal("durable failure detail lost cause", states) |
| + } |
| +} |
| + |
| +func TestLinuxInspectorDisappearingStatIsUnknown(t *testing.T) { |
| + p, o := processFixture(t) |
| + ctx := context.Background() |
| + wfMust(t, p.Track(ctx, o)) |
| + c := childProcess(t, t.TempDir(), "stripped") |
| + pid := c.Process.Pid |
| + dir := filepath.Join(p.root, strconv.Itoa(pid)) |
| + wfMust(t, os.Mkdir(dir, 0700)) |
| + stat := filepath.Join(dir, "stat") |
| + wfMust(t, os.Symlink(filepath.Join("/proc", strconv.Itoa(pid), "stat"), stat)) |
| + wfMust(t, os.Symlink("/", filepath.Join(dir, "cwd"))) |
| + fifo := filepath.Join(dir, "environ") |
| + wfMust(t, unix.Mkfifo(fifo, 0600)) |
| + wfMust(t, p.BeginCommand(ctx, o, pid, "command")) |
| + result := make(chan ProcessInventory, 1) |
| + fail := make(chan error, 1) |
| + go func() { inv, err := p.Remaining(ctx, o); result <- inv; fail <- err }() |
| + writer, err := os.OpenFile(fifo, os.O_WRONLY, 0600) |
| + wfMust(t, err) |
| + wfMust(t, os.Remove(stat)) |
| + wfMust(t, writer.Close()) |
| + inv := <-result |
| + wfMust(t, <-fail) |
| + if inv.CoverageKnown { |
| + t.Fatal("missing second stat produced known coverage while PID directory exists") |
| + } |
| +} |
diff --git a/internal/runner/journal.go b/internal/runner/journal.go| index 40e6b4f5..173a3dc5 100644 |
| --- a/internal/runner/journal.go |
| +++ b/internal/runner/journal.go |
| @@ -259,6 +259,9 @@ func (j *Journal) RecordIntent(ctx context.Context, i paseo.Intent) error { |
| if string(old) != string(b) { |
| return runnerproto.ErrInvalid |
| } |
| + if _, err = tx.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='creation-refused' AND state_key=?", key); err != nil { |
| + return err |
| + } |
| return tx.Commit() |
| } |
| if !errors.Is(err, sql.ErrNoRows) { |
diff --git a/internal/runner/lease_check_r1_test.go b/internal/runner/lease_check_r1_test.go| index df6a2c0a..8ea08741 100644 |
| --- a/internal/runner/lease_check_r1_test.go |
| +++ b/internal/runner/lease_check_r1_test.go |
| @@ -67,7 +67,9 @@ func TestRunnerLeaseLongCheck(t *testing.T) { |
| 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) |
| + leaseCtx, leaseCancel := context.WithCancelCause(ctx) |
| + ctx = leaseCtx |
| + go s.watchLease(ctx, leaseCancel, r, l, done) |
| defer func() { cancel(); <-done }() |
| var validations atomic.Int32 |
| s.mu.Lock() |
diff --git a/internal/runner/lease_linux.go b/internal/runner/lease_linux.go| index 08970466..299180a9 100644 |
| --- a/internal/runner/lease_linux.go |
| +++ b/internal/runner/lease_linux.go |
| @@ -52,6 +52,26 @@ func (l *leaseGuard) check(now ClockReading) error { |
| defer l.mu.Unlock() |
| return l.checkLocked(now) |
| } |
| +func (l *leaseGuard) checkClock(clock ElapsedClock) (ClockReading, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + now, err := clock.Read() |
| + if err != nil { |
| + return now, err |
| + } |
| + return now, l.checkLocked(now) |
| +} |
| + |
| +func (l *leaseGuard) renewClock(clock ElapsedClock, sent ClockReading, deadline time.Time) error { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + received, err := clock.Read() |
| + if err != nil { |
| + return err |
| + } |
| + return l.renewReplyLocked(sent, received, deadline) |
| +} |
| + |
| func (l *leaseGuard) checkLocked(now ClockReading) error { |
| if l.expired || now.BootID != l.last.BootID || now.Elapsed < l.last.Elapsed || now.Wall.Before(l.last.Wall) || (l.end > 0 && now.Elapsed >= l.end) || now.Elapsed >= l.attemptEnd { |
| l.expired = true |
| @@ -87,6 +107,9 @@ func (l *leaseGuard) bound() time.Time { l.mu.Lock(); defer l.mu.Unlock(); retur |
| func (l *leaseGuard) renewReply(sent, received ClockReading, deadline time.Time) error { |
| l.mu.Lock() |
| defer l.mu.Unlock() |
| + return l.renewReplyLocked(sent, received, deadline) |
| +} |
| +func (l *leaseGuard) renewReplyLocked(sent, received ClockReading, deadline time.Time) error { |
| if err := l.checkLocked(received); err != nil { |
| return err |
| } |
diff --git a/internal/runner/lease_r3_test.go b/internal/runner/lease_r3_test.go| new file mode 100644 |
| index 00000000..1528f4a8 |
| --- /dev/null |
| +++ b/internal/runner/lease_r3_test.go |
| @@ -0,0 +1,100 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestRunnerLeaseConcurrentClockReads(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + start := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"} |
| + l, err := newLease(start, start.Wall.Add(time.Minute), start.Wall.Add(5*time.Minute)) |
| + wfMust(t, err) |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + var mu sync.Mutex |
| + reads := 0 |
| + s.clock = clockFuncR3(func() (ClockReading, error) { |
| + mu.Lock() |
| + reads++ |
| + n := reads |
| + mu.Unlock() |
| + if n == 2 { |
| + close(entered) |
| + <-release |
| + } |
| + return ClockReading{Wall: start.Wall.Add(time.Duration(n) * time.Millisecond), Elapsed: start.Elapsed + time.Duration(n)*time.Millisecond, BootID: start.BootID}, nil |
| + }) |
| + ctx, cancel := context.WithCancelCause(context.Background()) |
| + defer cancel(nil) |
| + done := make(chan struct{}) |
| + go s.watchLease(ctx, cancel, r, l, done) |
| + <-entered |
| + current := make(chan error, 1) |
| + go func() { |
| + _, err := l.checkClock(s.clock) |
| + current <- err |
| + }() |
| + // Let the later read finish first if clock sampling is outside the lease lock. |
| + select { |
| + case err = <-current: |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + close(release) |
| + select { |
| + case <-done: |
| + t.Fatal("concurrent valid clock reads expired lease", context.Cause(ctx)) |
| + case <-time.After(150 * time.Millisecond): |
| + } |
| + cancel(nil) |
| + <-done |
| + if !errors.Is(context.Cause(ctx), context.Canceled) { |
| + t.Fatal(context.Cause(ctx)) |
| + } |
| +} |
| + |
| +func TestRunnerLeaseConcurrentRenewalClockRead(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(5*time.Minute)) |
| + wfMust(t, err) |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + var mu sync.Mutex |
| + reads := 0 |
| + clock := clockFuncR3(func() (ClockReading, error) { |
| + mu.Lock() |
| + reads++ |
| + n := reads |
| + mu.Unlock() |
| + if n == 1 { |
| + close(entered) |
| + <-release |
| + } |
| + return ClockReading{Wall: start.Wall.Add(time.Duration(n) * time.Millisecond), Elapsed: start.Elapsed + time.Duration(n)*time.Millisecond, BootID: start.BootID}, nil |
| + }) |
| + renewal := make(chan error, 1) |
| + go func() { renewal <- l.renewClock(clock, start, start.Wall.Add(time.Minute)) }() |
| + <-entered |
| + current := make(chan error, 1) |
| + go func() { _, err := l.checkClock(clock); current <- err }() |
| + received := false |
| + select { |
| + case err = <-current: |
| + received = true |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + close(release) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = <-renewal; err != nil { |
| + t.Fatal("concurrent valid renewal reading expired lease", err) |
| + } |
| + if !received { |
| + wfMust(t, <-current) |
| + } |
| +} |
diff --git a/internal/runner/paseo/cancellation_r3_test.go b/internal/runner/paseo/cancellation_r3_test.go| new file mode 100644 |
| index 00000000..75a2e2c1 |
| --- /dev/null |
| +++ b/internal/runner/paseo/cancellation_r3_test.go |
| @@ -0,0 +1,113 @@ |
| +package paseo |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestPaseoCancelledCallKeepsCleanup(t *testing.T) { |
| + c := testClient(t, "late-reply", nil) |
| + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) |
| + defer cancel() |
| + err := c.call(ctx, "delayed", struct{}{}, nil) |
| + if !errors.Is(err, ErrUncertain) { |
| + t.Fatal("cancelled effect lost uncertainty", err) |
| + } |
| + for _, op := range []func(context.Context, Agent) error{c.Stop, c.Archive} { |
| + if err := op(context.Background(), fixtureAgent()); err != nil { |
| + t.Fatal("cancelled call killed cleanup client", err) |
| + } |
| + } |
| + c.mu.Lock() |
| + pending := len(c.pending) |
| + c.mu.Unlock() |
| + if pending != 0 { |
| + t.Fatal("abandoned requests retained", pending) |
| + } |
| +} |
| + |
| +func TestPaseoCancelledSubscriptionKeepsCleanup(t *testing.T) { |
| + c := testClient(t, "normal", nil) |
| + a := createFixture(t, c) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + sub, err := c.Subscribe(ctx, a, Cursor{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = <-sub.Ready; err != nil { |
| + t.Fatal(err) |
| + } |
| + cancel() |
| + select { |
| + case <-sub.done: |
| + case <-time.After(time.Second): |
| + t.Fatal("subscription not closed") |
| + } |
| + if err = c.Stop(context.Background(), a); err != nil { |
| + t.Fatal("subscription cancellation killed cleanup client", err) |
| + } |
| + if err = c.Archive(context.Background(), a); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestPaseoDefinitivePolicyCodes(t *testing.T) { |
| + for _, code := range []string{"policy_mismatch", "invalid_mcp"} { |
| + t.Run(code, func(t *testing.T) { |
| + var refusal Intent |
| + c := testClient(t, code, func(cfg *Config) { |
| + cfg.RecordCreationRefusal = func(_ context.Context, i Intent) error { refusal = i; return nil } |
| + }) |
| + _, err := c.CreateAgent(context.Background(), AgentRequest{Workspace: fixtureWorkspace(), Selection: fixtureSelection(), IdempotencyKey: "intent", ModeID: "default", ReadPolicy: fixturePolicy()}) |
| + if !errors.Is(err, ErrPolicy) { |
| + t.Fatal("specific policy code lost", err) |
| + } |
| + if refusal.Key != "intent" { |
| + t.Fatal("definitive policy refusal not recorded", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type blockedWriteR3 struct { |
| + io.WriteCloser |
| + entered chan struct{} |
| + release chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (w *blockedWriteR3) Write(b []byte) (int, error) { |
| + w.once.Do(func() { close(w.entered) }) |
| + <-w.release |
| + return w.WriteCloser.Write(b) |
| +} |
| +func TestPaseoCancelledBlockedWriteKeepsCleanup(t *testing.T) { |
| + c := testClient(t, "normal", nil) |
| + w := &blockedWriteR3{WriteCloser: c.stdin, entered: make(chan struct{}), release: make(chan struct{})} |
| + c.stdin = w |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + result := make(chan error, 1) |
| + go func() { result <- c.call(ctx, "delayed", struct{}{}, nil) }() |
| + <-w.entered |
| + cancel() |
| + select { |
| + case err := <-result: |
| + if !errors.Is(err, ErrUncertain) { |
| + t.Error("cancelled write lost uncertainty", err) |
| + } |
| + case <-time.After(time.Second): |
| + t.Error("cancelled request waits for blocked write") |
| + } |
| + close(w.release) |
| + if err := c.Stop(context.Background(), fixtureAgent()); err != nil { |
| + t.Fatal("cancelled write killed cleanup", err) |
| + } |
| + if err := c.Archive(context.Background(), fixtureAgent()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/runner/paseo/client.go b/internal/runner/paseo/client.go| index 7b6ebc1e..d1ca1108 100644 |
| --- a/internal/runner/paseo/client.go |
| +++ b/internal/runner/paseo/client.go |
| @@ -21,15 +21,16 @@ import ( |
| ) |
| type frame struct { |
| - Version int `json:"version"` |
| - Type string `json:"type"` |
| - ID string `json:"id,omitempty"` |
| - Op string `json:"op,omitempty"` |
| - Params json.RawMessage `json:"params,omitempty"` |
| - Result json.RawMessage `json:"result,omitempty"` |
| - Error string `json:"error,omitempty"` |
| - SubscriptionID string `json:"subscription_id,omitempty"` |
| - Event *Event `json:"event,omitempty"` |
| + DefinitiveCreateFailure bool `json:"definitive_create_failure,omitempty"` |
| + Version int `json:"version"` |
| + Type string `json:"type"` |
| + ID string `json:"id,omitempty"` |
| + Op string `json:"op,omitempty"` |
| + Params json.RawMessage `json:"params,omitempty"` |
| + Result json.RawMessage `json:"result,omitempty"` |
| + Error string `json:"error,omitempty"` |
| + SubscriptionID string `json:"subscription_id,omitempty"` |
| + Event *Event `json:"event,omitempty"` |
| } |
| type agentState struct { |
| agent Agent |
| @@ -223,41 +224,44 @@ func (c *Client) call(ctx context.Context, op string, params any, out any) error |
| c.pending[id] = ch |
| c.mu.Unlock() |
| defer func() { c.mu.Lock(); delete(c.pending, id); c.mu.Unlock() }() |
| - // A cancelled operation may have reached the daemon. Tear down the bridge; |
| - // creation intents and message IDs remain available to the recovery owner. |
| - finished := make(chan struct{}) |
| - defer close(finished) |
| + written := make(chan error, 1) |
| go func() { |
| - select { |
| - case <-ctx.Done(): |
| - select { |
| - case <-finished: |
| - return |
| - default: |
| - c.fail(ErrUncertain) |
| - } |
| - case <-c.done: |
| - case <-finished: |
| + c.writeMu.Lock() |
| + defer c.writeMu.Unlock() |
| + if ctx.Err() != nil { |
| + written <- ctx.Err() |
| + return |
| } |
| + _, err := c.stdin.Write(append(b, '\n')) |
| + if err != nil { |
| + c.fail(ErrUncertain) |
| + } |
| + written <- err |
| }() |
| - c.writeMu.Lock() |
| - _, err = c.stdin.Write(append(b, '\n')) |
| - c.writeMu.Unlock() |
| - if err != nil { |
| - c.fail(ErrUncertain) |
| + select { |
| + case err := <-written: |
| + if err != nil { |
| + return ErrUncertain |
| + } |
| + case <-ctx.Done(): |
| return ErrUncertain |
| + case <-c.done: |
| + return c.failure |
| } |
| select { |
| case f := <-ch: |
| if f.Error != "" { |
| - return bridgeError(f.Error) |
| + err := bridgeError(f.Error) |
| + if f.DefinitiveCreateFailure && (op == "create_agent" || op == "create_workspace") { |
| + err = errors.Join(err, ErrCreateRefused) |
| + } |
| + return err |
| } |
| if out != nil { |
| return decode(f.Result, out) |
| } |
| return nil |
| case <-ctx.Done(): |
| - c.fail(ErrUncertain) |
| return ErrUncertain |
| case <-c.done: |
| return c.failure |
| @@ -271,7 +275,7 @@ func bridgeError(code string) error { |
| return ErrCreationAbsent |
| case "create_refused": |
| return ErrCreateRefused |
| - case "policy_mismatch": |
| + case "policy_mismatch", "invalid_mcp": |
| return ErrPolicy |
| case "wrong_server", "identity_mismatch": |
| return ErrIdentity |
| @@ -551,7 +555,7 @@ func (c *Client) Subscribe(ctx context.Context, a Agent, cursor Cursor) (*Subscr |
| go func() { |
| select { |
| case <-ctx.Done(): |
| - c.fail(ErrUncertain) |
| + _ = sub.Close(context.WithoutCancel(ctx)) |
| case <-sub.done: |
| case <-c.done: |
| } |
diff --git a/internal/runner/paseo/client_test.go b/internal/runner/paseo/client_test.go| index c06f01f3..852122f3 100644 |
| --- a/internal/runner/paseo/client_test.go |
| +++ b/internal/runner/paseo/client_test.go |
| @@ -238,6 +238,9 @@ func TestPaseoHelper(t *testing.T) { |
| fmt.Println(string(b)) |
| continue |
| } |
| + if mode == "late-reply" && q.Op == "delayed" { |
| + time.Sleep(150 * time.Millisecond) |
| + } |
| if mode == "hang" { |
| time.Sleep(time.Minute) |
| } |
| @@ -271,6 +274,9 @@ func TestPaseoHelper(t *testing.T) { |
| } |
| result = fixtureWorkspace() |
| case "create_agent": |
| + if mode == "policy_mismatch" || mode == "invalid_mcp" { |
| + code = mode |
| + } |
| if mode == "refused" { |
| code = "create_refused" |
| } |
| @@ -303,7 +309,11 @@ func TestPaseoHelper(t *testing.T) { |
| code = "invalid_permission" |
| } |
| } |
| - b, _ := json.Marshal(map[string]any{"version": 1, "type": "result", "id": q.ID, "result": result, "error": code}) |
| + reply := map[string]any{"version": 1, "type": "result", "id": q.ID, "result": result, "error": code} |
| + if mode == "policy_mismatch" || mode == "invalid_mcp" { |
| + reply["definitive_create_failure"] = true |
| + } |
| + b, _ := json.Marshal(reply) |
| fmt.Println(string(b)) |
| } |
| os.Exit(0) |
| @@ -382,8 +392,8 @@ func TestPaseoPolicyAndRecovery(t *testing.T) { |
| } |
| select { |
| case <-c.waited: |
| - case <-time.After(time.Second): |
| - t.Fatal("bridge survived cancellation") |
| + t.Fatal("bridge killed by cancellation") |
| + default: |
| } |
| }) |
| t.Run("lost creation reply is not replaced", func(t *testing.T) { |
diff --git a/internal/runner/process_linux.go b/internal/runner/process_linux.go| index b675513c..6b74e2b2 100644 |
| --- a/internal/runner/process_linux.go |
| +++ b/internal/runner/process_linux.go |
| @@ -232,6 +232,7 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term |
| return inv, err |
| } |
| all := map[int]procEntry{} |
| + observed := map[int]procEntry{} |
| attributed := map[int]string{} |
| known := map[string]string{} |
| pathsByPID := map[int][]string{} |
| @@ -269,11 +270,13 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term |
| } |
| e, err := p.entry(pid) |
| if err != nil { |
| - if !os.IsNotExist(err) { |
| + _, dirErr := os.Stat(filepath.Join(p.root, d.Name())) |
| + if !os.IsNotExist(dirErr) { |
| unknown() |
| } |
| continue |
| } |
| + observed[pid] = e |
| if e.dead { |
| continue |
| } |
| @@ -290,7 +293,15 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term |
| env, envErr := os.ReadFile(filepath.Join(p.root, d.Name(), "environ")) |
| cwd, cwdErr := os.Readlink(filepath.Join(p.root, d.Name(), "cwd")) |
| after, err := p.entry(pid) |
| + if err == nil { |
| + observed[pid] = after |
| + } |
| if os.IsNotExist(err) || err == nil && after.dead { |
| + if err != nil { |
| + if _, dirErr := os.Stat(filepath.Join(p.root, d.Name())); !os.IsNotExist(dirErr) { |
| + unknown() |
| + } |
| + } |
| delete(all, pid) |
| continue |
| } |
| @@ -417,8 +428,8 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term |
| if record.Closed { |
| continue |
| } |
| - record.Known = liveIdentities(record.Known, all) |
| - record.Owner.ExecutorGroups = liveIdentities(record.Owner.ExecutorGroups, all) |
| + record.Known = p.retainedIdentities(ctx, record.Known, observed) |
| + record.Owner.ExecutorGroups = p.retainedIdentities(ctx, record.Owner.ExecutorGroups, observed) |
| for command, ids := range record.Commands { |
| members := map[int]bool{} |
| for _, id := range ids { |
| @@ -442,7 +453,7 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term |
| } |
| } |
| } |
| - record.Commands[command] = liveIdentities(ids, all) |
| + record.Commands[command] = p.retainedIdentities(ctx, ids, observed) |
| saved := map[string]bool{} |
| for _, id := range ids { |
| saved[identityKey(id)] = true |
| @@ -453,7 +464,7 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term |
| record.Commands[command] = append(record.Commands[command], id) |
| } |
| } |
| - record.Commands[command] = liveIdentities(record.Commands[command], all) |
| + record.Commands[command] = p.retainedIdentities(ctx, record.Commands[command], observed) |
| } |
| } |
| @@ -607,6 +618,9 @@ func (j *Journal) saveState(ctx context.Context, kind, key string, v any) error |
| } |
| _, err = j.db.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES(?,?,?) ON CONFLICT(kind,state_key) DO UPDATE SET body=excluded.body", kind, key, raw) |
| if err != nil { |
| + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| + return err |
| + } |
| return j.fail() |
| } |
| return nil |
| @@ -766,14 +780,23 @@ func (p *LinuxProcessInspector) EndCommand(ctx context.Context, o ProcessOwner, |
| return failures |
| } |
| -func liveIdentities(ids []ProcessIdentity, all map[int]procEntry) []ProcessIdentity { |
| +func (p *LinuxProcessInspector) retainedIdentities(ctx context.Context, ids []ProcessIdentity, observed map[int]procEntry) []ProcessIdentity { |
| var live []ProcessIdentity |
| seen := map[ProcessIdentity]bool{} |
| for _, id := range ids { |
| - if e, ok := all[id.PID]; ok && e.id == id && !seen[id] { |
| - live = append(live, id) |
| - seen[id] = true |
| + if seen[id] { |
| + continue |
| + } |
| + if e, ok := observed[id.PID]; ok && (e.id != id || e.dead) { |
| + continue |
| + } |
| + if ctx.Err() == nil { |
| + if _, err := os.Stat(filepath.Join(p.root, strconv.Itoa(id.PID))); os.IsNotExist(err) { |
| + continue |
| + } |
| } |
| + live = append(live, id) |
| + seen[id] = true |
| } |
| sort.Slice(live, func(i, j int) bool { return live[i].PID < live[j].PID }) |
| return live |
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go| index d63b1a60..b0bf17ec 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 |
| + FailureDetail string |
| StopError string |
| SocketPath, CapabilityPath string |
| Proof *ContainmentProof |
| @@ -61,7 +62,7 @@ type Supervisor struct { |
| mu sync.Mutex |
| runMu sync.Mutex |
| activeKey string |
| - activeCancel context.CancelFunc |
| + activeCancel context.CancelCauseFunc |
| activeSocket *AttemptSocket |
| activeCurrent func(context.Context) error |
| monitorStop func() |
| @@ -124,8 +125,8 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| return paseo.ErrUncertain |
| } |
| s.states[key] = r |
| - active, cancel := context.WithCancel(ctx) |
| - defer cancel() |
| + active, cancel := context.WithCancelCause(ctx) |
| + defer cancel(nil) |
| defer func() { |
| if s.monitorStop != nil { |
| s.monitorStop() |
| @@ -149,9 +150,11 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| go s.watchLease(active, cancel, r, lease, done) |
| err = s.workflow.run(active, s, r, lease) |
| if err != nil { |
| + err = errors.Join(err, context.Cause(active)) |
| r.FailurePhase = r.Phase |
| + r.FailureDetail = err.Error() |
| } |
| - cancel() |
| + cancel(nil) |
| <-done |
| cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) |
| defer cleanupCancel() |
| @@ -175,13 +178,13 @@ func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState, |
| } |
| return errors.Join(err, bookkeepingErr, cleanupErr) |
| } |
| -func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, r *attemptState, l *leaseGuard, done chan struct{}) { |
| +func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelCauseFunc, r *attemptState, l *leaseGuard, done chan struct{}) { |
| defer close(done) |
| tick := time.NewTicker(100 * time.Millisecond) |
| defer tick.Stop() |
| last, err := s.clock.Read() |
| if err != nil { |
| - cancel() |
| + cancel(attemptCancellation{"watchLease.Read", err}) |
| return |
| } |
| renewAt := last.Elapsed + 15*time.Second |
| @@ -190,9 +193,9 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, |
| case <-ctx.Done(): |
| return |
| case <-tick.C: |
| - now, err := s.clock.Read() |
| - if err != nil || l.check(now) != nil { |
| - cancel() |
| + now, err := l.checkClock(s.clock) |
| + if err != nil { |
| + cancel(attemptCancellation{"watchLease.check", err}) |
| return |
| } |
| if now.Elapsed < renewAt { |
| @@ -210,11 +213,7 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, |
| 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) |
| + return l.renewClock(s.clock, sent, deadline) |
| }) |
| if err == nil { |
| s.mu.Lock() |
| @@ -232,7 +231,7 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, |
| return |
| case err := <-reply: |
| if err != nil { |
| - cancel() |
| + cancel(attemptCancellation{"watchLease.renew", err}) |
| return |
| } |
| s.mu.Lock() |
| @@ -240,16 +239,16 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, |
| s.mu.Unlock() |
| if socket != nil { |
| if err = socket.RenewLease(ctx, l.bound()); err != nil { |
| - cancel() |
| + cancel(attemptCancellation{"watchLease.RenewLease", err}) |
| return |
| } |
| } |
| renewAt = now.Elapsed + 15*time.Second |
| goto renewed |
| case <-tick.C: |
| - n, e := s.clock.Read() |
| - if e != nil || l.check(n) != nil { |
| - cancel() |
| + _, e := l.checkClock(s.clock) |
| + if e != nil { |
| + cancel(attemptCancellation{"watchLease.checkRenewal", e}) |
| return |
| } |
| } |
| @@ -268,7 +267,7 @@ func (s *Supervisor) Cancel(ctx context.Context, scope team.Scope, h team.Handle |
| var stopErr error |
| if active { |
| stopErr = s.api.Call(ctx, "stop", stop, nil) |
| - cancel() |
| + cancel(attemptCancellation{"Supervisor.Cancel", context.Canceled}) |
| } |
| s.runMu.Lock() |
| defer s.runMu.Unlock() |
diff --git a/internal/runner/workflow.go b/internal/runner/workflow.go| index 565a3709..50d815e4 100644 |
| --- a/internal/runner/workflow.go |
| +++ b/internal/runner/workflow.go |
| @@ -3,6 +3,7 @@ package runner |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "path/filepath" |
| "strings" |
| "time" |
| @@ -38,7 +39,12 @@ func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) { |
| func selection(a runnerproto.Assignment) paseo.Selection { |
| return paseo.Selection{ConnectionID: a.Selection.ConnectionID, Provider: a.Selection.Provider, Family: a.Selection.Family, Model: a.Selection.Model, AccountID: a.Selection.AccountID} |
| } |
| -func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard) error { |
| +func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard) (runErr error) { |
| + defer func() { |
| + if runErr != nil { |
| + runErr = errors.Join(runErr, context.Cause(ctx)) |
| + } |
| + }() |
| if r.Claim.Assignment.Kind == "prepare" { |
| r.Owner = ProcessOwner{LocalOnly: true, Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: r.Claim.Assignment.ID, Workspace: paseo.Workspace{Path: w.cfg.Workspaces.PreparationDirectory()}} |
| if err := s.save(ctx, r); err != nil { |
| @@ -47,7 +53,8 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if err := s.inspector.Track(ctx, r.Owner); err != nil { |
| return err |
| } |
| - ctx, stopMonitoring := monitorOwnership(ctx, s.inspector, r.Owner) |
| + var stopMonitoring func() |
| + ctx, stopMonitoring = monitorOwnership(ctx, s.inspector, r.Owner) |
| s.monitorStop = stopMonitoring |
| inspector, ok := s.inspector.(*LinuxProcessInspector) |
| @@ -102,13 +109,10 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| } |
| var socket *AttemptSocket |
| current := func(ctx context.Context) error { |
| - now, err := s.clock.Read() |
| + _, err := l.checkClock(s.clock) |
| if err != nil { |
| return err |
| } |
| - if err = l.check(now); err != nil { |
| - return err |
| - } |
| if err = retryAuthority(ctx, func() error { return remoteError(w.cfg.Workspaces.ValidateTurn(ctx, r.Claim.Assignment, ws)) }); err != nil { |
| return err |
| } |
| @@ -397,7 +401,7 @@ func reviewVerdict(decision string) team.Verdict { |
| } |
| func monitorOwnership(parent context.Context, inspector ProcessInspector, owner ProcessOwner) (context.Context, func()) { |
| - ctx, cancel := context.WithCancel(parent) |
| + ctx, cancel := context.WithCancelCause(parent) |
| sampling, stop := context.WithCancel(context.WithoutCancel(parent)) |
| done := make(chan struct{}) |
| go func() { |
| @@ -417,10 +421,23 @@ func monitorOwnership(parent context.Context, inspector ProcessInspector, owner |
| inv, err = inspector.Remaining(sampling, owner) |
| } |
| if err != nil || !inv.CoverageKnown { |
| - cancel() |
| + if err == nil { |
| + err = paseo.ErrUncertain |
| + } |
| + cancel(attemptCancellation{"monitorOwnership", err}) |
| } |
| } |
| } |
| }() |
| - return ctx, func() { stop(); cancel(); <-done } |
| + return ctx, func() { stop(); cancel(nil); <-done } |
| +} |
| + |
| +type attemptCancellation struct { |
| + operation string |
| + cause error |
| +} |
| + |
| +func (e attemptCancellation) Error() string { |
| + return string(marshal(map[string]string{"operation": e.operation, "cause": e.cause.Error()})) |
| } |
| +func (e attemptCancellation) Unwrap() error { return e.cause } |
diff --git a/internal/runner/workflow_integration_test.go b/internal/runner/workflow_integration_test.go| index f98abbc1..abaf7c6b 100644 |
| --- a/internal/runner/workflow_integration_test.go |
| +++ b/internal/runner/workflow_integration_test.go |
| @@ -395,7 +395,7 @@ func runBugWorkflowMode(t *testing.T, reject bool, failover string) { |
| 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) |
| + t.Fatalf("%s (%s): %v cause/detail=%s %s", step, s.states[attemptKey(scope, h)].FailurePhase, err, s.states[attemptKey(scope, h)].FailureDetail, b) |
| } |
| } |
| if failover != "" { |
diff --git a/runner/paseo/bridge.mjs b/runner/paseo/bridge.mjs| index 4a8583a9..86aec2af 100644 |
| --- a/runner/paseo/bridge.mjs |
| +++ b/runner/paseo/bridge.mjs |
| @@ -372,10 +372,17 @@ function validateEnv(env) { |
| } |
| } |
| +export function bridgeFailure(error) { |
| + const codes = new Set(['creation_absent', 'creation_receipts_required', 'invalid_request', 'frame_too_large', 'invalid_event', 'local_daemon_required', 'wrong_server', 'daemon_credential_unavailable', 'unsupported_client_version', 'unsupported_daemon_version', 'unsupported_provider', 'invalid_mcp', 'invalid_env', 'policy_mismatch', 'identity_mismatch', 'uncertain', 'timeline_gap', 'subscription_not_ready', 'invalid_permission', 'unknown_permission']); |
| + const definitive = error.definitiveCreateFailure === true; |
| + const policy = ['policy_mismatch', 'invalid_mcp'].includes(error.message); |
| + return { error: definitive && !policy ? 'create_refused' : codes.has(error.message) ? error.message : 'uncertain', definitive_create_failure: definitive }; |
| +} |
| + |
| export async function run(input, output, diagnostic) { |
| let bridge, buffer = Buffer.alloc(0), stopped = false, connecting = false; |
| const pending = new Set(); |
| - const codes = new Set(['creation_absent', 'creation_receipts_required', 'invalid_request', 'frame_too_large', 'invalid_event', 'local_daemon_required', 'wrong_server', 'daemon_credential_unavailable', 'unsupported_client_version', 'unsupported_daemon_version', 'unsupported_provider', 'invalid_mcp', 'invalid_env', 'policy_mismatch', 'identity_mismatch', 'uncertain', 'timeline_gap', 'subscription_not_ready', 'invalid_permission', 'unknown_permission']); |
| + |
| const write = value => { |
| if (stopped) return; |
| if (output.writableLength > MAX_FRAME * 8) fail('frame_too_large'); |
| @@ -398,9 +405,8 @@ export async function run(input, output, diagnostic) { |
| } |
| write({ version: 1, type: 'result', id: q.id, result }); |
| } catch (error) { |
| - const code = error.definitiveCreateFailure ? 'create_refused' : codes.has(error.message) ? error.message : 'uncertain'; |
| diagnostic.write('paseo_bridge_error\n'); |
| - write({ version: 1, type: 'result', id: typeof q?.id === 'string' ? q.id : '', error: code, result: {} }); |
| + write({ version: 1, type: 'result', id: typeof q?.id === 'string' ? q.id : '', ...bridgeFailure(error), result: {} }); |
| } |
| } |
| try { |
diff --git a/runner/paseo/bridge.test.mjs b/runner/paseo/bridge.test.mjs| index ceba4517..25129b34 100644 |
| --- a/runner/paseo/bridge.test.mjs |
| +++ b/runner/paseo/bridge.test.mjs |
| @@ -1,7 +1,7 @@ |
| import test from 'node:test'; |
| import assert from 'node:assert/strict'; |
| import { readFile } from 'node:fs/promises'; |
| -import { Bridge, connectLocal, normalizeEvent, providerPolicy, loadSDK, MAX_FRAME } from './bridge.mjs'; |
| +import { Bridge, bridgeFailure, connectLocal, normalizeEvent, providerPolicy, loadSDK, MAX_FRAME } from './bridge.mjs'; |
| const selection = { provider: 'claude', family: 'anthropic', model: 'claude-haiku-4-5', account_id: 'account-fixture' }; |
| const policy = { denied_paths: ['/protected'], config_hash: 'policy-fixture' }; |
| @@ -385,3 +385,16 @@ test('creation absence requires a complete lookup', async () => { |
| assert.equal(calls,2); |
| } |
| }); |
| + |
| + |
| +test('definitive policy failures retain their specific wire codes', async () => { |
| + for (const [field,code] of [['provider_options','policy_mismatch'],['mcp_servers','invalid_mcp']]) { |
| + const f=fake(); const r=request(); r[field]=null; |
| + await assert.rejects(f.bridge.createAgent(r), e => { |
| + assert.deepEqual(bridgeFailure(e), {error:code, definitive_create_failure:true}); |
| + return true; |
| + }); |
| + } |
| + assert.deepEqual(bridgeFailure(Object.assign(new Error('invalid_request'),{definitiveCreateFailure:true})),{error:'create_refused',definitive_create_failure:true}); |
| + assert.deepEqual(bridgeFailure(new Error('policy_mismatch')),{error:'policy_mismatch',definitive_create_failure:false}); |
| +}); |