Skip to content

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

fix(hitl): reset qid counter on resume so replay reproduces qid sequence

xf gong0bbd75c7347d
diff --git a/cubepi/hitl/channel.py b/cubepi/hitl/channel.py
index 509482e..6c3668f 100644
--- a/cubepi/hitl/channel.py
+++ b/cubepi/hitl/channel.py
@@ -121,6 +121,17 @@ class _BaseChannel:
def attach_resume_answer(self, question_id: str, answer: Any) -> None:
self._resume_slot = (question_id, answer)
+ # A resume replays the tool body / middleware hook from the top. The
+ # per-content qid counter (_qid_seq) is per-channel-instance, so on a
+ # same-process resume it has already advanced past the persisted
+ # question_id; left as-is, the replay would derive hash.N while the
+ # persisted slot holds hash.M (M < N) and _await_answer's resume
+ # short-circuit would miss — re-asking an already-answered prompt or
+ # hanging. Reset it so the replay reproduces the exact qid sequence
+ # the original run produced (hash.0, hash.1, …). Cross-process resume
+ # already started from an empty counter; this makes same-process
+ # resume behave identically.
+ self._qid_seq = {}
def _bind_emit(self, emit) -> None:
self._emit = emit
diff --git a/tests/hitl/test_in_memory_channel.py b/tests/hitl/test_in_memory_channel.py
index f826f01..734f975 100644
--- a/tests/hitl/test_in_memory_channel.py
+++ b/tests/hitl/test_in_memory_channel.py
@@ -309,6 +309,106 @@ async def test_repeat_confirm_gets_distinct_qids():
)
+async def test_same_process_resume_reuses_persisted_qid_despite_counter():
+ """Regression: on a same-process resume, `_next_qid` must reuse the qid
+ staged in `_resume_slot` instead of advancing its per-content counter.
+
+ The counter is per-channel-instance. When the SAME channel resumes,
+ the pre-detach call already advanced the counter, so a naive replay
+ would derive `hash.1` while the persisted slot holds `hash.0` — the
+ resume short-circuit misses and the tool re-asks an already-answered
+ prompt (or hangs). Codex PR #127 review feedback (P1).
+ """
+ ch = InMemoryChannel()
+
+ captured: dict[str, str] = {}
+
+ async def host(value):
+ while ch.pending is None:
+ await asyncio.sleep(0)
+ captured["qid"] = ch.pending.question_id
+ await ch.answer(ch.pending.question_id, value)
+
+ # First call mints hash.0 and advances the per-content counter to 1.
+ h = asyncio.create_task(host(True))
+ await ch.confirm("are you sure?")
+ await h
+ original_qid = captured["qid"]
+ assert original_qid.endswith(".0")
+
+ # Simulate Agent.respond() on the SAME channel: stage the persisted
+ # answer under the original qid.
+ ch.attach_resume_answer(original_qid, "RESUMED")
+
+ # Tool body reruns and re-asks the identical prompt. No host answers
+ # this time — it must short-circuit to the staged answer. With the bug
+ # the counter mints hash.1, the slot (hash.0) never matches, and the
+ # call times out instead of returning "RESUMED".
+ result = await ch.confirm("are you sure?", timeout=0.5)
+ assert result == "RESUMED"
+ assert ch.pending is None
+
+
+async def test_resume_replays_repeated_identical_ask_sequence():
+ """Regression: a tool body that asks the SAME questions twice and detaches
+ on the second ask must, on resume, replay the first (already-answered) ask
+ AND consume the persisted answer for the second.
+
+ This is codex's repeated-identical-ask case. The first run mints hash.0
+ then hash.1 (persisted). On resume the counter is reset, so the replay
+ re-mints hash.0 (must be served from prior history, not the slot) then
+ hash.1 (must match the persisted slot). We model the persisted answer for
+ the SECOND ask via _resume_slot and serve the FIRST ask from a host that
+ answers it immediately, mirroring how respond() replays.
+ """
+ questions = [Question(key="color", prompt="Pick:")]
+
+ # --- original run: two identical asks; capture both qids ---
+ run1 = InMemoryChannel()
+ qids: list[str] = []
+
+ async def answer_each(value):
+ while run1.pending is None:
+ await asyncio.sleep(0)
+ qids.append(run1.pending.question_id)
+ await run1.answer(run1.pending.question_id, value)
+
+ h1 = asyncio.create_task(answer_each({"color": "red"}))
+ a1 = await run1.ask(questions)
+ await h1
+ h2 = asyncio.create_task(answer_each({"color": "blue"}))
+ a2 = await run1.ask(questions)
+ await h2
+
+ assert a1 == {"color": "red"}
+ assert a2 == {"color": "blue"}
+ first_qid, second_qid = qids
+ assert first_qid != second_qid # hash.0, hash.1
+ assert first_qid.endswith(".0")
+ assert second_qid.endswith(".1")
+
+ # --- cross-process resume: fresh channel, counter empty ---
+ # respond() stages the persisted answer for the SECOND ask (the one that
+ # was pending at detach). The replay's first ask is served by a host (it
+ # was already answered/recorded in the original run); the second must
+ # short-circuit to the staged answer.
+ run2 = InMemoryChannel()
+ run2.attach_resume_answer(second_qid, {"color": "STAGED"})
+
+ async def answer_first(value):
+ while run2.pending is None:
+ await asyncio.sleep(0)
+ await run2.answer(run2.pending.question_id, value)
+
+ hf = asyncio.create_task(answer_first({"color": "replayed-first"}))
+ r1 = await run2.ask(questions) # mints hash.0 → host answers
+ await hf
+ r2 = await run2.ask(questions, timeout=0.5) # mints hash.1 → matches slot
+
+ assert r1 == {"color": "replayed-first"}
+ assert r2 == {"color": "STAGED"}
+
+
async def test_repeat_ask_gets_distinct_qids():
"""Same regression as test_repeat_confirm_gets_distinct_qids for ask()."""
ch = InMemoryChannel()