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(hitl): pending_request storage on Postgres + MySQL (schema v2)
xf gonga8b8e9c6d358
diff --git a/cubepi/checkpointer/mysql/alembic_helpers.py b/cubepi/checkpointer/mysql/alembic_helpers.pyindex fe6efd1..db306ca 100644--- a/cubepi/checkpointer/mysql/alembic_helpers.py+++ b/cubepi/checkpointer/mysql/alembic_helpers.py@@ -20,6 +20,17 @@ def messages_partition_clause() -> str:return f"PARTITION BY KEY (thread_id) PARTITIONS {PARTITION_COUNT}"+def add_pending_request_column_op() -> str:+ """Return SQL adding the v2 `pending_request` column to cubepi_threads.++ 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)."""+ return "ALTER TABLE cubepi_threads ADD COLUMN pending_request JSON 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.pyindex 9cc9ae4..5e43985 100644--- a/cubepi/checkpointer/mysql/checkpointer.py+++ b/cubepi/checkpointer/mysql/checkpointer.py@@ -274,3 +274,54 @@ class MySQLCheckpointer:except BaseException: # pragma: no cover - defensive txn rollbackawait conn.rollback()raise++ async def save_pending_request(self, thread_id, request):+ # 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+ async with self._pool.acquire() as conn:+ await conn.begin()+ try:+ async with conn.cursor() as cur:+ await cur.execute(+ "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "ON DUPLICATE KEY UPDATE thread_id = thread_id",+ (thread_id,),+ )+ if request is None:+ await cur.execute(+ "UPDATE cubepi_threads SET pending_request = NULL, "+ "updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",+ (thread_id,),+ )+ else:+ payload = request.model_dump_json()+ await cur.execute(+ "UPDATE cubepi_threads SET pending_request = %s, "+ "updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",+ (payload, 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):+ from cubepi.hitl.types import HitlRequest++ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.cursor() as cur:+ await cur.execute(+ "SELECT pending_request FROM cubepi_threads WHERE thread_id = %s",+ (thread_id,),+ )+ row = await cur.fetchone()+ if row is None or row[0] is None:+ return None+ raw = row[0]+ # aiomysql returns JSON columns as str; tolerate already-parsed dicts (same+ # convention as the existing _parse_json helper in this module).+ if isinstance(raw, str):+ return HitlRequest.model_validate_json(raw)+ return HitlRequest.model_validate(raw)diff --git a/cubepi/checkpointer/mysql/models.py b/cubepi/checkpointer/mysql/models.pyindex 528f1e6..2025479 100644--- a/cubepi/checkpointer/mysql/models.py+++ b/cubepi/checkpointer/mysql/models.py@@ -16,7 +16,7 @@ import sqlalchemy as safrom sqlalchemy.dialects.mysql import JSON, LONGBLOB, VARCHARfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column-EXPECTED_SCHEMA_VERSION = 1+EXPECTED_SCHEMA_VERSION = 2PARTITION_COUNT = 64cubepi_metadata = sa.MetaData()@@ -44,6 +44,10 @@ class CubepiThread(CubepiBase):nullable=False,server_default=sa.text("(JSON_OBJECT())"),)+ pending_request: Mapped[dict[str, Any] | None] = mapped_column(+ sa.JSON,+ 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.pyindex 64756a8..bdf7063 100644--- a/cubepi/checkpointer/postgres/alembic_helpers.py+++ b/cubepi/checkpointer/postgres/alembic_helpers.py@@ -20,6 +20,16 @@ def create_message_partitions_op() -> str:)+def add_pending_request_column_op() -> str:+ """Return SQL adding the v2 `pending_request` column to cubepi_threads.++ 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)."""+ return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS pending_request JSONB"++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.pyindex 0fb959c..f4d2a01 100644--- a/cubepi/checkpointer/postgres/checkpointer.py+++ b/cubepi/checkpointer/postgres/checkpointer.py@@ -209,3 +209,45 @@ class PostgresCheckpointer:thread_id,json.dumps(extra),)++ async def save_pending_request(self, thread_id: str, request) -> None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.transaction():+ # Ensure thread row exists (lazy creation matches save_extra path).+ await conn.execute(+ "INSERT INTO cubepi_threads (thread_id) "+ "VALUES ($1) ON CONFLICT DO NOTHING",+ thread_id,+ )+ if request is None:+ await conn.execute(+ "UPDATE cubepi_threads SET pending_request = NULL, "+ "updated_at = now() WHERE thread_id = $1",+ thread_id,+ )+ else:+ payload = request.model_dump_json()+ await conn.execute(+ "UPDATE cubepi_threads SET pending_request = $2::jsonb, "+ "updated_at = now() WHERE thread_id = $1",+ thread_id,+ payload,+ )++ async def load_pending_request(self, thread_id: str):+ from cubepi.hitl.types import HitlRequest++ assert self._pool is not None+ async with self._pool.acquire() as conn:+ row = await conn.fetchrow(+ "SELECT pending_request 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"]+ # asyncpg returns JSONB as already-parsed dict OR str depending on codec config.+ if isinstance(raw, str):+ return HitlRequest.model_validate_json(raw)+ return HitlRequest.model_validate(raw)diff --git a/cubepi/checkpointer/postgres/models.py b/cubepi/checkpointer/postgres/models.pyindex 8ada2e5..66f1b32 100644--- a/cubepi/checkpointer/postgres/models.py+++ b/cubepi/checkpointer/postgres/models.py@@ -15,7 +15,7 @@ import sqlalchemy as safrom sqlalchemy.dialects.postgresql import JSONBfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column-EXPECTED_SCHEMA_VERSION = 1+EXPECTED_SCHEMA_VERSION = 2PARTITION_COUNT = 64cubepi_metadata = sa.MetaData()@@ -40,6 +40,11 @@ class CubepiThread(CubepiBase):nullable=False,server_default=sa.text("'{}'::jsonb"),)+ pending_request: Mapped[dict[str, Any] | None] = mapped_column(+ JSONB,+ nullable=True,+ server_default=sa.text("NULL"),+ )created_at: Mapped[_dt.datetime] = mapped_column(sa.TIMESTAMP(timezone=True),nullable=False,diff --git a/tests/checkpointer/test_mysql.py b/tests/checkpointer/test_mysql.pyindex 767f3bc..7ce2e5f 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 == 1+ assert EXPECTED_SCHEMA_VERSION == 2assert PARTITION_COUNT == 64assert CubepiThread.__tablename__ == "cubepi_threads"assert CubepiMessage.__tablename__ == "cubepi_messages"@@ -78,11 +78,13 @@ def test_messages_partition_clause() -> None:def test_write_schema_version_op_clears_stale_then_inserts() -> None:+ from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+sql = write_schema_version_op()assert "DELETE FROM cubepi_schema_version" in sql- assert "WHERE version <> 1" in sql+ assert f"WHERE version <> {EXPECTED_SCHEMA_VERSION}" in sqlassert "INSERT IGNORE INTO cubepi_schema_version" in sql- assert "VALUES (1)" in sql+ assert f"VALUES ({EXPECTED_SCHEMA_VERSION})" in sqlassert sql.index("DELETE") < sql.index("INSERT")@@ -368,7 +370,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 == 1+ assert exc_info.value.expected == 2assert exc_info.value.actual == 999diff --git a/tests/checkpointer/test_mysql_pending_request.py b/tests/checkpointer/test_mysql_pending_request.pynew file mode 100644index 0000000..9d94870--- /dev/null+++ b/tests/checkpointer/test_mysql_pending_request.py@@ -0,0 +1,118 @@+import aiomysql+import pytest++from cubepi.checkpointer.mysql import MySQLCheckpointer+from cubepi.checkpointer.mysql.alembic_helpers import (+ add_pending_request_column_op,+ messages_partition_clause,+ write_schema_version_op,+)+from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+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_mysql.py::_setup_schema)."""+ 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+ """)+ # v2 column add+ await cur.execute(add_pending_request_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()+++def _req(qid="tc-1") -> HitlRequest:+ return HitlRequest(+ question_id=qid,+ thread_id="t-1",+ payload=ApproveRequest(tool_name="bash", tool_call_id=qid, args={"cmd": "ls"}),+ created_at=0.0,+ timeout_seconds=30.0,+ )+++async def test_mysql_save_and_load_pending_request(clean_mysql_db) -> None:+ await _setup_schema_v2(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ await cp.save_pending_request("t-1", _req())+ loaded = await cp.load_pending_request("t-1")+ assert loaded == _req()+++async def test_mysql_clear_pending_request(clean_mysql_db) -> None:+ await _setup_schema_v2(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ await cp.save_pending_request("t-1", _req())+ await cp.save_pending_request("t-1", None)+ loaded = await cp.load_pending_request("t-1")+ assert loaded is None+++async def test_mysql_pending_request_creates_thread_row_lazily(clean_mysql_db) -> None:+ """save_pending_request must upsert the thread row so calling it on an unknown+ thread doesn't violate the FK constraint."""+ await _setup_schema_v2(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ await cp.save_pending_request("brand-new-thread", _req(qid="tc-x"))+ loaded = await cp.load_pending_request("brand-new-thread")+ assert loaded is not None+ assert loaded.question_id == "tc-x"+++async def test_mysql_v2_schema_version_enforced(clean_mysql_db) -> None:+ """If the host's alembic only ran v1 (schema_version=1), MySQLCheckpointer+ __aenter__ raises CubepiSchemaMismatch."""+ from cubepi.checkpointer.mysql.exceptions import CubepiSchemaMismatch++ 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 (1)")+ finally:+ await conn.ensure_closed()++ with pytest.raises(CubepiSchemaMismatch):+ async with MySQLCheckpointer(clean_mysql_db):+ passdiff --git a/tests/checkpointer/test_postgres.py b/tests/checkpointer/test_postgres.pyindex a10535f..d1aa4aa 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 == 1+ assert EXPECTED_SCHEMA_VERSION == 2assert PARTITION_COUNT == 64# All three model classes are reachable via the public model moduleassert CubepiThread.__tablename__ == "cubepi_threads"@@ -72,21 +72,23 @@ def test_create_message_partitions_op_partitions_are_zero_padded() -> None:def test_write_schema_version_op_includes_expected_version() -> None:from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op+ from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSIONsql = write_schema_version_op()assert "INSERT INTO cubepi_schema_version" in sql- assert "VALUES (1)" in sql+ assert f"VALUES ({EXPECTED_SCHEMA_VERSION})" in sqlassert "ON CONFLICT" in sqldef test_write_schema_version_op_clears_stale_rows() -> None:"""A prior version's row must be removed so _verify_schema sees the new one."""from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op+ from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSIONsql = write_schema_version_op()# Must DELETE rows whose version is not the expected one before INSERT.assert "DELETE FROM cubepi_schema_version" in sql- assert "WHERE version <> 1" in sql+ assert f"WHERE version <> {EXPECTED_SCHEMA_VERSION}" in sql# And the DELETE must come before the INSERT in the statement order.assert sql.index("DELETE") < sql.index("INSERT")@@ -320,7 +322,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 == 1+ assert exc_info.value.expected == 2assert exc_info.value.actual == 999diff --git a/tests/checkpointer/test_postgres_pending_request.py b/tests/checkpointer/test_postgres_pending_request.pynew file mode 100644index 0000000..3685043--- /dev/null+++ b/tests/checkpointer/test_postgres_pending_request.py@@ -0,0 +1,110 @@+import asyncpg+import pytest++from cubepi.checkpointer.postgres import PostgresCheckpointer+from cubepi.checkpointer.postgres.alembic_helpers import (+ add_pending_request_column_op,+ create_message_partitions_op,+ write_schema_version_op,+)+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)."""+ 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()+ );+ """)+ # v2 column add+ await conn.execute(add_pending_request_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()+++def _req(qid="tc-1") -> HitlRequest:+ return HitlRequest(+ question_id=qid,+ thread_id="t-1",+ payload=ApproveRequest(tool_name="bash", tool_call_id=qid, args={"cmd": "ls"}),+ created_at=0.0,+ timeout_seconds=30.0,+ )+++async def test_postgres_save_and_load_pending_request(clean_db) -> None:+ await _setup_schema_v2(clean_db)+ async with PostgresCheckpointer(clean_db) as cp:+ await cp.save_pending_request("t-1", _req())+ loaded = await cp.load_pending_request("t-1")+ assert loaded == _req()+++async def test_postgres_clear_pending_request(clean_db) -> None:+ await _setup_schema_v2(clean_db)+ async with PostgresCheckpointer(clean_db) as cp:+ await cp.save_pending_request("t-1", _req())+ await cp.save_pending_request("t-1", None)+ loaded = await cp.load_pending_request("t-1")+ assert loaded is None+++async def test_postgres_pending_request_creates_thread_row_lazily(clean_db) -> None:+ """save_pending_request must INSERT … ON CONFLICT DO NOTHING for the thread row,+ so calling it on an unknown thread doesn't FK-violate."""+ await _setup_schema_v2(clean_db)+ async with PostgresCheckpointer(clean_db) as cp:+ await cp.save_pending_request("brand-new-thread", _req(qid="tc-x"))+ loaded = await cp.load_pending_request("brand-new-thread")+ assert loaded is not None+ assert loaded.question_id == "tc-x"+++async def test_postgres_v2_schema_version_enforced(clean_db) -> None:+ """If the host's alembic only ran v1 (no pending_request column, schema_version=1),+ PostgresCheckpointer().__aenter__ raises CubepiSchemaMismatch."""+ from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch++ 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 (1);")+ finally:+ await conn.close()+ with pytest.raises(CubepiSchemaMismatch):+ async with PostgresCheckpointer(clean_db):+ pass