Skip to content

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

feat(postgres): claim_run with lazy threads-row create

xf gong0b1f532e2512
diff --git a/cubepi/checkpointer/postgres/checkpointer.py b/cubepi/checkpointer/postgres/checkpointer.py
index 9c559cc..e0354de 100644
--- a/cubepi/checkpointer/postgres/checkpointer.py
+++ b/cubepi/checkpointer/postgres/checkpointer.py
@@ -13,6 +13,10 @@ import asyncpg
import msgpack
from cubepi.checkpointer.base import CheckpointData
+from cubepi.checkpointer.exceptions import (
+ RunAlreadyClaimedError,
+ RunAlreadyCompletedError,
+)
from cubepi.checkpointer.postgres.exceptions import (
CubepiSchemaMismatch,
CubepiSchemaUninitialized,
@@ -160,6 +164,9 @@ class PostgresCheckpointer:
if not messages:
return
assert self._pool is not None
+ run_ids = {
+ rid for m in messages if (rid := getattr(m, "run_id", None)) is not None
+ }
async with self._pool.acquire() as conn:
async with conn.transaction():
# Per-thread advisory lock for monotonic seq allocation
@@ -173,6 +180,20 @@ class PostgresCheckpointer:
"VALUES ($1) ON CONFLICT DO NOTHING",
thread_id,
)
+ # Pre-flight: reject append on any completed run_id.
+ if run_ids:
+ done_rows = await conn.fetch(
+ "SELECT run_id FROM cubepi_runs "
+ "WHERE thread_id = $1 AND run_id = ANY($2::text[]) "
+ "AND completed_at IS NOT NULL",
+ thread_id,
+ list(run_ids),
+ )
+ if done_rows:
+ bad = ", ".join(r["run_id"] for r in done_rows)
+ raise RunAlreadyCompletedError(
+ f"append on completed run thread={thread_id} runs={bad}"
+ )
last_seq = (
await conn.fetchval(
"SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "
@@ -195,15 +216,54 @@ class PostgresCheckpointer:
_role_of(m),
json.dumps(m.metadata),
payload,
+ getattr(m, "run_id", None),
)
)
await conn.executemany(
"INSERT INTO cubepi_messages "
- "(thread_id, seq, role, metadata, payload) "
- "VALUES ($1, $2, $3, $4, $5)",
+ "(thread_id, seq, role, metadata, payload, run_id) "
+ "VALUES ($1, $2, $3, $4, $5, $6)",
rows,
)
+ async def claim_run(self, thread_id: str, run_id: str) -> None:
+ assert self._pool is not None
+ async with self._pool.acquire() as conn:
+ async with conn.transaction():
+ await conn.execute(
+ "SELECT pg_advisory_xact_lock(hashtext($1))",
+ thread_id,
+ )
+ # Lazy thread row creation (claim may precede any append).
+ await conn.execute(
+ "INSERT INTO cubepi_threads (thread_id) "
+ "VALUES ($1) ON CONFLICT (thread_id) DO NOTHING",
+ thread_id,
+ )
+ # Pre-check under the advisory lock so a duplicate doesn't
+ # raise UniqueViolation (which would abort the txn before
+ # we could distinguish in-flight vs completed).
+ row = await conn.fetchrow(
+ "SELECT completed_at FROM cubepi_runs "
+ "WHERE thread_id = $1 AND run_id = $2",
+ thread_id,
+ run_id,
+ )
+ if row is not None:
+ if row["completed_at"] is not None:
+ raise RunAlreadyCompletedError(
+ f"thread={thread_id} run={run_id} already completed"
+ )
+ raise RunAlreadyClaimedError(
+ f"thread={thread_id} run={run_id} in flight"
+ )
+ await conn.execute(
+ "INSERT INTO cubepi_runs (thread_id, run_id) "
+ "VALUES ($1, $2)",
+ thread_id,
+ run_id,
+ )
+
async def save_extra(self, thread_id: str, extra: JsonObject) -> None:
assert self._pool is not None
async with self._pool.acquire() as conn:
diff --git a/tests/checkpointer/test_postgres_runs.py b/tests/checkpointer/test_postgres_runs.py
new file mode 100644
index 0000000..b9ea83b
--- /dev/null
+++ b/tests/checkpointer/test_postgres_runs.py
@@ -0,0 +1,92 @@
+"""PostgresCheckpointer run-lifecycle tests."""
+
+import asyncpg
+import pytest
+
+from cubepi.checkpointer.exceptions import (
+ RunAlreadyClaimedError,
+ RunAlreadyCompletedError,
+)
+from cubepi.checkpointer.postgres import PostgresCheckpointer
+from cubepi.providers.base import TextContent, UserMessage
+
+
+async def test_claim_run_creates_threads_row_lazily(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ await cp.claim_run("t-lazy", "r1")
+ conn = await asyncpg.connect(pg_v4_dsn)
+ try:
+ row = await conn.fetchrow(
+ "SELECT thread_id FROM cubepi_threads WHERE thread_id = $1",
+ "t-lazy",
+ )
+ assert row is not None
+ run = await conn.fetchrow(
+ "SELECT completed_at FROM cubepi_runs "
+ "WHERE thread_id = $1 AND run_id = $2",
+ "t-lazy",
+ "r1",
+ )
+ assert run is not None
+ assert run["completed_at"] is None
+ finally:
+ await conn.close()
+
+
+async def test_claim_collision_in_flight_raises_claimed(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ await cp.claim_run("t", "r1")
+ with pytest.raises(RunAlreadyClaimedError):
+ await cp.claim_run("t", "r1")
+
+
+async def test_append_on_completed_run_id_rejected(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ await cp.claim_run("t", "r1")
+ # Mark complete via direct UPDATE — mark_run_complete arrives in Task 16.
+ # We exercise the append pre-flight independently here.
+ conn = await asyncpg.connect(pg_v4_dsn)
+ try:
+ await conn.execute(
+ "UPDATE cubepi_runs SET completed_at = now(), completion_seq = 1 "
+ "WHERE thread_id = $1 AND run_id = $2",
+ "t",
+ "r1",
+ )
+ finally:
+ await conn.close()
+ msg = UserMessage(content=[TextContent(text="late")], run_id="r1")
+ with pytest.raises(RunAlreadyCompletedError):
+ await cp.append("t", [msg])
+
+
+async def test_append_persists_run_id_into_column(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ await cp.claim_run("t", "r1")
+ msg = UserMessage(content=[TextContent(text="hi")], run_id="r1")
+ await cp.append("t", [msg])
+ conn = await asyncpg.connect(pg_v4_dsn)
+ try:
+ row = await conn.fetchrow(
+ "SELECT run_id FROM cubepi_messages WHERE thread_id = $1",
+ "t",
+ )
+ assert row is not None
+ assert row["run_id"] == "r1"
+ finally:
+ await conn.close()
+
+
+async def test_append_in_flight_run_id_ok(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ await cp.claim_run("t", "r1")
+ msg = UserMessage(content=[TextContent(text="ok")], run_id="r1")
+ await cp.append("t", [msg])
+ data = await cp.load("t")
+ assert data is not None
+ assert len(data.messages) == 1