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(sqlite): claim_run, mark_run_complete, load_pending
xf gong3d79d35269b7
diff --git a/cubepi/checkpointer/sqlite.py b/cubepi/checkpointer/sqlite.pyindex 4e49da5..dd8e6b2 100644--- a/cubepi/checkpointer/sqlite.py+++ b/cubepi/checkpointer/sqlite.py@@ -8,7 +8,12 @@ from typing import Any, AsyncIterator, castimport aiosqlitefrom cubepi.checkpointer.base import CheckpointData-from cubepi.checkpointer.exceptions import CheckpointerLockTimeoutError+from cubepi.checkpointer.exceptions import (+ CheckpointerLockTimeoutError,+ RunAlreadyClaimedError,+ RunAlreadyCompletedError,+ RunNotClaimedError,+)from cubepi.hitl.types import HitlRequestfrom cubepi.providers.base import (AssistantMessage,@@ -142,7 +147,26 @@ class SQLiteCheckpointer:async def append(self, thread_id: str, messages: list[Message]) -> None:assert self._db is not None+ run_ids = {+ rid+ for m in messages+ if (rid := getattr(m, "run_id", None)) is not None+ }async with self._lock, _writer_txn(self._db):+ if run_ids:+ placeholders = ",".join("?" for _ in run_ids)+ cur = await self._db.execute(+ f"SELECT run_id FROM runs WHERE thread_id = ? "+ f"AND run_id IN ({placeholders}) "+ f"AND completed_at IS NOT NULL",+ (thread_id, *run_ids),+ )+ done = await cur.fetchall()+ if done:+ bad = ", ".join(r[0] for r in done)+ raise RunAlreadyCompletedError(+ f"append on completed run thread={thread_id} runs={bad}"+ )for msg in messages:msg_json = _serialize_message(msg)await self._db.execute(@@ -196,6 +220,71 @@ class SQLiteCheckpointer:(thread_id, payload, run_id),)+ async def claim_run(self, thread_id: str, run_id: str) -> None:+ assert self._db is not None+ async with self._lock, _writer_txn(self._db):+ cur = await self._db.execute(+ "SELECT completed_at FROM runs "+ "WHERE thread_id = ? AND run_id = ?",+ (thread_id, run_id),+ )+ row = await cur.fetchone()+ if row is not None:+ completed_at = row[0]+ if completed_at is None:+ raise RunAlreadyClaimedError(+ f"thread={thread_id} run={run_id} in flight"+ )+ raise RunAlreadyCompletedError(+ f"thread={thread_id} run={run_id} already completed"+ )+ await self._db.execute(+ "INSERT INTO runs (thread_id, run_id) VALUES (?, ?)",+ (thread_id, run_id),+ )++ async def mark_run_complete(self, thread_id: str, run_id: str) -> None:+ assert self._db is not None+ async with self._lock, _writer_txn(self._db):+ cur = await self._db.execute(+ "SELECT completed_at FROM runs "+ "WHERE thread_id = ? AND run_id = ?",+ (thread_id, run_id),+ )+ row = await cur.fetchone()+ if row is None:+ raise RunNotClaimedError(+ f"thread={thread_id} run={run_id} has no claim row"+ )+ if row[0] is not None:+ return # idempotent success+ cur = await self._db.execute(+ "SELECT COALESCE(MAX(completion_seq), 0) + 1 FROM runs "+ "WHERE thread_id = ? AND completion_seq IS NOT NULL",+ (thread_id,),+ )+ (next_seq,) = await cur.fetchone()+ await self._db.execute(+ "UPDATE runs SET completed_at = julianday('now'), "+ "completion_seq = ? WHERE thread_id = ? AND run_id = ?",+ (next_seq, thread_id, run_id),+ )++ async def load_pending(+ self, thread_id: str+ ) -> tuple[HitlRequest, str | None] | None:+ assert self._db is not None+ async with self._lock:+ cur = await self._db.execute(+ "SELECT request_json, run_id FROM thread_pending_request "+ "WHERE thread_id = ?",+ (thread_id,),+ )+ row = await cur.fetchone()+ if row is None:+ return None+ return HitlRequest.model_validate_json(row[0]), row[1]+async def load_pending_request(self, thread_id: str) -> HitlRequest | None:assert self._db is not Noneasync with self._lock:diff --git a/tests/checkpointer/test_sqlite_runs.py b/tests/checkpointer/test_sqlite_runs.pynew file mode 100644index 0000000..6e5e4fc--- /dev/null+++ b/tests/checkpointer/test_sqlite_runs.py@@ -0,0 +1,117 @@+import tempfile+from pathlib import Path++import pytest++from cubepi.checkpointer.exceptions import (+ RunAlreadyClaimedError,+ RunAlreadyCompletedError,+ RunNotClaimedError,+)+from cubepi.checkpointer.sqlite import SQLiteCheckpointer+from cubepi.providers.base import TextContent, UserMessage+++async def test_claim_then_complete_roundtrip():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) 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_in_flight_raises_claimed():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) as cp:+ await cp.claim_run("t", "r1")+ with pytest.raises(RunAlreadyClaimedError):+ await cp.claim_run("t", "r1")+++async def test_claim_collision_completed_raises_completed():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) 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():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) as cp:+ with pytest.raises(RunNotClaimedError):+ await cp.mark_run_complete("t", "r1")+++async def test_completion_seq_monotonic_per_thread():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) as cp:+ for rid in ("A", "B", "C"):+ await cp.claim_run("t", rid)+ await cp.mark_run_complete("t", rid)+ cur = await cp._db.execute(+ "SELECT run_id, completion_seq FROM runs WHERE thread_id = ? "+ "ORDER BY completion_seq",+ ("t",),+ )+ rows = await cur.fetchall()+ assert [r[0] for r in rows] == ["A", "B", "C"]+ seqs = [r[1] for r in rows]+ assert seqs == sorted(seqs)+ assert len(set(seqs)) == 3+++async def test_append_on_completed_run_id_rejected():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) as cp:+ await cp.claim_run("t", "r1")+ 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_append_in_flight_run_id_ok():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) 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 and len(data.messages) == 1+++async def test_load_pending_returns_tuple_with_run_id():+ from cubepi.hitl.types import ConfirmRequest, HitlRequest++ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) 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():+ with tempfile.TemporaryDirectory() as d:+ async with SQLiteCheckpointer(str(Path(d) / "x.db")) as cp:+ assert await cp.load_pending("t") is None