|
| 1 | +"""Coverage tests for ``runtime.graph._handle_agent_failure`` (graph.py:613-644). |
| 2 | +
|
| 3 | +This helper is invoked by the agent runner when an agent body raises a |
| 4 | +non-pause exception (anything other than ``GraphInterrupt``). It reloads |
| 5 | +the session (absorbing partial tool writes), appends a failure |
| 6 | +``AgentRun``, marks the session ``status='error'``, persists, and returns |
| 7 | +the state dict the LangGraph node yields. |
| 8 | +""" |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +from runtime.config import EmbeddingConfig, MetadataConfig, ProviderConfig |
| 14 | +from runtime.graph import _handle_agent_failure |
| 15 | +from runtime.state import AgentRun, Session |
| 16 | +from runtime.storage.embeddings import build_embedder |
| 17 | +from runtime.storage.engine import build_engine |
| 18 | +from runtime.storage.models import Base |
| 19 | +from runtime.storage.session_store import SessionStore |
| 20 | + |
| 21 | + |
| 22 | +@pytest.fixture |
| 23 | +def store(tmp_path) -> SessionStore: |
| 24 | + eng = build_engine(MetadataConfig(url=f"sqlite:///{tmp_path}/test.db")) |
| 25 | + Base.metadata.create_all(eng) |
| 26 | + embedder = build_embedder( |
| 27 | + EmbeddingConfig(provider="s", model="x", dim=1024), |
| 28 | + {"s": ProviderConfig(kind="stub")}, |
| 29 | + ) |
| 30 | + return SessionStore(engine=eng, embedder=embedder) |
| 31 | + |
| 32 | + |
| 33 | +def _seed_session(store: SessionStore, *, agents_run: list[AgentRun] | None = None) -> Session: |
| 34 | + """Create + persist a baseline session and return it.""" |
| 35 | + inc = store.create(query="probe", environment="dev", |
| 36 | + reporter_id="u1", reporter_team="t") |
| 37 | + if agents_run: |
| 38 | + inc.agents_run.extend(agents_run) |
| 39 | + store.save(inc) |
| 40 | + inc = store.load(inc.id) |
| 41 | + return inc |
| 42 | + |
| 43 | + |
| 44 | +class TestHappyPath: |
| 45 | + def test_failure_run_appended_and_status_set_to_error(self, store): |
| 46 | + inc = _seed_session(store) |
| 47 | + result = _handle_agent_failure( |
| 48 | + skill_name="triage", |
| 49 | + started_at="2026-05-15T00:00:00Z", |
| 50 | + exc=RuntimeError("upstream blew up"), |
| 51 | + inc_id=inc.id, |
| 52 | + store=store, |
| 53 | + fallback=inc, |
| 54 | + ) |
| 55 | + # Returned state dict |
| 56 | + assert result["last_agent"] == "triage" |
| 57 | + assert result["next_route"] is None |
| 58 | + assert result["error"] == "upstream blew up" |
| 59 | + assert isinstance(result["session"], Session) |
| 60 | + # Persisted session reflects the failure |
| 61 | + loaded = store.load(inc.id) |
| 62 | + assert loaded.status == "error" |
| 63 | + assert len(loaded.agents_run) == 1 |
| 64 | + run = loaded.agents_run[0] |
| 65 | + assert run.agent == "triage" |
| 66 | + assert run.summary == "agent failed: upstream blew up" |
| 67 | + |
| 68 | + def test_appends_to_existing_run_history(self, store): |
| 69 | + prior = AgentRun( |
| 70 | + agent="intake", |
| 71 | + started_at="2026-05-15T00:00:00Z", |
| 72 | + ended_at="2026-05-15T00:00:01Z", |
| 73 | + summary="completed: routed to triage", |
| 74 | + ) |
| 75 | + inc = _seed_session(store, agents_run=[prior]) |
| 76 | + _handle_agent_failure( |
| 77 | + skill_name="triage", |
| 78 | + started_at="2026-05-15T00:00:02Z", |
| 79 | + exc=TimeoutError("provider hung"), |
| 80 | + inc_id=inc.id, |
| 81 | + store=store, |
| 82 | + fallback=inc, |
| 83 | + ) |
| 84 | + loaded = store.load(inc.id) |
| 85 | + assert [r.agent for r in loaded.agents_run] == ["intake", "triage"] |
| 86 | + assert "agent failed: provider hung" in loaded.agents_run[1].summary |
| 87 | + |
| 88 | + def test_preserves_partial_tool_writes_via_reload(self, store): |
| 89 | + """If a tool wrote to the session before the agent raised, |
| 90 | + the reload-then-append pattern must keep that tool's write.""" |
| 91 | + inc = _seed_session(store) |
| 92 | + # Simulate a tool write that already persisted. |
| 93 | + from runtime.state import ToolCall |
| 94 | + inc.tool_calls.append(ToolCall( |
| 95 | + agent="triage", |
| 96 | + tool="lookup_similar_incidents", |
| 97 | + args={"query": "x"}, |
| 98 | + result={"hits": []}, |
| 99 | + ts="2026-05-15T00:00:00Z", |
| 100 | + )) |
| 101 | + store.save(inc) |
| 102 | + # Caller's stale `fallback` reference does not have the tool call. |
| 103 | + stale = inc.model_copy(deep=True) |
| 104 | + stale.tool_calls = [] |
| 105 | + _handle_agent_failure( |
| 106 | + skill_name="triage", |
| 107 | + started_at="2026-05-15T00:00:02Z", |
| 108 | + exc=RuntimeError("oops"), |
| 109 | + inc_id=inc.id, |
| 110 | + store=store, |
| 111 | + fallback=stale, |
| 112 | + ) |
| 113 | + loaded = store.load(inc.id) |
| 114 | + # Tool call survived because _handle_agent_failure reloaded |
| 115 | + # before appending its failure run. |
| 116 | + assert len(loaded.tool_calls) == 1 |
| 117 | + assert loaded.tool_calls[0].tool == "lookup_similar_incidents" |
| 118 | + |
| 119 | + |
| 120 | +class TestFallbackPath: |
| 121 | + def test_uses_fallback_when_session_missing_from_store(self, store): |
| 122 | + # Session never persisted; store.load(inc_id) raises FileNotFoundError. |
| 123 | + from runtime.state import Session |
| 124 | + ghost = Session( |
| 125 | + id="INC-20260515-999", |
| 126 | + status="in_progress", |
| 127 | + created_at="2026-05-15T00:00:00Z", |
| 128 | + updated_at="2026-05-15T00:00:00Z", |
| 129 | + ) |
| 130 | + result = _handle_agent_failure( |
| 131 | + skill_name="intake", |
| 132 | + started_at="2026-05-15T00:00:00Z", |
| 133 | + exc=RuntimeError("dropped on the floor"), |
| 134 | + inc_id="INC-20260515-999", |
| 135 | + store=store, |
| 136 | + fallback=ghost, |
| 137 | + ) |
| 138 | + # The fallback was used, the failure run was appended, |
| 139 | + # and the now-populated fallback was saved. |
| 140 | + assert result["session"].status == "error" |
| 141 | + loaded = store.load("INC-20260515-999") |
| 142 | + assert loaded.id == "INC-20260515-999" |
| 143 | + assert loaded.status == "error" |
| 144 | + assert len(loaded.agents_run) == 1 |
| 145 | + assert loaded.agents_run[0].agent == "intake" |
0 commit comments