Repository navigation
Expand file tree
/
Copy pathtest_run_queue_workflow.py
More file actions
574 lines (502 loc) · 17.8 KB
/
Copy pathtest_run_queue_workflow.py
File metadata and controls
574 lines (502 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import subprocess
from pathlib import Path
import pytest
from conftest import (
FakeRunProcessController,
InlineRunExecutorSpawner,
bind_inline_executor,
initialize_repository,
)
from codealmanac.app import create_app
from codealmanac.core.errors import ExecutionFailed
from codealmanac.integrations.runs.process import worker_command
from codealmanac.services.harnesses.models import (
HarnessAgentKind,
HarnessKind,
HarnessReadiness,
HarnessRunResult,
HarnessRunStatus,
)
from codealmanac.services.harnesses.requests import RunHarnessRequest
from codealmanac.services.runs.models import RunKind, RunStatus, RunWorkerSpawnResult
from codealmanac.services.runs.requests import (
CancelRunRequest,
ListRunsRequest,
MarkRunRunningRequest,
ReadRunLogRequest,
ShowRunRequest,
SpawnRunWorkerRequest,
StartRunRequest,
)
from codealmanac.services.search.requests import SearchPagesRequest
from codealmanac.settings import AppConfig
from codealmanac.workflows.build.requests import BuildRequest
from codealmanac.workflows.ingest.requests import IngestRequest
from codealmanac.workflows.run_queue import DrainRunQueueRequest
class QueueWritingHarnessAdapter:
kind = HarnessKind.CODEX
def __init__(self):
self.requests: list[RunHarnessRequest] = []
def check(self) -> HarnessReadiness:
return HarnessReadiness(
kind=self.kind,
available=True,
message="codex ready",
)
def run(self, request: RunHarnessRequest, on_event=None) -> HarnessRunResult:
self.requests.append(request)
page = request.cwd / "almanac/queued-note.md"
page.write_text(
"""---
title: Queued Note
topics: [concepts]
sources: []
---
# Queued Note
The queued worker turned the note into durable wiki knowledge.
""",
encoding="utf-8",
)
return HarnessRunResult(
kind=self.kind,
status=HarnessRunStatus.SUCCEEDED,
output_text="updated wiki",
summary="queued ingest completed",
changed_files=(page,),
)
class FakeWorkerSpawner:
def __init__(self):
self.requests: list[SpawnRunWorkerRequest] = []
def spawn(self, request: SpawnRunWorkerRequest) -> RunWorkerSpawnResult:
self.requests.append(request)
return RunWorkerSpawnResult(
child_pid=4242,
command=("fake-codealmanac-worker",),
)
def test_run_queue_start_persists_spec_and_spawns_worker(
tmp_path: Path,
isolated_home: Path,
):
repo = tmp_path / "repo"
repo.mkdir()
(repo / "note.md").write_text("queue design note\n", encoding="utf-8")
spawner = FakeWorkerSpawner()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(QueueWritingHarnessAdapter(),),
worker_spawner=spawner,
)
initialize_repository(app, repo)
result = app.workflows.queue.start_ingest(
IngestRequest(
cwd=repo,
inputs=("note.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
)
)
runs = app.runs.list(ListRunsRequest(repository_name=repo.name))
assert result.worker.child_pid == 4242
assert result.run.status == RunStatus.QUEUED
assert runs[0].run_id == result.run.run_id
assert spawner.requests == [SpawnRunWorkerRequest(cwd=repo)]
assert (isolated_home / ".codealmanac/codealmanac.db").is_file()
assert not (repo / "almanac/jobs").exists()
class FailingWorkerSpawner:
def spawn(self, request: SpawnRunWorkerRequest) -> RunWorkerSpawnResult:
raise OSError("fake spawn failure")
def test_run_queue_start_handles_worker_spawn_failure(
tmp_path: Path,
isolated_home: Path,
):
repo = tmp_path / "repo"
repo.mkdir()
(repo / "note.md").write_text("queue design note\n", encoding="utf-8")
spawner = FailingWorkerSpawner()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(QueueWritingHarnessAdapter(),),
worker_spawner=spawner,
)
initialize_repository(app, repo)
with pytest.raises(ExecutionFailed, match="fake spawn failure"):
app.workflows.queue.start_ingest(
IngestRequest(
cwd=repo,
inputs=("note.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
)
)
runs = app.runs.list(ListRunsRequest(repository_name=repo.name))
assert len(runs) == 1
assert runs[0].status == RunStatus.QUEUED
def test_run_queue_drains_persisted_ingest_spec(
tmp_path: Path,
isolated_home: Path,
):
repo = tmp_path / "repo"
repo.mkdir()
(repo / "note.md").write_text("queue design note\n", encoding="utf-8")
harness = QueueWritingHarnessAdapter()
executors = InlineRunExecutorSpawner()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(harness,),
executor_spawner=executors,
process_controller=FakeRunProcessController(),
)
bind_inline_executor(app, executors)
initialize_repository(app, repo)
initialize_git(repo)
commit_all(repo, "initial wiki")
queued = app.workflows.queue.queue_ingest(
IngestRequest(
cwd=repo,
inputs=("note.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
title="Ingest queued note",
guidance="Keep the page short.",
auto_commit=False,
)
)
result = app.workflows.queue.drain(DrainRunQueueRequest())
runs = app.runs.list(ListRunsRequest(repository_name=repo.name))
log = app.runs.log(
ReadRunLogRequest(repository_name=repo.name, run_id=queued.run_id)
)
matches = app.search.search(SearchPagesRequest(cwd=repo, query="worker"))
assert result.lock_acquired is True
assert [record.run_id for record in result.processed] == [queued.run_id]
assert runs[0].status == RunStatus.DONE
assert runs[0].summary == "queued ingest completed"
assert matches[0].slug == "queued-note"
assert len(harness.requests) == 1
assert "Keep the page short." in harness.requests[0].prompt
assert '"auto_commit": false' in harness.requests[0].prompt
assert "Do not run git commit." in harness.requests[0].prompt
assert tuple(event.message for event in log[:2]) == (
"queued ingest",
"running",
)
def test_run_queue_processes_work_queued_at_idle_handoff(
tmp_path: Path,
isolated_home: Path,
monkeypatch: pytest.MonkeyPatch,
):
repo = tmp_path / "repo"
repo.mkdir()
(repo / "note.md").write_text("late queue design note\n", encoding="utf-8")
harness = QueueWritingHarnessAdapter()
executors = InlineRunExecutorSpawner()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(harness,),
executor_spawner=executors,
process_controller=FakeRunProcessController(),
)
bind_inline_executor(app, executors)
initialize_repository(app, repo)
initialize_git(repo)
commit_all(repo, "initial wiki")
release_if_idle = app.runs.release_worker_if_idle
queued_run_id: str | None = None
def queue_before_handoff(request):
nonlocal queued_run_id
if queued_run_id is None:
queued = app.workflows.queue.queue_ingest(
IngestRequest(
cwd=repo,
inputs=("note.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
auto_commit=False,
)
)
queued_run_id = queued.run_id
return release_if_idle(request)
monkeypatch.setattr(app.runs, "release_worker_if_idle", queue_before_handoff)
result = app.workflows.queue.drain(DrainRunQueueRequest())
assert queued_run_id is not None
assert [record.run_id for record in result.processed] == [queued_run_id]
assert app.runs.show(ShowRunRequest(run_id=queued_run_id)).status == RunStatus.DONE
assert len(harness.requests) == 1
def test_run_queue_max_runs_leaves_later_work_for_next_worker(
tmp_path: Path,
isolated_home: Path,
):
repo = tmp_path / "repo"
repo.mkdir()
(repo / "first.md").write_text("first queue note\n", encoding="utf-8")
(repo / "second.md").write_text("second queue note\n", encoding="utf-8")
harness = QueueWritingHarnessAdapter()
executors = InlineRunExecutorSpawner()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(harness,),
executor_spawner=executors,
process_controller=FakeRunProcessController(),
)
bind_inline_executor(app, executors)
initialize_repository(app, repo)
initialize_git(repo)
commit_all(repo, "initial wiki")
first = app.workflows.queue.queue_ingest(
IngestRequest(
cwd=repo,
inputs=("first.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
auto_commit=False,
)
)
second = app.workflows.queue.queue_ingest(
IngestRequest(
cwd=repo,
inputs=("second.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
auto_commit=False,
)
)
first_drain = app.workflows.queue.drain(DrainRunQueueRequest(max_runs=1))
assert [record.run_id for record in first_drain.processed] == [first.run_id]
assert app.runs.show(ShowRunRequest(run_id=first.run_id)).status == RunStatus.DONE
assert (
app.runs.show(ShowRunRequest(run_id=second.run_id)).status
== RunStatus.QUEUED
)
second_drain = app.workflows.queue.drain(DrainRunQueueRequest(max_runs=1))
assert [record.run_id for record in second_drain.processed] == [second.run_id]
assert app.runs.show(ShowRunRequest(run_id=second.run_id)).status == RunStatus.DONE
def test_run_queue_drains_persisted_build_spec(
tmp_path: Path,
isolated_home: Path,
):
repo = tmp_path / "repo"
repo.mkdir()
initialize_git(repo)
harness = QueueWritingHarnessAdapter()
executors = InlineRunExecutorSpawner()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(harness,),
executor_spawner=executors,
process_controller=FakeRunProcessController(),
)
bind_inline_executor(app, executors)
queued = app.workflows.queue.queue_build(
BuildRequest(
path=repo,
harness=HarnessKind.CODEX,
model="gpt-5.5",
name="repo",
guidance="Write the smallest useful first wiki.",
)
)
result = app.workflows.queue.drain(DrainRunQueueRequest())
runs = app.runs.list(ListRunsRequest(repository_name="repo"))
assert queued.status == RunStatus.QUEUED
assert (repo / "almanac/README.md").is_file()
assert result.lock_acquired is True
assert [record.run_id for record in result.processed] == [queued.run_id]
assert runs[0].status == RunStatus.DONE
assert len(harness.requests) == 1
assert harness.requests[0].agent is HarnessAgentKind.BUILD
assert "Build Operation" not in harness.requests[0].prompt
assert "Write the smallest useful first wiki." in harness.requests[0].prompt
def test_run_queue_skips_cancelled_queued_runs(
tmp_path: Path,
isolated_home: Path,
):
repo = tmp_path / "repo"
repo.mkdir()
(repo / "note.md").write_text("cancelled queue note\n", encoding="utf-8")
harness = QueueWritingHarnessAdapter()
processes = FakeRunProcessController()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(harness,),
process_controller=processes,
)
initialize_repository(app, repo)
queued = app.workflows.queue.queue_ingest(
IngestRequest(
cwd=repo,
inputs=("note.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
)
)
app.workflows.queue.cancel(
CancelRunRequest(repository_name=repo.name, run_id=queued.run_id)
)
result = app.workflows.queue.drain(DrainRunQueueRequest())
runs = app.runs.list(ListRunsRequest(repository_name=repo.name))
assert result.lock_acquired is True
assert result.processed == ()
assert runs[0].status == RunStatus.CANCELLED
assert harness.requests == []
def test_worker_command_targets_codealmanac_module(tmp_path: Path):
command = worker_command(SpawnRunWorkerRequest(cwd=tmp_path))
assert command[1:] == [
"-m",
"codealmanac.cli.main",
"__run-worker",
"--cwd",
str(tmp_path),
]
def test_run_queue_cancels_running_executor_before_terminal_status(
tmp_path: Path,
isolated_home: Path,
):
repo = tmp_path / "repo"
repo.mkdir()
processes = FakeRunProcessController()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
process_controller=processes,
)
repository = initialize_repository(app, repo)
run = app.runs.start(
StartRunRequest(
repository_id=repository.repository_id,
kind=RunKind.GARDEN,
)
)
app.runs.mark_running(
MarkRunRunningRequest(run_id=run.run_id, execution=processes.execution)
)
result = app.workflows.queue.cancel(CancelRunRequest(run_id=run.run_id))
log = app.runs.log(ReadRunLogRequest(run_id=run.run_id))
assert processes.terminated == [processes.execution]
assert result.changed is True
assert result.record.status == RunStatus.CANCELLED
assert tuple(event.message for event in log) == (
"queued garden",
"running",
"cancellation requested",
"cancelled",
)
def test_run_queue_does_not_claim_cancelled_when_termination_fails(
tmp_path: Path,
isolated_home: Path,
):
class FailingController(FakeRunProcessController):
def terminate(self, execution):
raise ExecutionFailed("executor would not stop")
repo = tmp_path / "repo"
repo.mkdir()
processes = FailingController()
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
process_controller=processes,
)
repository = initialize_repository(app, repo)
run = app.runs.start(
StartRunRequest(
repository_id=repository.repository_id,
kind=RunKind.GARDEN,
)
)
app.runs.mark_running(
MarkRunRunningRequest(run_id=run.run_id, execution=processes.execution)
)
with pytest.raises(ExecutionFailed, match="executor would not stop"):
app.workflows.queue.cancel(CancelRunRequest(run_id=run.run_id))
current = app.runs.show(ShowRunRequest(run_id=run.run_id))
assert current.status == RunStatus.RUNNING
assert current.cancellation_requested_at is not None
def test_queue_manager_continues_after_running_job_is_cancelled(
tmp_path: Path,
isolated_home: Path,
):
class CancellingProcess:
pid = 4242
def __init__(self, app, run_id, execution):
self.app = app
self.run_id = run_id
self.execution = execution
def wait(self):
self.app.runs.mark_running(
MarkRunRunningRequest(
run_id=self.run_id,
execution=self.execution,
)
)
self.app.workflows.queue.cancel(CancelRunRequest(run_id=self.run_id))
return -15
class CancellingThenInlineSpawner(InlineRunExecutorSpawner):
def __init__(self, execution):
super().__init__()
self.app = None
self.execution = execution
def spawn(self, request):
if self.app is not None and not self.requests:
self.requests.append(request)
return CancellingProcess(self.app, request.run_id, self.execution)
return super().spawn(request)
repo = tmp_path / "repo"
repo.mkdir()
(repo / "note.md").write_text("queue continuation note\n", encoding="utf-8")
harness = QueueWritingHarnessAdapter()
processes = FakeRunProcessController()
executors = CancellingThenInlineSpawner(processes.execution)
app = create_app(
AppConfig(database_path=isolated_home / ".codealmanac/codealmanac.db"),
harness_adapters=(harness,),
executor_spawner=executors,
process_controller=processes,
)
executors.app = app
bind_inline_executor(app, executors)
initialize_repository(app, repo)
first = app.workflows.queue.queue_ingest(
IngestRequest(
cwd=repo,
inputs=("note.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
)
)
second = app.workflows.queue.queue_ingest(
IngestRequest(
cwd=repo,
inputs=("note.md",),
harness=HarnessKind.CODEX,
model="gpt-5.5",
)
)
result = app.workflows.queue.drain(DrainRunQueueRequest())
assert [record.run_id for record in result.processed] == [
first.run_id,
second.run_id,
]
assert [record.status for record in result.processed] == [
RunStatus.CANCELLED,
RunStatus.DONE,
]
assert len(harness.requests) == 1
def initialize_git(repo: Path) -> None:
run_git(repo, "init")
def commit_all(repo: Path, message: str) -> None:
run_git(repo, "add", ".")
run_git(
repo,
"-c",
"user.email=agent@example.com",
"-c",
"user.name=CodeAlmanac Test",
"commit",
"-m",
message,
)
def run_git(repo: Path, *args: str) -> None:
subprocess.run(
("git", *args),
cwd=repo,
text=True,
capture_output=True,
check=True,
)