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(postgres): snapshot + fork (threads-first, set-based)
xf gong05b91307f517
diff --git a/cubepi/checkpointer/postgres/checkpointer.py b/cubepi/checkpointer/postgres/checkpointer.pyindex d79f7de..3065c98 100644--- a/cubepi/checkpointer/postgres/checkpointer.py+++ b/cubepi/checkpointer/postgres/checkpointer.py@@ -17,6 +17,9 @@ from cubepi.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,+ RunNotCompletedError,+ ThreadAlreadyExistsError,+ ThreadNotFoundError,)from cubepi.checkpointer.postgres.exceptions import (CubepiSchemaMismatch,@@ -128,7 +131,8 @@ class PostgresCheckpointer:thread_id,)extra_row = await conn.fetchrow(- "SELECT extra FROM cubepi_threads WHERE thread_id = $1",+ "SELECT extra, parent_thread_id FROM cubepi_threads "+ "WHERE thread_id = $1",thread_id,)@@ -149,6 +153,7 @@ class PostgresCheckpointer:)messages.append(cls.model_validate(data))+ parent_thread_id: str | None = Noneif extra_row is not None:raw_extra = extra_row["extra"]extra = (@@ -156,10 +161,13 @@ class PostgresCheckpointer:if isinstance(raw_extra, str)else (raw_extra or {}))+ parent_thread_id = extra_row["parent_thread_id"]else:extra = {}- return CheckpointData(messages=messages, extra=extra)+ return CheckpointData(+ messages=messages, extra=extra, parent_thread_id=parent_thread_id+ )async def append(self, thread_id: str, messages: list[Message]) -> None:if not messages:@@ -259,8 +267,7 @@ class PostgresCheckpointer:f"thread={thread_id} run={run_id} in flight")await conn.execute(- "INSERT INTO cubepi_runs (thread_id, run_id) "- "VALUES ($1, $2)",+ "INSERT INTO cubepi_runs (thread_id, run_id) VALUES ($1, $2)",thread_id,run_id,)@@ -319,6 +326,154 @@ class PostgresCheckpointer:req = HitlRequest.model_validate(raw)return req, row["run_id"]+ async def snapshot(self, thread_id: str, *, after_run_id: str) -> list[Message]:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ # Source thread must exist.+ t_row = await conn.fetchrow(+ "SELECT 1 FROM cubepi_threads WHERE thread_id = $1",+ thread_id,+ )+ if t_row is None:+ raise ThreadNotFoundError(f"thread={thread_id}")+ cutoff = await conn.fetchval(+ "SELECT completion_seq FROM cubepi_runs "+ "WHERE thread_id = $1 AND run_id = $2",+ thread_id,+ after_run_id,+ )+ if cutoff is None:+ raise RunNotCompletedError(+ f"thread={thread_id} run={after_run_id} not completed"+ )+ rows = await conn.fetch(+ "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "WHERE thread_id = $1 AND ("+ " run_id IS NULL OR run_id IN ("+ " SELECT run_id FROM cubepi_runs "+ " WHERE thread_id = $1 "+ " AND completion_seq IS NOT NULL "+ " AND completion_seq <= $2"+ " )"+ ") ORDER BY seq",+ thread_id,+ cutoff,+ )+ messages: list[Message] = []+ for r in rows:+ cls = _ROLE_TO_CLS.get(r["role"])+ if cls is None:+ raise ValueError(f"unknown role in DB: {r['role']!r}")+ data = msgpack.unpackb(bytes(r["payload"]), raw=False)+ raw_meta = r["metadata"]+ data["metadata"] = (+ json.loads(raw_meta) if isinstance(raw_meta, str) else (raw_meta or {})+ )+ messages.append(cls.model_validate(data))+ return messages++ async def fork(+ self,+ src_thread_id: str,+ new_thread_id: str,+ *,+ after_run_id: str,+ metadata: JsonObject | None = None,+ ) -> None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.transaction():+ # Serialize concurrent forks/appends on src by taking the+ # src thread's per-thread advisory lock.+ await conn.execute(+ "SELECT pg_advisory_xact_lock(hashtext($1))",+ src_thread_id,+ )+ # Source must exist (threads row is created lazily by append+ # / claim_run / save_extra / save_pending_request — so its+ # presence is the canonical "thread exists" gate).+ t_row = await conn.fetchrow(+ "SELECT 1 FROM cubepi_threads WHERE thread_id = $1",+ src_thread_id,+ )+ if t_row is None:+ raise ThreadNotFoundError(f"thread={src_thread_id}")+ # Destination must not exist.+ dst_row = await conn.fetchrow(+ "SELECT 1 FROM cubepi_threads WHERE thread_id = $1",+ new_thread_id,+ )+ if dst_row is not None:+ raise ThreadAlreadyExistsError(f"thread={new_thread_id}")+ # Cutoff: after_run_id must be completed on src.+ cutoff = await conn.fetchval(+ "SELECT completion_seq FROM cubepi_runs "+ "WHERE thread_id = $1 AND run_id = $2",+ src_thread_id,+ after_run_id,+ )+ if cutoff is None:+ raise RunNotCompletedError(+ f"thread={src_thread_id} run={after_run_id} not completed"+ )+ # Build merged extra (carry parent's extra + fork metadata).+ src_extra_row = await conn.fetchrow(+ "SELECT extra FROM cubepi_threads WHERE thread_id = $1",+ src_thread_id,+ )+ raw_extra = (+ src_extra_row["extra"] if src_extra_row is not None else None+ )+ if isinstance(raw_extra, str):+ base_extra = json.loads(raw_extra)+ else:+ base_extra = dict(raw_extra) if raw_extra else {}+ if metadata is not None:+ base_extra["fork"] = json.loads(json.dumps(metadata))+ # INSERT destination threads row first to satisfy the+ # cubepi_messages / cubepi_runs FKs on subsequent copies.+ await conn.execute(+ "INSERT INTO cubepi_threads "+ "(thread_id, parent_thread_id, forked_at_seq, extra) "+ "VALUES ($1, $2, $3, $4::jsonb)",+ new_thread_id,+ src_thread_id,+ cutoff,+ json.dumps(base_extra),+ )+ # Copy messages whose run is NULL (legacy prefix) or completed+ # at or before cutoff. Preserve seq from the source.+ await conn.execute(+ "INSERT INTO cubepi_messages "+ "(thread_id, seq, role, metadata, payload, run_id) "+ "SELECT $1, seq, role, metadata, payload, run_id "+ "FROM cubepi_messages "+ "WHERE thread_id = $2 AND ("+ " run_id IS NULL OR run_id IN ("+ " SELECT run_id FROM cubepi_runs "+ " WHERE thread_id = $2 "+ " AND completion_seq IS NOT NULL "+ " AND completion_seq <= $3"+ " )"+ ") ORDER BY seq",+ new_thread_id,+ src_thread_id,+ cutoff,+ )+ # Copy completed runs satisfying the cutoff.+ await conn.execute(+ "INSERT INTO cubepi_runs "+ "(thread_id, run_id, claimed_at, completed_at, completion_seq) "+ "SELECT $1, run_id, claimed_at, completed_at, completion_seq "+ "FROM cubepi_runs "+ "WHERE thread_id = $2 "+ "AND completion_seq IS NOT NULL "+ "AND completion_seq <= $3",+ new_thread_id,+ src_thread_id,+ cutoff,+ )+async def save_extra(self, thread_id: str, extra: JsonObject) -> None:assert self._pool is not Noneasync with self._pool.acquire() as conn:diff --git a/cubepi/checkpointer/postgres/models.py b/cubepi/checkpointer/postgres/models.pyindex ac1e3b4..4d45fac 100644--- a/cubepi/checkpointer/postgres/models.py+++ b/cubepi/checkpointer/postgres/models.py@@ -126,9 +126,7 @@ class CubepiRun(CubepiBase):completed_at: Mapped[_dt.datetime | None] = mapped_column(sa.TIMESTAMP(timezone=True), nullable=True)- completion_seq: Mapped[int | None] = mapped_column(- sa.BigInteger, nullable=True- )+ completion_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)class CubepiSchemaVersion(CubepiBase):diff --git a/examples/checkpointing_postgres.py b/examples/checkpointing_postgres.pyindex 955f835..a75cb26 100644--- a/examples/checkpointing_postgres.py+++ b/examples/checkpointing_postgres.py@@ -32,7 +32,9 @@ from cubepi.agent.agent import Agentfrom cubepi.checkpointer.postgres import PostgresCheckpointerfrom cubepi.checkpointer.postgres.alembic_helpers import (add_pending_request_column_op,+ add_run_id_column_op,create_message_partitions_op,+ upgrade_v3_to_v4_op,write_schema_version_op,)from cubepi.providers.faux import FauxProvider, faux_assistant_message@@ -65,6 +67,7 @@ async def bootstrap_schema(dsn: str) -> None:);""")await conn.execute(add_pending_request_column_op()) # v1 -> v2 column+ await conn.execute(add_run_id_column_op()) # v2 -> v3 columnawait conn.execute("""CREATE TABLE cubepi_messages (thread_id TEXT NOT NULL@@ -85,6 +88,8 @@ async def bootstrap_schema(dsn: str) -> None:await conn.execute("CREATE TABLE cubepi_schema_version (version INTEGER PRIMARY KEY);")+ # v3 -> v4: run_id on cubepi_messages + cubepi_runs partitioned table.+ await conn.execute(upgrade_v3_to_v4_op())await conn.execute(write_schema_version_op()) # record EXPECTED_SCHEMA_VERSIONfinally:await conn.close()diff --git a/tests/checkpointer/test_postgres_fork.py b/tests/checkpointer/test_postgres_fork.pynew file mode 100644index 0000000..e3003bf--- /dev/null+++ b/tests/checkpointer/test_postgres_fork.py@@ -0,0 +1,131 @@+"""PostgresCheckpointer snapshot/fork tests."""++from __future__ import annotations++import asyncio++import pytest++from cubepi.checkpointer.exceptions import (+ RunNotCompletedError,+ ThreadAlreadyExistsError,+ ThreadNotFoundError,+)+from cubepi.checkpointer.postgres import PostgresCheckpointer+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(pg_v4_dsn):+ async with PostgresCheckpointer(pg_v4_dsn) as cp:+ 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(pg_v4_dsn):+ async with PostgresCheckpointer(pg_v4_dsn) as cp:+ await cp.append("src", [_msg(None, "legacy")])+ 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 loaded is not None+ assert [m.content[0].text for m in loaded.messages] == ["legacy", "a1"]+++async def test_fork_unknown_src_raises_thread_not_found(pg_v4_dsn):+ async with PostgresCheckpointer(pg_v4_dsn) as cp:+ with pytest.raises(ThreadNotFoundError):+ await cp.fork("missing", "dst", after_run_id="X")+++async def test_fork_unknown_run_id_raises_not_completed(pg_v4_dsn):+ async with PostgresCheckpointer(pg_v4_dsn) as cp:+ 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(pg_v4_dsn):+ async with PostgresCheckpointer(pg_v4_dsn) as cp:+ 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(pg_v4_dsn):+ async with PostgresCheckpointer(pg_v4_dsn) as cp:+ 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 is not None+ assert loaded.extra["original"] == "x"+ assert loaded.extra["fork"] == {"source": "test"}+++async def test_snapshot_matches_fork_messages(pg_v4_dsn):+ async with PostgresCheckpointer(pg_v4_dsn) as cp:+ 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"]+++async def test_fork_serialized_with_concurrent_append(pg_v4_dsn):+ """The fork's per-thread advisory lock must serialize with append.++ Without it, an append racing the fork could leak a partial in-flight+ run into the destination's messages. We assert the destination ONLY+ contains the completed prefix regardless of who runs first.+ """+ async with PostgresCheckpointer(pg_v4_dsn, min_pool_size=2, max_pool_size=4) as cp:+ await cp.claim_run("src", "A")+ await cp.append("src", [_msg("A", "a1")])+ await cp.mark_run_complete("src", "A")+ # Start an in-flight run B that an append targets.+ await cp.claim_run("src", "B")++ async def do_fork() -> None:+ await cp.fork("src", "dst", after_run_id="A")++ async def do_append() -> None:+ await cp.append("src", [_msg("B", "b1")])++ await asyncio.gather(do_fork(), do_append())+ loaded = await cp.load("dst")+ assert loaded is not None+ # Destination must NOT contain b1 — only the completed prefix.+ texts = [m.content[0].text for m in loaded.messages]+ assert texts == ["a1"]diff --git a/tests/checkpointer/test_postgres_runs.py b/tests/checkpointer/test_postgres_runs.pyindex 60f3780..9d9c31a 100644--- a/tests/checkpointer/test_postgres_runs.py+++ b/tests/checkpointer/test_postgres_runs.py@@ -24,8 +24,7 @@ async def test_claim_run_creates_threads_row_lazily(pg_v4_dsn):)assert row is not Nonerun = await conn.fetchrow(- "SELECT completed_at FROM cubepi_runs "- "WHERE thread_id = $1 AND run_id = $2",+ "SELECT completed_at FROM cubepi_runs WHERE thread_id = $1 AND run_id = $2","t-lazy","r1",)diff --git a/tests/checkpointer/test_postgres_schema_version_v3.py b/tests/checkpointer/test_postgres_schema_version_v3.pyindex 396f630..c003841 100644--- a/tests/checkpointer/test_postgres_schema_version_v3.py+++ b/tests/checkpointer/test_postgres_schema_version_v3.py@@ -27,7 +27,7 @@ async def test_postgres_v2_database_refused_with_actionable_error(clean_db) -> Npassmsg = str(ei.value)- assert "expected 3" in msg or "expected=3" in msg+ assert "expected 4" in msg or "expected=4" in msgassert "actual 2" in msg or "actual=2" in msg# Hint mentions the host alembic migration path so operators know what to do.assert "alembic" in msg.lower()@@ -59,6 +59,6 @@ async def test_mysql_v2_database_refused_with_actionable_error(clean_mysql_db) -passmsg = str(ei.value)- assert "expected 3" in msg or "expected=3" in msg+ assert "expected 4" in msg or "expected=4" in msgassert "actual 2" in msg or "actual=2" in msgassert "alembic" in msg.lower()