Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

test: lift patch coverage on new fork-feature code paths

xf gong903550ee41fd
diff --git a/tests/agent/test_agent_fork.py b/tests/agent/test_agent_fork.py
index 798dd65..23ff2ca 100644
--- a/tests/agent/test_agent_fork.py
+++ b/tests/agent/test_agent_fork.py
@@ -46,3 +46,38 @@ async def test_agent_fork_does_not_mutate_self_thread_id():
await a.prompt("hello", run_id="R1")
await a.fork("src", "dst", after_run_id="R1")
assert a.thread_id == "src"
+
+
+async def test_agent_fork_v3_only_checkpointer_raises_CheckpointerError():
+ """A pre-v4 checkpointer (no claim_run / mark_run_complete) is in
+ 'degraded mode': vanilla prompt() works but fork() must surface
+ CheckpointerError so callers know the backend cannot support fork.
+ """
+ from cubepi.checkpointer.exceptions import CheckpointerError
+
+ class _V3Only:
+ async def load(self, thread_id):
+ return None
+
+ async def append(self, thread_id, msgs):
+ pass
+
+ async def save_extra(self, thread_id, extra):
+ pass
+
+ async def save_pending_request(self, thread_id, req, *, run_id=None):
+ pass
+
+ async def load_pending_request(self, thread_id):
+ return None
+
+ # No claim_run / mark_run_complete → not _run_aware.
+
+ a = Agent(
+ model=_ok_faux().model("faux-model"),
+ checkpointer=_V3Only(),
+ thread_id="src",
+ )
+ with pytest.raises(CheckpointerError, match="does not support fork"):
+ await a.fork("src", "dst", after_run_id="R1")
diff --git a/tests/agent/test_agent_run_id.py b/tests/agent/test_agent_run_id.py
index 0b65a3c..06ab0e4 100644
--- a/tests/agent/test_agent_run_id.py
+++ b/tests/agent/test_agent_run_id.py
@@ -94,3 +94,27 @@ async def test_prompt_rejects_mismatched_run_id_before_claim():
assert "R1" not in cp._runs.get("t", {})
# ... and a second prompt with the same run_id succeeds:
await a.prompt("hi", run_id="R1")
+
+
+async def test_process_event_rejects_mismatched_message_run_id():
+ """`_process_event` for MessageEndEvent stamps msg.run_id with
+ state.active_run_id when msg.run_id is None, but raises if the
+ message already carries a DIFFERENT run_id (defensive — a provider
+ or middleware bug that produced the wrong stamp must not silently
+ write to the persisted history)."""
+ from cubepi.agent.types import MessageEndEvent
+ from cubepi.providers.base import (
+ AssistantMessage,
+ TextContent,
+ )
+
+ a = Agent(model=_ok_faux().model("faux-model"))
+ a._state.active_run_id = "R_active"
+ bad_msg = AssistantMessage(
+ content=[TextContent(text="bad")],
+ stop_reason="end_turn",
+ run_id="R_OTHER",
+ )
+ with pytest.raises(ValueError, match="does not match"):
+ await a._process_event(MessageEndEvent(message=bad_msg))
diff --git a/tests/agent/test_respond_resume_run_id.py b/tests/agent/test_respond_resume_run_id.py
index e157ea9..0e4e175 100644
--- a/tests/agent/test_respond_resume_run_id.py
+++ b/tests/agent/test_respond_resume_run_id.py
@@ -174,6 +174,73 @@ async def test_respond_resume_with_legacy_pending_does_not_crash() -> None:
assert cp._runs["t"]["R1"].completed_at is None
+async def test_respond_leaves_active_run_id_set_on_resume_raise() -> None:
+ """Spec §3.7 parity: if the HITL resume body raises, respond() must
+ NOT clear active_run_id. Callers can observe which run failed."""
+ cp = MemoryCheckpointer()
+ p = _pause_then_finish_provider()
+
+ def _model():
+ return p.model("faux-model")
+
+ await _drive_pause(cp, _model)
+
+ ch2 = CheckpointedChannel(checkpointer=cp, thread_id="t", run_id="R1")
+ tool2 = ask_user_tool(ch2)
+ a2 = Agent(
+ model=_model(),
+ tools=[tool2],
+ checkpointer=cp,
+ thread_id="t",
+ channel=ch2,
+ )
+
+ class _Boom(Exception):
+ pass
+
+ async def _explode():
+ raise _Boom("simulated resume failure")
+
+ # Patch the resume body to raise.
+ a2._run_hitl_resume = _explode # type: ignore[method-assign]
+
+ loaded = await cp.load_pending("t")
+ assert loaded is not None
+ qid = loaded[0].question_id
+
+ with pytest.raises(_Boom):
+ await a2.respond(question_id=qid, answer="yes")
+ # active_run_id stays SET on raise (no else: clear ran).
+ assert a2.state.active_run_id == "R1"
+
+
+async def test_respond_defaults_question_id_to_pending() -> None:
+ """respond() without an explicit question_id picks it up from the
+ persisted pending row."""
+ cp = MemoryCheckpointer()
+ p = _pause_then_finish_provider()
+
+ def _model():
+ return p.model("faux-model")
+
+ await _drive_pause(cp, _model)
+
+ ch2 = CheckpointedChannel(checkpointer=cp, thread_id="t", run_id="R1")
+ tool2 = ask_user_tool(ch2)
+ a2 = Agent(
+ model=_model(),
+ tools=[tool2],
+ checkpointer=cp,
+ thread_id="t",
+ channel=ch2,
+ )
+ # Don't pass question_id — respond() must default to pending's id.
+ await a2.respond(answer="yes")
+ assert cp._runs["t"]["R1"].completed_at is not None
+
+
@pytest.mark.asyncio
async def test_respond_rejects_mismatched_channel_run_id() -> None:
"""Regression for codex R2 P2: respond() must reject a CheckpointedChannel
diff --git a/tests/checkpointer/test_memory_fork.py b/tests/checkpointer/test_memory_fork.py
index f200644..b501914 100644
--- a/tests/checkpointer/test_memory_fork.py
+++ b/tests/checkpointer/test_memory_fork.py
@@ -95,3 +95,44 @@ async def test_snapshot_matches_fork_messages():
await cp.mark_run_complete("src", "A")
msgs = await cp.snapshot("src", after_run_id="A")
assert [m.content[0].text for m in msgs] == ["a1"]
+
+
+async def test_snapshot_unknown_thread_raises_thread_not_found():
+ cp = MemoryCheckpointer()
+ with pytest.raises(ThreadNotFoundError):
+ await cp.snapshot("missing", after_run_id="A")
+
+
+async def test_snapshot_uncompleted_run_raises_not_completed():
+ cp = MemoryCheckpointer()
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ # NOT calling mark_run_complete — run is claimed but uncompleted.
+ with pytest.raises(RunNotCompletedError):
+ await cp.snapshot("src", after_run_id="A")
+
+
+async def test_snapshot_includes_legacy_null_run_id_and_skips_uncompleted():
+ """Snapshot must:
+ - copy messages with run_id=None as legacy (pre-v4) history
+ - skip messages whose run_id belongs to an uncompleted later run
+ """
+ cp = MemoryCheckpointer()
+ # Pre-v4 legacy message (no run_id).
+ await cp.append("src", [_msg(None, "legacy")])
+ # Completed run A.
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ await cp.mark_run_complete("src", "A")
+ # Later uncompleted run B (claimed but not completed).
+ await cp.claim_run("src", "B")
+ await cp.append("src", [_msg("B", "b1-in-flight")])
+ # Snapshot after A should include legacy + A but NOT B.
+ msgs = await cp.snapshot("src", after_run_id="A")
+ texts = [m.content[0].text for m in msgs]
+ assert "legacy" in texts
+ assert "a1" in texts
+ assert "b1-in-flight" not in texts
diff --git a/tests/checkpointer/test_sqlite_fork.py b/tests/checkpointer/test_sqlite_fork.py
index 17aca86..6a38d01 100644
--- a/tests/checkpointer/test_sqlite_fork.py
+++ b/tests/checkpointer/test_sqlite_fork.py
@@ -102,3 +102,15 @@ async def test_snapshot_matches_fork_messages():
await cp.mark_run_complete("src", "A")
msgs = await cp.snapshot("src", after_run_id="A")
assert [m.content[0].text for m in msgs] == ["a1"]
+
+
+async def test_snapshot_uncompleted_run_raises_not_completed():
+ """Snapshot must mirror fork's "RunNotCompleted" behavior."""
+ with tempfile.TemporaryDirectory() as d:
+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) as cp:
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ # NOT marking complete.
+ with pytest.raises(RunNotCompletedError):
+ await cp.snapshot("src", after_run_id="A")