oficina / equipo Public

fix: recover unacknowledged launches and bound idle preflight storage

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 1e54a4149cecb638892d672ea587763b482882cb parent 3cf98b6
18 files changed, +624 −29
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +249 −0
  • internal/equipo/runner_report_validation.go +13 −0
  • internal/runner/capture.go +9 −1
  • internal/runner/containment/recovery.go +20 −0
  • internal/runner/direct_namespaces.go +33 −5
  • internal/runner/direct_recovery.go +1 −1
  • internal/runner/direct_upload.go +27 −0
  • internal/runner/direct_upload_test.go +33 −0
  • internal/runner/direct_workflow.go +6 −7
  • internal/runner/direct_workflow_test.go +38 −0
  • internal/runner/journal.go +6 −1
  • internal/runner/journal_reset.go +1 −1
  • internal/runner/preflight_cache.go +67 −0
  • internal/runner/preflight_cache_test.go +72 −0
  • internal/runner/provider/accounts.go +23 −0
  • internal/runner/runtime.go +13 −12
  • internal/runner/runtime_direct.go +12 −1
  • internal/runnerproto/containment.go +1 −0
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index 2d3118f4..e1dfbb8e 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -25010,3 +25010,252 @@ Exit 0:
ok amadan.net/oficina/equipo/internal/directlive 92.875s
```
+
+## B2-I1
+
+Persist launch acknowledgment before releasing the harness. Cleanup verifies every local exit, reports unacknowledged namespaces as unstarted and moves pending launch events into the unstarted-launch journal record before acknowledging them locally. The instance accepts a matching unstarted exit even if it received the launch but its reply was lost. No capacity is freed without local containment. No UI strings.
+
+Interpretations: Red commands use the named tests in the green command. All listed mutations compile and were restored.
+
+### B2-I1-red
+
+```text
+--- FAIL: TestDirectUnacknowledgedNamespace (0.62s)
+ --- FAIL: TestDirectUnacknowledgedNamespace/crash-before-upload (0.32s)
+ direct_workflow_test.go:235: unacknowledged namespace reported as started
+ --- FAIL: TestDirectUnacknowledgedNamespace/stop-race (0.30s)
+ direct_workflow_test.go:235: unacknowledged namespace reported as started
+FAIL
+rastrillo-budget/v1 ran 619ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.623s
+FAIL
+```
+
+### B2-I1-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^TestDirect(UnacknowledgedNamespace|CancelWaitsForNamespaces)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 2.071s
+```
+
+### B2-I1-mut-unstarted
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^TestDirect(UnacknowledgedNamespace|CancelWaitsForNamespaces)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUnacknowledgedNamespace (1.10s)
+ --- FAIL: TestDirectUnacknowledgedNamespace/crash-before-upload (0.58s)
+ direct_workflow_test.go:248: unacknowledged namespace reported as started
+ --- FAIL: TestDirectUnacknowledgedNamespace/stop-race (0.51s)
+ direct_workflow_test.go:248: unacknowledged namespace reported as started
+FAIL
+rastrillo-budget/v1 ran 2.073s
+FAIL amadan.net/oficina/equipo/internal/runner 2.084s
+FAIL
+```
+
+### B2-I1-mut-deadletter
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^TestDirect(UnacknowledgedNamespace|CancelWaitsForNamespaces)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUnacknowledgedNamespace (1.18s)
+ --- FAIL: TestDirectUnacknowledgedNamespace/stop-race (0.58s)
+ direct_workflow_test.go:253: runner_not_claimed
+FAIL
+rastrillo-budget/v1 ran 2.114s
+FAIL amadan.net/oficina/equipo/internal/runner 2.119s
+FAIL
+```
+
+### B2-I1-mut-ack
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^TestDirect(UnacknowledgedNamespace|CancelWaitsForNamespaces)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCancelWaitsForNamespaces (0.63s)
+ direct_workflow_test.go:97: missing namespace proof: {Unstarted:[{ID:cc0461a02d9cc784961fff9693f9d1f4 AttemptKey:check-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532942] ManifestHash:6d0cfdebb5b3f1696756a6d92a891c8de1deec5f2e11cfd3b30c78c1c8fce5e9 HostPID:2752220 StartTicks:861060988 ExitCode:-1 Signal:9 ObservedAt:2026-11-04 00:41:37.21542386 +0000 UTC} {ID:fbaf64a6e1a4222288092f44528f9b2d AttemptKey:model-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532756] ManifestHash:303b67b638b7f583e28d952a6ca16dcb1f1717f5172f10325618c1bbcf742a68 HostPID:2752205 StartTicks:861060971 ExitCode:-1 Signal:9 ObservedAt:2026-11-04 00:41:37.275092971 +0000 UTC}] Namespaces:[] CheckedAt:2026-11-04 00:41:37.333968737 +0000 UTC Version:2 Scope:{Account:team Job:1} Handle:{Revision:0 Attempt:1 Fence:1 Runner:runner} Owner:{LocalOnly:false Attempt:0 Fence:0 Marker: AgentID: Workspace:{ServerID: ProjectID: WorkspaceID: Path:} ExecutorGroups:[]} Inventory:{Observed:[] ExecutorGroups:[] Processes:[] TerminalIDs:[] CoverageKnown:false BootID: CheckedAt:0001-01-01 00:00:00 +0000 UTC} Observed:[] Empty:false}
+FAIL
+rastrillo-budget/v1 ran 1.572s
+FAIL amadan.net/oficina/equipo/internal/runner 1.577s
+FAIL
+```
+
+
+## B2-I2
+
+Release contained no-turn frames at capture end, including cancelled preflights. Prune unowned preflight rows only after verified namespace records are forgotten. Preserve workflow-owned namespace records and all turn evidence. A pending-byte budget refusal does not latch a storage failure. Cache successful preflights by binding, current source fingerprint and policy hash; construction and release verification still validate binary, policy and home inputs on every discovery. This covers B2-M6. No UI strings.
+
+Interpretations: Red commands use the named tests in the green command. All listed mutations compile and were restored.
+
+### B2-I2-red
+
+```text
+--- FAIL: TestIdlePreflightStorageBounded (0.10s)
+ preflight_cache_test.go:21: idle poll 0 retained 1 frames and 1 attempts
+--- FAIL: TestDirectBudgetDrainsWithoutReset (0.05s)
+ preflight_cache_test.go:28: budget overrun latched journal: provider_uncertain
+ runner.journal
+--- FAIL: TestDirectPreflightCache (0.00s)
+ preflight_cache_test.go:34: idle polls/claim reran preflight 12 times
+FAIL
+rastrillo-budget/v1 ran 156ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.158s
+FAIL
+```
+
+### B2-I2-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^Test(IdlePreflightStorageBounded|DirectBudgetDrainsWithoutReset|DirectPreflightCache)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 1.290s
+```
+
+### B2-I2-mut-frames
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^Test(IdlePreflightStorageBounded|DirectBudgetDrainsWithoutReset|DirectPreflightCache)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestIdlePreflightStorageBounded (0.19s)
+ preflight_cache_test.go:32: idle poll 0 retained 1 frames and 1 attempts
+FAIL
+rastrillo-budget/v1 ran 253ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.256s
+FAIL
+```
+
+### B2-I2-mut-prune
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^Test(IdlePreflightStorageBounded|DirectBudgetDrainsWithoutReset|DirectPreflightCache)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestIdlePreflightStorageBounded (0.15s)
+ preflight_cache_test.go:32: idle poll 0 retained 0 frames and 1 attempts
+FAIL
+rastrillo-budget/v1 ran 213ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.222s
+FAIL
+```
+
+### B2-I2-mut-budget
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^Test(IdlePreflightStorageBounded|DirectBudgetDrainsWithoutReset|DirectPreflightCache)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectBudgetDrainsWithoutReset (0.14s)
+ preflight_cache_test.go:45: budget overrun latched journal: provider_uncertain
+ runner.journal
+FAIL
+rastrillo-budget/v1 ran 1.502s
+FAIL amadan.net/oficina/equipo/internal/runner 1.508s
+FAIL
+```
+
+### B2-I2-mut-cache
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^Test(IdlePreflightStorageBounded|DirectBudgetDrainsWithoutReset|DirectPreflightCache)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectPreflightCache (0.00s)
+ preflight_cache_test.go:57: idle polls/claim reran preflight 12 times
+FAIL
+rastrillo-budget/v1 ran 1.154s
+FAIL amadan.net/oficina/equipo/internal/runner 1.157s
+FAIL
+```
+
+### B2-I2-mut-invalidation
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^Test(IdlePreflightStorageBounded|DirectBudgetDrainsWithoutReset|DirectPreflightCache)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectPreflightCache (0.00s)
+ preflight_cache_test.go:63: changed input did not invalidate cache
+FAIL
+rastrillo-budget/v1 ran 1.119s
+FAIL amadan.net/oficina/equipo/internal/runner 1.127s
+FAIL
+```
+
+
+## B2-I3
+
+Upload each event with its own assignment, scope, handle and action. Close the launcher, await the event consumer and drain again before returning. Tests reject a stale event uploaded under another attempt and require final close events to drain. No UI strings.
+
+Interpretations: Red commands use the named tests in the green command. All listed mutations compile and were restored.
+
+### B2-I3-red
+
+```text
+--- FAIL: TestDirectUploadUsesEventIdentity (0.04s)
+ direct_upload_test.go:15: runner.invalid
+--- FAIL: TestDirectCloseDrainsFinalEvents (0.00s)
+ direct_upload_test.go:20: close event not drained
+FAIL
+rastrillo-budget/v1 ran 44ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.050s
+FAIL
+```
+
+### B2-I3-green
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^TestDirect(UploadUsesEventIdentity|CloseDrainsFinalEvents)$' -count=1`
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.045s
+```
+
+### B2-I3-mut-envelope
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^TestDirect(UploadUsesEventIdentity|CloseDrainsFinalEvents)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUploadUsesEventIdentity (0.04s)
+ direct_upload_test.go:23: runner.invalid
+FAIL
+rastrillo-budget/v1 ran 40ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.043s
+FAIL
+```
+
+### B2-I3-mut-drain
+
+`CGO_ENABLED=0 go test ./internal/runner -run '^TestDirect(UploadUsesEventIdentity|CloseDrainsFinalEvents)$' -count=1`
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCloseDrainsFinalEvents (0.00s)
+ direct_upload_test.go:31: close event not drained
+FAIL
+rastrillo-budget/v1 ran 40ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.042s
+FAIL
+```
+
diff --git a/internal/equipo/runner_report_validation.go b/internal/equipo/runner_report_validation.go
index d28dc5b9..408b4863 100644
--- a/internal/equipo/runner_report_validation.go
+++ b/internal/equipo/runner_report_validation.go
@@ -217,6 +217,19 @@ func validateNamespaceContainment(ctx context.Context, a Assignment, q RunnerReq
}
launches[n.ID] = n
}
+ seenUnstarted := map[string]bool{}
+ for _, exit := range p.Unstarted {
+ if exit.ID == "" || seenUnstarted[exit.ID] || exit.ObservedAt.IsZero() {
+ return ErrForbidden
+ }
+ seenUnstarted[exit.ID] = true
+ if n, ok := launches[exit.ID]; ok {
+ if !n.Matches(exit) {
+ return ErrForbidden
+ }
+ delete(launches, exit.ID)
+ }
+ }
if len(launches) != len(p.Namespaces) {
return ErrForbidden
}
diff --git a/internal/runner/capture.go b/internal/runner/capture.go
index 467cb7b4..549e1f99 100644
--- a/internal/runner/capture.go
+++ b/internal/runner/capture.go
@@ -269,6 +269,11 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
fail(e)
}
}
+ cleanup, stopCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ if e := f.journal.releaseDirectFrames(cleanup); e != nil {
+ fail(e)
+ }
+ stopCleanup()
input.Close()
stdout.Close()
stderr.Close()
@@ -317,7 +322,10 @@ func (j *Journal) AppendFrame(ctx context.Context, attempt, stream string, seq i
if e := tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); e != nil {
return e
}
- if blocked != 0 || size < 0 || int64(len(body)) > j.maxBytes-size {
+ if size >= 0 && int64(len(body)) > j.maxBytes-size {
+ return ErrJournalBudget
+ }
+ if blocked != 0 || size < 0 {
return ErrJournal
}
if _, e := tx.ExecContext(ctx, "INSERT INTO direct_frames(stream,sequence,body) VALUES(?,?,?)", stream, seq, body); e != nil {
diff --git a/internal/runner/containment/recovery.go b/internal/runner/containment/recovery.go
index edccc196..edf5cc42 100644
--- a/internal/runner/containment/recovery.go
+++ b/internal/runner/containment/recovery.go
@@ -336,3 +336,23 @@ func (m *Manager) RecoverUnstarted(ctx context.Context, r Record) (Proof, error)
}
return m.Recover(ctx, r)
}
+
+// Forget removes only an already verified, exited namespace's durable records.
+func (m *Manager) Forget(ctx context.Context, r Record) error {
+ proof, err := m.Recover(ctx, r)
+ if err != nil {
+ return err
+ }
+ if !proof.Verified {
+ return errIdentity
+ }
+ for _, suffix := range []string{".json", ".exit.json"} {
+ if err = os.Remove(filepath.Join(m.cfg.ScratchRoot, r.ID+suffix)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ }
+ m.mu.Lock()
+ delete(m.processes, r.ID)
+ m.mu.Unlock()
+ return nil
+}
diff --git a/internal/runner/direct_namespaces.go b/internal/runner/direct_namespaces.go
index 9a23af2b..0f346035 100644
--- a/internal/runner/direct_namespaces.go
+++ b/internal/runner/direct_namespaces.go
@@ -13,9 +13,10 @@ import (
type namespaceAdmissionKey struct{}
type namespaceState struct {
- Owner string
- Record containment.Record
- Proof *containment.Proof
+ LaunchAcknowledged bool
+ Owner string
+ Record containment.Record
+ Proof *containment.Proof
}
func (s *Supervisor) namespaceContext(ctx context.Context, r *attemptState) context.Context {
@@ -28,7 +29,10 @@ func (s *Supervisor) namespaceContext(ctx context.Context, r *attemptState) cont
return nil
}
n := runnerproto.NamespaceLaunch{ID: record.ID, AttemptKey: record.AttemptKey, OwnerKey: owner, BootID: record.BootID, NamespaceID: record.NamespaceID, ManifestHash: record.ManifestHash, PolicyHash: record.PolicyHash, HostPID: record.HostPID, StartTicks: record.StartTicks}
- return s.namespaceEvent(ctx, r, "namespace.launch", record.AttemptKey, record.ID, n)
+ if err := s.namespaceEvent(ctx, r, "namespace.launch", record.AttemptKey, record.ID, n); err != nil {
+ return err
+ }
+ return s.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record, LaunchAcknowledged: true})
})
}
@@ -124,7 +128,16 @@ func (s *Supervisor) cleanupDirect(ctx context.Context, r *attemptState) (Contai
}
}
if n.Record.HostPID != 0 {
- proof.Namespaces = append(proof.Namespaces, runnerproto.NamespaceExit{ID: p.Record.ID, AttemptKey: p.Record.AttemptKey, BootID: p.Record.BootID, NamespaceID: p.Record.NamespaceID, ManifestHash: p.Record.ManifestHash, HostPID: p.Record.HostPID, StartTicks: p.Record.StartTicks, ExitCode: p.Exit.Code, Signal: p.Exit.Signal, ObservedAt: p.Exit.ObservedAt})
+ exit := runnerproto.NamespaceExit{ID: p.Record.ID, AttemptKey: p.Record.AttemptKey, BootID: p.Record.BootID, NamespaceID: p.Record.NamespaceID, ManifestHash: p.Record.ManifestHash, HostPID: p.Record.HostPID, StartTicks: p.Record.StartTicks, ExitCode: p.Exit.Code, Signal: p.Exit.Signal, ObservedAt: p.Exit.ObservedAt}
+ if n.LaunchAcknowledged {
+ proof.Namespaces = append(proof.Namespaces, exit)
+ } else {
+ proof.Unstarted = append(proof.Unstarted, exit)
+ id := runnerproto.EventHash([]string{"namespace.launch", n.Record.AttemptKey, n.Record.ID})
+ if err = s.journal.deadLetterLaunch(ctx, id); err != nil {
+ failures = errors.Join(failures, err)
+ }
+ }
}
}
if failures != nil {
@@ -154,3 +167,18 @@ func (s *Supervisor) cleanupDirect(ctx context.Context, r *attemptState) (Contai
}
return s.reportContainment(ctx, r)
}
+
+func (j *Journal) deadLetterLaunch(ctx context.Context, id string) error {
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if _, err = tx.ExecContext(ctx, "INSERT OR IGNORE INTO journal_supervisor(kind,state_key,body) SELECT 'unstarted-launch',id,body FROM journal_events WHERE id=?", id); err != nil {
+ return err
+ }
+ if _, err = tx.ExecContext(ctx, "UPDATE journal_events SET acked=1 WHERE id=?", id); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
diff --git a/internal/runner/direct_recovery.go b/internal/runner/direct_recovery.go
index 506c47f6..ee659cb4 100644
--- a/internal/runner/direct_recovery.go
+++ b/internal/runner/direct_recovery.go
@@ -324,7 +324,7 @@ func (j *Journal) BindSession(ctx context.Context, s provider.Session) error {
func (j *Journal) releaseDirectFrames(ctx context.Context) error {
_, err := j.db.ExecContext(ctx, `DELETE FROM direct_frames WHERE pending=1 AND EXISTS (
- SELECT 1 FROM direct_attempts a WHERE a.stream=direct_frames.stream AND contained=1 AND (recovered=1 OR EXISTS(SELECT 1 FROM direct_turns t WHERE t.attempt=a.attempt)) AND NOT EXISTS(
+ SELECT 1 FROM direct_attempts a WHERE a.stream=direct_frames.stream AND contained=1 AND NOT EXISTS(
SELECT 1 FROM direct_turns t WHERE t.attempt=a.attempt AND t.state IN ('intent','dispatched')) AND NOT EXISTS(
SELECT 1 FROM journal_events e WHERE e.acked=0 AND json_extract(e.body,'$.agent_id')=a.attempt)
AND NOT EXISTS(SELECT 1 FROM direct_events d WHERE d.attempt=a.attempt AND d.projected=0))`)
diff --git a/internal/runner/direct_upload.go b/internal/runner/direct_upload.go
new file mode 100644
index 00000000..ccfdb15b
--- /dev/null
+++ b/internal/runner/direct_upload.go
@@ -0,0 +1,27 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+)
+
+func (s *Supervisor) uploadDirectEvent(ctx context.Context, r *attemptState, e Event) error {
+ q := runnerproto.RunnerRequest{Version: 2, AssignmentID: e.AssignmentID, Scope: e.Scope, Handle: e.Handle, RequestID: e.ID, ActionID: e.ActionID}
+ q.Event, _ = runnerproto.Marshal(e)
+ return s.api.Call(ctx, "events", q, nil)
+}
+func finishDirectStream(ctx context.Context, close func() error, done chan error, drain func(context.Context) error) error {
+ if err := close(); err != nil {
+ return err
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case err := <-done:
+ done <- err
+ if err != nil {
+ return err
+ }
+ }
+ return drain(ctx)
+}
diff --git a/internal/runner/direct_upload_test.go b/internal/runner/direct_upload_test.go
new file mode 100644
index 00000000..9fcad326
--- /dev/null
+++ b/internal/runner/direct_upload_test.go
@@ -0,0 +1,33 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "encoding/json"
+ "testing"
+)
+
+func TestDirectUploadUsesEventIdentity(t *testing.T) {
+ s, r, _, _ := cleanupFixture(t)
+ e := Event{Version: 2, ID: "stale-A", AssignmentID: "attempt-A", Scope: r.Claim.Scope, Handle: r.Claim.Handle}
+ e.Handle.Attempt++
+ e.Handle.Fence++
+ s.api = apiFuncR3(func(_ context.Context, _ string, q runnerproto.RunnerRequest, _ any) error {
+ var saved Event
+ mustJournal(t, json.Unmarshal(q.Event, &saved))
+ if q.AssignmentID != saved.AssignmentID || q.Scope != saved.Scope || q.Handle != saved.Handle {
+ return runnerproto.ErrInvalid
+ }
+ return nil
+ })
+ mustJournal(t, s.uploadDirectEvent(context.Background(), r, e))
+}
+func TestDirectCloseDrainsFinalEvents(t *testing.T) {
+ done := make(chan error, 1)
+ pending, uploaded := 0, 0
+ err := finishDirectStream(context.Background(), func() error { pending++; done <- nil; return nil }, done, func(context.Context) error { uploaded += pending; pending = 0; return nil })
+ mustJournal(t, err)
+ if uploaded != 1 || pending != 0 {
+ t.Fatal("close event not drained")
+ }
+}
diff --git a/internal/runner/direct_workflow.go b/internal/runner/direct_workflow.go
index 4d6f54fa..92565112 100644
--- a/internal/runner/direct_workflow.go
+++ b/internal/runner/direct_workflow.go
@@ -105,11 +105,7 @@ func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attempt
}
var action atomic.Int64
pump := EventPump{Journal: s.journal, Contain: func(ctx context.Context) error { return launcher.Interrupt(ctx, session) }, Upload: func(ctx context.Context, e Event) error {
- q := r.request(e.ID)
- q.RequestID = e.ID
- q.ActionID = e.ActionID
- q.Event, _ = runnerproto.Marshal(e)
- return s.api.Call(ctx, "events", q, nil)
+ return s.uploadDirectEvent(ctx, r, e)
}}
streamCtx, stopStream := context.WithCancel(ctx)
notices := make(chan provider.Event, 64)
@@ -122,7 +118,7 @@ func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attempt
return
case e, ok := <-events:
if !ok {
- drainDone <- errDirectUncertain
+ drainDone <- nil
return
}
template := Event{Version: 2, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ServerID: "direct", ActionID: team.ActionID(action.Load()), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
@@ -256,7 +252,7 @@ func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attempt
if e.Kind == "turn.failed" {
return team.ErrEvidence
}
- return launcher.Close(ctx, session)
+ return finishDirectStream(ctx, func() error { return launcher.Close(ctx, session) }, drainDone, pump.Drain)
}
}
@@ -273,6 +269,9 @@ func nextDirectNotice(ctx context.Context, notices <-chan provider.Event, done c
return provider.Event{}, ctx.Err()
case err := <-done:
done <- err
+ if err == nil {
+ err = errDirectUncertain
+ }
select {
case event := <-notices:
return event, nil
diff --git a/internal/runner/direct_workflow_test.go b/internal/runner/direct_workflow_test.go
index 7d6281aa..72b2d5cc 100644
--- a/internal/runner/direct_workflow_test.go
+++ b/internal/runner/direct_workflow_test.go
@@ -221,3 +221,41 @@ func TestDirectRestartAndLeaseLoss(t *testing.T) {
})
}
}
+
+func TestDirectUnacknowledgedNamespace(t *testing.T) {
+ for _, kind := range []string{"crash-before-upload", "stop-race"} {
+ t.Run(kind, func(t *testing.T) {
+ s, r, _, host, l := directNamespaceFixture(t)
+ mustJournal(t, s.save(context.Background(), r))
+ s.api = apiFuncR3(func(context.Context, string, runnerproto.RunnerRequest, any) error { return ErrNotClaimed })
+ var manifest struct{ Argv []string }
+ mustJournal(t, json.Unmarshal(l.Policy.Manifest, &manifest))
+ if _, err := host.Start(s.namespaceContext(context.Background(), r), l, manifest.Argv); err == nil {
+ t.Fatal("unacknowledged launch ran")
+ }
+ if kind == "crash-before-upload" {
+ _, err := s.journal.db.Exec("DELETE FROM journal_events")
+ mustJournal(t, err)
+ }
+ s.api = apiFuncR3(func(_ context.Context, op string, q runnerproto.RunnerRequest, out any) error {
+ if op == "events" {
+ return ErrNotClaimed
+ }
+ if op == "contained" {
+ var proof ContainmentProof
+ mustJournal(t, json.Unmarshal(q.Proof, &proof))
+ if len(proof.Namespaces) != 0 {
+ t.Fatal("unacknowledged namespace reported as started")
+ }
+ }
+ return nil
+ })
+ mustJournal(t, s.Recover(context.Background()))
+ pending, err := s.journal.Pending(context.Background(), 128)
+ mustJournal(t, err)
+ if len(pending) != 0 {
+ t.Fatal("rejected launch kept pending")
+ }
+ })
+ }
+}
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 3dd428f9..9e3c1637 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -19,6 +19,8 @@ type Event = runnerproto.Event
const MaxJournalBytes int64 = 128 << 20
+var ErrJournalBudget = errors.New("runner_journal_budget")
+
var ErrJournal = errors.Join(provider.ErrUncertain, errors.New("runner.journal"))
type Journal struct {
@@ -159,7 +161,10 @@ func (j *Journal) AdmissionAllowed(ctx context.Context) error {
if err := j.db.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&saved, &size); err != nil {
return j.storageFailure(ctx, err)
}
- if saved != 0 || size >= j.maxBytes {
+ if size >= j.maxBytes {
+ return ErrJournalBudget
+ }
+ if saved != 0 {
return ErrJournal
}
var unreconciled int
diff --git a/internal/runner/journal_reset.go b/internal/runner/journal_reset.go
index d3e1f9f1..ada31730 100644
--- a/internal/runner/journal_reset.go
+++ b/internal/runner/journal_reset.go
@@ -9,7 +9,7 @@ import (
)
func nonStorageError(err error) bool {
- return errors.Is(err, provider.ErrIdentity) || errors.Is(err, errDirectUncertain) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, runnerproto.ErrInvalid)
+ return errors.Is(err, ErrJournalBudget) || errors.Is(err, provider.ErrIdentity) || errors.Is(err, errDirectUncertain) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, runnerproto.ErrInvalid)
}
func (j *Journal) storageFailure(ctx context.Context, err error) error {
if ctx.Err() != nil {
diff --git a/internal/runner/preflight_cache.go b/internal/runner/preflight_cache.go
new file mode 100644
index 00000000..c66e5882
--- /dev/null
+++ b/internal/runner/preflight_cache.go
@@ -0,0 +1,67 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "context"
+ "encoding/json"
+)
+
+func (r *Runtime) cachedPreflight(ctx context.Context, id, key string, probe func() error) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.preflightCache == nil {
+ r.preflightCache = map[string]string{}
+ }
+ if r.preflightCache[id] == key && key != "" {
+ return nil
+ }
+ delete(r.preflightCache, id)
+ if err := probe(); err != nil {
+ return err
+ }
+ r.preflightCache[id] = key
+ return nil
+}
+func (j *Journal) prunePreflights(ctx context.Context, forget func(context.Context, containment.Record) error) error {
+ rows, err := j.db.QueryContext(ctx, `SELECT a.attempt,a.record FROM direct_attempts a WHERE contained=1
+ AND (attempt LIKE 'codex-preflight-%' OR attempt LIKE 'claude-preflight-%')
+ AND NOT EXISTS(SELECT 1 FROM direct_turns t WHERE t.attempt=a.attempt)
+ AND NOT EXISTS(SELECT 1 FROM direct_frames f WHERE f.stream=a.stream)
+ AND NOT EXISTS(SELECT 1 FROM direct_events e WHERE e.attempt=a.attempt)
+ AND NOT EXISTS(SELECT 1 FROM journal_supervisor s WHERE s.kind='namespace' AND json_extract(s.body,'$.Record.AttemptKey')=a.attempt)`)
+ if err != nil {
+ return err
+ }
+ var records []containment.Record
+ for rows.Next() {
+ var attempt string
+ var raw []byte
+ if err = rows.Scan(&attempt, &raw); err != nil {
+ break
+ }
+ var record containment.Record
+ if err = json.Unmarshal(raw, &record); err != nil {
+ break
+ }
+ records = append(records, record)
+ }
+ if err == nil {
+ err = rows.Err()
+ }
+ rows.Close()
+ if err != nil {
+ return err
+ }
+ for _, record := range records {
+ if err = forget(ctx, record); err != nil {
+ return err
+ }
+ if _, err = j.db.ExecContext(ctx, "DELETE FROM direct_attempts WHERE attempt=? AND contained=1", record.AttemptKey); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/runner/preflight_cache_test.go b/internal/runner/preflight_cache_test.go
new file mode 100644
index 00000000..1b5b7a22
--- /dev/null
+++ b/internal/runner/preflight_cache_test.go
@@ -0,0 +1,72 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+)
+
+func TestIdlePreflightStorageBounded(t *testing.T) {
+ j, l, _, p := directFixture(t, "codex")
+ ctx := context.Background()
+ _, err := j.db.Exec("DELETE FROM direct_attempts")
+ mustJournal(t, err)
+ for i := 0; i < 12; i++ {
+ l.AttemptKey = fmt.Sprintf("codex-preflight-%d", i)
+ l.Selection.ConnectionID = ""
+ p.record.AttemptKey = l.AttemptKey
+ p.record.ID = fmt.Sprintf("%032x", i+1)
+ mustJournal(t, j.recordDirectLaunch(ctx, l, p.record))
+ mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.record.ID, 1, []byte(`{"id":1,"result":{}}`)))
+ _, err = j.db.Exec("UPDATE direct_attempts SET contained=1 WHERE attempt=?", l.AttemptKey)
+ mustJournal(t, err)
+ mustJournal(t, j.releaseDirectFrames(ctx))
+ mustJournal(t, j.prunePreflights(ctx, func(context.Context, containment.Record) error { return nil }))
+ var frames, attempts int
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&frames))
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_attempts").Scan(&attempts))
+ if frames != 0 || attempts != 0 {
+ t.Fatalf("idle poll %d retained %d frames and %d attempts", i, frames, attempts)
+ }
+ }
+}
+func TestDirectBudgetDrainsWithoutReset(t *testing.T) {
+ j, l, _, p := directFixture(t, "codex")
+ ctx := context.Background()
+ j.maxBytes = 20
+ if err := j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"message":"`+strings.Repeat("x", 30)+`"}`)); err == nil {
+ t.Fatal("overrun accepted")
+ }
+ j.maxBytes = 1024
+ if err := j.AdmissionAllowed(ctx); err != nil {
+ t.Fatalf("budget overrun latched journal: %v", err)
+ }
+ mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"ok":true}`)))
+}
+func TestDirectPreflightCache(t *testing.T) {
+ r := &Runtime{}
+ calls := 0
+ probe := func() error { calls++; return nil }
+ for i := 0; i < 12; i++ {
+ mustJournal(t, r.cachedPreflight(context.Background(), "binding", "same", probe))
+ }
+ if calls != 1 {
+ t.Fatalf("idle polls/claim reran preflight %d times", calls)
+ }
+ for _, key := range []string{"account-changed", "policy-changed", "binary-changed", "home-changed"} {
+ mustJournal(t, r.cachedPreflight(context.Background(), "binding", key, probe))
+ }
+ if calls != 5 {
+ t.Fatal("changed input did not invalidate cache")
+ }
+ if err := r.cachedPreflight(context.Background(), "binding", "bad", func() error { return provider.ErrPolicy }); err == nil {
+ t.Fatal("failed preflight cached")
+ }
+ mustJournal(t, r.cachedPreflight(context.Background(), "binding", "bad", probe))
+ if calls != 6 {
+ t.Fatal("failure retained")
+ }
+}
diff --git a/internal/runner/provider/accounts.go b/internal/runner/provider/accounts.go
index c156d2b0..282ec023 100644
--- a/internal/runner/provider/accounts.go
+++ b/internal/runner/provider/accounts.go
@@ -770,3 +770,26 @@ func claudeAccountMetadata(dir *os.File) ([]byte, error) {
}
return json.Marshal(map[string]any{"oauthAccount": selected, "hasCompletedOnboarding": true})
}
+
+// PreflightFingerprint identifies the current source generation without granting authority.
+func (l *AccountLease) PreflightFingerprint(ctx context.Context) (string, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ if l.closed || l.contained {
+ return "", ErrContainment
+ }
+ _, generation, err := l.snapshot()
+ if err != nil {
+ return "", err
+ }
+ info, err := l.dir.Stat()
+ if err != nil {
+ return "", err
+ }
+ raw, _ := json.Marshal([]any{l.source, hex.EncodeToString(generation[:]), info.Sys()})
+ sum := sha256.Sum256(raw)
+ return hex.EncodeToString(sum[:]), nil
+}
diff --git a/internal/runner/runtime.go b/internal/runner/runtime.go
index 4e44590e..5ad526c2 100644
--- a/internal/runner/runtime.go
+++ b/internal/runner/runtime.go
@@ -20,18 +20,19 @@ import (
)
type Runtime struct {
- lastReports []runnerproto.ConnectionReport
- namespaces *containment.Manager
- launchers map[string]provider.Launcher
- host provider.ProcessHost
- cfg Config
- lock *os.File
- journal *Journal
- api *HTTPInstance
- service *Service
- sandbox *checks.CodexSandbox
- mu sync.Mutex
- current *RunClaim
+ preflightCache map[string]string
+ lastReports []runnerproto.ConnectionReport
+ namespaces *containment.Manager
+ launchers map[string]provider.Launcher
+ host provider.ProcessHost
+ cfg Config
+ lock *os.File
+ journal *Journal
+ api *HTTPInstance
+ service *Service
+ sandbox *checks.CodexSandbox
+ mu sync.Mutex
+ current *RunClaim
}
func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) {
diff --git a/internal/runner/runtime_direct.go b/internal/runner/runtime_direct.go
index 3676a424..e520b034 100644
--- a/internal/runner/runtime_direct.go
+++ b/internal/runner/runtime_direct.go
@@ -90,7 +90,15 @@ func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.Connect
report.IsolationConfigHash = l.Policy.Hash
// Certification is a release gate. Do not advertise an uncertified route.
if r.verifyRelease() == nil && certifiedDirect(b.Provider, b.ExpectedIdentity.ProviderVersion, l.Policy.Hash) {
- _, err = r.launchers[b.Provider].Preflight(ctx, l.Binding, l.Policy)
+ lease, leaseErr := l.Binding.AccountLease()
+ err = leaseErr
+ if err == nil {
+ var fingerprint string
+ fingerprint, err = lease.PreflightFingerprint(ctx)
+ if err == nil {
+ err = r.cachedPreflight(ctx, b.ID, runnerproto.EventHash([]string{fingerprint, l.Policy.Hash}), func() error { _, e := r.launchers[b.Provider].Preflight(ctx, l.Binding, l.Policy); return e })
+ }
+ }
if err == nil {
report.Available = true
report.ReadIsolation = true
@@ -111,6 +119,9 @@ func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.Connect
if e := os.RemoveAll(work); e != nil {
return nil, e
}
+ if err = r.journal.prunePreflights(ctx, r.namespaces.Forget); err != nil {
+ return nil, err
+ }
reports = append(reports, report)
}
return reports, nil
diff --git a/internal/runnerproto/containment.go b/internal/runnerproto/containment.go
index d57588f0..b6eebcbe 100644
--- a/internal/runnerproto/containment.go
+++ b/internal/runnerproto/containment.go
@@ -31,6 +31,7 @@ type ProcessInventory struct {
CheckedAt time.Time `json:"checked_at"`
}
type ContainmentProof struct {
+ Unstarted []NamespaceExit `json:"unstarted,omitempty"`
Namespaces []NamespaceExit `json:"namespaces,omitempty"`
CheckedAt time.Time `json:"checked_at,omitempty"`
// Zero identifies a historical proof without a version field.