Skip to content

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

feat(postgres): mark_run_complete (idempotent) + load_pending

xf gongf8567ae337c8
diff --git a/cubepi/checkpointer/postgres/checkpointer.py b/cubepi/checkpointer/postgres/checkpointer.py
index e0354de..d79f7de 100644
--- a/cubepi/checkpointer/postgres/checkpointer.py
+++ b/cubepi/checkpointer/postgres/checkpointer.py
@@ -16,6 +16,7 @@ from cubepi.checkpointer.base import CheckpointData
from cubepi.checkpointer.exceptions import (
RunAlreadyClaimedError,
RunAlreadyCompletedError,
+ RunNotClaimedError,
)
from cubepi.checkpointer.postgres.exceptions import (
CubepiSchemaMismatch,
@@ -264,6 +265,60 @@ class PostgresCheckpointer:
run_id,
)
+ async def mark_run_complete(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,
+ )
+ 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 None:
+ raise RunNotClaimedError(
+ f"thread={thread_id} run={run_id} has no claim row"
+ )
+ if row["completed_at"] is not None:
+ return # idempotent success
+ next_seq = await conn.fetchval(
+ "SELECT COALESCE(MAX(completion_seq), 0) + 1 "
+ "FROM cubepi_runs WHERE thread_id = $1 "
+ "AND completion_seq IS NOT NULL",
+ thread_id,
+ )
+ await conn.execute(
+ "UPDATE cubepi_runs SET completed_at = now(), "
+ "completion_seq = $3 "
+ "WHERE thread_id = $1 AND run_id = $2",
+ thread_id,
+ run_id,
+ next_seq,
+ )
+
+ async def load_pending(
+ self, thread_id: str
+ ) -> tuple[HitlRequest, str | None] | None:
+ assert self._pool is not None
+ async with self._pool.acquire() as conn:
+ row = await conn.fetchrow(
+ "SELECT pending_request, run_id FROM cubepi_threads "
+ "WHERE thread_id = $1",
+ thread_id,
+ )
+ if row is None or row["pending_request"] is None:
+ return None
+ raw = row["pending_request"]
+ if isinstance(raw, str): # pragma: no cover — codec-dependent
+ req = HitlRequest.model_validate_json(raw)
+ else:
+ req = HitlRequest.model_validate(raw)
+ return req, row["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
index b9ea83b..60f3780 100644
--- a/tests/checkpointer/test_postgres_runs.py
+++ b/tests/checkpointer/test_postgres_runs.py
@@ -6,6 +6,7 @@ import pytest
from cubepi.checkpointer.exceptions import (
RunAlreadyClaimedError,
RunAlreadyCompletedError,
+ RunNotClaimedError,
)
from cubepi.checkpointer.postgres import PostgresCheckpointer
from cubepi.providers.base import TextContent, UserMessage
@@ -46,23 +47,83 @@ async def test_claim_collision_in_flight_raises_claimed(pg_v4_dsn):
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()
+ await cp.mark_run_complete("t", "r1")
msg = UserMessage(content=[TextContent(text="late")], run_id="r1")
with pytest.raises(RunAlreadyCompletedError):
await cp.append("t", [msg])
+async def test_claim_then_complete_roundtrip(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ await cp.claim_run("t", "r1")
+ await cp.mark_run_complete("t", "r1")
+ # Idempotent: second mark is a no-op.
+ await cp.mark_run_complete("t", "r1")
+
+
+async def test_claim_collision_completed_raises_completed(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ await cp.claim_run("t", "r1")
+ await cp.mark_run_complete("t", "r1")
+ with pytest.raises(RunAlreadyCompletedError):
+ await cp.claim_run("t", "r1")
+
+
+async def test_mark_without_claim_raises_not_claimed(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ with pytest.raises(RunNotClaimedError):
+ await cp.mark_run_complete("t", "r1")
+
+
+async def test_completion_seq_monotonic_per_thread(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ for rid in ("A", "B", "C"):
+ await cp.claim_run("t", rid)
+ await cp.mark_run_complete("t", rid)
+ conn = await asyncpg.connect(pg_v4_dsn)
+ try:
+ rows = await conn.fetch(
+ "SELECT run_id, completion_seq FROM cubepi_runs "
+ "WHERE thread_id = $1 ORDER BY completion_seq",
+ "t",
+ )
+ assert [r["run_id"] for r in rows] == ["A", "B", "C"]
+ seqs = [r["completion_seq"] for r in rows]
+ assert seqs == sorted(seqs)
+ assert len(set(seqs)) == 3
+ finally:
+ await conn.close()
+
+
+async def test_load_pending_returns_tuple_with_run_id(pg_v4_dsn):
+ from cubepi.hitl.types import ConfirmRequest, HitlRequest
+
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ req = HitlRequest(
+ question_id="q1",
+ thread_id="t",
+ payload=ConfirmRequest(prompt="hi"),
+ created_at=0.0,
+ )
+ await cp.save_pending_request("t", req, run_id="r-1")
+ res = await cp.load_pending("t")
+ assert res is not None
+ got_req, got_run_id = res
+ assert got_req.question_id == "q1"
+ assert got_run_id == "r-1"
+
+
+async def test_load_pending_returns_none_when_empty(pg_v4_dsn):
+ async with PostgresCheckpointer(pg_v4_dsn) as cp:
+ assert await cp.load_pending("t") is None
+
+
@pytest.mark.asyncio
async def test_append_persists_run_id_into_column(pg_v4_dsn):
async with PostgresCheckpointer(pg_v4_dsn) as cp: