fix: avoid cancellation journal latches and add guarded reset
10 files changed,
+243
−23
cmd/equipo-runner/main.go+3 −1docs/live-gate.md+11 −0internal/runner/events.go+3 −3internal/runner/final_journal_test.go+117 −0internal/runner/journal.go+8 −5internal/runner/journal_reset.go+66 −0internal/runner/process_linux.go+1 −1internal/runner/questions.go+6 −6internal/runner/service.go+21 −0internal/runner/tool_journal.go+7 −7
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go| index b52a2545..6668f8ba 100644 |
| --- a/cmd/equipo-runner/main.go |
| +++ b/cmd/equipo-runner/main.go |
| @@ -36,7 +36,7 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| } |
| return 0 |
| } |
| - if args[0] != "run" && args[0] != "enrol" && args[0] != "preflight" { |
| + if args[0] != "run" && args[0] != "enrol" && args[0] != "preflight" && args[0] != "reset" { |
| return fail() |
| } |
| cfg, err := runner.LoadConfig(getenv) |
| @@ -47,6 +47,8 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| switch args[0] { |
| case "enrol": |
| err = runner.Enrol(ctx, cfg, output) |
| + case "reset": |
| + err = runner.Reset(ctx, cfg) |
| case "run": |
| err = runner.Run(ctx, cfg) |
| case "preflight": |
diff --git a/docs/live-gate.md b/docs/live-gate.md| index cfe85339..d148c73d 100644 |
| --- a/docs/live-gate.md |
| +++ b/docs/live-gate.md |
| @@ -155,3 +155,14 @@ background process. Inspect agent, workspace, terminal and process cleanup. |
| A missing receipt or uncertain containment must remain unknown and charged, |
| never stopped or succeeded. Preserve the gate evidence, remove only owned |
| scratch and sentinels, and leave only the service you installed running. |
| + |
| +## Reset a blocked journal |
| + |
| +Stop the user service before running `equipo-runner reset` with the same runner |
| +environment. The command takes the state lock, refetches unresolved claims, |
| +reconciles and contains saved attempts, and uploads pending events. It clears the |
| +journal block only after those checks succeed and no pending events, tools or |
| +uncontained attempts remain. If it fails, keep the service stopped and resolve the |
| +reported cause before trying again. Do not delete the journal or edit its block |
| +flag. After a successful reset, restart the user service. New turns still require |
| +fresh authority and timeline recovery. |
diff --git a/internal/runner/events.go b/internal/runner/events.go| index 006f0b5b..5aee3e20 100644 |
| --- a/internal/runner/events.go |
| +++ b/internal/runner/events.go |
| @@ -62,7 +62,7 @@ func (j *Journal) BeginReplay(ctx context.Context, a paseo.Agent) error { |
| } |
| _, err := j.db.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,'',0,-1) ON CONFLICT(stream) DO UPDATE SET ready=-1`, streamKey(a)) |
| if err != nil { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| return nil |
| } |
| @@ -94,7 +94,7 @@ func (j *Journal) Recovered(ctx context.Context, a paseo.Agent, c paseo.Cursor) |
| // Called only after Subscribe.Ready and durable draining of its refetch. |
| tx, err := j.db.BeginTx(ctx, nil) |
| if err != nil { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| defer tx.Rollback() |
| var phase int |
| @@ -240,7 +240,7 @@ func journalStreamEvent(ctx context.Context, tx *sql.Tx, e Event) error { |
| } |
| func (p *EventPump) storageFailure(ctx context.Context, err error) error { |
| - _ = p.Journal.fail() |
| + _ = p.Journal.storageFailure(ctx, err) |
| cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) |
| defer cancel() |
| return errors.Join(err, p.Contain(cleanup)) |
diff --git a/internal/runner/final_journal_test.go b/internal/runner/final_journal_test.go| new file mode 100644 |
| index 00000000..64f7ffb6 |
| --- /dev/null |
| +++ b/internal/runner/final_journal_test.go |
| @@ -0,0 +1,117 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestJournalCancellationDoesNotLatch(t *testing.T) { |
| + for _, op := range []string{"event", "replay", "tool", "intent", "question", "pending", "ack"} { |
| + t.Run(op, func(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private/j.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + ctx, cancel := context.WithCancel(journalCtx) |
| + cancel() |
| + switch op { |
| + case "event": |
| + err = j.Append(ctx, journalEvent("event", 1)) |
| + case "replay": |
| + err = j.BeginReplay(ctx, paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}) |
| + case "tool": |
| + err = j.appendTool(ctx, ToolSubmission{RequestID: "tool"}, "hash") |
| + case "intent": |
| + err = j.RecordIntent(ctx, paseo.Intent{Kind: "agent", Key: "intent", RequestHash: "hash", Request: json.RawMessage(`{}`)}) |
| + case "question": |
| + err = (&QuestionRelay{Journal: j}).Invalidate(ctx, runnerproto.Question{}) |
| + case "pending": |
| + _, err = j.Pending(ctx, 10) |
| + case "ack": |
| + err = j.Ack(ctx, "event") |
| + } |
| + if err == nil { |
| + t.Fatal("cancelled operation succeeded") |
| + } |
| + if err = j.AdmissionAllowed(journalCtx); err != nil { |
| + t.Fatal("cancellation latched journal", err) |
| + } |
| + }) |
| + } |
| +} |
| +func TestJournalInvalidEventDoesNotLatch(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private/j.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} |
| + e := journalEvent("same", 1) |
| + mustJournal(t, pump.Append(journalCtx, e, nil)) |
| + e.Payload = json.RawMessage(`{"changed":true}`) |
| + if err = pump.Append(journalCtx, e, nil); !errors.Is(err, runnerproto.ErrInvalid) { |
| + t.Fatal("conflict accepted", err) |
| + } |
| + if err = j.AdmissionAllowed(journalCtx); err != nil { |
| + t.Fatal("conflict latched journal", err) |
| + } |
| +} |
| + |
| +type blockedSource struct{ claims int } |
| + |
| +func (s *blockedSource) Poll(context.Context) ([]runnerproto.Assignment, error) { |
| + return []runnerproto.Assignment{{ID: "blocked", Revision: 1}}, nil |
| +} |
| +func (s *blockedSource) Claim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| + s.claims++ |
| + return runnerproto.ClaimResponse{}, ErrClaimRefused |
| +} |
| +func TestBlockedJournalDoesNotClaim(t *testing.T) { |
| + s, _, _, _ := cleanupFixture(t) |
| + _, err := s.journal.db.Exec("DELETE FROM journal_supervisor WHERE kind='attempt'") |
| + mustJournal(t, err) |
| + s.states = map[string]*attemptState{} |
| + _ = s.journal.fail() |
| + source := &blockedSource{} |
| + service := Service{Supervisor: s, Source: source} |
| + ctx, cancel := context.WithTimeout(journalCtx, 100*time.Millisecond) |
| + defer cancel() |
| + _ = service.Run(ctx) |
| + if source.claims != 0 { |
| + t.Fatal("blocked journal claimed work", source.claims) |
| + } |
| +} |
| +func TestJournalResetRequiresReconciliation(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private/j.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + _ = j.fail() |
| + if err = j.resetAfterReconcile(journalCtx, func(context.Context) error { return paseo.ErrUncertain }); err == nil { |
| + t.Fatal("failed reconciliation reset block") |
| + } |
| + if j.AdmissionAllowed(journalCtx) == nil { |
| + t.Fatal("failed reconciliation reopened admission") |
| + } |
| + mustJournal(t, j.resetAfterReconcile(journalCtx, func(context.Context) error { return nil })) |
| + mustJournal(t, j.AdmissionAllowed(journalCtx)) |
| +} |
| + |
| +func TestJournalCancelWhileAppendWaits(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private/j.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + conn, err := j.db.Conn(journalCtx) |
| + mustJournal(t, err) |
| + ctx, cancel := context.WithCancel(journalCtx) |
| + done := make(chan error, 1) |
| + go func() { done <- j.Append(ctx, journalEvent("waiting", 1)) }() |
| + cancel() |
| + _ = conn.Close() |
| + if err = <-done; !errors.Is(err, context.Canceled) { |
| + t.Fatal("cancelled append lost cause", err) |
| + } |
| + mustJournal(t, j.AdmissionAllowed(journalCtx)) |
| +} |
diff --git a/internal/runner/journal.go b/internal/runner/journal.go| index 173a3dc5..73482cd5 100644 |
| --- a/internal/runner/journal.go |
| +++ b/internal/runner/journal.go |
| @@ -114,6 +114,9 @@ func (j *Journal) fail() error { |
| return ErrJournal |
| } |
| func (j *Journal) AdmissionAllowed(ctx context.Context) error { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| j.mu.Lock() |
| blocked := j.blocked |
| j.mu.Unlock() |
| @@ -143,7 +146,7 @@ func (j *Journal) appendRedacted(ctx context.Context, e Event, secrets []string) |
| } |
| err = j.append(ctx, e, hash, body) |
| if err != nil && !errors.Is(err, runnerproto.ErrInvalid) { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| return err |
| } |
| @@ -198,7 +201,7 @@ func (j *Journal) Pending(ctx context.Context, limit int) ([]Event, error) { |
| } |
| rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_events WHERE acked=0 ORDER BY ordinal LIMIT ?", limit) |
| if err != nil { |
| - return nil, j.fail() |
| + return nil, j.storageFailure(ctx, err) |
| } |
| defer rows.Close() |
| result := []Event{} |
| @@ -215,7 +218,7 @@ func (j *Journal) Pending(ctx context.Context, limit int) ([]Event, error) { |
| func (j *Journal) Ack(ctx context.Context, id string) error { |
| result, err := j.db.ExecContext(ctx, "UPDATE journal_events SET acked=1 WHERE event_key=(SELECT event_key FROM journal_aliases WHERE id=?)", id) |
| if err != nil { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| n, err := result.RowsAffected() |
| if err != nil || n != 1 { |
| @@ -248,7 +251,7 @@ func (j *Journal) RecordIntent(ctx context.Context, i paseo.Intent) error { |
| } |
| tx, err := j.db.BeginTx(ctx, nil) |
| if err != nil { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| err = func() error { |
| defer tx.Rollback() |
| @@ -273,7 +276,7 @@ func (j *Journal) RecordIntent(ctx context.Context, i paseo.Intent) error { |
| return tx.Commit() |
| }() |
| if err != nil && !errors.Is(err, runnerproto.ErrInvalid) { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| return err |
| } |
diff --git a/internal/runner/journal_reset.go b/internal/runner/journal_reset.go| new file mode 100644 |
| index 00000000..1b040916 |
| --- /dev/null |
| +++ b/internal/runner/journal_reset.go |
| @@ -0,0 +1,66 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "errors" |
| +) |
| + |
| +func nonStorageError(err error) bool { |
| + return 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 { |
| + return ctx.Err() |
| + } |
| + if nonStorageError(err) { |
| + return err |
| + } |
| + return j.fail() |
| +} |
| + |
| +// The operator reset holds admission closed until recovered work is contained |
| +// and every durable event has been accepted by the instance. |
| +func (j *Journal) resetAfterReconcile(ctx context.Context, reconcile func(context.Context) error) error { |
| + if reconcile == nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + _ = j.fail() |
| + if err := reconcile(ctx); err != nil { |
| + return err |
| + } |
| + var pending int |
| + if err := j.db.QueryRowContext(ctx, `SELECT |
| + (SELECT count(*) FROM journal_events WHERE acked=0)+ |
| + (SELECT count(*) FROM journal_tools WHERE acked=0)+ |
| + (SELECT count(*) FROM journal_supervisor WHERE kind='attempt' AND json_extract(body,'$.Phase')!='contained')`).Scan(&pending); err != nil { |
| + return j.storageFailure(ctx, err) |
| + } |
| + if pending != 0 { |
| + return ErrJournal |
| + } |
| + if _, err := j.db.ExecContext(ctx, "UPDATE journal_state SET blocked=0 WHERE id=1"); err != nil { |
| + return j.storageFailure(ctx, err) |
| + } |
| + j.mu.Lock() |
| + j.blocked = false |
| + j.mu.Unlock() |
| + return nil |
| +} |
| + |
| +func Reset(ctx context.Context, c Config) error { |
| + r, err := openRuntime(ctx, c) |
| + if err != nil { |
| + return err |
| + } |
| + defer r.Close() |
| + if err = r.wire(ctx); err != nil { |
| + return err |
| + } |
| + return r.journal.resetAfterReconcile(ctx, func(ctx context.Context) error { |
| + if err := r.service.recoverClaims(ctx); err != nil { |
| + return err |
| + } |
| + return r.service.Supervisor.Recover(ctx) |
| + }) |
| +} |
diff --git a/internal/runner/process_linux.go b/internal/runner/process_linux.go| index 6b74e2b2..1ec1c630 100644 |
| --- a/internal/runner/process_linux.go |
| +++ b/internal/runner/process_linux.go |
| @@ -621,7 +621,7 @@ func (j *Journal) saveState(ctx context.Context, kind, key string, v any) error |
| if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| return err |
| } |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| return nil |
| } |
diff --git a/internal/runner/questions.go b/internal/runner/questions.go| index a5312cce..7821e77a 100644 |
| --- a/internal/runner/questions.go |
| +++ b/internal/runner/questions.go |
| @@ -91,7 +91,7 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans |
| } |
| tx, err := r.Journal.db.BeginTx(ctx, nil) |
| if err != nil { |
| - return r.Journal.fail() |
| + return r.Journal.storageFailure(ctx, err) |
| } |
| defer tx.Rollback() |
| var old, state string |
| @@ -107,17 +107,17 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans |
| } |
| if !errors.Is(err, sql.ErrNoRows) { |
| tx.Rollback() |
| - return r.Journal.fail() |
| + return r.Journal.storageFailure(ctx, err) |
| } |
| if err = r.journalAdmissionTx(ctx, tx); err != nil { |
| return err |
| } |
| if _, err = tx.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", key, hash); err != nil { |
| tx.Rollback() |
| - return r.Journal.fail() |
| + return r.Journal.storageFailure(ctx, err) |
| } |
| if err = tx.Commit(); err != nil { |
| - return r.Journal.fail() |
| + return r.Journal.storageFailure(ctx, err) |
| } |
| q.ExpiresAt, err = r.Current(ctx, q) |
| if err != nil { |
| @@ -127,7 +127,7 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans |
| return err |
| } |
| if _, err = r.Journal.db.ExecContext(ctx, "UPDATE journal_answers SET state='delivered' WHERE answer_key=?", key); err != nil { |
| - return r.Journal.fail() |
| + return r.Journal.storageFailure(ctx, err) |
| } |
| return nil |
| } |
| @@ -203,7 +203,7 @@ func (r *QuestionRelay) Invalidate(ctx context.Context, q runnerproto.Question) |
| } |
| key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) |
| if _, err := r.Journal.db.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,'','invalid') ON CONFLICT(answer_key) DO UPDATE SET state='invalid'", key); err != nil { |
| - return r.Journal.fail() |
| + return r.Journal.storageFailure(ctx, err) |
| } |
| return nil |
| } |
diff --git a/internal/runner/service.go b/internal/runner/service.go| index 65f3512e..90bbec4a 100644 |
| --- a/internal/runner/service.go |
| +++ b/internal/runner/service.go |
| @@ -7,6 +7,7 @@ import ( |
| "crypto/rand" |
| "encoding/json" |
| "errors" |
| + "time" |
| ) |
| type AssignmentSource interface { |
| @@ -38,6 +39,15 @@ func (s *Service) Run(ctx context.Context) error { |
| return err |
| } |
| for _, a := range assignments { |
| + if err := s.Supervisor.journal.AdmissionAllowed(ctx); err != nil { |
| + if ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + if err := serviceBackoff(ctx); err != nil { |
| + return err |
| + } |
| + break |
| + } |
| if err = s.Supervisor.journal.saveState(ctx, "assignment", a.ID, a); err != nil { |
| return err |
| } |
| @@ -129,3 +139,14 @@ func (s *Service) clearClaim(ctx context.Context, q runnerproto.ClaimRequest) er |
| _, err := s.Supervisor.journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='claim' AND state_key=?", q.AssignmentID) |
| return err |
| } |
| + |
| +func serviceBackoff(ctx context.Context) error { |
| + timer := time.NewTimer(500 * time.Millisecond) |
| + defer timer.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-timer.C: |
| + return nil |
| + } |
| +} |
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go| index 804e11d4..51e90a18 100644 |
| --- a/internal/runner/tool_journal.go |
| +++ b/internal/runner/tool_journal.go |
| @@ -25,7 +25,7 @@ type ToolSubmission struct { |
| func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash string) error { |
| tx, err := j.db.BeginTx(ctx, nil) |
| if err != nil { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| defer tx.Rollback() |
| key := runnerproto.EventHash([]any{v.InstanceID, v.TaskID, v.Attempt, v.Fence, v.RequestID}) |
| @@ -40,7 +40,7 @@ func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash st |
| } |
| if !errors.Is(err, sql.ErrNoRows) { |
| tx.Rollback() |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| raw, err := json.Marshal(v) |
| if err != nil { |
| @@ -49,7 +49,7 @@ func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash st |
| var size int64 |
| if err = tx.QueryRowContext(ctx, "SELECT (SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)+(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)").Scan(&size); err != nil { |
| tx.Rollback() |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| if size+int64(len(raw)) > j.maxBytes { |
| return ErrJournal |
| @@ -59,17 +59,17 @@ func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash st |
| AND json_extract(body,'$.instance_id')=? AND json_extract(body,'$.task_id')=? |
| AND json_extract(body,'$.attempt')=? AND json_extract(body,'$.fence')=?`, v.InstanceID, v.TaskID, v.Attempt, v.Fence).Scan(&pending, &attemptBytes); err != nil { |
| tx.Rollback() |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| if pending >= 128 || attemptBytes+int64(len(raw)) > j.maxBytes/4 { |
| return ErrJournal |
| } |
| if _, err = tx.ExecContext(ctx, "INSERT INTO journal_tools(request_key,content_hash,body,acked) VALUES(?,?,?,0)", key, hash, raw); err != nil { |
| tx.Rollback() |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| if err = tx.Commit(); err != nil { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| return nil |
| } |
| @@ -100,7 +100,7 @@ func (j *Journal) AckTool(ctx context.Context, v ToolSubmission) error { |
| key := runnerproto.EventHash([]any{v.InstanceID, v.TaskID, v.Attempt, v.Fence, v.RequestID}) |
| _, err := j.db.ExecContext(ctx, "UPDATE journal_tools SET acked=1 WHERE request_key=?", key) |
| if err != nil { |
| - return j.fail() |
| + return j.storageFailure(ctx, err) |
| } |
| return nil |
| } |