| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | ) |
| 17 | |
| 18 | func codexUsage(turn string, input, output int64) provider.Event { |
| 19 | return provider.Event{SessionID: "session", TurnID: turn, Kind: "usage", Payload: json.RawMessage(fmt.Sprintf(`{"params":{"tokenUsage":{"total":{"inputTokens":%d,"outputTokens":%d},"last":{"inputTokens":14200,"outputTokens":46}}}}`, input, output))} |
| 20 | } |
| 21 | func directComplete(turn string) provider.Event { |
| 22 | return provider.Event{SessionID: "session", TurnID: turn, Kind: "turn.completed", Payload: json.RawMessage(`{"params":{"turn":{"status":"completed"}}}`)} |
| 23 | } |
| 24 | func TestDirectUsageDeltas(t *testing.T) { |
| 25 | ctx := context.Background() |
| 26 | j, _, s, _ := directFixture(t, "codex") |
| 27 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 28 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 29 | for _, v := range []provider.Event{codexUsage("turn", 14054, 96), codexUsage("turn", 28254, 142)} { |
| 30 | _, err := j.ObserveDirect(ctx, s, v) |
| 31 | mustJournal(t, err) |
| 32 | } |
| 33 | u, err := j.ObserveDirect(ctx, s, directComplete("turn")) |
| 34 | mustJournal(t, err) |
| 35 | if u == nil || u.InputTokens != 28254 || u.OutputTokens != 142 || u.Calls != 1 { |
| 36 | t.Fatalf("cumulative totals settled incorrectly: %+v", u) |
| 37 | } |
| 38 | again, err := j.ObserveDirect(ctx, s, directComplete("turn")) |
| 39 | mustJournal(t, err) |
| 40 | if again == nil || *again != *u { |
| 41 | t.Fatal("duplicate changed charge") |
| 42 | } |
| 43 | path := j.path |
| 44 | mustJournal(t, j.Close()) |
| 45 | j, err = OpenJournal(ctx, path) |
| 46 | mustJournal(t, err) |
| 47 | defer j.Close() |
| 48 | // A new admitted turn in the same live attempt demonstrates the durable baseline. |
| 49 | next := provider.Turn{ID: "next", AdmissionID: "next-admission", Prompt: "hello"} |
| 50 | mustJournal(t, j.BeginTurn(ctx, s, next)) |
| 51 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, next.Prompt)) |
| 52 | _, err = j.ObserveDirect(ctx, s, codexUsage("next", 30000, 150)) |
| 53 | mustJournal(t, err) |
| 54 | u, err = j.ObserveDirect(ctx, s, directComplete("next")) |
| 55 | mustJournal(t, err) |
| 56 | if u == nil || u.InputTokens != 1746 || u.OutputTokens != 8 { |
| 57 | t.Fatalf("baseline reset on reopen: %+v", u) |
| 58 | } |
| 59 | for _, kind := range []string{"reset", "compaction", "missing", "overflow"} { |
| 60 | t.Run(kind, func(t *testing.T) { |
| 61 | a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "codex", ProviderVersion: "0.165.0", Subscription: true}) |
| 62 | a.Observe(codexUsage("one", 100, 10)) |
| 63 | a.Observe(directComplete("one")) |
| 64 | e := codexUsage("two", 90, 9) |
| 65 | if kind == "missing" { |
| 66 | e.Payload = json.RawMessage(`{"params":{"tokenUsage":{"total":{"inputTokens":101}}}}`) |
| 67 | } |
| 68 | if kind == "overflow" { |
| 69 | e.Payload = json.RawMessage(`{"params":{"tokenUsage":{"total":{"inputTokens":9223372036854775808,"outputTokens":12}}}}`) |
| 70 | } |
| 71 | a.Observe(e) |
| 72 | if a.Observe(directComplete("two")) != nil { |
| 73 | t.Fatal("uncertain counters became known") |
| 74 | } |
| 75 | a.Observe(codexUsage("three", 200, 20)) |
| 76 | if a.Observe(directComplete("three")) != nil { |
| 77 | t.Fatal("lost baseline regained authority") |
| 78 | } |
| 79 | }) |
| 80 | } |
| 81 | a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "claude", ProviderVersion: "2.1.312", Subscription: true}) |
| 82 | for i, cost := range []float64{.1, .15} { |
| 83 | e := provider.Event{SessionID: "session", TurnID: fmt.Sprint(i), Kind: "turn.completed", Payload: json.RawMessage(fmt.Sprintf(`{"usage":{"input_tokens":2,"cache_read_input_tokens":3566,"cache_creation_input_tokens":378,"output_tokens":3},"total_cost_usd":%g,"modelUsage":{"model":{"inputTokens":999999}}}`, cost))} |
| 84 | u := a.Observe(e) |
| 85 | if u == nil || u.InputTokens != 3946 || u.OutputTokens != 3 { |
| 86 | t.Fatalf("Claude per-turn usage: %+v", u) |
| 87 | } |
| 88 | a.Observe(e) |
| 89 | } |
| 90 | if a.EstimatedCostUSD() != .15 { |
| 91 | t.Fatal("summed cumulative cost", a.EstimatedCostUSD()) |
| 92 | } |
| 93 | } |
| 94 | func TestDirectCompletionReplay(t *testing.T) { |
| 95 | j, _, s, _ := directFixture(t, "codex") |
| 96 | ctx := context.Background() |
| 97 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 98 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 99 | _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142)) |
| 100 | mustJournal(t, err) |
| 101 | pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} |
| 102 | template := journalEvent("ignored", 1) |
| 103 | template.ActionID = 1 |
| 104 | mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template)) |
| 105 | rows, err := j.RecoverDirect(ctx) |
| 106 | mustJournal(t, err) |
| 107 | if len(rows) != 1 || rows[0].State != "completed_needs_containment" || rows[0].Usage == nil || rows[0].Usage.InputTokens != 28254 { |
| 108 | t.Fatalf("completion replay lost accounting: %+v", rows) |
| 109 | } |
| 110 | pending, err := j.Pending(ctx, 10) |
| 111 | mustJournal(t, err) |
| 112 | if len(pending) != 1 { |
| 113 | t.Fatal("projection not atomic", len(pending)) |
| 114 | } |
| 115 | mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template)) |
| 116 | pending, err = j.Pending(ctx, 10) |
| 117 | mustJournal(t, err) |
| 118 | if len(pending) != 1 { |
| 119 | t.Fatal("duplicate outbox") |
| 120 | } |
| 121 | mustJournal(t, j.Ack(ctx, pending[0].ID)) |
| 122 | pending, err = j.Pending(ctx, 10) |
| 123 | mustJournal(t, err) |
| 124 | if len(pending) != 0 { |
| 125 | t.Fatal("ack not durable") |
| 126 | } |
| 127 | } |
| 128 | func TestDirectInterruptedWaitsForPerson(t *testing.T) { |
| 129 | j, _, s, _ := directFixture(t, "claude") |
| 130 | ctx := context.Background() |
| 131 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 132 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 133 | _, err := j.db.Exec("INSERT INTO journal_answers VALUES('answer','hash','pending')") |
| 134 | mustJournal(t, err) |
| 135 | rows, err := j.RecoverDirect(ctx) |
| 136 | mustJournal(t, err) |
| 137 | if len(rows) != 1 || rows[0].Usage != nil || rows[0].State != "waiting_for_person" { |
| 138 | t.Fatalf("unknown charge erased: %+v", rows) |
| 139 | } |
| 140 | var state string |
| 141 | mustJournal(t, j.db.QueryRow("SELECT state FROM journal_answers").Scan(&state)) |
| 142 | if state != "invalid" { |
| 143 | t.Fatal("pending answer remained valid") |
| 144 | } |
| 145 | late, err := j.ObserveDirect(ctx, s, provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)}) |
| 146 | if late != nil { |
| 147 | t.Fatal("late completion returned known usage after interruption") |
| 148 | } |
| 149 | mustJournal(t, err) |
| 150 | rows, err = j.RecoverDirect(ctx) |
| 151 | mustJournal(t, err) |
| 152 | if rows[0].State != "waiting_for_person" || rows[0].Usage != nil { |
| 153 | t.Fatal("late completion erased interruption") |
| 154 | } |
| 155 | } |
| 156 | func TestDirectJournalUpgrade(t *testing.T) { |
| 157 | j, _, _, _ := directFixture(t, "claude") |
| 158 | ctx := context.Background() |
| 159 | mustJournal(t, j.Append(ctx, journalEvent("legacy", 1))) |
| 160 | _, err := j.db.Exec("DROP INDEX journal_coordinator_delivery; DROP TABLE coordinator_tool_claims; DROP TABLE coordinator_tools; DROP TABLE direct_attempts; DROP TABLE direct_turns; DROP TABLE direct_frames; DROP TABLE direct_events; DROP TABLE direct_usage; PRAGMA user_version=1") |
| 161 | mustJournal(t, err) |
| 162 | path := j.path |
| 163 | mustJournal(t, j.Close()) |
| 164 | j, err = OpenJournal(ctx, path) |
| 165 | mustJournal(t, err) |
| 166 | defer j.Close() |
| 167 | var v int |
| 168 | mustJournal(t, j.db.QueryRow("PRAGMA user_version").Scan(&v)) |
| 169 | if v != 6 { |
| 170 | t.Fatalf("journal version %d", v) |
| 171 | } |
| 172 | events, err := j.Pending(ctx, 10) |
| 173 | mustJournal(t, err) |
| 174 | if len(events) != 1 || events[0].ID != "legacy" { |
| 175 | t.Fatal("upgrade lost v1 outbox") |
| 176 | } |
| 177 | var sync int |
| 178 | mustJournal(t, j.db.QueryRow("PRAGMA synchronous").Scan(&sync)) |
| 179 | if sync != 2 { |
| 180 | t.Fatal("capture commits are not FULL synchronous") |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestDirectInterruptedBinding(t *testing.T) { |
| 185 | j, l, _, p := directFixture(t, "claude") |
| 186 | for _, field := range []string{"policy", "manifest", "attempt", "stream", "egress", "boot", "parent"} { |
| 187 | t.Run(field, func(t *testing.T) { |
| 188 | r := p.record |
| 189 | switch field { |
| 190 | case "policy": |
| 191 | r.PolicyHash = "other" |
| 192 | case "manifest": |
| 193 | r.ManifestHash = "other" |
| 194 | case "attempt": |
| 195 | r.AttemptKey = "other" |
| 196 | case "stream": |
| 197 | r.ID = "other" |
| 198 | case "egress": |
| 199 | r.EgressHash = "other" |
| 200 | case "boot": |
| 201 | r.BootID = "other" |
| 202 | case "parent": |
| 203 | r.ParentTicks++ |
| 204 | } |
| 205 | if j.validateDirectRecord(context.Background(), r) == nil { |
| 206 | t.Fatal("recovered identity mismatch accepted", field) |
| 207 | } |
| 208 | }) |
| 209 | } |
| 210 | if err := j.validateDirectRecord(context.Background(), p.record); err != nil { |
| 211 | t.Fatal(err) |
| 212 | } |
| 213 | // A durable record with a changed policy must also disagree with the saved launch. |
| 214 | bad := p.record |
| 215 | bad.PolicyHash = "changed" |
| 216 | raw, _ := json.Marshal(bad) |
| 217 | _, err := j.db.Exec("UPDATE direct_attempts SET record=?", raw) |
| 218 | mustJournal(t, err) |
| 219 | if j.validateDirectRecord(context.Background(), bad) == nil { |
| 220 | t.Fatal("namespace record detached from journaled launch", l.Policy.Hash) |
| 221 | } |
| 222 | } |
| 223 | func TestDirectJournalProjectionAtomic(t *testing.T) { |
| 224 | j, _, s, _ := directFixture(t, "codex") |
| 225 | ctx := context.Background() |
| 226 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 227 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 228 | _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142)) |
| 229 | mustJournal(t, err) |
| 230 | _, err = j.db.Exec("CREATE TRIGGER fail_projection BEFORE INSERT ON journal_events BEGIN SELECT RAISE(ABORT,'injected outbox failure'); END") |
| 231 | mustJournal(t, err) |
| 232 | template := journalEvent("ignored", 1) |
| 233 | template.ActionID = 1 |
| 234 | if _, err = j.appendDirect(ctx, s, directComplete("turn"), &template); err == nil { |
| 235 | t.Fatal("injected outbox failure ignored") |
| 236 | } |
| 237 | var state string |
| 238 | mustJournal(t, j.db.QueryRow("SELECT state FROM direct_turns").Scan(&state)) |
| 239 | if state == "completed" { |
| 240 | t.Fatal("completion escaped projection rollback") |
| 241 | } |
| 242 | var n int |
| 243 | mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_events WHERE json_extract(body,'$.Kind')='turn.completed'").Scan(&n)) |
| 244 | if n != 0 { |
| 245 | t.Fatal("checkpoint escaped rollback") |
| 246 | } |
| 247 | } |
| 248 | func TestDirectJournalChunks(t *testing.T) { |
| 249 | j, _, s, _ := directFixture(t, "codex") |
| 250 | ctx := context.Background() |
| 251 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 252 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 253 | payload := json.RawMessage(`{"output":"` + strings.Repeat("猫", 15000) + `","status":"completed"}`) |
| 254 | e := provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "tool.completed", Payload: payload, Sequence: 3} |
| 255 | pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} |
| 256 | template := journalEvent("ignored", 1) |
| 257 | mustJournal(t, pump.AppendDirect(ctx, s, e, template)) |
| 258 | events, err := j.Pending(ctx, 100) |
| 259 | mustJournal(t, err) |
| 260 | var decoded []byte |
| 261 | for i, event := range events { |
| 262 | if len(event.Payload) > 16<<10 { |
| 263 | t.Fatal("oversize upload") |
| 264 | } |
| 265 | if i == len(events)-1 { |
| 266 | if event.Kind != "tool.completed" { |
| 267 | t.Fatal("lifecycle truncated") |
| 268 | } |
| 269 | break |
| 270 | } |
| 271 | var chunk struct { |
| 272 | Index, Total int |
| 273 | Data string `json:"base64"` |
| 274 | } |
| 275 | mustJournal(t, json.Unmarshal(event.Payload, &chunk)) |
| 276 | if chunk.Index != i || chunk.Total != len(events)-1 { |
| 277 | t.Fatal("unordered chunks") |
| 278 | } |
| 279 | b, err := base64.StdEncoding.DecodeString(chunk.Data) |
| 280 | mustJournal(t, err) |
| 281 | decoded = append(decoded, b...) |
| 282 | } |
| 283 | var envelope struct { |
| 284 | Event provider.Event `json:"event"` |
| 285 | } |
| 286 | mustJournal(t, json.Unmarshal(decoded, &envelope)) |
| 287 | if string(envelope.Event.Payload) != string(payload) { |
| 288 | t.Fatal("tool output truncated") |
| 289 | } |
| 290 | e.Sequence = 4 |
| 291 | mustJournal(t, pump.AppendDirect(ctx, s, e, template)) |
| 292 | events2, err := j.Pending(ctx, 100) |
| 293 | mustJournal(t, err) |
| 294 | if len(events2) != 2*len(events) { |
| 295 | t.Fatal("identical later output was deduplicated") |
| 296 | } |
| 297 | } |
| 298 | func TestDirectUsageResumeBinding(t *testing.T) { |
| 299 | j, l, s, p := directFixture(t, "codex") |
| 300 | ctx := context.Background() |
| 301 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 302 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 303 | _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142)) |
| 304 | mustJournal(t, err) |
| 305 | _, err = j.ObserveDirect(ctx, s, directComplete("turn")) |
| 306 | mustJournal(t, err) |
| 307 | _, err = j.db.Exec("UPDATE direct_attempts SET contained=1") |
| 308 | mustJournal(t, err) |
| 309 | l.AttemptKey = "resume" |
| 310 | l.ResumeSessionID = s.ID |
| 311 | p.record.ID = strings.Repeat("b", 32) |
| 312 | p.record.AttemptKey = l.AttemptKey |
| 313 | mustJournal(t, j.recordDirectLaunch(ctx, l, p.record)) |
| 314 | s.AttemptKey = l.AttemptKey |
| 315 | mustJournal(t, j.BeginTurn(ctx, s, provider.Turn{ID: "resumed", AdmissionID: "resumed-admit", Prompt: "hello"})) |
| 316 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 317 | _, err = j.ObserveDirect(ctx, s, codexUsage("resumed", 30000, 150)) |
| 318 | mustJournal(t, err) |
| 319 | u, err := j.ObserveDirect(ctx, s, directComplete("resumed")) |
| 320 | mustJournal(t, err) |
| 321 | if u == nil || u.InputTokens != 1746 || u.OutputTokens != 8 { |
| 322 | t.Fatalf("resume lost baseline: %+v", u) |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | func TestDirectUsageResumeRejectsChangedBinding(t *testing.T) { |
| 327 | for _, field := range []string{"policy", "account", "binding", "version", "unknown-resume"} { |
| 328 | t.Run(field, func(t *testing.T) { |
| 329 | j, l, s, p := directFixture(t, "codex") |
| 330 | ctx := context.Background() |
| 331 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 332 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 333 | _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 100, 10)) |
| 334 | mustJournal(t, err) |
| 335 | _, err = j.ObserveDirect(ctx, s, directComplete("turn")) |
| 336 | mustJournal(t, err) |
| 337 | _, err = j.db.Exec("UPDATE direct_attempts SET contained=1") |
| 338 | mustJournal(t, err) |
| 339 | l.AttemptKey = "resume" |
| 340 | l.ResumeSessionID = s.ID |
| 341 | p.record.ID = strings.Repeat("b", 32) |
| 342 | p.record.AttemptKey = l.AttemptKey |
| 343 | switch field { |
| 344 | case "policy": |
| 345 | l.Policy.Hash = "changed" |
| 346 | p.record.PolicyHash = l.Policy.Hash |
| 347 | case "account": |
| 348 | l.Binding.AccountID = "changed" |
| 349 | l.Selection.AccountID = "changed" |
| 350 | s.AccountID = "changed" |
| 351 | case "binding": |
| 352 | l.Binding.ID = "changed" |
| 353 | case "version": |
| 354 | l.Binding.Expected.ProviderVersion = "changed" |
| 355 | case "unknown-resume": |
| 356 | l.ResumeSessionID = "unknown" |
| 357 | s.ID = "unknown" |
| 358 | } |
| 359 | mustJournal(t, j.recordDirectLaunch(ctx, l, p.record)) |
| 360 | s.AttemptKey = l.AttemptKey |
| 361 | if j.BeginTurn(ctx, s, provider.Turn{ID: "resumed", AdmissionID: "resumed-admit", Prompt: "hello"}) == nil { |
| 362 | t.Fatal("resume trusted changed durable binding", field) |
| 363 | } |
| 364 | }) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | func TestDirectInterruptedReconcileIntent(t *testing.T) { |
| 369 | for _, kind := range []string{"intent", "before-namespace-record", "policy-mismatch", "manifest-mismatch"} { |
| 370 | t.Run(kind, func(t *testing.T) { |
| 371 | j, _, _, p := directFixture(t, "codex") |
| 372 | ctx := context.Background() |
| 373 | root := t.TempDir() |
| 374 | mustJournal(t, os.Chmod(root, 0700)) |
| 375 | binary, err := os.Executable() |
| 376 | mustJournal(t, err) |
| 377 | m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: root}) |
| 378 | mustJournal(t, err) |
| 379 | boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id") |
| 380 | mustJournal(t, err) |
| 381 | p.record.BootID = strings.TrimSpace(string(boot)) |
| 382 | raw, _ := json.Marshal(p.record) |
| 383 | _, err = j.db.Exec("UPDATE direct_attempts SET record=?", raw) |
| 384 | mustJournal(t, err) |
| 385 | if kind == "policy-mismatch" { |
| 386 | p.record.PolicyHash = "other" |
| 387 | } |
| 388 | if kind == "manifest-mismatch" { |
| 389 | p.record.ManifestHash = "other" |
| 390 | } |
| 391 | raw, _ = json.Marshal(p.record) |
| 392 | dir := filepath.Join(root, "attempt-"+p.ID()) |
| 393 | mustJournal(t, os.Mkdir(dir, 0700)) |
| 394 | mustJournal(t, os.WriteFile(filepath.Join(dir, "scratch"), []byte("owned"), 0600)) |
| 395 | if kind != "before-namespace-record" { |
| 396 | mustJournal(t, os.WriteFile(filepath.Join(root, p.ID()+".json"), raw, 0600)) |
| 397 | } |
| 398 | _, err = j.RecoverDirect(ctx) |
| 399 | mustJournal(t, err) |
| 400 | if j.AdmissionAllowed(ctx) == nil { |
| 401 | t.Fatal("missing containment admitted dependent work") |
| 402 | } |
| 403 | rows, err := j.ReconcileDirect(ctx, m) |
| 404 | if strings.HasSuffix(kind, "mismatch") { |
| 405 | if err == nil { |
| 406 | t.Fatal("mismatch accepted") |
| 407 | } |
| 408 | if _, err = os.Stat(dir); err != nil { |
| 409 | t.Fatal("mismatch removed scratch") |
| 410 | } |
| 411 | return |
| 412 | } |
| 413 | mustJournal(t, err) |
| 414 | if len(rows) != 1 || rows[0].State != "never_started" || rows[0].Usage != nil { |
| 415 | t.Fatalf("intent not safely retired: %+v", rows) |
| 416 | } |
| 417 | if _, err = os.Stat(dir); !os.IsNotExist(err) { |
| 418 | t.Fatal("scratch remains", err) |
| 419 | } |
| 420 | mustJournal(t, j.AdmissionAllowed(ctx)) |
| 421 | }) |
| 422 | } |
| 423 | } |
| 424 | func TestDirectUsageCompaction(t *testing.T) { |
| 425 | a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "codex", ProviderVersion: "0.165.0", Subscription: true}) |
| 426 | a.Observe(codexUsage("turn", 100, 10)) |
| 427 | a.Observe(provider.Event{SessionID: "session", TurnID: "turn", Kind: "item/completed", Payload: json.RawMessage(`{"params":{"item":{"type":"contextCompaction"}}}`)}) |
| 428 | a.Observe(codexUsage("turn", 200, 20)) |
| 429 | if a.Observe(directComplete("turn")) != nil { |
| 430 | t.Fatal("compaction invented verified baseline") |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | func TestDirectCompletionNeedsContainment(t *testing.T) { |
| 435 | j, l, s, p := directFixture(t, "codex") |
| 436 | ctx := context.Background() |
| 437 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 438 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 439 | _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 100, 10)) |
| 440 | mustJournal(t, err) |
| 441 | _, err = j.ObserveDirect(ctx, s, directComplete("turn")) |
| 442 | mustJournal(t, err) |
| 443 | l.AttemptKey = "resume" |
| 444 | l.ResumeSessionID = s.ID |
| 445 | p.record.ID = strings.Repeat("b", 32) |
| 446 | p.record.AttemptKey = l.AttemptKey |
| 447 | mustJournal(t, j.recordDirectLaunch(ctx, l, p.record)) |
| 448 | s.AttemptKey = l.AttemptKey |
| 449 | if j.BeginTurn(ctx, s, provider.Turn{ID: "new", AdmissionID: "new-admit", Prompt: "hello"}) == nil { |
| 450 | t.Fatal("completion without containment admitted dependent work") |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | func TestDirectJournalProjectionSecrets(t *testing.T) { |
| 455 | j, _, s, _ := directFixture(t, "codex") |
| 456 | ctx := context.Background() |
| 457 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 458 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 459 | e := provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "tool.output", Sequence: 1, Payload: json.RawMessage(`{"output":"Bearer private-token ` + strings.Repeat("x", 20000) + ` custom-secret","input_tokens":9007199254740993}`)} |
| 460 | p := EventPump{Journal: j, Secrets: []string{"custom-secret"}, Contain: func(context.Context) error { return nil }} |
| 461 | mustJournal(t, p.AppendDirect(ctx, s, e, journalEvent("template", 1))) |
| 462 | events, err := j.Pending(ctx, 100) |
| 463 | mustJournal(t, err) |
| 464 | var all []byte |
| 465 | for _, event := range events { |
| 466 | var chunk struct { |
| 467 | Data string `json:"base64"` |
| 468 | } |
| 469 | mustJournal(t, json.Unmarshal(event.Payload, &chunk)) |
| 470 | if chunk.Data != "" { |
| 471 | b, err := base64.StdEncoding.DecodeString(chunk.Data) |
| 472 | mustJournal(t, err) |
| 473 | all = append(all, b...) |
| 474 | } |
| 475 | } |
| 476 | if strings.Contains(string(all), "private-token") || strings.Contains(string(all), "custom-secret") || !strings.Contains(string(all), "9007199254740993") { |
| 477 | t.Fatal("projection leaked credentials or rounded counters") |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | func TestDirectUsageClaudeUnknown(t *testing.T) { |
| 482 | for _, usage := range []string{`{}`, `{"input_tokens":1,"output_tokens":2}`, `{"input_tokens":9223372036854775807,"cache_read_input_tokens":1,"cache_creation_input_tokens":0,"output_tokens":2}`, `{"input_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":-1,"output_tokens":2}`} { |
| 483 | a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "claude", ProviderVersion: "2.1.312", Subscription: true}) |
| 484 | e := provider.Event{SessionID: "session", TurnID: "turn", Kind: "turn.completed", Payload: json.RawMessage(`{"usage":` + usage + `}`)} |
| 485 | if a.Observe(e) != nil { |
| 486 | t.Fatalf("unknown Claude usage settled: %s", usage) |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | func TestDirectInterruptedManifestIntegrity(t *testing.T) { |
| 492 | j, l, _, p := directFixture(t, "codex") |
| 493 | l.Policy.Manifest = json.RawMessage(`{"changed":true}`) |
| 494 | raw, _ := json.Marshal(l) |
| 495 | _, err := j.db.Exec("UPDATE direct_attempts SET launch=?", raw) |
| 496 | mustJournal(t, err) |
| 497 | if j.validateDirectRecord(context.Background(), p.record) == nil { |
| 498 | t.Fatal("changed saved launch manifest accepted") |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | func TestDirectJournalFrameRetirement(t *testing.T) { |
| 503 | j, l, s, p := directFixture(t, "codex") |
| 504 | ctx := context.Background() |
| 505 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 506 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 507 | mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"n":1}`))) |
| 508 | _, err := j.db.Exec("UPDATE direct_attempts SET contained=1") |
| 509 | mustJournal(t, err) |
| 510 | mustJournal(t, j.releaseDirectFrames(ctx)) |
| 511 | var pending int |
| 512 | mustJournal(t, j.db.QueryRow("SELECT pending FROM direct_frames").Scan(&pending)) |
| 513 | if pending != 1 { |
| 514 | t.Fatal("raw bytes retired before normalization") |
| 515 | } |
| 516 | template := journalEvent("template", 1) |
| 517 | template.ActionID = 1 |
| 518 | pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(context.Context, Event) error { return nil }} |
| 519 | mustJournal(t, pump.AppendDirect(ctx, s, codexUsage("turn", 28254, 142), template)) |
| 520 | mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template)) |
| 521 | mustJournal(t, j.releaseDirectFrames(ctx)) |
| 522 | mustJournal(t, j.db.QueryRow("SELECT pending FROM direct_frames").Scan(&pending)) |
| 523 | if pending != 1 { |
| 524 | t.Fatal("raw bytes retired before upload acknowledgement") |
| 525 | } |
| 526 | mustJournal(t, pump.Flush(ctx, 10)) |
| 527 | mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&pending)) |
| 528 | if pending != 0 { |
| 529 | t.Fatal("acknowledged bytes still fill pending budget") |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | func TestDirectInterruptedSyntheticFailure(t *testing.T) { |
| 534 | j, _, s, _ := directFixture(t, "codex") |
| 535 | ctx := context.Background() |
| 536 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 537 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 538 | p := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} |
| 539 | template := journalEvent("template", 1) |
| 540 | template.ActionID = 1 |
| 541 | mustJournal(t, p.AppendDirect(ctx, s, provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "turn.failed"}, template)) |
| 542 | rows, err := j.RecoverDirect(ctx) |
| 543 | mustJournal(t, err) |
| 544 | if rows[0].State != "waiting_for_person" || rows[0].Usage != nil { |
| 545 | t.Fatal("adapter failure invented accounting") |
| 546 | } |
| 547 | events, err := j.Pending(ctx, 10) |
| 548 | mustJournal(t, err) |
| 549 | if len(events) != 1 || events[0].Kind != "turn.failed" { |
| 550 | t.Fatal("adapter failure lost before upload") |
| 551 | } |
| 552 | } |
| 553 | |