forked from omnigent-ai/omnigent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_runner_dispatch.py
More file actions
6620 lines (5804 loc) · 257 KB
/
Copy pathtest_runner_dispatch.py
File metadata and controls
6620 lines (5804 loc) · 257 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""End-to-end runner-dispatch tests: server → runner → spawned harness.
The load-bearing assertion: the runner FastAPI app, when given a
real :class:`HarnessProcessManager`, accepts a
POST /v1/sessions/{conversation_id}/events?stream=true,
spawns a harness subprocess (using the existing
``omnigent/runtime/harnesses/`` machinery — NOT a parallel impl),
forwards the request to the harness via UDS, and streams the
harness's SSE response back through the runner's own SSE response.
Architecture verified end-to-end:
- A real ``HarnessProcessManager`` is started (writes its instance
dir, runs orphan sweep, starts the idle reaper).
- A test-only harness module is registered in ``_HARNESS_MODULES``.
- The runner FastAPI app is built with ``process_manager=mgr``.
- The test posts to the runner's
/v1/sessions/{conversation_id}/events?stream=true with a message
body + harness name.
- The runner calls ``mgr.get_client()`` → spawns a uvicorn
subprocess running the test harness on a UDS → returns the
per-conversation httpx client.
- The runner POSTs the request to the harness via that client.
- The harness drives an LLM call via ``run_turn`` and streams SSE
back.
- The runner relays each SSE chunk through to the test client.
The OpenAI-key-gated test runs the full chain against gpt-4o-mini.
The unkeyed test asserts on plumbing only (handler is reached,
503 on bad harness name).
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import tempfile
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from types import SimpleNamespace, TracebackType
from typing import Any, cast
import httpx
import pytest
from fastapi import FastAPI
from omnigent.runner import create_runner_app
from omnigent.runner.app import (
_build_spawn_env_from_spec,
_forward_harness_response,
_resolve_harness_config,
)
from omnigent.runtime.harnesses import _HARNESS_MODULES
from omnigent.runtime.harnesses.process_manager import HarnessProcessManager
from omnigent.session_lifecycle import CLOSED_LABEL_KEY, CLOSED_LABEL_VALUE
from omnigent.spec.types import AgentSpec, ExecutorSpec
from tests.runner.helpers import NullServerClient
_TEST_HARNESS_NAME = "runner-test-default"
_TEST_HARNESS_MODULE = "tests._fixtures.runner_test_harness"
@pytest.fixture(autouse=True)
def _assume_harness_clis_installed(monkeypatch: pytest.MonkeyPatch) -> None:
"""Neutralize the sub-agent dispatch CLI preflight for hermetic tests.
The named-mode child-create path refuses to spawn a sub-agent whose
harness CLI (``claude`` / ``codex`` / ``pi``) is absent from ``PATH``
(see ``missing_harness_cli``, dispatched from ``tool_dispatch``). These
dispatch tests run in a hermetic environment where those binaries may be
absent (e.g. CI), so without this stub they would fail at the preflight
instead of exercising the create / continue logic under test. Tests that
specifically assert the preflight re-patch ``missing_harness_cli`` in
their own body, which wins over this autouse default.
:param monkeypatch: Pytest monkeypatch fixture.
"""
monkeypatch.setattr(
"omnigent.onboarding.harness_install.missing_harness_cli",
lambda harness: None,
)
@asynccontextmanager
async def _runner_test_client(app: FastAPI) -> AsyncIterator[httpx.AsyncClient]:
"""Create a test client against a runner ASGI app.
:param app: Runner app under test.
:returns: Async context manager yielding an ``httpx.AsyncClient``.
"""
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://runner") as client:
yield client
class _FakeHarnessStream:
"""
Async context manager that yields scripted harness SSE chunks.
:param chunks: SSE chunks returned by ``aiter_text``.
:param status_code: HTTP status exposed to the runner.
"""
def __init__(self, chunks: list[str], status_code: int = 200) -> None:
"""
Store scripted stream state.
:param chunks: SSE chunks returned by ``aiter_text``.
:param status_code: HTTP status exposed to the runner.
"""
self._chunks = chunks
self.status_code = status_code
async def __aenter__(self) -> _FakeHarnessStream:
"""
Enter the fake stream context.
:returns: This fake stream.
"""
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc: BaseException | None,
tb: TracebackType | None,
) -> None:
"""
Exit the fake stream without suppressing exceptions.
:param exc_type: Exception type from the context, if any.
:param exc: Exception value from the context, if any.
:param tb: Traceback from the context, if any.
:returns: None.
"""
del exc_type, exc, tb
async def aiter_text(self) -> AsyncIterator[str]:
"""
Yield scripted text chunks.
:returns: Async iterator of SSE chunks.
"""
for chunk in self._chunks:
yield chunk
async def _drain_published_statuses(
conv: str,
*,
until: str,
timeout: float,
) -> list[str]:
"""Collect ``session.status`` values a runner published for a session.
Reads the runner's module-level per-session event queue
(``omnigent.runner.app._session_event_queues_ref``) — the same queue
the SSE ``/stream`` endpoint drains — and returns the ordered list of
``session.status`` values seen, stopping once *until* is published. This
polls the in-process queue rather than a concurrent SSE ``GET`` because
``httpx.ASGITransport`` does not interleave a streaming response with a
concurrent ``POST`` on the same client, so a live SSE subscriber would
never observe the background turn's events.
:param conv: Session/conversation identifier, e.g. ``"conv_abc123"``.
:param until: Stop once this ``session.status`` value is observed,
e.g. ``"failed"``.
:param timeout: Hard cap in seconds — if *until* never arrives the poll
gives up and returns what it saw, so a hang regression fails the
assertion instead of spinning forever.
:returns: Ordered ``session.status`` values published for *conv*.
"""
from omnigent.runner.app import _session_event_queues_ref
statuses: list[str] = []
deadline = asyncio.get_running_loop().time() + timeout
while asyncio.get_running_loop().time() < deadline:
queue = _session_event_queues_ref.get(conv)
drained = False
while queue is not None and not queue.empty():
event = queue.get_nowait()
drained = True
if isinstance(event, dict) and event.get("type") == "session.status":
status = event.get("status")
if isinstance(status, str):
statuses.append(status)
if until in statuses:
return statuses
if not drained:
# Let the background turn task make progress before re-polling.
await asyncio.sleep(0.02)
return statuses
async def _drain_failed_status_event(
conv: str,
*,
timeout: float,
) -> dict[str, Any] | None:
"""Return the first ``session.status: failed`` event a runner published.
Mirrors :func:`_drain_published_statuses` but returns the full event
dict (not just the status string) so a test can assert the carried
``error`` payload. Used to prove a SETUP-phase failure forwards its
error message on the terminal ``failed`` event instead of dropping it.
:param conv: Session/conversation identifier, e.g. ``"conv_abc123"``.
:param timeout: Hard cap in seconds; returns ``None`` if no failed
event arrives so a regression fails the assertion rather than
hanging.
:returns: The ``session.status: failed`` event dict, or ``None``.
"""
from omnigent.runner.app import _session_event_queues_ref
deadline = asyncio.get_running_loop().time() + timeout
while asyncio.get_running_loop().time() < deadline:
queue = _session_event_queues_ref.get(conv)
drained = False
while queue is not None and not queue.empty():
event = queue.get_nowait()
drained = True
if (
isinstance(event, dict)
and event.get("type") == "session.status"
and event.get("status") == "failed"
):
return event
if not drained:
await asyncio.sleep(0.02)
return None
class _FakeHarnessClient:
"""
Harness client stub exposing ``stream`` for runner proxy tests.
:param chunks: SSE chunks returned by the fake stream.
"""
def __init__(self, chunks: list[str]) -> None:
"""
Store scripted stream chunks.
:param chunks: SSE chunks returned by the fake stream.
"""
self._chunks = chunks
def stream(
self,
method: str,
url: str,
*,
json: dict[str, object],
timeout: float | None,
) -> _FakeHarnessStream:
"""
Return a fake streaming response.
:param method: HTTP method, e.g. ``"POST"``.
:param url: Harness endpoint path.
:param json: JSON body sent to the harness.
:param timeout: Request timeout.
:returns: Fake stream context manager.
"""
del method, url, json, timeout
return _FakeHarnessStream(self._chunks)
class _FakeProcessManager:
"""
Process manager stub for runner dispatch tests.
:param harness_client: Optional harness client to return.
"""
def __init__(self, harness_client: _FakeHarnessClient | None = None) -> None:
"""
Store the optional harness client.
:param harness_client: Optional harness client to return.
"""
self._harness_client = harness_client
async def get_client(
self,
conversation_id: str,
harness_name: str,
*,
env: dict[str, str] | None = None,
) -> _FakeHarnessClient:
"""
Return the configured fake harness client.
:param conversation_id: Omnigent conversation id.
:param harness_name: Harness name requested by the runner.
:param env: Optional spawn environment.
:returns: Configured fake harness client.
:raises AssertionError: If no fake client was configured.
"""
del conversation_id, harness_name, env
if self._harness_client is None:
raise AssertionError("get_client should not be called")
return self._harness_client
@pytest.fixture
async def started_manager() -> AsyncIterator[HarnessProcessManager]:
"""A real, started HarnessProcessManager with the test harness registered.
Uses a short ``/tmp/oa-rtest`` parent rather than pytest's
``tmp_path`` because UDS paths on Linux are capped at 108 chars
and the manager's per-conversation socket layout
(``<parent>/ap-<uuid32>/<conv_id>.sock``) blows past that when
nested under pytest's already-long ``/tmp/pytest-of-.../...``
tree.
Yields the started manager; on teardown, shuts it down so any
spawned subprocesses are reaped before the test ends.
"""
import shutil
import uuid
short_parent = Path(f"/tmp/oa-rtest-{uuid.uuid4().hex[:8]}")
short_parent.mkdir(mode=0o700, parents=True, exist_ok=True)
# Inject the test-only harness module into the registry. We
# mutate the dict directly per the registry's documented test-
# injection pattern; restore on teardown to avoid leaking into
# other tests.
_HARNESS_MODULES[_TEST_HARNESS_NAME] = _TEST_HARNESS_MODULE
mgr = HarnessProcessManager(tmp_parent=short_parent)
await mgr.start()
try:
yield mgr
finally:
await mgr.shutdown()
_HARNESS_MODULES.pop(_TEST_HARNESS_NAME, None)
shutil.rmtree(short_parent, ignore_errors=True)
# ── Plumbing tests (no LLM key required) ─────────────────
def test_forward_harness_response_preserves_no_body_responses() -> None:
"""204/304 harness side-channel responses must not serialize JSON null.
Returning ``JSONResponse(status_code=204, content=None)`` writes ``b"null"``
even though Uvicorn/HTTP semantics require an empty body for 204. That
manifests under uvicorn as ``Response content longer than Content-Length``.
"""
response = _forward_harness_response(httpx.Response(204, content=b""))
assert response.status_code == 204
assert response.body == b""
assert b"content-length" not in dict(response.raw_headers)
def test_forward_harness_response_preserves_json_body() -> None:
response = _forward_harness_response(httpx.Response(404, json={"error": "not_found"}))
assert response.status_code == 404
assert response.body == b'{"error":"not_found"}'
assert dict(response.raw_headers)[b"content-length"] == b"21"
@pytest.mark.asyncio
async def test_runner_post_without_manager_returns_501() -> None:
"""Scaffold-mode preserved when no manager is wired up."""
app = create_runner_app(server_client=NullServerClient()) # type: ignore[arg-type] # no process_manager → scaffold
async with _runner_test_client(app) as http:
response = await http.post(
"/v1/sessions/conv_x/events?stream=true",
json={
"type": "message",
"role": "user",
"harness": _TEST_HARNESS_NAME,
"model": "fake/model",
"content": [],
},
)
assert response.status_code == 501
assert "HarnessProcessManager" in response.json()["detail"]
@pytest.mark.asyncio
async def test_runner_resolves_harness_from_fallback_when_no_agent_id(
started_manager: HarnessProcessManager,
) -> None:
"""Without agent_id or server_base_url, runner falls back to the
test-default harness. Verifies the fallback path doesn't crash."""
app = create_runner_app(
process_manager=started_manager,
server_client=NullServerClient(), # type: ignore[arg-type]
)
async with _runner_test_client(app) as http:
# No agent_id → runner falls back to "runner-test-default"
# harness. With that registered in _HARNESS_MODULES, the
# runner must spawn the harness and return its SSE stream.
# Missing LLM credentials are represented inside that stream
# as ``response.failed``, not as a runner spawn failure.
response = await http.post(
"/v1/sessions/c_fallback/events?stream=true",
json={
"type": "message",
"role": "user",
"model": "x",
"content": [{"role": "user", "content": "test"}],
},
)
assert response.status_code == 200
assert response.headers["content-type"].startswith("text/event-stream")
assert "event: response.created" in response.text
class _RecordingProcessManager:
"""
Process manager stub that records the harness name get_client saw.
Unlike :class:`_FakeProcessManager`, this captures the resolved
harness name so a test can assert which harness the runner chose,
and signals an event when the background turn reaches dispatch.
:param captured: Dict the recorded harness name is written into
under the ``"harness"`` key.
:param reached: Event set once ``get_client`` is called.
"""
def __init__(self, captured: dict[str, str], reached: asyncio.Event) -> None:
"""
Store the capture sink and the reached-dispatch event.
:param captured: Dict the harness name is written into.
:param reached: Event set once ``get_client`` is called.
"""
self._captured = captured
self._reached = reached
async def get_client(
self,
conversation_id: str,
harness_name: str,
*,
env: dict[str, str] | None = None,
) -> _FakeHarnessClient:
"""
Record the harness name and return an empty fake harness client.
:param conversation_id: Omnigent conversation id.
:param harness_name: Harness name the runner resolved — the
value under test.
:param env: Optional spawn environment (ignored).
:returns: A fake harness client with an empty SSE stream so the
background turn completes immediately.
"""
del conversation_id, env
self._captured["harness"] = harness_name
self._reached.set()
return _FakeHarnessClient([])
@pytest.mark.asyncio
async def test_runner_resolves_agent_from_server_snapshot_when_msg_lacks_agent_id() -> None:
"""A turn-triggering message that races ahead of session assignment
arrives with no ``agent_id`` and an empty spec cache. The runner must
resolve the agent from the authoritative server snapshot
(``GET /v1/sessions/{id}``) rather than falling through to the
test-only ``runner-test-default`` harness, which would silently drop
the turn (the first-message race).
"""
conv = "conv_ondemand_race"
resolved_agent_id = "ag_resolved_from_snapshot"
resolved_harness = "runner-test-resolved"
def _server_handler(request: httpx.Request) -> httpx.Response:
"""
Stub Omnigent server: the session snapshot carries the agent_id.
:param request: Outbound request from the runner.
:returns: Snapshot with ``agent_id`` for the session GET; benign
payloads otherwise so the background turn can proceed.
"""
if request.method == "GET" and request.url.path == f"/v1/sessions/{conv}":
return httpx.Response(200, json={"id": conv, "agent_id": resolved_agent_id})
if request.url.path.endswith("/items"):
return httpx.Response(
200,
json={
"object": "list",
"data": [],
"first_id": None,
"last_id": None,
"has_more": False,
},
)
return httpx.Response(200, json={})
server_client = httpx.AsyncClient(
transport=httpx.MockTransport(_server_handler),
base_url="http://server",
)
async def _snapshot_spec_resolver(agent_id: str, session_id: str | None = None) -> AgentSpec:
"""
Resolve the spec for the agent_id read from the snapshot.
:param agent_id: Agent id the runner resolved. MUST equal the
snapshot's agent_id — the message body carried none, so any
other value means the on-demand snapshot path didn't run.
:param session_id: Session id (unused).
:returns: A minimal spec whose harness is ``resolved_harness``.
"""
# The agent_id can only come from the server snapshot here — the
# POST body below omits it. If this fires with a different value
# (or not at all), the on-demand resolution path is broken.
assert agent_id == resolved_agent_id
return AgentSpec(
spec_version=1,
name="ondemand-agent",
executor=ExecutorSpec(type="omnigent", config={"harness": resolved_harness}),
)
captured: dict[str, str] = {}
reached_dispatch = asyncio.Event()
app = create_runner_app(
process_manager=cast(
HarnessProcessManager,
_RecordingProcessManager(captured, reached_dispatch),
),
spec_resolver=_snapshot_spec_resolver,
server_client=server_client,
)
try:
async with _runner_test_client(app) as http:
response = await http.post(
# No ``?stream=true`` → background turn, the production
# path the Omnigent server uses to forward session messages.
f"/v1/sessions/{conv}/events",
json={
"type": "message",
"role": "user",
"model": "x",
"content": [{"role": "user", "content": "hi"}],
# No agent_id — this is the race condition under test.
},
)
# Background turn accepted; dispatch happens asynchronously.
assert response.status_code == 202
await asyncio.wait_for(reached_dispatch.wait(), timeout=10.0)
finally:
await server_client.aclose()
# The harness came from the snapshot-resolved spec, proving the
# runner fetched agent_id from the server when the message lacked it.
# Without the fix this is "runner-test-default" (the fallback) and the
# real turn never dispatches.
assert captured["harness"] == resolved_harness
class _ContentCapturingProcessManager:
"""
Process manager stub that captures the body sent to the harness.
Returns a harness client whose ``stream`` records the JSON body
(which carries the turn's ``content`` history) into a shared sink
and yields an empty SSE stream so the background turn completes
immediately.
:param captured: Dict the harness request body is written into
under the ``"body"`` key.
:param reached: Event set once the harness stream is opened.
"""
def __init__(self, captured: dict[str, Any], reached: asyncio.Event) -> None:
"""
Store the capture sink and the reached-dispatch event.
:param captured: Dict the harness request body is written into.
:param reached: Event set once the harness stream is opened.
"""
self._captured = captured
self._reached = reached
async def get_client(
self,
conversation_id: str,
harness_name: str,
*,
env: dict[str, str] | None = None,
) -> _ContentCapturingHarnessClient:
"""
Return a harness client that records the body it is sent.
:param conversation_id: Omnigent conversation id (unused).
:param harness_name: Harness name the runner resolved (unused).
:param env: Optional spawn environment (unused).
:returns: A capturing harness client.
"""
del conversation_id, harness_name, env
return _ContentCapturingHarnessClient(self._captured, self._reached)
class _ContentCapturingHarnessClient:
"""
Harness client stub that records the JSON body of each stream.
:param captured: Dict the request body is written into under
``"body"``.
:param reached: Event set once ``stream`` is invoked.
"""
def __init__(self, captured: dict[str, Any], reached: asyncio.Event) -> None:
"""
Store the capture sink and reached event.
:param captured: Dict the request body is written into.
:param reached: Event set once ``stream`` is invoked.
"""
self._captured = captured
self._reached = reached
def stream(
self,
method: str,
url: str,
*,
json: dict[str, Any],
timeout: float | None,
) -> _FakeHarnessStream:
"""
Record the body and return an empty SSE stream.
:param method: HTTP method (unused).
:param url: Harness endpoint path (unused).
:param json: JSON body sent to the harness — captured here.
:param timeout: Request timeout (unused).
:returns: An empty fake stream so the turn completes at once.
"""
del method, url, timeout
self._captured["body"] = json
self._reached.set()
return _FakeHarnessStream([])
@pytest.mark.asyncio
async def test_runner_reloads_full_history_on_cold_cache_after_restart() -> None:
"""A message to a cold session reloads prior history, not just itself.
Regression for an agent (e.g. nessie) losing all chat context after a
server/runner restart. On restart the runner's in-memory
``_session_histories`` cache is empty; the old code seeded it with ONLY
the incoming message (``setdefault(conv, []).append(...)``), so the
harness ran the turn with no prior context. This is acute for the
claude-sdk harness, which on a cold SDK session replays the in-memory
history verbatim as the prompt — a one-message cache erased the whole
conversation.
The fix rehydrates the full history from the store on the first touch of
a conversation. The stub server models invariant I1 (persist-before-
forward): its ``GET /items`` returns the prior turns AND the just-posted
message (``item_3``), and the forwarded body carries
``persisted_item_id="item_3"`` — so the reload drops that exact item by
id and appends the runner's copy, proving no duplication.
"""
from omnigent.runner import app as runner_app
conv = "conv_restart_history_reload"
prior_user = "what is the capital of France?"
prior_assistant = "Paris."
new_user = "and of Germany?"
def _server_handler(request: httpx.Request) -> httpx.Response:
"""
Stub Omnigent server: snapshot + full persisted history on ``/items``.
:param request: Outbound request from the runner.
:returns: Snapshot for the session GET; the persisted history
(prior turns + the new message, per invariant I1) for
``/items``; benign payloads otherwise.
"""
if request.method == "GET" and request.url.path == f"/v1/sessions/{conv}":
return httpx.Response(200, json={"id": conv, "agent_id": "ag_restart"})
if request.url.path.endswith("/items"):
return httpx.Response(
200,
json={
"object": "list",
"data": [
{
"id": "item_1",
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": prior_user}],
},
{
"id": "item_2",
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": prior_assistant}],
},
# Persist-before-forward (I1): the new message is
# already in the store when the runner reloads.
{
"id": "item_3",
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": new_user}],
},
],
"first_id": "item_1",
"last_id": "item_3",
"has_more": False,
},
)
return httpx.Response(200, json={})
server_client = httpx.AsyncClient(
transport=httpx.MockTransport(_server_handler),
base_url="http://server",
)
async def _spec_resolver(agent_id: str, session_id: str | None = None) -> AgentSpec:
"""
Resolve a minimal spec for the restarted session.
:param agent_id: Agent id resolved from the snapshot (unused).
:param session_id: Session id (unused).
:returns: A minimal spec on a benign test harness.
"""
del agent_id, session_id
return AgentSpec(
spec_version=1,
name="restart-agent",
executor=ExecutorSpec(
type="omnigent",
config={"harness": "runner-test-resolved"},
),
)
captured: dict[str, Any] = {}
reached = asyncio.Event()
app = create_runner_app(
process_manager=cast(
HarnessProcessManager,
_ContentCapturingProcessManager(captured, reached),
),
spec_resolver=_spec_resolver,
server_client=server_client,
)
# Simulate a fresh runner process: no cached history for this conv.
runner_app._session_histories_ref.pop(conv, None)
try:
async with _runner_test_client(app) as http:
response = await http.post(
# No ``?stream=true`` → background turn, the production path
# the Omnigent server uses to forward session messages.
f"/v1/sessions/{conv}/events",
json={
"type": "message",
"role": "user",
"model": "x",
# The store id the Omnigent server persisted for this turn
# (matches ``item_3`` from the stub ``/items``), so the
# cold-cache reload drops that exact item and the dedup
# fires (no duplicate).
"persisted_item_id": "item_3",
"content": [{"type": "input_text", "text": new_user}],
},
)
assert response.status_code == 202
await asyncio.wait_for(reached.wait(), timeout=10.0)
finally:
await server_client.aclose()
runner_app._session_histories_ref.pop(conv, None)
content = captured["body"]["content"]
texts = [
block.get("text")
for item in content
if isinstance(item, dict)
for block in item.get("content", [])
if isinstance(block, dict)
]
# Prior context survived the restart...
assert prior_user in texts, f"prior user turn missing from reloaded history: {texts}"
assert prior_assistant in texts, f"prior assistant turn missing: {texts}"
# ...and the new message is present exactly once (reload didn't dup it).
assert texts.count(new_user) == 1, f"new message not delivered exactly once: {texts}"
# The full 3-item history reached the harness, not just the new message.
assert len(content) == 3, f"expected full history, got {len(content)} items: {content}"
@pytest.mark.asyncio
async def test_runner_cold_cache_appends_message_when_store_lacks_it() -> None:
"""A cold-cache message NOT yet in the store is appended, not dropped.
Not every forward is persist-before-forward (invariant I1): native-
terminal web injections (claude-native/codex-native) are forwarded
WITHOUT persisting first, so a fresh ``GET /items`` returns the prior
turns but NOT the just-posted message. If the cold-cache reload simply
overwrote ``_session_histories`` with that load, the new input would be
dropped — and the native executor, which types only the LATEST user
message into its pane, would inject stale text.
This drives the cold path with a stub server whose history reload
excludes the new message and asserts the harness still receives it,
appended as the latest turn, with prior context preserved.
"""
from omnigent.runner import app as runner_app
conv = "conv_cold_cache_append"
prior_user = "first question"
prior_assistant = "first answer"
new_user = "second question not yet persisted"
def _server_handler(request: httpx.Request) -> httpx.Response:
"""
Stub Omnigent server: history reload that does NOT include the new message.
:param request: Outbound request from the runner.
:returns: Snapshot for the session GET; prior turns only (no
new message, modeling a forward-without-persist) for
``/items``; benign payloads otherwise.
"""
if request.method == "GET" and request.url.path == f"/v1/sessions/{conv}":
return httpx.Response(200, json={"id": conv, "agent_id": "ag_cold"})
if request.url.path.endswith("/items"):
return httpx.Response(
200,
json={
"object": "list",
"data": [
{
"id": "item_1",
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": prior_user}],
},
{
"id": "item_2",
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": prior_assistant}],
},
# No item for ``new_user`` — the forward did not
# persist it before reaching the runner.
],
"first_id": "item_1",
"last_id": "item_2",
"has_more": False,
},
)
return httpx.Response(200, json={})
server_client = httpx.AsyncClient(
transport=httpx.MockTransport(_server_handler),
base_url="http://server",
)
async def _spec_resolver(agent_id: str, session_id: str | None = None) -> AgentSpec:
"""
Resolve a minimal spec for the session.
:param agent_id: Agent id resolved from the snapshot (unused).
:param session_id: Session id (unused).
:returns: A minimal spec on a benign test harness.
"""
del agent_id, session_id
return AgentSpec(
spec_version=1,
name="cold-cache-agent",
executor=ExecutorSpec(
type="omnigent",
config={"harness": "runner-test-resolved"},
),
)
captured: dict[str, Any] = {}
reached = asyncio.Event()
app = create_runner_app(
process_manager=cast(
HarnessProcessManager,
_ContentCapturingProcessManager(captured, reached),
),
spec_resolver=_spec_resolver,
server_client=server_client,
)
runner_app._session_histories_ref.pop(conv, None)
try:
async with _runner_test_client(app) as http:
response = await http.post(
f"/v1/sessions/{conv}/events",
json={
"type": "message",
"role": "user",
"model": "x",
# No ``persisted_item_id``: the native-terminal forward
# skipped persist-before-forward, so there's nothing in the
# store to drop — the runner must append, not dedup.
"content": [{"type": "input_text", "text": new_user}],
},
)
assert response.status_code == 202
await asyncio.wait_for(reached.wait(), timeout=10.0)
finally:
await server_client.aclose()
runner_app._session_histories_ref.pop(conv, None)
content = captured["body"]["content"]
texts = [
block.get("text")
for item in content
if isinstance(item, dict)
for block in item.get("content", [])
if isinstance(block, dict)
]
# Prior context preserved, and the not-yet-persisted message was
# appended (not dropped) as the latest turn — present exactly once.
assert texts == [prior_user, prior_assistant, new_user], (
f"expected prior history + appended new message, got {texts}"
)
@pytest.mark.asyncio
async def test_runner_cold_cache_keeps_trailing_user_when_no_persisted_id() -> None:
"""A real trailing user message is kept when no ``persisted_item_id`` is sent.
Regression for the id-based dedup replacing the old role heuristic. The
earlier fix unconditionally popped a trailing *user* item, assuming it was
always this turn's persisted input. That's wrong when the forward did NOT
persist-before-forward AND the store legitimately ends with a user
message — e.g. a crash mid-turn where the prior user prompt was persisted
but its assistant reply never was, or a native-terminal injection. Popping
there deletes real history.
With id-based dedup, no ``persisted_item_id`` means nothing is dropped: the
real trailing user message survives and the new message is appended.
"""
from omnigent.runner import app as runner_app
conv = "conv_cold_cache_keep_user"
# A prior user prompt whose assistant reply was never persisted (e.g. the
# runner crashed mid-turn), so the store ends on a USER message.
prior_user = "prompt whose reply was lost to a crash"
new_user = "follow-up not persisted before forward"
def _server_handler(request: httpx.Request) -> httpx.Response:
"""
Stub Omnigent server: history reload ending on a real prior user message.
:param request: Outbound request from the runner.
:returns: Snapshot for the session GET; a single prior user item
(no assistant reply, no new message) for ``/items``; benign
payloads otherwise.
"""
if request.method == "GET" and request.url.path == f"/v1/sessions/{conv}":
return httpx.Response(200, json={"id": conv, "agent_id": "ag_keep"})
if request.url.path.endswith("/items"):
return httpx.Response(
200,
json={
"object": "list",
"data": [
{
"id": "item_1",
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": prior_user}],
},
],
"first_id": "item_1",
"last_id": "item_1",
"has_more": False,
},
)
return httpx.Response(200, json={})
server_client = httpx.AsyncClient(
transport=httpx.MockTransport(_server_handler),
base_url="http://server",
)
async def _spec_resolver(agent_id: str, session_id: str | None = None) -> AgentSpec:
"""
Resolve a minimal spec for the session.
:param agent_id: Agent id (unused).
:param session_id: Session id (unused).
:returns: A minimal spec on a benign test harness.
"""
del agent_id, session_id
return AgentSpec(
spec_version=1,
name="keep-user-agent",
executor=ExecutorSpec(
type="omnigent",
config={"harness": "runner-test-resolved"},
),
)