| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "strings" |
| 9 | "sync/atomic" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 14 | ) |
| 15 | |
| 16 | func directUnblocked(t *testing.T, j *Journal) { |
| 17 | t.Helper() |
| 18 | var blocked int |
| 19 | mustJournal(t, j.db.QueryRow("SELECT blocked FROM journal_state").Scan(&blocked)) |
| 20 | if blocked != 0 || j.AdmissionAllowed(context.Background()) != nil { |
| 21 | t.Fatal("attempt fault fenced unrelated work") |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | func TestDirectFaultIsolation(t *testing.T) { |
| 26 | for _, kind := range []string{"torn", "oversized", "malformed", "stall", "short-input", "identity", "unknown-frame", "unknown-turn", "unknown-event", "pump-identity", "storage", "interrupt-storage", "event-storage", "intent-storage"} { |
| 27 | t.Run(kind, func(t *testing.T) { |
| 28 | ctx := context.Background() |
| 29 | j, l, s, p := directFixture(t, "codex") |
| 30 | switch kind { |
| 31 | case "event-storage", "intent-storage": |
| 32 | mustJournal(t, j.BindSession(ctx, s)) |
| 33 | if kind == "event-storage" { |
| 34 | _, err := j.db.Exec("DROP TABLE direct_turns") |
| 35 | mustJournal(t, err) |
| 36 | if _, err = j.ObserveDirect(ctx, s, directComplete("turn")); err == nil { |
| 37 | t.Fatal("missing turn table accepted") |
| 38 | } |
| 39 | } else { |
| 40 | var pages int |
| 41 | mustJournal(t, j.db.QueryRow("PRAGMA page_count").Scan(&pages)) |
| 42 | _, err := j.db.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", pages)) |
| 43 | mustJournal(t, err) |
| 44 | turn := directTurn() |
| 45 | turn.AdmissionID = strings.Repeat("a", 20000) |
| 46 | if err = j.BeginTurn(ctx, s, turn); err == nil { |
| 47 | t.Fatal("full intent write accepted") |
| 48 | } |
| 49 | } |
| 50 | case "identity": |
| 51 | mustJournal(t, j.interruptDirect(ctx, l.AttemptKey, true)) |
| 52 | if j.recordDirectLaunch(ctx, l, p.record) == nil { |
| 53 | t.Fatal("relaunch accepted") |
| 54 | } |
| 55 | case "unknown-frame": |
| 56 | if j.AppendFrame(ctx, "missing", p.ID(), 1, []byte(`{}`)) == nil { |
| 57 | t.Fatal("unknown frame accepted") |
| 58 | } |
| 59 | case "unknown-turn", "unknown-event", "pump-identity": |
| 60 | s.AttemptKey = "missing" |
| 61 | var err error |
| 62 | if kind == "unknown-turn" { |
| 63 | err = j.BeginTurn(ctx, s, directTurn()) |
| 64 | } else if kind == "unknown-event" { |
| 65 | _, err = j.ObserveDirect(ctx, s, directComplete("turn")) |
| 66 | } else { |
| 67 | pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} |
| 68 | err = pump.AppendDirect(ctx, s, directComplete("turn"), journalEvent("e", 1)) |
| 69 | } |
| 70 | if err == nil { |
| 71 | t.Fatal("unknown attempt accepted") |
| 72 | } |
| 73 | default: |
| 74 | raw := "{}\n" |
| 75 | switch kind { |
| 76 | case "torn": |
| 77 | raw = `{"partial":` |
| 78 | case "oversized": |
| 79 | raw = "{\"text\":\"" + strings.Repeat("x", MaxFrameBytes) + "\"}\n" |
| 80 | case "malformed": |
| 81 | raw = "bad\n" |
| 82 | case "storage": |
| 83 | // A broken journal table is a storage fault, unlike malformed provider JSON. |
| 84 | _, err := j.db.Exec("DROP TABLE direct_frames") |
| 85 | mustJournal(t, err) |
| 86 | case "interrupt-storage": |
| 87 | _, err := j.db.Exec("DROP TABLE journal_answers") |
| 88 | mustJournal(t, err) |
| 89 | raw = "bad\n" |
| 90 | case "short-input": |
| 91 | r, w := io.Pipe() |
| 92 | defer w.Close() |
| 93 | p.out = r |
| 94 | p.writable = shortDirectInput{} |
| 95 | } |
| 96 | if kind != "short-input" { |
| 97 | p.out = io.NopCloser(strings.NewReader(raw)) |
| 98 | } |
| 99 | cap, err := NewCaptureFactory(j).Open(ctx, p, l) |
| 100 | if err == nil { |
| 101 | if kind == "short-input" { |
| 102 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 103 | if _, err = cap.Input.Write(directPrompt("codex")); err == nil { |
| 104 | t.Fatal("short input accepted") |
| 105 | } |
| 106 | } |
| 107 | select { |
| 108 | case err = <-cap.Done: |
| 109 | case <-time.After(8 * time.Second): |
| 110 | t.Fatal("containment stalled") |
| 111 | } |
| 112 | } |
| 113 | if err == nil || !p.stopped.Load() { |
| 114 | t.Fatal("fault not contained", err) |
| 115 | } |
| 116 | } |
| 117 | if kind == "storage" || kind == "interrupt-storage" || kind == "event-storage" || kind == "intent-storage" { |
| 118 | j.mu.Lock() |
| 119 | blocked := j.blocked |
| 120 | j.mu.Unlock() |
| 121 | if !blocked { |
| 122 | t.Fatal("storage fault did not fence journal") |
| 123 | } |
| 124 | return |
| 125 | } |
| 126 | directUnblocked(t, j) |
| 127 | l.AttemptKey = "attempt-b" |
| 128 | p.record.AttemptKey = l.AttemptKey |
| 129 | p.record.ID = strings.Repeat("b", 32) |
| 130 | s.AttemptKey = l.AttemptKey |
| 131 | s.ID = "session-b" |
| 132 | mustJournal(t, j.recordDirectLaunch(ctx, l, p.record)) |
| 133 | mustJournal(t, j.BeginTurn(ctx, s, provider.Turn{ID: "b", AdmissionID: "b", Prompt: "hello"})) |
| 134 | }) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | func TestDirectTerminalTransition(t *testing.T) { |
| 139 | for _, state := range []string{"intent", "completed", "waiting_for_person"} { |
| 140 | t.Run(state, func(t *testing.T) { |
| 141 | ctx := context.Background() |
| 142 | j, _, s, _ := directFixture(t, "codex") |
| 143 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 144 | if state != "intent" { |
| 145 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 146 | } |
| 147 | if state == "completed" { |
| 148 | _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142)) |
| 149 | mustJournal(t, err) |
| 150 | _, err = j.ObserveDirect(ctx, s, directComplete("turn")) |
| 151 | mustJournal(t, err) |
| 152 | } |
| 153 | if state == "waiting_for_person" { |
| 154 | mustJournal(t, j.interruptDirect(ctx, s.AttemptKey, true)) |
| 155 | } |
| 156 | var before []byte |
| 157 | mustJournal(t, j.db.QueryRow("SELECT usage FROM direct_turns").Scan(&before)) |
| 158 | for _, kind := range []string{"turn.completed", "turn.failed"} { |
| 159 | e := directComplete("turn") |
| 160 | e.Kind = kind |
| 161 | e.Sequence = 99 // A distinct observation, not idempotent replay. |
| 162 | _, err := j.ObserveDirect(ctx, s, e) |
| 163 | if state != "waiting_for_person" && err == nil { |
| 164 | t.Fatal("accepted terminal observation for", state) |
| 165 | } |
| 166 | var afterState string |
| 167 | var after []byte |
| 168 | mustJournal(t, j.db.QueryRow("SELECT state,usage FROM direct_turns").Scan(&afterState, &after)) |
| 169 | if afterState != state || string(before) != string(after) { |
| 170 | t.Fatalf("terminal event changed %s to %s or replaced usage", state, afterState) |
| 171 | } |
| 172 | } |
| 173 | directUnblocked(t, j) |
| 174 | }) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | // Hold failure cleanup open after the stdout owner reaches its final Close. |
| 179 | type finalCloseInput struct { |
| 180 | entered, release chan struct{} |
| 181 | calls atomic.Int32 |
| 182 | } |
| 183 | |
| 184 | func (p *finalCloseInput) Write([]byte) (int, error) { return 0, io.ErrClosedPipe } |
| 185 | func (p *finalCloseInput) Close() error { |
| 186 | if p.calls.Add(1) == 1 { |
| 187 | close(p.entered) |
| 188 | <-p.release |
| 189 | } |
| 190 | return nil |
| 191 | } |
| 192 | |
| 193 | type slowContainProcess struct { |
| 194 | *directProcess |
| 195 | entered, release chan struct{} |
| 196 | } |
| 197 | |
| 198 | func (p *slowContainProcess) Contain(context.Context) error { |
| 199 | close(p.entered) |
| 200 | <-p.release |
| 201 | return errors.New("containment failed") |
| 202 | } |
| 203 | func TestDirectCaptureFailurePublication(t *testing.T) { |
| 204 | j, l, _, base := directFixture(t, "codex") |
| 205 | in := &finalCloseInput{entered: make(chan struct{}), release: make(chan struct{})} |
| 206 | base.writable = in |
| 207 | p := &slowContainProcess{directProcess: base, entered: make(chan struct{}), release: make(chan struct{})} |
| 208 | cap, err := NewCaptureFactory(j).Open(context.Background(), p, l) |
| 209 | mustJournal(t, err) |
| 210 | <-in.entered |
| 211 | writer := make(chan struct{}) |
| 212 | go func() { _, _ = cap.Input.Write([]byte("{\"method\":\"initialized\"}\n")); close(writer) }() |
| 213 | <-p.entered |
| 214 | close(in.release) |
| 215 | var early bool |
| 216 | select { |
| 217 | case <-cap.Done: |
| 218 | early = true |
| 219 | case <-time.After(100 * time.Millisecond): |
| 220 | } |
| 221 | close(p.release) |
| 222 | <-writer |
| 223 | if early { |
| 224 | t.Fatal("Done published while failure cleanup still writes its result") |
| 225 | } |
| 226 | if err = <-cap.Done; err == nil || !strings.Contains(err.Error(), "containment failed") { |
| 227 | t.Fatal("failure result lost", err) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | func TestDirectJournalPrunesFrames(t *testing.T) { |
| 232 | j, l, _, p := directFixture(t, "codex") |
| 233 | ctx := context.Background() |
| 234 | // Simulate a v2 archive and one pending frame awaiting retirement. |
| 235 | _, err := j.db.Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<200) INSERT INTO direct_frames(stream,sequence,body,pending) SELECT ?,x,'{}',0 FROM n", p.ID()) |
| 236 | mustJournal(t, err) |
| 237 | _, err = j.db.Exec("DROP INDEX journal_coordinator_delivery; DROP TABLE coordinator_tool_claims; DROP TABLE coordinator_tools; DROP INDEX IF EXISTS direct_frames_pending; DROP INDEX IF EXISTS direct_events_projected; PRAGMA user_version=2") |
| 238 | mustJournal(t, err) |
| 239 | path := j.path |
| 240 | mustJournal(t, j.Close()) |
| 241 | j, err = OpenJournal(ctx, path) |
| 242 | mustJournal(t, err) |
| 243 | defer j.Close() |
| 244 | var n int |
| 245 | mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames WHERE pending=0").Scan(&n)) |
| 246 | if n != 0 { |
| 247 | t.Error("upgrade kept retired frames", n) |
| 248 | } |
| 249 | for _, spec := range []struct{ table, column string }{{"direct_frames", "pending"}, {"direct_events", "projected"}} { |
| 250 | mustJournal(t, j.db.QueryRow("SELECT count(*) FROM sqlite_master m JOIN pragma_index_info(m.name) i WHERE m.type='index' AND m.tbl_name=? AND i.seqno=0 AND i.name=?", spec.table, spec.column).Scan(&n)) |
| 251 | if n == 0 { |
| 252 | t.Error("missing pending index", spec.table) |
| 253 | } |
| 254 | } |
| 255 | mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 201, []byte(`{}`))) |
| 256 | _, err = j.db.Exec("UPDATE direct_attempts SET contained=1,recovered=1") |
| 257 | mustJournal(t, err) |
| 258 | mustJournal(t, j.Append(ctx, journalEvent("ack", 1))) |
| 259 | mustJournal(t, j.Ack(ctx, "ack")) |
| 260 | mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&n)) |
| 261 | if n != 0 { |
| 262 | t.Error("retired frames not pruned", n) |
| 263 | } |
| 264 | _, err = j.db.Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<200) INSERT INTO direct_frames(stream,sequence,body,pending) SELECT ?,x,'{}',0 FROM n", p.ID()) |
| 265 | mustJournal(t, err) |
| 266 | mustJournal(t, j.Ack(ctx, "ack")) |
| 267 | mustJournal(t, j.db.QueryRow("SELECT changes()").Scan(&n)) |
| 268 | if n != 0 { |
| 269 | t.Error("ACK touched archived frames", n) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | func TestDirectProjectionFaultQuarantines(t *testing.T) { |
| 274 | for _, kind := range []string{"protocol", "containment", "interrupt-storage"} { |
| 275 | t.Run(kind, func(t *testing.T) { |
| 276 | ctx := context.Background() |
| 277 | j, _, s, _ := directFixture(t, "codex") |
| 278 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 279 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 280 | if kind == "interrupt-storage" { |
| 281 | _, err := j.db.Exec("DROP TABLE journal_answers") |
| 282 | mustJournal(t, err) |
| 283 | } |
| 284 | called := false |
| 285 | pump := EventPump{Journal: j, Contain: func(context.Context) error { |
| 286 | called = true |
| 287 | if kind == "containment" { |
| 288 | return provider.ErrContainment |
| 289 | } |
| 290 | return nil |
| 291 | }} |
| 292 | e := directComplete("turn") |
| 293 | e.Payload = []byte("invalid") |
| 294 | if pump.AppendDirect(ctx, s, e, journalEvent("bad", 1)) == nil || !called { |
| 295 | t.Fatal("protocol fault escaped containment") |
| 296 | } |
| 297 | if kind == "interrupt-storage" { |
| 298 | j.mu.Lock() |
| 299 | blocked := j.blocked |
| 300 | j.mu.Unlock() |
| 301 | if !blocked { |
| 302 | t.Fatal("failed quarantine did not fence") |
| 303 | } |
| 304 | return |
| 305 | } |
| 306 | var recovered, contained int |
| 307 | var state string |
| 308 | mustJournal(t, j.db.QueryRow("SELECT recovered,contained FROM direct_attempts").Scan(&recovered, &contained)) |
| 309 | mustJournal(t, j.db.QueryRow("SELECT state FROM direct_turns").Scan(&state)) |
| 310 | if recovered != 1 || state != "waiting_for_person" { |
| 311 | t.Fatal("projection fault left attempt active", recovered, state) |
| 312 | } |
| 313 | if kind == "containment" { |
| 314 | if contained != 0 || j.AdmissionAllowed(ctx) == nil { |
| 315 | t.Fatal("uncontained attempt admitted work") |
| 316 | } |
| 317 | } else { |
| 318 | directUnblocked(t, j) |
| 319 | } |
| 320 | }) |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | func TestDirectUsageBeforeDispatch(t *testing.T) { |
| 325 | ctx := context.Background() |
| 326 | j, _, s, _ := directFixture(t, "codex") |
| 327 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 328 | _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142)) |
| 329 | mustJournal(t, err) |
| 330 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 331 | usage, err := j.ObserveDirect(ctx, s, directComplete("turn")) |
| 332 | mustJournal(t, err) |
| 333 | if usage != nil { |
| 334 | t.Fatal("undispatched usage became settled accounting", usage) |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | func TestDirectJournalRetainsUndecodedStartup(t *testing.T) { |
| 339 | ctx := context.Background() |
| 340 | j, l, _, p := directFixture(t, "codex") |
| 341 | mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{}`))) |
| 342 | _, err := j.db.Exec("UPDATE direct_attempts SET contained=1") |
| 343 | mustJournal(t, err) |
| 344 | mustJournal(t, j.releaseDirectFrames(ctx)) |
| 345 | var n int |
| 346 | mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames WHERE pending=1").Scan(&n)) |
| 347 | if n != 1 { |
| 348 | t.Fatal("startup frame retired before consumption or recovery") |
| 349 | } |
| 350 | mustJournal(t, j.interruptDirect(ctx, l.AttemptKey, true)) |
| 351 | mustJournal(t, j.releaseDirectFrames(ctx)) |
| 352 | mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&n)) |
| 353 | if n != 0 { |
| 354 | t.Fatal("recovered startup retained raw frames") |
| 355 | } |
| 356 | } |
| 357 | |