Skip to content

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

feat(checkpointer): add v3 run_id column + atomic save_pending_request

xf gong8c63005497be
diff --git a/cubepi/checkpointer/memory.py b/cubepi/checkpointer/memory.py
index c7659af..743cb8f 100644
--- a/cubepi/checkpointer/memory.py
+++ b/cubepi/checkpointer/memory.py
@@ -10,6 +10,9 @@ class MemoryCheckpointer:
def __init__(self) -> None:
self._store: dict[str, CheckpointData] = {}
self._pending: dict[str, HitlRequest] = {}
+ # run_id slot, persisted alongside _pending. Cleared together with
+ # the pending request so clear-pending implicitly clears run_id.
+ self._pending_run_id: dict[str, str | None] = {}
async def load(self, thread_id: str) -> CheckpointData | None:
return self._store.get(thread_id)
@@ -24,11 +27,22 @@ class MemoryCheckpointer:
self._store[thread_id] = CheckpointData()
self._store[thread_id].extra.update(extra)
- async def save_pending_request(self, thread_id: str, request: Any) -> None:
+ async def save_pending_request(
+ self,
+ thread_id: str,
+ request: Any,
+ *,
+ run_id: str | None = None,
+ ) -> None:
if request is None:
self._pending.pop(thread_id, None)
+ self._pending_run_id.pop(thread_id, None)
else:
self._pending[thread_id] = request
+ self._pending_run_id[thread_id] = run_id
async def load_pending_request(self, thread_id: str) -> Any:
return self._pending.get(thread_id)
+
+ async def load_pending_run_id(self, thread_id: str) -> str | None:
+ return self._pending_run_id.get(thread_id)
diff --git a/cubepi/checkpointer/mysql/alembic_helpers.py b/cubepi/checkpointer/mysql/alembic_helpers.py
index db306ca..b18ea9b 100644
--- a/cubepi/checkpointer/mysql/alembic_helpers.py
+++ b/cubepi/checkpointer/mysql/alembic_helpers.py
@@ -26,11 +26,21 @@ def add_pending_request_column_op() -> str:
Call inside the host's alembic v1→v2 upgrade() via op.execute(). MySQL does
not support IF NOT EXISTS for ADD COLUMN; guard with a schema check in the
alembic migration if idempotence is required. Hosts must also bump
- `cubepi_schema_version` via write_schema_version_op() (EXPECTED_SCHEMA_VERSION
- is now 2)."""
+ `cubepi_schema_version` via write_schema_version_op()."""
return "ALTER TABLE cubepi_threads ADD COLUMN pending_request JSON NULL"
+def add_run_id_column_op() -> str:
+ """Return SQL adding the v3 `run_id` column to cubepi_threads.
+
+ Call inside the host's alembic v2→v3 upgrade() via op.execute(). MySQL does
+ not support IF NOT EXISTS for ADD COLUMN; guard with a schema check in the
+ alembic migration if idempotence is required. Hosts must also bump
+ `cubepi_schema_version` via write_schema_version_op() (EXPECTED_SCHEMA_VERSION
+ is now 3)."""
+ return "ALTER TABLE cubepi_threads ADD COLUMN run_id VARCHAR(64) NULL"
+
+
def write_schema_version_op() -> str:
"""Return SQL setting cubepi_schema_version to the current version.
diff --git a/cubepi/checkpointer/mysql/checkpointer.py b/cubepi/checkpointer/mysql/checkpointer.py
index 001a663..f254322 100644
--- a/cubepi/checkpointer/mysql/checkpointer.py
+++ b/cubepi/checkpointer/mysql/checkpointer.py
@@ -152,8 +152,13 @@ class MySQLCheckpointer:
raise CubepiSchemaMismatch(
expected=EXPECTED_SCHEMA_VERSION,
actual=actual,
- hint="cubepi was upgraded but host alembic is behind. "
- "Generate a new revision and apply.",
+ hint=(
+ "cubepi was upgraded but host alembic is behind. "
+ "Generate a new alembic revision that calls "
+ "add_run_id_column_op() + write_schema_version_op() "
+ "(see cubepi.checkpointer.mysql.alembic_helpers) "
+ "and run `alembic upgrade head` against this database."
+ ),
)
async def load(self, thread_id: str) -> CheckpointData | None:
@@ -275,7 +280,13 @@ class MySQLCheckpointer:
await conn.rollback()
raise
- async def save_pending_request(self, thread_id, request):
+ async def save_pending_request(
+ self,
+ thread_id: str,
+ request: Any,
+ *,
+ run_id: str | None = None,
+ ) -> None:
# Matches the explicit-begin/commit/rollback pattern used by
# save_extra and append (see cubepi/checkpointer/mysql/checkpointer.py).
assert self._pool is not None
@@ -289,24 +300,28 @@ class MySQLCheckpointer:
(thread_id,),
)
if request is None:
+ # Clearing pending implicitly clears run_id — one statement.
await cur.execute(
- "UPDATE cubepi_threads SET pending_request = NULL, "
+ "UPDATE cubepi_threads "
+ "SET pending_request = NULL, run_id = NULL, "
"updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",
(thread_id,),
)
else:
payload = request.model_dump_json()
+ # pending + run_id written atomically.
await cur.execute(
- "UPDATE cubepi_threads SET pending_request = %s, "
+ "UPDATE cubepi_threads "
+ "SET pending_request = %s, run_id = %s, "
"updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",
- (payload, thread_id),
+ (payload, run_id, thread_id),
)
await conn.commit()
except BaseException: # pragma: no cover - defensive txn rollback
await conn.rollback()
raise
- async def load_pending_request(self, thread_id):
+ async def load_pending_request(self, thread_id: str) -> Any:
from cubepi.hitl.types import HitlRequest
assert self._pool is not None
@@ -325,3 +340,19 @@ class MySQLCheckpointer:
if isinstance(raw, str): # pragma: no cover — codec-dependent
return HitlRequest.model_validate_json(raw)
return HitlRequest.model_validate(raw)
+
+ async def load_pending_run_id(self, thread_id: str) -> str | None:
+ """Return just the run_id stored alongside the pending request.
+
+ Returns None when the thread is unknown, has no pending request, or
+ was written by a pre-v3 host (legacy rows have run_id NULL).
+ """
+ assert self._pool is not None
+ async with self._pool.acquire() as conn:
+ async with conn.cursor() as cur:
+ await cur.execute(
+ "SELECT run_id FROM cubepi_threads WHERE thread_id = %s",
+ (thread_id,),
+ )
+ row = await cur.fetchone()
+ return row[0] if row is not None else None
diff --git a/cubepi/checkpointer/mysql/models.py b/cubepi/checkpointer/mysql/models.py
index 2025479..eab9e5c 100644
--- a/cubepi/checkpointer/mysql/models.py
+++ b/cubepi/checkpointer/mysql/models.py
@@ -16,7 +16,7 @@ import sqlalchemy as sa
from sqlalchemy.dialects.mysql import JSON, LONGBLOB, VARCHAR
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
-EXPECTED_SCHEMA_VERSION = 2
+EXPECTED_SCHEMA_VERSION = 3
PARTITION_COUNT = 64
cubepi_metadata = sa.MetaData()
@@ -48,6 +48,12 @@ class CubepiThread(CubepiBase):
sa.JSON,
nullable=True,
)
+ # v3: host-side run identifier persisted alongside pending_request. See
+ # the parallel docstring on cubepi/checkpointer/postgres/models.py.
+ run_id: Mapped[str | None] = mapped_column(
+ VARCHAR(64),
+ nullable=True,
+ )
created_at: Mapped[_dt.datetime] = mapped_column(
sa.TIMESTAMP,
nullable=False,
diff --git a/cubepi/checkpointer/postgres/alembic_helpers.py b/cubepi/checkpointer/postgres/alembic_helpers.py
index bdf7063..12ace4c 100644
--- a/cubepi/checkpointer/postgres/alembic_helpers.py
+++ b/cubepi/checkpointer/postgres/alembic_helpers.py
@@ -25,11 +25,22 @@ def add_pending_request_column_op() -> str:
Call inside the host's alembic v1→v2 upgrade() via op.execute(). The new
column is JSONB NULL. Idempotent under repeated execution via IF NOT EXISTS.
- Hosts must also bump `cubepi_schema_version` via write_schema_version_op()
- (already documented; EXPECTED_SCHEMA_VERSION is now 2)."""
+ Hosts must also bump `cubepi_schema_version` via write_schema_version_op()."""
return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS pending_request JSONB"
+def add_run_id_column_op() -> str:
+ """Return SQL adding the v3 `run_id` column to cubepi_threads.
+
+ Call inside the host's alembic v2→v3 upgrade() via op.execute(). The new
+ column is TEXT NULL — it carries an opaque host-side identifier (e.g. the
+ cubebox run_id) persisted atomically with `pending_request`. Idempotent
+ under repeated execution via IF NOT EXISTS. Hosts must also bump
+ `cubepi_schema_version` via write_schema_version_op() (EXPECTED_SCHEMA_VERSION
+ is now 3)."""
+ return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS run_id TEXT"
+
+
def write_schema_version_op() -> str:
"""Return SQL setting cubepi_schema_version to the current version.
diff --git a/cubepi/checkpointer/postgres/checkpointer.py b/cubepi/checkpointer/postgres/checkpointer.py
index f577456..f957ff6 100644
--- a/cubepi/checkpointer/postgres/checkpointer.py
+++ b/cubepi/checkpointer/postgres/checkpointer.py
@@ -103,8 +103,13 @@ class PostgresCheckpointer:
raise CubepiSchemaMismatch(
expected=EXPECTED_SCHEMA_VERSION,
actual=row["version"],
- hint="cubepi was upgraded but host alembic is behind. "
- "Generate a new revision and apply.",
+ hint=(
+ "cubepi was upgraded but host alembic is behind. "
+ "Generate a new alembic revision that calls "
+ "add_run_id_column_op() + write_schema_version_op() "
+ "(see cubepi.checkpointer.postgres.alembic_helpers) "
+ "and run `alembic upgrade head` against this database."
+ ),
)
async def load(self, thread_id: str) -> CheckpointData | None:
@@ -210,7 +215,13 @@ class PostgresCheckpointer:
json.dumps(extra),
)
- async def save_pending_request(self, thread_id: str, request) -> None:
+ async def save_pending_request(
+ self,
+ thread_id: str,
+ request,
+ *,
+ run_id: str | None = None,
+ ) -> None:
assert self._pool is not None
async with self._pool.acquire() as conn:
async with conn.transaction():
@@ -221,18 +232,24 @@ class PostgresCheckpointer:
thread_id,
)
if request is None:
+ # Clearing pending implicitly clears run_id — one statement.
await conn.execute(
- "UPDATE cubepi_threads SET pending_request = NULL, "
+ "UPDATE cubepi_threads "
+ "SET pending_request = NULL, run_id = NULL, "
"updated_at = now() WHERE thread_id = $1",
thread_id,
)
else:
payload = request.model_dump_json()
+ # Write pending + run_id in the SAME atomic UPDATE so a
+ # crash between them is impossible.
await conn.execute(
- "UPDATE cubepi_threads SET pending_request = $2::jsonb, "
+ "UPDATE cubepi_threads "
+ "SET pending_request = $2::jsonb, run_id = $3, "
"updated_at = now() WHERE thread_id = $1",
thread_id,
payload,
+ run_id,
)
async def load_pending_request(self, thread_id: str):
@@ -251,3 +268,17 @@ class PostgresCheckpointer:
if isinstance(raw, str): # pragma: no cover — codec-dependent
return HitlRequest.model_validate_json(raw)
return HitlRequest.model_validate(raw)
+
+ async def load_pending_run_id(self, thread_id: str) -> str | None:
+ """Return just the run_id stored alongside the pending request.
+
+ Returns None when the thread is unknown, has no pending request, or
+ was written by a pre-v3 host (legacy rows have run_id NULL).
+ """
+ assert self._pool is not None
+ async with self._pool.acquire() as conn:
+ row = await conn.fetchrow(
+ "SELECT run_id FROM cubepi_threads WHERE thread_id = $1",
+ thread_id,
+ )
+ return row["run_id"] if row is not None else None
diff --git a/cubepi/checkpointer/postgres/models.py b/cubepi/checkpointer/postgres/models.py
index 66f1b32..8eb448b 100644
--- a/cubepi/checkpointer/postgres/models.py
+++ b/cubepi/checkpointer/postgres/models.py
@@ -15,7 +15,7 @@ import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
-EXPECTED_SCHEMA_VERSION = 2
+EXPECTED_SCHEMA_VERSION = 3
PARTITION_COUNT = 64
cubepi_metadata = sa.MetaData()
@@ -45,6 +45,15 @@ class CubepiThread(CubepiBase):
nullable=True,
server_default=sa.text("NULL"),
)
+ # v3: host-side run identifier (e.g. cubebox run_id) persisted alongside
+ # pending_request so a worker that recovers after crash can map the paused
+ # HITL back to the run that produced it. Written atomically with
+ # pending_request via save_pending_request(..., run_id=...).
+ run_id: Mapped[str | None] = mapped_column(
+ sa.Text,
+ nullable=True,
+ server_default=sa.text("NULL"),
+ )
created_at: Mapped[_dt.datetime] = mapped_column(
sa.TIMESTAMP(timezone=True),
nullable=False,
diff --git a/cubepi/checkpointer/sqlite.py b/cubepi/checkpointer/sqlite.py
index 632093d..c904305 100644
--- a/cubepi/checkpointer/sqlite.py
+++ b/cubepi/checkpointer/sqlite.py
@@ -35,9 +35,19 @@ class SQLiteCheckpointer:
"CREATE TABLE IF NOT EXISTS thread_pending_request ("
" thread_id TEXT PRIMARY KEY,"
" request_json TEXT NOT NULL,"
+ " run_id TEXT,"
" created_at REAL NOT NULL DEFAULT (julianday('now'))"
")"
)
+ # One-shot migration: older DBs (created before run_id existed) have
+ # the table without the run_id column. SQLite has no schema_version
+ # gate, so we ALTER inline when it's missing.
+ cur = await self._db.execute("PRAGMA table_info(thread_pending_request)")
+ cols = {row[1] for row in await cur.fetchall()}
+ if "run_id" not in cols:
+ await self._db.execute(
+ "ALTER TABLE thread_pending_request ADD COLUMN run_id TEXT"
+ )
await self._db.commit()
return self
@@ -105,20 +115,28 @@ class SQLiteCheckpointer:
)
await self._db.commit()
- async def save_pending_request(self, thread_id: str, request: Any) -> None:
+ async def save_pending_request(
+ self,
+ thread_id: str,
+ request: Any,
+ *,
+ run_id: str | None = None,
+ ) -> None:
assert self._db is not None
async with self._lock:
if request is None:
+ # Clearing pending implicitly clears the associated run_id.
await self._db.execute(
"DELETE FROM thread_pending_request WHERE thread_id = ?",
(thread_id,),
)
else:
payload = request.model_dump_json()
+ # Single statement writes pending + run_id atomically.
await self._db.execute(
"INSERT OR REPLACE INTO thread_pending_request "
- "(thread_id, request_json) VALUES (?, ?)",
- (thread_id, payload),
+ "(thread_id, request_json, run_id) VALUES (?, ?, ?)",
+ (thread_id, payload, run_id),
)
await self._db.commit()
@@ -134,6 +152,16 @@ class SQLiteCheckpointer:
row = await cursor.fetchone()
return HitlRequest.model_validate_json(row[0]) if row else None
+ async def load_pending_run_id(self, thread_id: str) -> str | None:
+ assert self._db is not None
+ async with self._lock:
+ cursor = await self._db.execute(
+ "SELECT run_id FROM thread_pending_request WHERE thread_id = ?",
+ (thread_id,),
+ )
+ row = await cursor.fetchone()
+ return row[0] if row else None
+
def _serialize_message(msg: Any) -> str:
if hasattr(msg, "model_dump"):
diff --git a/tests/checkpointer/test_mysql.py b/tests/checkpointer/test_mysql.py
index 7ce2e5f..183b120 100644
--- a/tests/checkpointer/test_mysql.py
+++ b/tests/checkpointer/test_mysql.py
@@ -36,7 +36,7 @@ def test_models_import() -> None:
cubepi_metadata,
)
- assert EXPECTED_SCHEMA_VERSION == 2
+ assert EXPECTED_SCHEMA_VERSION == 3
assert PARTITION_COUNT == 64
assert CubepiThread.__tablename__ == "cubepi_threads"
assert CubepiMessage.__tablename__ == "cubepi_messages"
@@ -221,6 +221,14 @@ async def _setup_schema(dsn: str) -> None:
REFERENCES cubepi_threads (thread_id)
) ENGINE=InnoDB
""")
+ # Bring cubepi_threads up to the v3 shape via the public helpers.
+ from cubepi.checkpointer.mysql.alembic_helpers import (
+ add_pending_request_column_op,
+ add_run_id_column_op,
+ )
+
+ await cur.execute(add_pending_request_column_op())
+ await cur.execute(add_run_id_column_op())
await cur.execute(
"""
CREATE TABLE cubepi_messages (
@@ -370,7 +378,7 @@ async def test_version_mismatch_raises(clean_mysql_db) -> None:
with pytest.raises(CubepiSchemaMismatch) as exc_info:
async with MySQLCheckpointer(clean_mysql_db):
pass
- assert exc_info.value.expected == 2
+ assert exc_info.value.expected == 3
assert exc_info.value.actual == 999
diff --git a/tests/checkpointer/test_mysql_pending_request.py b/tests/checkpointer/test_mysql_pending_request.py
index 9d94870..638fa3b 100644
--- a/tests/checkpointer/test_mysql_pending_request.py
+++ b/tests/checkpointer/test_mysql_pending_request.py
@@ -4,6 +4,7 @@ import pytest
from cubepi.checkpointer.mysql import MySQLCheckpointer
from cubepi.checkpointer.mysql.alembic_helpers import (
add_pending_request_column_op,
+ add_run_id_column_op,
messages_partition_clause,
write_schema_version_op,
)
@@ -29,8 +30,9 @@ async def _setup_schema_v2(dsn: str) -> None:
REFERENCES cubepi_threads (thread_id)
) ENGINE=InnoDB
""")
- # v2 column add
+ # v2 + v3 column adds
await cur.execute(add_pending_request_column_op())
+ await cur.execute(add_run_id_column_op())
await cur.execute(
"""
CREATE TABLE cubepi_messages (
diff --git a/tests/checkpointer/test_postgres.py b/tests/checkpointer/test_postgres.py
index d1aa4aa..f9dd308 100644
--- a/tests/checkpointer/test_postgres.py
+++ b/tests/checkpointer/test_postgres.py
@@ -17,7 +17,7 @@ def test_models_import() -> None:
cubepi_metadata,
)
- assert EXPECTED_SCHEMA_VERSION == 2
+ assert EXPECTED_SCHEMA_VERSION == 3
assert PARTITION_COUNT == 64
# All three model classes are reachable via the public model module
assert CubepiThread.__tablename__ == "cubepi_threads"
@@ -200,10 +200,15 @@ async def _setup_schema(dsn: str) -> None:
) PARTITION BY HASH (thread_id);
""")
from cubepi.checkpointer.postgres.alembic_helpers import (
+ add_pending_request_column_op,
+ add_run_id_column_op,
create_message_partitions_op,
write_schema_version_op,
)
+ # Bring cubepi_threads up to the v3 shape (pending_request + run_id).
+ await conn.execute(add_pending_request_column_op())
+ await conn.execute(add_run_id_column_op())
await conn.execute(create_message_partitions_op())
await conn.execute("""
CREATE INDEX ix_cubepi_messages_metadata_gin
@@ -322,7 +327,7 @@ async def test_version_mismatch_raises(clean_db) -> None:
with pytest.raises(CubepiSchemaMismatch) as exc_info:
async with PostgresCheckpointer(clean_db):
pass
- assert exc_info.value.expected == 2
+ assert exc_info.value.expected == 3
assert exc_info.value.actual == 999
diff --git a/tests/checkpointer/test_postgres_pending_request.py b/tests/checkpointer/test_postgres_pending_request.py
index 3685043..12b610b 100644
--- a/tests/checkpointer/test_postgres_pending_request.py
+++ b/tests/checkpointer/test_postgres_pending_request.py
@@ -4,6 +4,7 @@ import pytest
from cubepi.checkpointer.postgres import PostgresCheckpointer
from cubepi.checkpointer.postgres.alembic_helpers import (
add_pending_request_column_op,
+ add_run_id_column_op,
create_message_partitions_op,
write_schema_version_op,
)
@@ -11,7 +12,10 @@ from cubepi.hitl.types import ApproveRequest, HitlRequest
async def _setup_schema_v2(dsn: str) -> None:
- """Bootstrap a v2 schema in a fresh DB (mirrors test_postgres.py::_setup_schema)."""
+ """Bootstrap the current cubepi schema in a fresh DB (now v3; legacy name kept).
+
+ Adds both the v2 pending_request column and the v3 run_id column so the
+ HITL pending tests can exercise save_pending_request(... run_id=...)."""
conn = await asyncpg.connect(dsn)
try:
await conn.execute("""
@@ -24,8 +28,9 @@ async def _setup_schema_v2(dsn: str) -> None:
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
""")
- # v2 column add
+ # v2 + v3 column adds
await conn.execute(add_pending_request_column_op())
+ await conn.execute(add_run_id_column_op())
await conn.execute("""
CREATE TABLE cubepi_messages (
thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) ON DELETE CASCADE,
diff --git a/tests/checkpointer/test_postgres_schema_version_v3.py b/tests/checkpointer/test_postgres_schema_version_v3.py
new file mode 100644
index 0000000..396f630
--- /dev/null
+++ b/tests/checkpointer/test_postgres_schema_version_v3.py
@@ -0,0 +1,64 @@
+"""Bumping EXPECTED_SCHEMA_VERSION to 3: a v2 database must be refused
+with a clear, actionable error so operators know they need to apply the
+host-side v2→v3 alembic migration."""
+
+from __future__ import annotations
+
+import asyncpg
+import pytest
+
+from cubepi.checkpointer.postgres import PostgresCheckpointer
+from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch
+
+
+async def test_postgres_v2_database_refused_with_actionable_error(clean_db) -> None:
+ conn = await asyncpg.connect(clean_db)
+ try:
+ await conn.execute(
+ "CREATE TABLE cubepi_schema_version (version INTEGER PRIMARY KEY);"
+ )
+ await conn.execute("INSERT INTO cubepi_schema_version (version) VALUES (2);")
+ finally:
+ await conn.close()
+
+ with pytest.raises(CubepiSchemaMismatch) as ei:
+ async with PostgresCheckpointer(clean_db):
+ pass
+
+ msg = str(ei.value)
+ assert "expected 3" in msg or "expected=3" in msg
+ assert "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()
+
+
+async def test_mysql_v2_database_refused_with_actionable_error(clean_mysql_db) -> None:
+ """Same policy for MySQL (parallel to the Postgres test above)."""
+ import aiomysql
+
+ from cubepi.checkpointer.mysql import MySQLCheckpointer
+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn
+ from cubepi.checkpointer.mysql.exceptions import (
+ CubepiSchemaMismatch as MysqlMismatch,
+ )
+
+ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))
+ try:
+ async with conn.cursor() as cur:
+ await cur.execute(
+ "CREATE TABLE cubepi_schema_version (version INT PRIMARY KEY) ENGINE=InnoDB"
+ )
+ await cur.execute("INSERT INTO cubepi_schema_version (version) VALUES (2)")
+ finally:
+ await conn.ensure_closed()
+
+ with pytest.raises(MysqlMismatch) as ei:
+ async with MySQLCheckpointer(clean_mysql_db):
+ pass
+
+ msg = str(ei.value)
+ assert "expected 3" in msg or "expected=3" in msg
+ assert "actual 2" in msg or "actual=2" in msg
+ assert "alembic" in msg.lower()
diff --git a/tests/checkpointer/test_save_pending_request_run_id.py b/tests/checkpointer/test_save_pending_request_run_id.py
new file mode 100644
index 0000000..bc764ec
--- /dev/null
+++ b/tests/checkpointer/test_save_pending_request_run_id.py
@@ -0,0 +1,327 @@
+"""Cross-backend tests for ``save_pending_request(request, run_id=...)``
+and ``load_pending_run_id`` — the run_id slot persisted next to a HITL
+pending request, used by host applications (e.g. cubebox) to recover the
+paused run after worker death.
+
+Postgres + MySQL tests reuse the v3 schema setup helpers (the v2 setup
++ the new run_id column add); Memory and SQLite are pure-Python.
+"""
+
+from __future__ import annotations
+
+import tempfile
+from typing import Any
+
+import pytest
+
+from cubepi.checkpointer.memory import MemoryCheckpointer
+from cubepi.checkpointer.sqlite import SQLiteCheckpointer
+from cubepi.hitl.types import ApproveRequest, HitlRequest
+
+
+def _req(thread_id: str = "t-1", qid: str = "tc-1") -> HitlRequest:
+ return HitlRequest(
+ question_id=qid,
+ thread_id=thread_id,
+ payload=ApproveRequest(tool_name="bash", tool_call_id=qid, args={"cmd": "ls"}),
+ created_at=0.0,
+ timeout_seconds=30.0,
+ )
+
+
+# ----------------------------- Memory --------------------------------------
+
+
+async def test_memory_save_with_run_id_roundtrip():
+ cp = MemoryCheckpointer()
+ await cp.save_pending_request("t-1", _req(), run_id="r-1")
+ assert (await cp.load_pending_request("t-1")) == _req()
+ assert (await cp.load_pending_run_id("t-1")) == "r-1"
+
+
+async def test_memory_legacy_save_without_run_id():
+ cp = MemoryCheckpointer()
+ await cp.save_pending_request("t-1", _req())
+ assert (await cp.load_pending_request("t-1")) == _req()
+ assert (await cp.load_pending_run_id("t-1")) is None
+
+
+async def test_memory_clear_clears_both_pending_and_run_id():
+ cp = MemoryCheckpointer()
+ await cp.save_pending_request("t-1", _req(), run_id="r-1")
+ await cp.save_pending_request("t-1", None)
+ assert (await cp.load_pending_request("t-1")) is None
+ assert (await cp.load_pending_run_id("t-1")) is None
+
+
+async def test_memory_load_pending_run_id_missing_thread():
+ cp = MemoryCheckpointer()
+ assert (await cp.load_pending_run_id("never-existed")) is None
+
+
+# ----------------------------- SQLite --------------------------------------
+
+
+async def sqlite_cp():
+ with tempfile.NamedTemporaryFile(suffix=".db") as f:
+ async with SQLiteCheckpointer(f.name) as cp:
+ yield cp
+
+
+async def test_sqlite_save_with_run_id_roundtrip(sqlite_cp):
+ await sqlite_cp.save_pending_request("t-1", _req(), run_id="r-1")
+ assert (await sqlite_cp.load_pending_request("t-1")) == _req()
+ assert (await sqlite_cp.load_pending_run_id("t-1")) == "r-1"
+
+
+async def test_sqlite_legacy_save_without_run_id(sqlite_cp):
+ await sqlite_cp.save_pending_request("t-1", _req())
+ assert (await sqlite_cp.load_pending_run_id("t-1")) is None
+
+
+async def test_sqlite_clear_clears_both_pending_and_run_id(sqlite_cp):
+ await sqlite_cp.save_pending_request("t-1", _req(), run_id="r-1")
+ await sqlite_cp.save_pending_request("t-1", None)
+ assert (await sqlite_cp.load_pending_request("t-1")) is None
+ assert (await sqlite_cp.load_pending_run_id("t-1")) is None
+
+
+async def test_sqlite_load_pending_run_id_missing_thread(sqlite_cp):
+ assert (await sqlite_cp.load_pending_run_id("never-existed")) is None
+
+
+async def test_sqlite_migration_from_v2_table_adds_run_id_column(tmp_path):
+ """Existing SQLite DBs (no run_id column) get the column added on __aenter__.
+
+ Simulates an upgrade: bootstrap a v2-style ``thread_pending_request`` table
+ without the run_id column, then open with the new SQLiteCheckpointer and
+ confirm the column exists + load_pending_run_id returns None for legacy rows.
+ """
+ import aiosqlite
+
+ db_path = str(tmp_path / "legacy.db")
+ conn = await aiosqlite.connect(db_path)
+ try:
+ await conn.execute(
+ "CREATE TABLE thread_pending_request ("
+ " thread_id TEXT PRIMARY KEY,"
+ " request_json TEXT NOT NULL,"
+ " created_at REAL NOT NULL DEFAULT (julianday('now'))"
+ ")"
+ )
+ # Insert a legacy row to confirm load_pending_run_id returns None for it.
+ await conn.execute(
+ "INSERT INTO thread_pending_request (thread_id, request_json) VALUES (?, ?)",
+ ("t-legacy", _req(qid="legacy-q").model_dump_json()),
+ )
+ await conn.commit()
+ finally:
+ await conn.close()
+
+ async with SQLiteCheckpointer(db_path) as cp:
+ # Column should now exist on the table.
+ cur = await cp._db.execute("PRAGMA table_info(thread_pending_request)")
+ cols = {row[1] for row in await cur.fetchall()}
+ assert "run_id" in cols
+ # Legacy row keeps its pending; run_id is None.
+ loaded = await cp.load_pending_request("t-legacy")
+ assert loaded is not None
+ assert (await cp.load_pending_run_id("t-legacy")) is None
+
+
+# ----------------------------- Postgres ------------------------------------
+
+
+async def _setup_pg_schema_v3(dsn: str) -> None:
+ """Bootstrap a v3 schema in a fresh Postgres DB."""
+ import asyncpg
+
+ from cubepi.checkpointer.postgres.alembic_helpers import (
+ add_pending_request_column_op,
+ add_run_id_column_op,
+ create_message_partitions_op,
+ write_schema_version_op,
+ )
+
+ conn = await asyncpg.connect(dsn)
+ try:
+ await conn.execute("""
+ CREATE TABLE cubepi_threads (
+ thread_id TEXT PRIMARY KEY,
+ parent_thread_id TEXT NULL REFERENCES cubepi_threads(thread_id),
+ forked_at_seq BIGINT NULL,
+ extra JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ """)
+ await conn.execute(add_pending_request_column_op())
+ await conn.execute(add_run_id_column_op())
+ await conn.execute("""
+ CREATE TABLE cubepi_messages (
+ thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) ON DELETE CASCADE,
+ seq BIGINT NOT NULL,
+ role TEXT NOT NULL,
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
+ payload BYTEA NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (thread_id, seq)
+ ) PARTITION BY HASH (thread_id);
+ """)
+ await conn.execute(create_message_partitions_op())
+ await conn.execute("""
+ CREATE INDEX ix_cubepi_messages_metadata_gin
+ ON cubepi_messages USING GIN (metadata jsonb_path_ops);
+ """)
+ await conn.execute("""
+ CREATE TABLE cubepi_schema_version (version INTEGER PRIMARY KEY);
+ """)
+ await conn.execute(write_schema_version_op())
+ finally:
+ await conn.close()
+
+
+async def test_postgres_save_with_run_id_roundtrip(clean_db) -> None:
+ from cubepi.checkpointer.postgres import PostgresCheckpointer
+
+ await _setup_pg_schema_v3(clean_db)
+ async with PostgresCheckpointer(clean_db) as cp:
+ await cp.save_pending_request("t-1", _req(), run_id="r-1")
+ assert (await cp.load_pending_request("t-1")) == _req()
+ assert (await cp.load_pending_run_id("t-1")) == "r-1"
+
+
+async def test_postgres_legacy_save_without_run_id(clean_db) -> None:
+ from cubepi.checkpointer.postgres import PostgresCheckpointer
+
+ await _setup_pg_schema_v3(clean_db)
+ async with PostgresCheckpointer(clean_db) as cp:
+ await cp.save_pending_request("t-1", _req())
+ assert (await cp.load_pending_run_id("t-1")) is None
+
+
+async def test_postgres_clear_clears_both_pending_and_run_id(clean_db) -> None:
+ from cubepi.checkpointer.postgres import PostgresCheckpointer
+
+ await _setup_pg_schema_v3(clean_db)
+ async with PostgresCheckpointer(clean_db) as cp:
+ await cp.save_pending_request("t-1", _req(), run_id="r-1")
+ await cp.save_pending_request("t-1", None)
+ assert (await cp.load_pending_request("t-1")) is None
+ assert (await cp.load_pending_run_id("t-1")) is None
+
+
+async def test_postgres_load_pending_run_id_missing_thread(clean_db) -> None:
+ from cubepi.checkpointer.postgres import PostgresCheckpointer
+
+ await _setup_pg_schema_v3(clean_db)
+ async with PostgresCheckpointer(clean_db) as cp:
+ assert (await cp.load_pending_run_id("never-existed")) is None
+
+
+# ----------------------------- MySQL ---------------------------------------
+
+
+async def _setup_mysql_schema_v3(dsn: str) -> None:
+ import aiomysql
+
+ from cubepi.checkpointer.mysql.alembic_helpers import (
+ add_pending_request_column_op,
+ add_run_id_column_op,
+ messages_partition_clause,
+ write_schema_version_op,
+ )
+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn
+
+ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(dsn))
+ try:
+ async with conn.cursor() as cur:
+ await cur.execute("""
+ CREATE TABLE cubepi_threads (
+ thread_id VARCHAR(255) COLLATE utf8mb4_bin PRIMARY KEY,
+ parent_thread_id VARCHAR(255) COLLATE utf8mb4_bin NULL,
+ forked_at_seq BIGINT NULL,
+ extra JSON NOT NULL DEFAULT (JSON_OBJECT()),
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
+ ON UPDATE CURRENT_TIMESTAMP,
+ CONSTRAINT fk_parent FOREIGN KEY (parent_thread_id)
+ REFERENCES cubepi_threads (thread_id)
+ ) ENGINE=InnoDB
+ """)
+ await cur.execute(add_pending_request_column_op())
+ await cur.execute(add_run_id_column_op())
+ await cur.execute(
+ """
+ CREATE TABLE cubepi_messages (
+ thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,
+ seq BIGINT NOT NULL,
+ role VARCHAR(32) NOT NULL,
+ metadata JSON NOT NULL DEFAULT (JSON_OBJECT()),
+ payload LONGBLOB NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (thread_id, seq)
+ ) ENGINE=InnoDB """
+ + messages_partition_clause()
+ )
+ await cur.execute("""
+ CREATE TABLE cubepi_schema_version (
+ version INT PRIMARY KEY
+ ) ENGINE=InnoDB
+ """)
+ for stmt in write_schema_version_op().split(";"):
+ if stmt.strip():
+ await cur.execute(stmt)
+ finally:
+ await conn.ensure_closed()
+
+
+async def test_mysql_save_with_run_id_roundtrip(clean_mysql_db) -> None:
+ from cubepi.checkpointer.mysql import MySQLCheckpointer
+
+ await _setup_mysql_schema_v3(clean_mysql_db)
+ async with MySQLCheckpointer(clean_mysql_db) as cp:
+ await cp.save_pending_request("t-1", _req(), run_id="r-1")
+ assert (await cp.load_pending_request("t-1")) == _req()
+ assert (await cp.load_pending_run_id("t-1")) == "r-1"
+
+
+async def test_mysql_legacy_save_without_run_id(clean_mysql_db) -> None:
+ from cubepi.checkpointer.mysql import MySQLCheckpointer
+
+ await _setup_mysql_schema_v3(clean_mysql_db)
+ async with MySQLCheckpointer(clean_mysql_db) as cp:
+ await cp.save_pending_request("t-1", _req())
+ assert (await cp.load_pending_run_id("t-1")) is None
+
+
+async def test_mysql_clear_clears_both_pending_and_run_id(clean_mysql_db) -> None:
+ from cubepi.checkpointer.mysql import MySQLCheckpointer
+
+ await _setup_mysql_schema_v3(clean_mysql_db)
+ async with MySQLCheckpointer(clean_mysql_db) as cp:
+ await cp.save_pending_request("t-1", _req(), run_id="r-1")
+ await cp.save_pending_request("t-1", None)
+ assert (await cp.load_pending_request("t-1")) is None
+ assert (await cp.load_pending_run_id("t-1")) is None
+
+
+async def test_mysql_load_pending_run_id_missing_thread(clean_mysql_db) -> None:
+ from cubepi.checkpointer.mysql import MySQLCheckpointer
+
+ await _setup_mysql_schema_v3(clean_mysql_db)
+ async with MySQLCheckpointer(clean_mysql_db) as cp:
+ assert (await cp.load_pending_run_id("never-existed")) is None
+
+
+# Suppress unused import warning for the typing import in scaffolding.
+_unused: Any = None