| 1 | // Package thin is the thin v1 runner: one outbound WebSocket with a |
| 2 | // durable outbox, a generation lease, and a long-lived Claude coordinator |
| 3 | // session per person inside the existing containment. |
| 4 | package thin |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "crypto/rand" |
| 9 | "database/sql" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "path/filepath" |
| 14 | "slices" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/runner/metered" |
| 19 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 20 | "amadan.net/oficina/equipo/internal/wire" |
| 21 | _ "modernc.org/sqlite" |
| 22 | ) |
| 23 | |
| 24 | // Run states on the runner. A run is reported once its reply or failure is |
| 25 | // in the outbox, and done once the instance acked that frame. |
| 26 | const ( |
| 27 | runRunning = "running" |
| 28 | runReported = "reported" |
| 29 | runDone = "done" |
| 30 | runSuperseded = "superseded" |
| 31 | ) |
| 32 | |
| 33 | // State is the runner's durable store: <state>/thin.db. |
| 34 | type State struct { |
| 35 | db *sql.DB |
| 36 | prefix string |
| 37 | // fault, in tests, fails the named write ("finish_ask") on demand. |
| 38 | fault func(op string) error |
| 39 | } |
| 40 | |
| 41 | const schema = ` |
| 42 | CREATE TABLE IF NOT EXISTS copy_attempts (step_id TEXT NOT NULL, attempt INTEGER NOT NULL, result TEXT NOT NULL, spent INTEGER NOT NULL, known INTEGER NOT NULL, PRIMARY KEY(step_id,attempt)); |
| 43 | CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); |
| 44 | CREATE TABLE IF NOT EXISTS inbox (frame_id TEXT PRIMARY KEY, seen_at TEXT NOT NULL); |
| 45 | CREATE TABLE IF NOT EXISTS outbox (seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, body TEXT NOT NULL, turn_id TEXT NOT NULL, acked INTEGER NOT NULL DEFAULT 0); |
| 46 | CREATE TABLE IF NOT EXISTS runs (turn_id TEXT PRIMARY KEY, person TEXT NOT NULL, attempt INTEGER NOT NULL, state TEXT NOT NULL, text TEXT NOT NULL, tail TEXT NOT NULL, cancel INTEGER NOT NULL DEFAULT 0, recovered INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); |
| 47 | CREATE INDEX IF NOT EXISTS runs_person ON runs(person, state, created_at); |
| 48 | CREATE TABLE IF NOT EXISTS creations (call_id TEXT PRIMARY KEY, repo TEXT NOT NULL, state TEXT NOT NULL); |
| 49 | CREATE TABLE IF NOT EXISTS sessions (person TEXT NOT NULL, provider TEXT NOT NULL, account TEXT NOT NULL, session_id TEXT NOT NULL, last_turn TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (person, provider)); |
| 50 | CREATE TABLE IF NOT EXISTS sessions_lane (person TEXT NOT NULL, lane TEXT NOT NULL, provider TEXT NOT NULL, account TEXT NOT NULL, session_id TEXT NOT NULL, last_turn TEXT NOT NULL, updated_at TEXT NOT NULL, PRIMARY KEY (person, lane, provider)); |
| 51 | ` |
| 52 | |
| 53 | // OpenState opens or creates the store in the locked state directory. |
| 54 | func OpenState(ctx context.Context, dir string) (*State, error) { |
| 55 | path := filepath.Join(dir, "thin.db") |
| 56 | d, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(FULL)") |
| 57 | if err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | d.SetMaxOpenConns(1) |
| 61 | if _, err = d.ExecContext(ctx, schema+accessSchema+stepSchema+watchSchema+askSchema+connSchema+usageSchema+profileSchema+connectSchema+effectSchema+fileSchema+relaySchema+candidatesSchema+metered.Schema+researchSchema+scheduleSchema); err != nil { |
| 62 | d.Close() |
| 63 | return nil, err |
| 64 | } |
| 65 | if err = migrateAccess(ctx, d); err != nil { |
| 66 | d.Close() |
| 67 | return nil, err |
| 68 | } |
| 69 | // Added in slice 2b: a run's kind (person, move_in or explore) and |
| 70 | // the person's own words (JSON list), apart from the frame's text. |
| 71 | // Added with attachments: the files a run carries (JSON list). |
| 72 | // Added with the Assistant: the run's lane (empty: the coordinator). |
| 73 | // Added with the Assistant's files: its earlier files, a JSON object |
| 74 | // (runEarlier), never read by runningAttachments. |
| 75 | for _, add := range []string{"ALTER TABLE runs ADD COLUMN placement_notes TEXT NOT NULL DEFAULT '[]'", "ALTER TABLE runs ADD COLUMN kind TEXT NOT NULL DEFAULT ''", "ALTER TABLE runs ADD COLUMN person_text TEXT NOT NULL DEFAULT '[]'", "ALTER TABLE runs ADD COLUMN attachments TEXT NOT NULL DEFAULT '[]'", "ALTER TABLE runs ADD COLUMN lane TEXT NOT NULL DEFAULT ''", "ALTER TABLE runs ADD COLUMN earlier TEXT NOT NULL DEFAULT '{}'"} { |
| 76 | if _, err = d.ExecContext(ctx, add); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 77 | d.Close() |
| 78 | return nil, err |
| 79 | } |
| 80 | } |
| 81 | // Added in slice 4b review: a question's namespace, its held final |
| 82 | // report, and whether its provider started. |
| 83 | // Added with metered connections (connectors spec S1): a question |
| 84 | // held by its connection's guard, until when and why. |
| 85 | for _, col := range []string{"ns_id TEXT NOT NULL DEFAULT ''", "final TEXT NOT NULL DEFAULT ''", "started INTEGER NOT NULL DEFAULT 0", "not_before TEXT NOT NULL DEFAULT ''", "hold TEXT NOT NULL DEFAULT ''"} { |
| 86 | if _, err = d.ExecContext(ctx, "ALTER TABLE asks ADD COLUMN "+col); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 87 | d.Close() |
| 88 | return nil, err |
| 89 | } |
| 90 | } |
| 91 | // A Run now's pinned connection (protocol 29, paused work): "" is |
| 92 | // leave on any connection, as every release before it. |
| 93 | if _, err = d.ExecContext(ctx, "ALTER TABLE releases ADD COLUMN connection TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 94 | d.Close() |
| 95 | return nil, err |
| 96 | } |
| 97 | // Added in slice 3 review: a step's namespace and the ending it |
| 98 | // reported while its termination is still to be proven. |
| 99 | // Added in slice 4 review: the task branch head last reported. |
| 100 | if _, err = d.ExecContext(ctx, "ALTER TABLE watches ADD COLUMN seen_head TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 101 | d.Close() |
| 102 | return nil, err |
| 103 | } |
| 104 | // design_options: a Design attempt's submitted options (task 18). |
| 105 | // render_audit: its render_page calls' records (branch review 8). |
| 106 | // outcome: what a worker's Engineering commit is (wire.Outcome*), kept |
| 107 | // apart from its progress phase, and worker_report the final report a |
| 108 | // restart sends again (Mac runners slice F). |
| 109 | for _, col := range []string{"ns_id", "final_state", "final_reason", "not_before", "deferred_since", "design_options", "render_audit", "outcome", "worker_report"} { |
| 110 | if _, err = d.ExecContext(ctx, "ALTER TABLE steps ADD COLUMN "+col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 111 | d.Close() |
| 112 | return nil, err |
| 113 | } |
| 114 | } |
| 115 | // Added with the scheduler (connectors spec S3): a step's revision |
| 116 | // (the attempt the instance sent; failover keeps it), priority, |
| 117 | // deadline and rank in the release order, its hold, and whether its |
| 118 | // deadline check fired. render_page's per-step counts (task 10). |
| 119 | for _, col := range []string{"revision INTEGER NOT NULL DEFAULT 0", "priority TEXT NOT NULL DEFAULT ''", "by_at TEXT NOT NULL DEFAULT ''", "rank INTEGER NOT NULL DEFAULT 2", "hold TEXT NOT NULL DEFAULT ''", "deadline_notified INTEGER NOT NULL DEFAULT 0", "housekeeping INTEGER NOT NULL DEFAULT 0", "render_calls INTEGER NOT NULL DEFAULT 0", "render_captures INTEGER NOT NULL DEFAULT 0"} { |
| 120 | if _, err = d.ExecContext(ctx, "ALTER TABLE steps ADD COLUMN "+col); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 121 | d.Close() |
| 122 | return nil, err |
| 123 | } |
| 124 | } |
| 125 | // Added in slice 4c review: until when a merged task's kept sessions |
| 126 | // stay (Paul: ask about merged work for 14 days). |
| 127 | if _, err = d.ExecContext(ctx, "ALTER TABLE kept_sessions ADD COLUMN expires_at TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 128 | d.Close() |
| 129 | return nil, err |
| 130 | } |
| 131 | // Added in Connections slice 1 review round 2: the home a sign-out |
| 132 | // still has to delete, and its provider, kept until it is gone. |
| 133 | for _, col := range []string{"home", "provider"} { |
| 134 | if _, err = d.ExecContext(ctx, "ALTER TABLE connect_cleanups ADD COLUMN "+col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 135 | d.Close() |
| 136 | return nil, err |
| 137 | } |
| 138 | } |
| 139 | // Added with token connections: an attempt's kind, and whether its |
| 140 | // sealed secret is committed (credential_present). |
| 141 | // Added with Claude's sign-in by a link: the namespace record of the |
| 142 | // attempt's contained setup-token, proven gone before its home goes. |
| 143 | // Added with metered connections (connectors spec S1): an API-key |
| 144 | // attempt's billing, budget (JSON) and the model the person picked. |
| 145 | for _, col := range []string{"kind", "secret", "namespace", "billing", "budget", "model"} { |
| 146 | if _, err = d.ExecContext(ctx, "ALTER TABLE connect_attempts ADD COLUMN "+col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| 147 | d.Close() |
| 148 | return nil, err |
| 149 | } |
| 150 | } |
| 151 | // Added with models chosen per step (connectors spec rev 3.3 §16, |
| 152 | // slice S5b): the allowed sets, each admission's model, family, |
| 153 | // tier and table versions, and each kept session's model and family, |
| 154 | // backfilled from the connection's one model (§16.5). |
| 155 | if err = migrateModels(ctx, d); err != nil { |
| 156 | d.Close() |
| 157 | return nil, err |
| 158 | } |
| 159 | s := &State{db: d} |
| 160 | if err = s.laneSessions(ctx); err != nil { |
| 161 | d.Close() |
| 162 | return nil, err |
| 163 | } |
| 164 | if s.prefix, err = s.meta(ctx, "frame_prefix"); err != nil { |
| 165 | d.Close() |
| 166 | return nil, err |
| 167 | } |
| 168 | if s.prefix == "" { |
| 169 | s.prefix = "r" + strings.ToLower(rand.Text()[:10]) |
| 170 | if err = s.setMeta(ctx, "frame_prefix", s.prefix); err != nil { |
| 171 | d.Close() |
| 172 | return nil, err |
| 173 | } |
| 174 | } |
| 175 | return s, nil |
| 176 | } |
| 177 | |
| 178 | func (s *State) Close() error { return s.db.Close() } |
| 179 | |
| 180 | func (s *State) meta(ctx context.Context, key string) (string, error) { |
| 181 | var v string |
| 182 | err := s.db.QueryRowContext(ctx, "SELECT value FROM meta WHERE key=?", key).Scan(&v) |
| 183 | if errors.Is(err, sql.ErrNoRows) { |
| 184 | return "", nil |
| 185 | } |
| 186 | return v, err |
| 187 | } |
| 188 | |
| 189 | func (s *State) setMeta(ctx context.Context, key, value string) error { |
| 190 | _, err := s.db.ExecContext(ctx, "INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", key, value) |
| 191 | return err |
| 192 | } |
| 193 | |
| 194 | // SaveGeneration records the execution lease the instance granted. |
| 195 | func (s *State) SaveGeneration(ctx context.Context, g int64) error { |
| 196 | return s.setMeta(ctx, "generation", fmt.Sprint(g)) |
| 197 | } |
| 198 | |
| 199 | func now() string { return time.Now().UTC().Format(time.RFC3339Nano) } |
| 200 | |
| 201 | // tx runs fn in one transaction. |
| 202 | func (s *State) tx(ctx context.Context, fn func(*sql.Tx) error) error { |
| 203 | t, err := s.db.BeginTx(ctx, nil) |
| 204 | if err != nil { |
| 205 | return err |
| 206 | } |
| 207 | defer t.Rollback() |
| 208 | if err = fn(t); err != nil { |
| 209 | return err |
| 210 | } |
| 211 | return t.Commit() |
| 212 | } |
| 213 | |
| 214 | // seen records a durable frame id; false means it was already applied. |
| 215 | func seen(t *sql.Tx, id string) (bool, error) { |
| 216 | res, err := t.Exec("INSERT INTO inbox(frame_id, seen_at) VALUES(?,?) ON CONFLICT DO NOTHING", id, now()) |
| 217 | if err != nil { |
| 218 | return false, err |
| 219 | } |
| 220 | n, err := res.RowsAffected() |
| 221 | return n == 1, err |
| 222 | } |
| 223 | |
| 224 | // enqueue adds a durable frame to the outbox in the caller's transaction. |
| 225 | func (s *State) enqueue(t *sql.Tx, kind, turnID string, body any) error { |
| 226 | raw, err := json.Marshal(body) |
| 227 | if err != nil { |
| 228 | return err |
| 229 | } |
| 230 | res, err := t.Exec("INSERT INTO outbox(id, kind, body, turn_id) VALUES(?,?,?,?)", s.prefix+"-pending-"+rand.Text(), kind, string(raw), turnID) |
| 231 | if err != nil { |
| 232 | return err |
| 233 | } |
| 234 | seq, err := res.LastInsertId() |
| 235 | if err != nil { |
| 236 | return err |
| 237 | } |
| 238 | _, err = t.Exec("UPDATE outbox SET id=? WHERE seq=?", fmt.Sprintf("%s-%d", s.prefix, seq), seq) |
| 239 | return err |
| 240 | } |
| 241 | |
| 242 | // Unacked returns outbox frames in order. |
| 243 | func (s *State) Unacked(ctx context.Context, after int64) ([]wire.Frame, int64, error) { |
| 244 | rows, err := s.db.QueryContext(ctx, "SELECT seq, id, kind, body FROM outbox WHERE acked=0 AND seq>? ORDER BY seq", after) |
| 245 | if err != nil { |
| 246 | return nil, after, err |
| 247 | } |
| 248 | defer rows.Close() |
| 249 | var out []wire.Frame |
| 250 | last := after |
| 251 | for rows.Next() { |
| 252 | var f wire.Frame |
| 253 | var body string |
| 254 | if err = rows.Scan(&last, &f.ID, &f.Type, &body); err != nil { |
| 255 | return nil, after, err |
| 256 | } |
| 257 | f.Data = json.RawMessage(body) |
| 258 | out = append(out, f) |
| 259 | } |
| 260 | return out, last, rows.Err() |
| 261 | } |
| 262 | |
| 263 | // Acked marks an outbox frame acked and finishes its run. |
| 264 | func (s *State) Acked(ctx context.Context, id string) error { |
| 265 | return s.tx(ctx, func(t *sql.Tx) error { |
| 266 | var kind, turn, body string |
| 267 | err := t.QueryRow("SELECT kind, turn_id, body FROM outbox WHERE id=? AND acked=0", id).Scan(&kind, &turn, &body) |
| 268 | if errors.Is(err, sql.ErrNoRows) { |
| 269 | return nil |
| 270 | } |
| 271 | if err != nil { |
| 272 | return err |
| 273 | } |
| 274 | if _, err = t.Exec("UPDATE outbox SET acked=1 WHERE id=?", id); err != nil { |
| 275 | return err |
| 276 | } |
| 277 | switch kind { |
| 278 | case wire.FrameReply: |
| 279 | var r wire.Reply |
| 280 | if err = json.Unmarshal([]byte(body), &r); err != nil { |
| 281 | return err |
| 282 | } |
| 283 | _, err = t.Exec("UPDATE runs SET state=? WHERE turn_id=? AND attempt=? AND state=?", runDone, turn, r.Attempt, runReported) |
| 284 | case wire.FrameTurn: |
| 285 | // Only the ack of a terminal report finishes a run; the ack of a |
| 286 | // recovery announcement (running, new attempt) does not. |
| 287 | var r wire.TurnReport |
| 288 | if err = json.Unmarshal([]byte(body), &r); err != nil { |
| 289 | return err |
| 290 | } |
| 291 | if wire.Terminal(r.State) { |
| 292 | _, err = t.Exec("UPDATE runs SET state=? WHERE turn_id=? AND attempt=? AND state IN (?,?)", runDone, turn, r.Attempt, runReported, runSuperseded) |
| 293 | } |
| 294 | case wire.FrameStep: |
| 295 | err = stepAcked(t, body) |
| 296 | case wire.FrameAnswer: |
| 297 | err = answerAcked(t, body) |
| 298 | } |
| 299 | return err |
| 300 | }) |
| 301 | } |
| 302 | |
| 303 | // run is one turn attempt held by this runner, in the coordinator's lane |
| 304 | // or the Assistant's. |
| 305 | type run struct { |
| 306 | PlacementNotes []wire.NotebookEntry |
| 307 | TurnID, Person, Text, Kind, Lane string |
| 308 | PersonText []string |
| 309 | Attachments []wire.AttachmentRef |
| 310 | // Earlier and EarlierMore are an Assistant turn's earlier files, kept |
| 311 | // apart from Attachments: they are listed, never protected. |
| 312 | Earlier []wire.AttachmentRef |
| 313 | EarlierMore int |
| 314 | Attempt int64 |
| 315 | Tail []wire.TailMessage |
| 316 | Cancel bool |
| 317 | Recovered bool |
| 318 | // Received is when the runner committed the message frame. |
| 319 | Received time.Time |
| 320 | } |
| 321 | |
| 322 | // runEarlier is a run's earlier column. |
| 323 | type runEarlier struct { |
| 324 | Files []wire.AttachmentRef `json:"files,omitempty"` |
| 325 | More int `json:"more,omitempty"` |
| 326 | } |
| 327 | |
| 328 | // creation is how far a create_project call got: "" (not started), |
| 329 | // "made" (the hub answered that this call created it, so it is ours to |
| 330 | // start), "created" (the repository exists, started) or "done" (the |
| 331 | // instance has it). |
| 332 | func (s *State) creation(ctx context.Context, callID, repo string) (string, error) { |
| 333 | var state, got string |
| 334 | err := s.db.QueryRowContext(ctx, "SELECT repo, state FROM creations WHERE call_id=?", callID).Scan(&got, &state) |
| 335 | if errors.Is(err, sql.ErrNoRows) { |
| 336 | return "", nil |
| 337 | } |
| 338 | if err == nil && got != repo { |
| 339 | return "", provider.ErrPolicy |
| 340 | } |
| 341 | return state, err |
| 342 | } |
| 343 | |
| 344 | func (s *State) setCreation(ctx context.Context, callID, repo, state string) error { |
| 345 | _, err := s.db.ExecContext(ctx, "INSERT INTO creations(call_id, repo, state) VALUES(?,?,?) ON CONFLICT(call_id) DO UPDATE SET state=excluded.state", callID, repo, state) |
| 346 | return err |
| 347 | } |
| 348 | |
| 349 | // AcceptReset records a reset command exactly once; it stays pending |
| 350 | // until ResetDone, so a restart applies it. |
| 351 | func (s *State) AcceptReset(ctx context.Context, frameID, person string) (fresh bool, err error) { |
| 352 | err = s.tx(ctx, func(t *sql.Tx) error { |
| 353 | if fresh, err = seen(t, frameID); err != nil || !fresh { |
| 354 | return err |
| 355 | } |
| 356 | _, err = t.Exec("INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", "reset:"+person, now()) |
| 357 | return err |
| 358 | }) |
| 359 | return fresh, err |
| 360 | } |
| 361 | |
| 362 | // pendingResets lists persons with a reset not yet applied. |
| 363 | func (s *State) pendingResets(ctx context.Context) ([]string, error) { |
| 364 | rows, err := s.db.QueryContext(ctx, "SELECT key FROM meta WHERE key LIKE 'reset:%' ORDER BY key") |
| 365 | if err != nil { |
| 366 | return nil, err |
| 367 | } |
| 368 | defer rows.Close() |
| 369 | var out []string |
| 370 | for rows.Next() { |
| 371 | var k string |
| 372 | if err = rows.Scan(&k); err != nil { |
| 373 | return nil, err |
| 374 | } |
| 375 | out = append(out, strings.TrimPrefix(k, "reset:")) |
| 376 | } |
| 377 | return out, rows.Err() |
| 378 | } |
| 379 | |
| 380 | // resetPending reports whether the person has a reset not yet applied. |
| 381 | func (s *State) resetPending(ctx context.Context, person string) (bool, error) { |
| 382 | v, err := s.meta(ctx, "reset:"+person) |
| 383 | return v != "", err |
| 384 | } |
| 385 | |
| 386 | // ResetDone clears a person's pending reset. |
| 387 | func (s *State) ResetDone(ctx context.Context, person string) error { |
| 388 | _, err := s.db.ExecContext(ctx, "DELETE FROM meta WHERE key=?", "reset:"+person) |
| 389 | return err |
| 390 | } |
| 391 | |
| 392 | // SendNotebook queues a durable report of a person's notebook. |
| 393 | func (s *State) SendNotebook(ctx context.Context, n wire.NotebookReport) error { |
| 394 | if n.Entries == nil { |
| 395 | n.Entries = []wire.NotebookEntry{} |
| 396 | } |
| 397 | return s.tx(ctx, func(t *sql.Tx) error { return s.enqueue(t, wire.FrameNotebook, "", n) }) |
| 398 | } |
| 399 | |
| 400 | // deleteSession forgets a person's session in one lane: the next |
| 401 | // process there starts a fresh one. |
| 402 | func (s *State) deleteSession(ctx context.Context, person, lane string) error { |
| 403 | _, err := s.db.ExecContext(ctx, "DELETE FROM sessions_lane WHERE person=? AND lane=?", person, lane) |
| 404 | return err |
| 405 | } |
| 406 | |
| 407 | // SendMoveIn queues a durable request for a move_in or explore turn. |
| 408 | func (s *State) SendMoveIn(ctx context.Context, m wire.MoveIn) error { |
| 409 | return s.tx(ctx, func(t *sql.Tx) error { return s.enqueue(t, wire.FrameMoveIn, "", m) }) |
| 410 | } |
| 411 | |
| 412 | // SendToolCall queues a durable tool call for the instance. |
| 413 | func (s *State) SendToolCall(ctx context.Context, c wire.ToolCall) error { |
| 414 | return s.tx(ctx, func(t *sql.Tx) error { return s.enqueue(t, wire.FrameToolCall, c.TurnID, c) }) |
| 415 | } |
| 416 | |
| 417 | // SeenResult records a tool result frame id; false means a repeat. |
| 418 | func (s *State) SeenResult(ctx context.Context, frameID string) (fresh bool, err error) { |
| 419 | err = s.tx(ctx, func(t *sql.Tx) error { fresh, err = seen(t, frameID); return err }) |
| 420 | return fresh, err |
| 421 | } |
| 422 | |
| 423 | // Accept records a message command exactly once. The caller acks after. |
| 424 | func (s *State) Accept(ctx context.Context, frameID string, m wire.MessageCommand) error { |
| 425 | notes, _ := json.Marshal(m.PlacementNotes) |
| 426 | tail, _ := json.Marshal(m.Tail) |
| 427 | own, _ := json.Marshal(m.PersonText) |
| 428 | files, _ := json.Marshal(m.Attachments) |
| 429 | if m.Attachments == nil { |
| 430 | files = []byte("[]") |
| 431 | } |
| 432 | earlier, _ := json.Marshal(runEarlier{Files: m.Earlier, More: m.EarlierMore}) |
| 433 | return s.tx(ctx, func(t *sql.Tx) error { |
| 434 | fresh, err := seen(t, frameID) |
| 435 | if err != nil || !fresh { |
| 436 | return err |
| 437 | } |
| 438 | if _, err = t.Exec("INSERT INTO runs(turn_id, person, attempt, state, text, tail, kind, person_text, attachments, earlier, lane, placement_notes, created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", m.TurnID, m.Person, max(m.Attempt, 1), runRunning, m.Text, string(tail), m.Kind, string(own), string(files), string(earlier), m.Lane, string(notes), now()); err != nil { |
| 439 | return err |
| 440 | } |
| 441 | // The running turn protects its files from here; their admissions |
| 442 | // (which protected them until now) are done. |
| 443 | for _, r := range m.Attachments { |
| 444 | if _, err = t.Exec("DELETE FROM file_admits WHERE attachment_id=? AND state=?", r.ID, admitDelivered); err != nil { |
| 445 | return err |
| 446 | } |
| 447 | } |
| 448 | return nil |
| 449 | }) |
| 450 | } |
| 451 | |
| 452 | // RequestCancel marks a held attempt cancelled exactly once. It reports |
| 453 | // whether the attempt is still running here. |
| 454 | func (s *State) RequestCancel(ctx context.Context, frameID string, c wire.CancelCommand) (bool, error) { |
| 455 | running := false |
| 456 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 457 | fresh, err := seen(t, frameID) |
| 458 | if err != nil || !fresh { |
| 459 | return err |
| 460 | } |
| 461 | // A cancel names the attempt the instance knew; a later attempt of |
| 462 | // the same turn (a failover or a recovery the instance had not yet |
| 463 | // heard of) is the same turn, and stops too. |
| 464 | res, err := t.Exec("UPDATE runs SET cancel=1 WHERE turn_id=? AND attempt>=? AND state=?", c.TurnID, c.Attempt, runRunning) |
| 465 | if err != nil { |
| 466 | return err |
| 467 | } |
| 468 | n, _ := res.RowsAffected() |
| 469 | running = n == 1 |
| 470 | if !running { |
| 471 | // A cancel for a turn this runner has not seen yet: hold a |
| 472 | // cancelled run, so a late message is never executed and the |
| 473 | // instance still gets its termination report. |
| 474 | _, err = t.Exec("INSERT INTO runs(turn_id, person, attempt, state, text, tail, cancel, created_at) VALUES(?,?,?,?,?,?,1,?) ON CONFLICT DO NOTHING", c.TurnID, c.Person, max(c.Attempt, 1), runRunning, "", "[]", now()) |
| 475 | } |
| 476 | return err |
| 477 | }) |
| 478 | return running, err |
| 479 | } |
| 480 | |
| 481 | // next is the person's oldest running run in the lane. |
| 482 | func (s *State) next(ctx context.Context, person, lane string) (run, bool, error) { |
| 483 | var r run |
| 484 | var tail, own, files, earlier, notes string |
| 485 | var cancel, recovered int |
| 486 | var received string |
| 487 | err := s.db.QueryRowContext(ctx, "SELECT turn_id, person, lane, attempt, text, tail, kind, person_text, attachments, earlier, placement_notes, cancel, recovered, created_at FROM runs WHERE person=? AND lane=? AND state=? ORDER BY created_at, turn_id LIMIT 1", person, lane, runRunning).Scan(&r.TurnID, &r.Person, &r.Lane, &r.Attempt, &r.Text, &tail, &r.Kind, &own, &files, &earlier, ¬es, &cancel, &recovered, &received) |
| 488 | r.Received, _ = time.Parse(time.RFC3339Nano, received) |
| 489 | if errors.Is(err, sql.ErrNoRows) { |
| 490 | return r, false, nil |
| 491 | } |
| 492 | if err != nil { |
| 493 | return r, false, err |
| 494 | } |
| 495 | r.Cancel, r.Recovered = cancel == 1, recovered == 1 |
| 496 | _ = json.Unmarshal([]byte(tail), &r.Tail) |
| 497 | _ = json.Unmarshal([]byte(own), &r.PersonText) |
| 498 | _ = json.Unmarshal([]byte(notes), &r.PlacementNotes) |
| 499 | _ = json.Unmarshal([]byte(files), &r.Attachments) |
| 500 | var e runEarlier |
| 501 | _ = json.Unmarshal([]byte(earlier), &e) |
| 502 | r.Earlier, r.EarlierMore = e.Files, e.More |
| 503 | return r, true, nil |
| 504 | } |
| 505 | |
| 506 | // workers lists every person and lane with a running run. |
| 507 | func (s *State) workers(ctx context.Context) ([]workerKey, error) { |
| 508 | rows, err := s.db.QueryContext(ctx, "SELECT DISTINCT person, lane FROM runs WHERE state=?", runRunning) |
| 509 | if err != nil { |
| 510 | return nil, err |
| 511 | } |
| 512 | defer rows.Close() |
| 513 | var out []workerKey |
| 514 | for rows.Next() { |
| 515 | var k workerKey |
| 516 | if err = rows.Scan(&k.Person, &k.Lane); err != nil { |
| 517 | return nil, err |
| 518 | } |
| 519 | out = append(out, k) |
| 520 | } |
| 521 | return out, rows.Err() |
| 522 | } |
| 523 | |
| 524 | // runLane is the lane of a held turn; the coordinator's when unknown. |
| 525 | func (s *State) runLane(ctx context.Context, turn string) string { |
| 526 | var lane string |
| 527 | _ = s.db.QueryRowContext(ctx, "SELECT lane FROM runs WHERE turn_id=?", turn).Scan(&lane) |
| 528 | return lane |
| 529 | } |
| 530 | |
| 531 | // Report ends a run: its reply or failure goes into the outbox in the same |
| 532 | // transaction as the state change. |
| 533 | func (s *State) Report(ctx context.Context, r run, reply *wire.Reply, report *wire.TurnReport, usage []wire.Usage) error { |
| 534 | return s.tx(ctx, func(t *sql.Tx) error { |
| 535 | res, err := t.Exec("UPDATE runs SET state=? WHERE turn_id=? AND attempt=? AND state=?", runReported, r.TurnID, r.Attempt, runRunning) |
| 536 | if err != nil { |
| 537 | return err |
| 538 | } |
| 539 | if n, _ := res.RowsAffected(); n != 1 { |
| 540 | return nil |
| 541 | } |
| 542 | if reply != nil { |
| 543 | return s.enqueue(t, wire.FrameReply, r.TurnID, reply) |
| 544 | } |
| 545 | if len(usage) > 0 { |
| 546 | // What the attempt used, though it did not reply. |
| 547 | if err := s.enqueue(t, wire.FrameUsage, r.TurnID, wire.UsageReport{TurnID: r.TurnID, Rows: usage}); err != nil { |
| 548 | return err |
| 549 | } |
| 550 | } |
| 551 | return s.enqueue(t, wire.FrameTurn, r.TurnID, report) |
| 552 | }) |
| 553 | } |
| 554 | |
| 555 | // Recover handles runs a previous process left running: one new attempt, |
| 556 | // announced to the instance; a second crash fails the turn visibly. |
| 557 | func (s *State) Recover(ctx context.Context) error { |
| 558 | return s.tx(ctx, func(t *sql.Tx) error { |
| 559 | rows, err := t.Query("SELECT turn_id, attempt, recovered, cancel FROM runs WHERE state=?", runRunning) |
| 560 | if err != nil { |
| 561 | return err |
| 562 | } |
| 563 | type stale struct { |
| 564 | turn string |
| 565 | attempt int64 |
| 566 | recovered, cancel int |
| 567 | } |
| 568 | var all []stale |
| 569 | for rows.Next() { |
| 570 | var x stale |
| 571 | if err = rows.Scan(&x.turn, &x.attempt, &x.recovered, &x.cancel); err != nil { |
| 572 | rows.Close() |
| 573 | return err |
| 574 | } |
| 575 | all = append(all, x) |
| 576 | } |
| 577 | rows.Close() |
| 578 | for _, x := range all { |
| 579 | // A run held waiting for a connection ran nothing: a restart is |
| 580 | // not a crash for it. It stays as it is and is held again. |
| 581 | var body string |
| 582 | if err := t.QueryRow("SELECT body FROM outbox WHERE turn_id=? AND kind=? ORDER BY seq DESC LIMIT 1", x.turn, wire.FrameTurn).Scan(&body); err == nil && x.cancel == 0 { |
| 583 | var last wire.TurnReport |
| 584 | if json.Unmarshal([]byte(body), &last) == nil && last.State == wire.TurnWaiting && last.Reason == wire.ReasonNoConnection && last.Attempt == x.attempt { |
| 585 | continue |
| 586 | } |
| 587 | } |
| 588 | if x.cancel != 0 { |
| 589 | // The previous process is gone (its namespaces die with it, |
| 590 | // and their exits are verified at start): the cancelled |
| 591 | // attempt is over and is never retried. |
| 592 | if _, err = t.Exec("UPDATE runs SET state=? WHERE turn_id=?", runReported, x.turn); err != nil { |
| 593 | return err |
| 594 | } |
| 595 | if err = s.enqueue(t, wire.FrameTurn, x.turn, wire.TurnReport{TurnID: x.turn, Attempt: x.attempt, State: wire.TurnCancelled, Reason: "cancelled"}); err != nil { |
| 596 | return err |
| 597 | } |
| 598 | continue |
| 599 | } |
| 600 | if x.recovered != 0 { |
| 601 | if _, err = t.Exec("UPDATE runs SET state=? WHERE turn_id=?", runReported, x.turn); err != nil { |
| 602 | return err |
| 603 | } |
| 604 | if err = s.enqueue(t, wire.FrameTurn, x.turn, wire.TurnReport{TurnID: x.turn, Attempt: x.attempt, State: wire.TurnFailed, Reason: "runner_restarted"}); err != nil { |
| 605 | return err |
| 606 | } |
| 607 | continue |
| 608 | } |
| 609 | if _, err = t.Exec("UPDATE runs SET attempt=attempt+1, recovered=1 WHERE turn_id=?", x.turn); err != nil { |
| 610 | return err |
| 611 | } |
| 612 | if err = s.enqueue(t, wire.FrameTurn, x.turn, wire.TurnReport{TurnID: x.turn, Attempt: x.attempt + 1, State: wire.TurnRunning}); err != nil { |
| 613 | return err |
| 614 | } |
| 615 | } |
| 616 | return nil |
| 617 | }) |
| 618 | } |
| 619 | |
| 620 | // Supersede marks every held run superseded after a newer generation took |
| 621 | // the lease; the instance learns from its own sync. |
| 622 | func (s *State) Supersede(ctx context.Context) error { |
| 623 | if _, err := s.db.ExecContext(ctx, "UPDATE runs SET state=? WHERE state=?", runSuperseded, runRunning); err != nil { |
| 624 | return err |
| 625 | } |
| 626 | _, err := s.db.ExecContext(ctx, "UPDATE steps SET state=? WHERE state=?", runSuperseded, runRunning) |
| 627 | return err |
| 628 | } |
| 629 | |
| 630 | // Sync is the runner's view sent on every connect: runs not yet acked as |
| 631 | // finished, and the durable sessions of both lanes. |
| 632 | func (s *State) Sync(ctx context.Context) (wire.Sync, error) { |
| 633 | out := wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}, Connections: []wire.HeldConnection{}} |
| 634 | steps, err := s.syncSteps(ctx) |
| 635 | if err != nil { |
| 636 | return out, err |
| 637 | } |
| 638 | out.Steps = steps |
| 639 | if out.Asks, err = s.syncAsks(ctx); err != nil { |
| 640 | return out, err |
| 641 | } |
| 642 | rows, err := s.db.QueryContext(ctx, "SELECT turn_id, attempt, state FROM runs WHERE state IN (?,?) ORDER BY created_at", runRunning, runReported) |
| 643 | if err != nil { |
| 644 | return out, err |
| 645 | } |
| 646 | for rows.Next() { |
| 647 | var r wire.Run |
| 648 | if err = rows.Scan(&r.TurnID, &r.Attempt, &r.State); err != nil { |
| 649 | rows.Close() |
| 650 | return out, err |
| 651 | } |
| 652 | out.Runs = append(out.Runs, r) |
| 653 | } |
| 654 | rows.Close() |
| 655 | rows, err = s.db.QueryContext(ctx, "SELECT person, lane, provider, account, session_id, last_turn FROM sessions_lane ORDER BY person, lane, provider") |
| 656 | if err != nil { |
| 657 | return out, err |
| 658 | } |
| 659 | defer rows.Close() |
| 660 | for rows.Next() { |
| 661 | var v wire.SessionState |
| 662 | if err = rows.Scan(&v.Person, &v.Lane, &v.Provider, &v.Account, &v.SessionID, &v.LastTurn); err != nil { |
| 663 | return out, err |
| 664 | } |
| 665 | out.Sessions = append(out.Sessions, v) |
| 666 | } |
| 667 | return out, rows.Err() |
| 668 | } |
| 669 | |
| 670 | // sessionRow is the durable session for a person in a lane. |
| 671 | type sessionRow struct { |
| 672 | Account, SessionID string |
| 673 | Updated time.Time |
| 674 | } |
| 675 | |
| 676 | func (s *State) session(ctx context.Context, person, lane, provider string) (sessionRow, bool, error) { |
| 677 | var r sessionRow |
| 678 | var updated string |
| 679 | err := s.db.QueryRowContext(ctx, "SELECT account, session_id, updated_at FROM sessions_lane WHERE person=? AND lane=? AND provider=?", person, lane, provider).Scan(&r.Account, &r.SessionID, &updated) |
| 680 | if errors.Is(err, sql.ErrNoRows) { |
| 681 | return r, false, nil |
| 682 | } |
| 683 | r.Updated, _ = time.Parse(time.RFC3339Nano, updated) |
| 684 | return r, err == nil, err |
| 685 | } |
| 686 | |
| 687 | func (s *State) saveSession(ctx context.Context, person, lane, provider, account, id, turn string) error { |
| 688 | _, err := s.db.ExecContext(ctx, "INSERT INTO sessions_lane(person, lane, provider, account, session_id, last_turn, updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(person, lane, provider) DO UPDATE SET account=excluded.account, session_id=excluded.session_id, last_turn=excluded.last_turn, updated_at=excluded.updated_at", person, lane, provider, account, id, turn, now()) |
| 689 | return err |
| 690 | } |
| 691 | |
| 692 | // laneSessions copies the coordinator sessions of a state file from |
| 693 | // before the Assistant into sessions_lane, once: sessions keyed by |
| 694 | // person and provider alone become the coordinator's lane. The old |
| 695 | // table stays and is never read again. |
| 696 | func (s *State) laneSessions(ctx context.Context) error { |
| 697 | return s.tx(ctx, func(t *sql.Tx) error { |
| 698 | res, err := t.Exec("INSERT INTO meta(key,value) VALUES('sessions_lane', ?) ON CONFLICT DO NOTHING", now()) |
| 699 | if err != nil { |
| 700 | return err |
| 701 | } |
| 702 | if n, _ := res.RowsAffected(); n == 0 { |
| 703 | return nil |
| 704 | } |
| 705 | _, err = t.Exec("INSERT OR IGNORE INTO sessions_lane(person, lane, provider, account, session_id, last_turn, updated_at) SELECT person, '', provider, account, session_id, last_turn, updated_at FROM sessions") |
| 706 | return err |
| 707 | }) |
| 708 | } |
| 709 | |
| 710 | // runningAttachments are the attachment ids the running turns name: |
| 711 | // files the sweep must keep. Any failure is an error, never "none". |
| 712 | func (s *State) runningAttachments(ctx context.Context) (map[string]bool, error) { |
| 713 | if s.fault != nil { |
| 714 | if err := s.fault("running_attachments"); err != nil { |
| 715 | return nil, err |
| 716 | } |
| 717 | } |
| 718 | out := map[string]bool{} |
| 719 | rows, err := s.db.QueryContext(ctx, "SELECT attachments FROM runs WHERE state=?", runRunning) |
| 720 | if err != nil { |
| 721 | return nil, err |
| 722 | } |
| 723 | defer rows.Close() |
| 724 | for rows.Next() { |
| 725 | var raw string |
| 726 | var refs []wire.AttachmentRef |
| 727 | if err := rows.Scan(&raw); err != nil { |
| 728 | return nil, err |
| 729 | } |
| 730 | if err := json.Unmarshal([]byte(raw), &refs); err != nil { |
| 731 | return nil, err |
| 732 | } |
| 733 | for _, r := range refs { |
| 734 | out[r.ID] = true |
| 735 | } |
| 736 | } |
| 737 | return out, rows.Err() |
| 738 | } |
| 739 | |
| 740 | // refused reports an attachment refused for room. |
| 741 | func (s *State) refused(ctx context.Context, id string) bool { |
| 742 | var n int |
| 743 | return s.db.QueryRowContext(ctx, "SELECT count(*) FROM file_refused WHERE attachment_id=?", id).Scan(&n) == nil && n > 0 |
| 744 | } |
| 745 | |
| 746 | // anyRefused reports whether any of a turn's attachments was refused for |
| 747 | // room on this runner. |
| 748 | func (s *State) anyRefused(ctx context.Context, refs []wire.AttachmentRef) bool { |
| 749 | for _, r := range refs { |
| 750 | if s.refused(ctx, r.ID) { |
| 751 | return true |
| 752 | } |
| 753 | } |
| 754 | return false |
| 755 | } |
| 756 | |
| 757 | // assistantUsers are the persons whose Assistant lane saved a session or |
| 758 | // took a turn since then. |
| 759 | func (s *State) assistantUsers(ctx context.Context, since time.Time) ([]string, error) { |
| 760 | rows, err := s.db.QueryContext(ctx, "SELECT person, updated_at FROM sessions_lane WHERE lane=? UNION ALL SELECT person, created_at FROM runs WHERE lane=?", wire.LaneAssistant, wire.LaneAssistant) |
| 761 | if err != nil { |
| 762 | return nil, err |
| 763 | } |
| 764 | defer rows.Close() |
| 765 | var out []string |
| 766 | for rows.Next() { |
| 767 | var p, at string |
| 768 | if err = rows.Scan(&p, &at); err != nil { |
| 769 | return nil, err |
| 770 | } |
| 771 | if t, err := time.Parse(time.RFC3339Nano, at); err == nil && t.After(since) && !slices.Contains(out, p) { |
| 772 | out = append(out, p) |
| 773 | } |
| 774 | } |
| 775 | return out, rows.Err() |
| 776 | } |
| 777 | |