CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(hitl): CheckpointedChannel.run_id + hitl.run_id/detached span attrs
xf gong26617e0fc072
diff --git a/cubepi/hitl/channel.py b/cubepi/hitl/channel.pyindex 6c3668f..5cf26c1 100644--- a/cubepi/hitl/channel.py+++ b/cubepi/hitl/channel.py@@ -185,6 +185,12 @@ class _BaseChannel:if kind == "approve":attrs["tool_call_id"] = payload.tool_call_idattrs["tool_name"] = payload.tool_name+ # Only CheckpointedChannel carries _run_id; _BaseChannel/InMemoryChannel+ # don't. hitl_span skips None-valued attrs, so leaving this out for the+ # base channel is correct.+ run_id = getattr(self, "_run_id", None)+ if run_id is not None:+ attrs["run_id"] = run_idoutcome = "unknown"from_resume = False@@ -286,8 +292,12 @@ class _BaseChannel:outcome = _outcome_from_exception(exc)raisefinally:+ # `detached` is a parallel boolean alongside `outcome` —+ # convenient for filtering spans by "this was a cross-process+ # suspend" without re-parsing the outcome string.span.set_attribute("hitl.from_resume", from_resume)span.set_attribute("hitl.outcome", outcome)+ span.set_attribute("hitl.detached", outcome == "detached")span.set_attribute("hitl.duration_seconds", time.monotonic() - t0)async def _on_pending_set(self, req: HitlRequest) -> None:@@ -484,6 +494,7 @@ class CheckpointedChannel(_BaseChannel):*,checkpointer: Any,thread_id: str,+ run_id: str | None = None,default_timeout: float | None = None,allow_inside_custom_tool: bool = False,) -> None:@@ -503,6 +514,12 @@ class CheckpointedChannel(_BaseChannel):)super().__init__(default_timeout=default_timeout, thread_id=thread_id)self._checkpointer = checkpointer+ # Optional host-side run identifier (e.g. cubebox run_id) persisted+ # alongside the pending request via save_pending_request. Lets a host+ # recover "which run owns this paused HITL" after worker crash in a+ # single atomic write — no two-step race between pending JSON and+ # run_id columns.+ self._run_id = run_idself._allow_inside_custom_tool = allow_inside_custom_toolasync def _on_pending_set(self, req: HitlRequest) -> None:@@ -514,7 +531,9 @@ class CheckpointedChannel(_BaseChannel):"Use ApprovalPolicyMiddleware or ask_user_tool, or pass ""allow_inside_custom_tool=True to opt in.")- await self._checkpointer.save_pending_request(self._thread_id, req)+ await self._checkpointer.save_pending_request(+ self._thread_id, req, run_id=self._run_id+ )await super()._on_pending_set(req)async def _on_pending_cleared(@@ -527,4 +546,5 @@ class CheckpointedChannel(_BaseChannel):if isinstance(exc, HitlDetached):return+ # request=None clears pending AND run_id atomically.await self._checkpointer.save_pending_request(self._thread_id, None)diff --git a/tests/hitl/test_checkpointed_channel_run_id.py b/tests/hitl/test_checkpointed_channel_run_id.pynew file mode 100644index 0000000..c3c6e4a--- /dev/null+++ b/tests/hitl/test_checkpointed_channel_run_id.py@@ -0,0 +1,107 @@+"""Tests for CheckpointedChannel.run_id — durable cross-process correlation+of a paused HITL request to the (cubebox/host) run that produced it.++The channel takes ``run_id`` at construction; whenever the channel writes+the pending request through the checkpointer (``save_pending_request``),+it must pass ``run_id=self._run_id`` so the run_id is persisted in the+same atomic statement as the pending JSON. This avoids the race where a+worker crashes between "wrote pending" and "wrote run_id".+"""++from __future__ import annotations++import asyncio++import pytest++from cubepi.checkpointer.memory import MemoryCheckpointer+from cubepi.hitl import ApproveAnswer+from cubepi.hitl.channel import CheckpointedChannel+from cubepi.hitl.types import Question+++async def test_run_id_persisted_on_approve():+ cp = MemoryCheckpointer()+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1", run_id="r-abc")++ async def host():+ while await cp.load_pending_request("t-1") is None:+ await asyncio.sleep(0)+ # run_id must be readable from the same checkpointer state.+ assert await cp.load_pending_run_id("t-1") == "r-abc"+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))++ asyncio.create_task(host())+ ans = await ch.approve(tool_name="bash", tool_call_id="tc-1", args={})+ assert ans.decision == "approve"+ # On success, pending + run_id are both cleared.+ assert await cp.load_pending_request("t-1") is None+ assert await cp.load_pending_run_id("t-1") is None+++async def test_run_id_persisted_on_confirm():+ cp = MemoryCheckpointer()+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-2", run_id="r-xyz")++ async def host():+ while await cp.load_pending_request("t-2") is None:+ await asyncio.sleep(0)+ assert await cp.load_pending_run_id("t-2") == "r-xyz"+ await ch.answer(ch.pending.question_id, True)++ asyncio.create_task(host())+ result = await ch.confirm("ok?")+ assert result is True+++async def test_run_id_persisted_on_ask():+ cp = MemoryCheckpointer()+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-3", run_id="r-ask")++ async def host():+ while await cp.load_pending_request("t-3") is None:+ await asyncio.sleep(0)+ assert await cp.load_pending_run_id("t-3") == "r-ask"+ await ch.answer(ch.pending.question_id, {"q1": "yes"})++ asyncio.create_task(host())+ result = await ch.ask([Question(key="q1", prompt="why?")])+ assert result == {"q1": "yes"}+++async def test_no_run_id_kwarg_leaves_run_id_none():+ """Backwards compat: legacy CheckpointedChannel(no run_id=) → no run_id stored."""+ cp = MemoryCheckpointer()+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-4")++ async def host():+ while await cp.load_pending_request("t-4") is None:+ await asyncio.sleep(0)+ assert await cp.load_pending_run_id("t-4") is None+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="deny"))++ asyncio.create_task(host())+ await ch.approve(tool_name="bash", tool_call_id="tc-2", args={})+++async def test_run_id_cleared_on_detach_stays_persisted():+ """On detach (HitlDetached) the pending row must remain — and so must run_id."""+ cp = MemoryCheckpointer()+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-5", run_id="r-detach")++ async def detacher():+ while ch.pending is None:+ await asyncio.sleep(0)+ from cubepi.hitl.exceptions import HitlDetached++ if ch._future is not None and not ch._future.done():+ ch._future.set_exception(HitlDetached())++ asyncio.create_task(detacher())+ from cubepi.hitl.exceptions import HitlDetached++ with pytest.raises(HitlDetached):+ await ch.confirm("ok?")+ # Both pending and run_id survive a detach (cross-process suspend).+ assert await cp.load_pending_request("t-5") is not None+ assert await cp.load_pending_run_id("t-5") == "r-detach"diff --git a/tests/hitl/test_hitl_span_attributes.py b/tests/hitl/test_hitl_span_attributes.pynew file mode 100644index 0000000..3899141--- /dev/null+++ b/tests/hitl/test_hitl_span_attributes.py@@ -0,0 +1,97 @@+"""Tests for the HITL trace span ``hitl.run_id`` + ``hitl.detached`` attrs.++``hitl.run_id`` should appear on spans emitted by a CheckpointedChannel+constructed with ``run_id=...``. ``hitl.detached`` should be True when+the unwind cause was HitlDetached (cross-process suspend), and False for+all other outcomes.+"""++from __future__ import annotations++import asyncio++import pytest++pytest.importorskip("opentelemetry")++from opentelemetry import trace+from opentelemetry.sdk.trace import TracerProvider+from opentelemetry.sdk.trace.export import SimpleSpanProcessor+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter++from cubepi.checkpointer.memory import MemoryCheckpointer+from cubepi.hitl import ApproveAnswer+from cubepi.hitl.channel import CheckpointedChannel, InMemoryChannel+from cubepi.hitl.exceptions import HitlDetached+++def exporter():+ # OTel forbids replacing the global TracerProvider once set, so attach a+ # fresh InMemorySpanExporter to whatever provider is already installed+ # (or install one if none is). Per-test exporter keeps tests independent.+ current = trace.get_tracer_provider()+ if not isinstance(current, TracerProvider):+ current = TracerProvider()+ trace.set_tracer_provider(current)+ exp = InMemorySpanExporter()+ current.add_span_processor(SimpleSpanProcessor(exp))+ yield exp+++async def test_checkpointed_channel_emits_run_id_attribute(exporter):+ cp = MemoryCheckpointer()+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1", run_id="r-trace")++ async def host():+ while ch.pending is None:+ await asyncio.sleep(0)+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))++ asyncio.create_task(host())+ await ch.approve(tool_name="bash", tool_call_id="tc-1", args={})++ spans = [s for s in exporter.get_finished_spans() if s.name == "hitl.approve"]+ assert len(spans) == 1+ assert spans[0].attributes["hitl.run_id"] == "r-trace"+ assert spans[0].attributes["hitl.detached"] is False+++async def test_in_memory_channel_omits_run_id_attribute(exporter):+ """InMemoryChannel has no run_id concept — the attribute must NOT be set+ (hitl_span skips None-valued attrs)."""+ ch = InMemoryChannel()++ async def host():+ while ch.pending is None:+ await asyncio.sleep(0)+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))++ asyncio.create_task(host())+ await ch.approve(tool_name="bash", tool_call_id="tc-2", args={})++ spans = [s for s in exporter.get_finished_spans() if s.name == "hitl.approve"]+ assert len(spans) == 1+ assert "hitl.run_id" not in spans[0].attributes+ assert spans[0].attributes["hitl.detached"] is False+++async def test_detached_outcome_marked_on_span(exporter):+ cp = MemoryCheckpointer()+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-2", run_id="r-detach")++ async def detacher():+ while ch.pending is None:+ await asyncio.sleep(0)+ if ch._future is not None and not ch._future.done():+ ch._future.set_exception(HitlDetached())++ asyncio.create_task(detacher())+ with pytest.raises(HitlDetached):+ await ch.confirm("ok?")++ spans = [s for s in exporter.get_finished_spans() if s.name == "hitl.confirm"]+ assert len(spans) == 1+ assert spans[0].attributes["hitl.detached"] is True+ assert spans[0].attributes["hitl.outcome"] == "detached"+ assert spans[0].attributes["hitl.run_id"] == "r-detach"diff --git a/tests/hitl/test_trace_spans.py b/tests/hitl/test_trace_spans.pyindex 845c30e..42f5328 100644--- a/tests/hitl/test_trace_spans.py+++ b/tests/hitl/test_trace_spans.py@@ -13,10 +13,16 @@ from cubepi.hitl.channel import InMemoryChannel@pytest.fixturedef exporter():- provider = TracerProvider()+ # OTel forbids replacing the global TracerProvider once set, so attach a+ # fresh InMemorySpanExporter to whatever provider is already installed+ # (or install one if none is). Clearing the exporter buffer per test+ # keeps tests independent.+ current = trace.get_tracer_provider()+ if not isinstance(current, TracerProvider):+ current = TracerProvider()+ trace.set_tracer_provider(current)exp = InMemorySpanExporter()- provider.add_span_processor(SimpleSpanProcessor(exp))- trace.set_tracer_provider(provider)+ current.add_span_processor(SimpleSpanProcessor(exp))yield exp