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(memory): snapshot + fork with set-based run_id selection
xf gong65a5c7fd716c
diff --git a/cubepi/checkpointer/memory.py b/cubepi/checkpointer/memory.pyindex 60c2339..61d6569 100644--- a/cubepi/checkpointer/memory.py+++ b/cubepi/checkpointer/memory.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import copyimport timefrom dataclasses import dataclass@@ -9,6 +10,9 @@ from cubepi.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,+ RunNotCompletedError,+ ThreadAlreadyExistsError,+ ThreadNotFoundError,)from cubepi.hitl.types import HitlRequestfrom cubepi.providers.base import Message@@ -22,6 +26,10 @@ class _RunState:completion_seq: int | None = None+def _legible_message_copy(m: Message) -> Message:+ return m.model_copy(deep=True)++class MemoryCheckpointer:def __init__(self) -> None:self._store: dict[str, CheckpointData] = {}@@ -112,3 +120,81 @@ class MemoryCheckpointer:next_seq = max(existing_seqs, default=0) + 1state.completed_at = time.time()state.completion_seq = next_seq++ async def snapshot(self, thread_id: str, *, after_run_id: str) -> list[Message]:+ async with self._lock:+ data = self._store.get(thread_id)+ if data is None and thread_id not in self._runs:+ raise ThreadNotFoundError(f"thread={thread_id}")+ runs = self._runs.get(thread_id, {})+ cutoff_state = runs.get(after_run_id)+ if cutoff_state is None or cutoff_state.completion_seq is None:+ raise RunNotCompletedError(+ f"thread={thread_id} run={after_run_id} not completed"+ )+ cutoff = cutoff_state.completion_seq+ selected: list[Message] = []+ for m in data.messages if data else []:+ if m.run_id is None:+ selected.append(_legible_message_copy(m))+ continue+ rs = runs.get(m.run_id)+ if rs is None or rs.completion_seq is None:+ continue+ if rs.completion_seq <= cutoff:+ selected.append(_legible_message_copy(m))+ return selected++ async def fork(+ self,+ src_thread_id: str,+ new_thread_id: str,+ *,+ after_run_id: str,+ metadata: JsonObject | None = None,+ ) -> None:+ async with self._lock:+ if new_thread_id in self._store or new_thread_id in self._runs:+ raise ThreadAlreadyExistsError(f"thread={new_thread_id}")+ src_data = self._store.get(src_thread_id)+ src_runs = self._runs.get(src_thread_id, {})+ if src_data is None and not src_runs:+ raise ThreadNotFoundError(f"thread={src_thread_id}")+ cutoff_state = src_runs.get(after_run_id)+ if cutoff_state is None or cutoff_state.completion_seq is None:+ raise RunNotCompletedError(+ f"thread={src_thread_id} run={after_run_id} not completed"+ )+ cutoff = cutoff_state.completion_seq+ # Select messages.+ new_messages: list[Message] = []+ for m in src_data.messages if src_data else []:+ if m.run_id is None:+ new_messages.append(_legible_message_copy(m))+ continue+ rs = src_runs.get(m.run_id)+ if rs is None or rs.completion_seq is None:+ continue+ if rs.completion_seq <= cutoff:+ new_messages.append(_legible_message_copy(m))+ # Deep copy extra and merge metadata.+ base_extra = copy.deepcopy(src_data.extra if src_data else {})+ if metadata is not None:+ base_extra["fork"] = copy.deepcopy(metadata)+ # Carry completed runs satisfying cutoff.+ new_runs: dict[str, _RunState] = {}+ for rid, state in src_runs.items():+ if state.completion_seq is None:+ continue+ if state.completion_seq <= cutoff:+ new_runs[rid] = _RunState(+ claimed_at=state.claimed_at,+ completed_at=state.completed_at,+ completion_seq=state.completion_seq,+ )+ self._store[new_thread_id] = CheckpointData(+ messages=new_messages,+ extra=base_extra,+ parent_thread_id=src_thread_id,+ )+ self._runs[new_thread_id] = new_runsdiff --git a/tests/checkpointer/test_memory_fork.py b/tests/checkpointer/test_memory_fork.pynew file mode 100644index 0000000..f200644--- /dev/null+++ b/tests/checkpointer/test_memory_fork.py@@ -0,0 +1,97 @@+import pytest++from cubepi.checkpointer.exceptions import (+ RunNotCompletedError,+ ThreadAlreadyExistsError,+ ThreadNotFoundError,+)+from cubepi.checkpointer.memory import MemoryCheckpointer+from cubepi.providers.base import TextContent, UserMessage+++def _msg(run_id: str | None, text: str) -> UserMessage:+ return UserMessage(content=[TextContent(text=text)], run_id=run_id)+++async def test_fork_copies_completed_runs_only():+ cp = MemoryCheckpointer()+ # Two completed runs A and B.+ await cp.claim_run("src", "A")+ await cp.append("src", [_msg("A", "a1"), _msg("A", "a2")])+ await cp.mark_run_complete("src", "A")+ await cp.claim_run("src", "B")+ await cp.append("src", [_msg("B", "b1")])+ await cp.mark_run_complete("src", "B")+ # An in-flight run C — must be excluded.+ await cp.claim_run("src", "C")+ await cp.append("src", [_msg("C", "c1")])+ await cp.fork("src", "dst", after_run_id="B")+ loaded = await cp.load("dst")+ assert loaded is not None+ texts = [m.content[0].text for m in loaded.messages]+ assert texts == ["a1", "a2", "b1"]+ assert loaded.parent_thread_id == "src"+++async def test_fork_includes_legacy_null_run_id_prefix():+ cp = MemoryCheckpointer()+ # Legacy NULL-run_id message.+ await cp.append("src", [_msg(None, "legacy")])+ # One completed run.+ await cp.claim_run("src", "A")+ await cp.append("src", [_msg("A", "a1")])+ await cp.mark_run_complete("src", "A")+ await cp.fork("src", "dst", after_run_id="A")+ loaded = await cp.load("dst")+ assert [m.content[0].text for m in loaded.messages] == ["legacy", "a1"]+++async def test_fork_unknown_src_raises_thread_not_found():+ cp = MemoryCheckpointer()+ with pytest.raises(ThreadNotFoundError):+ await cp.fork("missing", "dst", after_run_id="X")+++async def test_fork_unknown_run_id_raises_not_completed():+ cp = MemoryCheckpointer()+ await cp.append("src", [_msg(None, "x")])+ with pytest.raises(RunNotCompletedError):+ await cp.fork("src", "dst", after_run_id="missing")+++async def test_fork_destination_collision_raises_already_exists():+ cp = MemoryCheckpointer()+ await cp.claim_run("src", "A")+ await cp.append("src", [_msg("A", "a1")])+ await cp.mark_run_complete("src", "A")+ await cp.fork("src", "dst", after_run_id="A")+ with pytest.raises(ThreadAlreadyExistsError):+ await cp.fork("src", "dst", after_run_id="A")+++async def test_fork_carries_extra_and_writes_metadata():+ cp = MemoryCheckpointer()+ await cp.save_extra("src", {"original": "x"})+ await cp.claim_run("src", "A")+ await cp.append("src", [_msg("A", "a1")])+ await cp.mark_run_complete("src", "A")+ await cp.fork("src", "dst", after_run_id="A", metadata={"source": "test"})+ loaded = await cp.load("dst")+ assert loaded.extra["original"] == "x"+ assert loaded.extra["fork"] == {"source": "test"}+++async def test_snapshot_matches_fork_messages():+ cp = MemoryCheckpointer()+ await cp.claim_run("src", "A")+ await cp.append("src", [_msg("A", "a1")])+ 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"]