| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http/httptest" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 17 | ) |
| 18 | |
| 19 | var journalCtx = context.Background() |
| 20 | |
| 21 | func journalEvent(id string, seq int64) Event { |
| 22 | return Event{Version: 2, ID: id, TaskID: "task", AssignmentID: "assignment", ServerID: "server", AgentID: "agent", SessionID: "session", Epoch: "epoch", Kind: "timeline", Sequence: &seq, Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}, Payload: json.RawMessage(`{"text":"hello"}`), SourceTime: time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)} |
| 23 | } |
| 24 | func mustJournal(t *testing.T, err error) { |
| 25 | t.Helper() |
| 26 | if err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | } |
| 30 | func TestRunnerJournalCrashBoundaries(t *testing.T) { |
| 31 | path := filepath.Join(t.TempDir(), "private", "journal.db") |
| 32 | j, err := OpenJournal(journalCtx, path) |
| 33 | mustJournal(t, err) |
| 34 | pending, err := j.Pending(journalCtx, 10) |
| 35 | mustJournal(t, err) |
| 36 | if len(pending) != 0 { |
| 37 | t.Fatal("effect before append") |
| 38 | } |
| 39 | e := journalEvent("event", 1) |
| 40 | mustJournal(t, j.Append(journalCtx, e)) |
| 41 | mustJournal(t, j.Close()) |
| 42 | for i := 0; i < 2; i++ { |
| 43 | j, err = OpenJournal(journalCtx, path) |
| 44 | mustJournal(t, err) |
| 45 | pending, err = j.Pending(journalCtx, 10) |
| 46 | mustJournal(t, err) |
| 47 | if len(pending) != 1 { |
| 48 | t.Fatal("lost durable event", len(pending)) |
| 49 | } |
| 50 | mustJournal(t, j.Append(journalCtx, e)) |
| 51 | mustJournal(t, j.Close()) |
| 52 | } |
| 53 | j, err = OpenJournal(journalCtx, path) |
| 54 | mustJournal(t, err) |
| 55 | defer j.Close() |
| 56 | e.Payload = json.RawMessage(`{"text":"changed"}`) |
| 57 | if j.Append(journalCtx, e) == nil { |
| 58 | t.Fatal("changed duplicate accepted") |
| 59 | } |
| 60 | mustJournal(t, j.Ack(journalCtx, "event")) |
| 61 | mustJournal(t, j.Close()) |
| 62 | j, err = OpenJournal(journalCtx, path) |
| 63 | mustJournal(t, err) |
| 64 | defer j.Close() |
| 65 | pending, err = j.Pending(journalCtx, 10) |
| 66 | mustJournal(t, err) |
| 67 | if len(pending) != 0 { |
| 68 | t.Fatal("ACK did not survive reopen") |
| 69 | } |
| 70 | info, err := os.Stat(path) |
| 71 | mustJournal(t, err) |
| 72 | if info.Mode().Perm() != 0600 { |
| 73 | t.Fatal("journal is not private") |
| 74 | } |
| 75 | intent := provider.Intent{Kind: "agent", Key: "creation", RequestHash: "hash", Request: json.RawMessage(`{"idempotency_key":"creation"}`)} |
| 76 | mustJournal(t, j.RecordIntent(journalCtx, intent)) |
| 77 | mustJournal(t, j.RecordIntent(journalCtx, intent)) |
| 78 | intent.RequestHash = "changed" |
| 79 | if j.RecordIntent(journalCtx, intent) == nil { |
| 80 | t.Fatal("creation key changed") |
| 81 | } |
| 82 | } |
| 83 | func TestBufferFullStopsWork(t *testing.T) { |
| 84 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 85 | mustJournal(t, err) |
| 86 | defer j.Close() |
| 87 | j.maxBytes = 1 |
| 88 | stopped := 0 |
| 89 | p := EventPump{Journal: j, Contain: func(context.Context) error { stopped++; return nil }} |
| 90 | acked := false |
| 91 | if p.Append(journalCtx, journalEvent("full", 1), func() error { acked = true; return nil }) == nil { |
| 92 | t.Fatal("full journal accepted") |
| 93 | } |
| 94 | if stopped != 1 || acked { |
| 95 | t.Fatal("buffer full did not stop admission and contain", stopped, acked) |
| 96 | } |
| 97 | j.maxBytes = MaxJournalBytes |
| 98 | if j.AdmissionAllowed(journalCtx) != nil { |
| 99 | t.Fatal("drained budget remained latched") |
| 100 | } |
| 101 | mustJournal(t, j.Close()) |
| 102 | if p.Append(journalCtx, journalEvent("closed", 2), nil) == nil || stopped != 2 { |
| 103 | t.Fatal("disk failure did not contain") |
| 104 | } |
| 105 | } |
| 106 | func TestRunnerEventReplay(t *testing.T) { |
| 107 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 108 | mustJournal(t, err) |
| 109 | defer j.Close() |
| 110 | p := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} |
| 111 | mustJournal(t, p.Append(journalCtx, journalEvent("event", 1), func() error { |
| 112 | rows, err := j.Pending(journalCtx, 10) |
| 113 | if err != nil || len(rows) != 1 { |
| 114 | t.Fatal("ACK before append") |
| 115 | } |
| 116 | return nil |
| 117 | })) |
| 118 | calls := 0 |
| 119 | p.Upload = func(context.Context, Event) error { |
| 120 | calls++ |
| 121 | if calls == 1 { |
| 122 | return provider.ErrUncertain |
| 123 | } |
| 124 | return nil |
| 125 | } |
| 126 | if p.Flush(journalCtx, 10) == nil { |
| 127 | t.Fatal("lost upload was ACKed") |
| 128 | } |
| 129 | mustJournal(t, p.Flush(journalCtx, 10)) |
| 130 | rows, err := j.Pending(journalCtx, 10) |
| 131 | mustJournal(t, err) |
| 132 | if len(rows) != 0 || calls != 2 { |
| 133 | t.Fatal("replay failed") |
| 134 | } |
| 135 | } |
| 136 | func TestTimelineEpochReplacement(t *testing.T) { |
| 137 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 138 | mustJournal(t, err) |
| 139 | defer j.Close() |
| 140 | a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| 141 | if _, err = j.Cursor(journalCtx, a); err != nil { |
| 142 | t.Fatal(err) |
| 143 | } |
| 144 | if j.Ready(journalCtx, a) == nil { |
| 145 | t.Fatal("live before refetch") |
| 146 | } |
| 147 | mustJournal(t, j.Append(journalCtx, journalEvent("old", 1))) |
| 148 | mustJournal(t, j.BeginReplay(journalCtx, a)) |
| 149 | mustJournal(t, j.Recovered(journalCtx, a, provider.Cursor{Epoch: "epoch", Sequence: 1})) |
| 150 | mustJournal(t, j.Ready(journalCtx, a)) |
| 151 | mustJournal(t, j.BeginReplay(journalCtx, a)) |
| 152 | if j.Ready(journalCtx, a) == nil { |
| 153 | t.Fatal("reconnect retained readiness") |
| 154 | } |
| 155 | e := journalEvent("replacement", 1) |
| 156 | e.Epoch = "new" |
| 157 | reset := e |
| 158 | reset.ID = "reset" |
| 159 | reset.Kind = "timeline_replacement" |
| 160 | reset.Sequence = nil |
| 161 | mustJournal(t, j.Append(journalCtx, reset)) |
| 162 | mustJournal(t, j.BeginReplay(journalCtx, a)) |
| 163 | mustJournal(t, j.Append(journalCtx, e)) |
| 164 | mustJournal(t, j.Recovered(journalCtx, a, provider.Cursor{Epoch: "new", Sequence: 1})) |
| 165 | c, err := j.Cursor(journalCtx, a) |
| 166 | mustJournal(t, err) |
| 167 | if c.Epoch != "new" { |
| 168 | t.Fatal("epoch did not replace projection") |
| 169 | } |
| 170 | rows, err := j.Pending(journalCtx, 10) |
| 171 | mustJournal(t, err) |
| 172 | if len(rows) != 3 { |
| 173 | t.Fatal("epoch deleted accounting evidence") |
| 174 | } |
| 175 | mustJournal(t, j.Close()) |
| 176 | j, err = OpenJournal(journalCtx, j.path) |
| 177 | mustJournal(t, err) |
| 178 | defer j.Close() |
| 179 | if j.Ready(journalCtx, a) == nil { |
| 180 | t.Fatal("restart trusted old live readiness") |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestRunnerJournalCursorCannotSkip(t *testing.T) { |
| 185 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 186 | mustJournal(t, err) |
| 187 | defer j.Close() |
| 188 | a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| 189 | mustJournal(t, j.BeginReplay(journalCtx, a)) |
| 190 | if j.Recovered(journalCtx, a, provider.Cursor{Epoch: "epoch", Sequence: 9}) == nil { |
| 191 | t.Fatal("cursor skipped unjournaled events") |
| 192 | } |
| 193 | mustJournal(t, j.Append(journalCtx, journalEvent("saved", 1))) |
| 194 | if j.Recovered(journalCtx, a, provider.Cursor{Epoch: "epoch", Sequence: 2}) == nil { |
| 195 | t.Fatal("cursor advanced beyond durable event") |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | func TestRunnerJournalSecretsAndLog(t *testing.T) { |
| 200 | path := filepath.Join(t.TempDir(), "private", "journal.db") |
| 201 | j, err := OpenJournal(journalCtx, path) |
| 202 | mustJournal(t, err) |
| 203 | defer j.Close() |
| 204 | e := journalEvent("secret", 1) |
| 205 | e.Payload = json.RawMessage(`{"authorization":"Bearer credential-value","text":"Bearer credential-value Authorization: Basic eDpnaXQtY2FuYXJ5 <script>alert(1)</script>","inputTokens":2}`) |
| 206 | mustJournal(t, j.Append(journalCtx, e)) |
| 207 | rows, err := j.Pending(journalCtx, 10) |
| 208 | mustJournal(t, err) |
| 209 | if strings.Contains(string(rows[0].Payload), "credential-value") || strings.Contains(string(rows[0].Payload), "eDpnaXQtY2FuYXJ5") || !strings.Contains(string(rows[0].Payload), "inputTokens") { |
| 210 | t.Error("redaction lost accounting or leaked secret", string(rows[0].Payload)) |
| 211 | } |
| 212 | intent := provider.Intent{Kind: "agent", Key: "secret-intent", RequestHash: "hash", Request: json.RawMessage(`{"env":{"EQUIPO_TOOL_TOKEN":"private-key-value"}}`)} |
| 213 | mustJournal(t, j.RecordIntent(journalCtx, intent)) |
| 214 | var raw []byte |
| 215 | mustJournal(t, j.db.QueryRow("SELECT body FROM journal_intents").Scan(&raw)) |
| 216 | if strings.Contains(string(raw), "private-key-value") { |
| 217 | t.Fatal("intent persisted credential") |
| 218 | } |
| 219 | w := httptest.NewRecorder() |
| 220 | DownloadLog(w, []byte(`<script>secret</script> Bearer credential-value Authorization: Basic eDpnaXQtY2FuYXJ5`), []string{"secret"}) |
| 221 | if strings.Contains(w.Body.String(), "<script>") || strings.Contains(w.Body.String(), "credential-value") || strings.Contains(w.Body.String(), "eDpnaXQtY2FuYXJ5") || strings.Contains(w.Body.String(), "secret") || w.Header().Get("Content-Type") != "text/plain; charset=utf-8" { |
| 222 | t.Error("unsafe log download", w.Body.String()) |
| 223 | } |
| 224 | } |
| 225 | func TestBufferFullStopsWorkSQLite(t *testing.T) { |
| 226 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 227 | mustJournal(t, err) |
| 228 | defer j.Close() |
| 229 | var pages int |
| 230 | mustJournal(t, j.db.QueryRow("PRAGMA page_count").Scan(&pages)) |
| 231 | _, err = j.db.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", pages)) |
| 232 | mustJournal(t, err) |
| 233 | e := journalEvent("disk-full", 1) |
| 234 | e.Payload = json.RawMessage(`{"text":"` + strings.Repeat("x", 15000) + `"}`) |
| 235 | contained := false |
| 236 | p := EventPump{Journal: j, Contain: func(ctx context.Context) error { |
| 237 | if ctx.Err() != nil { |
| 238 | t.Fatal("containment inherited cancelled context") |
| 239 | } |
| 240 | contained = true |
| 241 | return nil |
| 242 | }} |
| 243 | if p.Append(journalCtx, e, nil) == nil || !contained || j.AdmissionAllowed(journalCtx) == nil { |
| 244 | t.Fatal("SQLite full did not stop and contain") |
| 245 | } |
| 246 | rows, err := j.Pending(journalCtx, 10) |
| 247 | mustJournal(t, err) |
| 248 | if len(rows) != 0 { |
| 249 | t.Fatal("partial disk-full append") |
| 250 | } |
| 251 | } |
| 252 | func TestRunnerJournalCrashProcess(t *testing.T) { |
| 253 | if path := os.Getenv("EQUIPO_TASK12_CRASH_PATH"); path != "" { |
| 254 | j, err := OpenJournal(journalCtx, path) |
| 255 | if err != nil { |
| 256 | os.Exit(11) |
| 257 | } |
| 258 | if os.Getenv("EQUIPO_TASK12_CRASH_STAGE") != "before" { |
| 259 | if j.Append(journalCtx, journalEvent("crash", 1)) != nil { |
| 260 | os.Exit(12) |
| 261 | } |
| 262 | } |
| 263 | os.Exit(0) |
| 264 | } |
| 265 | for _, stage := range []string{"before", "after"} { |
| 266 | t.Run(stage, func(t *testing.T) { |
| 267 | path := filepath.Join(t.TempDir(), "private", "journal.db") |
| 268 | cmd := exec.Command(os.Args[0], "-test.run=^TestRunnerJournalCrashProcess$") |
| 269 | cmd.Env = append(os.Environ(), "EQUIPO_TASK12_CRASH_PATH="+path, "EQUIPO_TASK12_CRASH_STAGE="+stage) |
| 270 | if b, err := cmd.CombinedOutput(); err != nil { |
| 271 | t.Fatal(err, string(b)) |
| 272 | } |
| 273 | j, err := OpenJournal(journalCtx, path) |
| 274 | mustJournal(t, err) |
| 275 | defer j.Close() |
| 276 | rows, err := j.Pending(journalCtx, 10) |
| 277 | mustJournal(t, err) |
| 278 | want := 0 |
| 279 | if stage == "after" { |
| 280 | want = 1 |
| 281 | } |
| 282 | if len(rows) != want { |
| 283 | t.Fatal("crash boundary lost event", stage, len(rows)) |
| 284 | } |
| 285 | }) |
| 286 | } |
| 287 | } |
| 288 | func TestRunnerJournalBackoffLease(t *testing.T) { |
| 289 | for _, attempt := range []int{-1, 0, 1, 4, 5, 100} { |
| 290 | delay := ReconnectDelay(attempt) |
| 291 | if delay < time.Second || delay > 30250*time.Millisecond { |
| 292 | t.Fatal("unbounded backoff", delay) |
| 293 | } |
| 294 | } |
| 295 | if WaitReconnect(journalCtx, 10, time.Now().Add(10*time.Millisecond)) == nil { |
| 296 | t.Fatal("backoff extended lease") |
| 297 | } |
| 298 | ctx, cancel := context.WithCancel(journalCtx) |
| 299 | cancel() |
| 300 | if WaitReconnect(ctx, 0, time.Now().Add(time.Minute)) == nil { |
| 301 | t.Fatal("reconnect ignored cancellation") |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | func TestTimelineEpochGapStopsLocalDispatch(t *testing.T) { |
| 306 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 307 | mustJournal(t, err) |
| 308 | defer j.Close() |
| 309 | a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| 310 | e := journalEvent("first", 1) |
| 311 | mustJournal(t, j.Append(journalCtx, e)) |
| 312 | mustJournal(t, j.BeginReplay(journalCtx, a)) |
| 313 | mustJournal(t, j.Recovered(journalCtx, a, provider.Cursor{Epoch: "epoch", Sequence: 1})) |
| 314 | mustJournal(t, j.Ready(journalCtx, a)) |
| 315 | e.ID = "gap" |
| 316 | e.Kind = "timeline_gap" |
| 317 | e.Sequence = nil |
| 318 | mustJournal(t, j.Append(journalCtx, e)) |
| 319 | if j.Ready(journalCtx, a) == nil { |
| 320 | t.Fatal("timeline gap retained live readiness") |
| 321 | } |
| 322 | request, _ := json.Marshal(struct { |
| 323 | Agent provider.Agent `json:"agent"` |
| 324 | }{a}) |
| 325 | if j.RecordIntent(journalCtx, provider.Intent{Kind: "turn", Key: "dispatch", RequestHash: "hash", Request: request}) == nil { |
| 326 | t.Fatal("gap allowed dispatch ID") |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | func TestRunnerJournalDurabilityConfiguration(t *testing.T) { |
| 331 | path := filepath.Join(t.TempDir(), "private", "journal.db") |
| 332 | j, err := OpenJournal(journalCtx, path) |
| 333 | mustJournal(t, err) |
| 334 | var syncLevel int |
| 335 | var mode string |
| 336 | mustJournal(t, j.db.QueryRow("PRAGMA synchronous").Scan(&syncLevel)) |
| 337 | mustJournal(t, j.db.QueryRow("PRAGMA journal_mode").Scan(&mode)) |
| 338 | if syncLevel != 2 || mode != "delete" { |
| 339 | t.Fatal("journal writes are not durably synced", syncLevel, mode) |
| 340 | } |
| 341 | _, err = j.db.Exec("PRAGMA user_version=7") |
| 342 | mustJournal(t, err) |
| 343 | mustJournal(t, j.Close()) |
| 344 | if other, err := OpenJournal(journalCtx, path); err == nil { |
| 345 | other.Close() |
| 346 | t.Fatal("newer journal accepted") |
| 347 | } |
| 348 | public := filepath.Join(t.TempDir(), "public") |
| 349 | mustJournal(t, os.Mkdir(public, 0755)) |
| 350 | if other, err := OpenJournal(journalCtx, filepath.Join(public, "journal.db")); err == nil { |
| 351 | other.Close() |
| 352 | t.Fatal("public journal directory accepted") |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | func TestTimelineEpochRefetchReadiness(t *testing.T) { |
| 357 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 358 | mustJournal(t, err) |
| 359 | defer j.Close() |
| 360 | a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| 361 | e := journalEvent("saved", 1) |
| 362 | mustJournal(t, j.Append(journalCtx, e)) |
| 363 | c := provider.Cursor{Epoch: "epoch", Sequence: 1} |
| 364 | if j.Recovered(journalCtx, a, c) == nil { |
| 365 | t.Fatal("recovered without starting refetch") |
| 366 | } |
| 367 | mustJournal(t, j.BeginReplay(journalCtx, a)) |
| 368 | e.ID = "gap-during-refetch" |
| 369 | e.Kind = "timeline_gap" |
| 370 | e.Sequence = nil |
| 371 | mustJournal(t, j.Append(journalCtx, e)) |
| 372 | if j.Recovered(journalCtx, a, c) == nil { |
| 373 | t.Fatal("gap during refetch regained readiness") |
| 374 | } |
| 375 | mustJournal(t, j.BeginReplay(journalCtx, a)) |
| 376 | mustJournal(t, j.Recovered(journalCtx, a, c)) |
| 377 | mustJournal(t, j.Ready(journalCtx, a)) |
| 378 | } |
| 379 | |
| 380 | func TestRunnerEventReplayRejectsMalformedBeforeRedaction(t *testing.T) { |
| 381 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 382 | mustJournal(t, err) |
| 383 | defer j.Close() |
| 384 | contained := false |
| 385 | acked := false |
| 386 | p := EventPump{Journal: j, Contain: func(context.Context) error { contained = true; return nil }} |
| 387 | e := journalEvent("invalid", 1) |
| 388 | e.Payload = json.RawMessage(`invalid`) |
| 389 | if p.Append(journalCtx, e, func() error { acked = true; return nil }) == nil || acked || !contained { |
| 390 | t.Fatal("redaction hid malformed event") |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | func TestRunnerEventDrainBacklog(t *testing.T) { |
| 395 | for _, failLast := range []bool{false, true} { |
| 396 | t.Run(fmt.Sprint(failLast), func(t *testing.T) { |
| 397 | j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| 398 | mustJournal(t, err) |
| 399 | defer j.Close() |
| 400 | uploaded := 0 |
| 401 | p := EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(_ context.Context, e Event) error { |
| 402 | if e.ID == "event-129" && failLast { |
| 403 | return provider.ErrUncertain |
| 404 | } |
| 405 | uploaded++ |
| 406 | return nil |
| 407 | }} |
| 408 | for i := int64(1); i <= 129; i++ { |
| 409 | mustJournal(t, p.Append(journalCtx, journalEvent(fmt.Sprintf("event-%d", i), i), nil)) |
| 410 | } |
| 411 | err = p.Drain(journalCtx) |
| 412 | if failLast { |
| 413 | if err != provider.ErrUncertain { |
| 414 | t.Fatalf("last batch failure lost: %v", err) |
| 415 | } |
| 416 | pending, err := j.Pending(journalCtx, 128) |
| 417 | mustJournal(t, err) |
| 418 | if len(pending) != 1 || pending[0].ID != "event-129" { |
| 419 | t.Fatalf("failed terminal ACKed: %+v", pending) |
| 420 | } |
| 421 | } else if err != nil || uploaded != 129 { |
| 422 | t.Fatalf("backlog not drained before completion: uploaded=%d err=%v", uploaded, err) |
| 423 | } |
| 424 | }) |
| 425 | } |
| 426 | } |
| 427 | |