Skip to content

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

feat(postgres): schema v3→v4 — add run_id column + cubepi_runs table

xf gongfbb68300a025
diff --git a/cubepi/checkpointer/postgres/alembic_helpers.py b/cubepi/checkpointer/postgres/alembic_helpers.py
index 12ace4c..2d1234c 100644
--- a/cubepi/checkpointer/postgres/alembic_helpers.py
+++ b/cubepi/checkpointer/postgres/alembic_helpers.py
@@ -41,6 +41,58 @@ def add_run_id_column_op() -> str:
return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS run_id TEXT"
+def create_runs_partitions_op() -> str:
+ """Return SQL DDL creating all child partitions of cubepi_runs.
+
+ Call inside an alembic upgrade() via op.execute(), AFTER the parent
+ cubepi_runs partitioned table has been created. Uses the same
+ PARTITION_COUNT as cubepi_messages.
+ """
+ return "\n".join(
+ f"CREATE TABLE cubepi_runs_p{i:02d} "
+ f"PARTITION OF cubepi_runs "
+ f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i});"
+ for i in range(PARTITION_COUNT)
+ )
+
+
+def upgrade_v3_to_v4_op() -> str:
+ """Return SQL applying the v3→v4 schema changes.
+
+ Adds the `run_id` column + index to `cubepi_messages` and creates
+ the partitioned `cubepi_runs` parent table with its child
+ partitions. Hosts must also bump `cubepi_schema_version` via
+ write_schema_version_op() (EXPECTED_SCHEMA_VERSION is now 4).
+
+ Call inside the host's alembic v3→v4 upgrade() via op.execute().
+ Idempotent under repeated execution via IF NOT EXISTS guards.
+ """
+ parts = [
+ "ALTER TABLE cubepi_messages ADD COLUMN IF NOT EXISTS run_id TEXT;",
+ (
+ "CREATE INDEX IF NOT EXISTS ix_cubepi_messages_thread_run "
+ "ON cubepi_messages (thread_id, run_id);"
+ ),
+ (
+ "CREATE TABLE IF NOT EXISTS cubepi_runs ("
+ " thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) "
+ "ON DELETE CASCADE,"
+ " run_id TEXT NOT NULL,"
+ " claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(),"
+ " completed_at TIMESTAMPTZ,"
+ " completion_seq BIGINT,"
+ " PRIMARY KEY (thread_id, run_id)"
+ ") PARTITION BY HASH (thread_id);"
+ ),
+ (
+ "CREATE INDEX IF NOT EXISTS ix_cubepi_runs_thread_seq "
+ "ON cubepi_runs (thread_id, completion_seq);"
+ ),
+ create_runs_partitions_op(),
+ ]
+ return "\n".join(parts)
+
+
def write_schema_version_op() -> str:
"""Return SQL setting cubepi_schema_version to the current version.
diff --git a/cubepi/checkpointer/postgres/models.py b/cubepi/checkpointer/postgres/models.py
index 8eb448b..ac1e3b4 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 = 3
+EXPECTED_SCHEMA_VERSION = 4
PARTITION_COUNT = 64
cubepi_metadata = sa.MetaData()
@@ -75,6 +75,7 @@ class CubepiMessage(CubepiBase):
postgresql_using="gin",
postgresql_ops={"metadata": "jsonb_path_ops"},
),
+ sa.Index("ix_cubepi_messages_thread_run", "thread_id", "run_id"),
{"postgresql_partition_by": "HASH (thread_id)"},
)
@@ -95,6 +96,9 @@ class CubepiMessage(CubepiBase):
server_default=sa.text("'{}'::jsonb"),
)
payload: Mapped[bytes] = mapped_column(sa.LargeBinary, nullable=False)
+ # v4: opaque host-side run identifier stamped on each message. Lets
+ # fork/snapshot include only messages from completed runs.
+ run_id: Mapped[str | None] = mapped_column(sa.Text, nullable=True)
created_at: Mapped[_dt.datetime] = mapped_column(
sa.TIMESTAMP(timezone=True),
nullable=False,
@@ -102,6 +106,31 @@ class CubepiMessage(CubepiBase):
)
+class CubepiRun(CubepiBase):
+ __tablename__ = "cubepi_runs"
+ __table_args__ = (
+ sa.Index("ix_cubepi_runs_thread_seq", "thread_id", "completion_seq"),
+ {"postgresql_partition_by": "HASH (thread_id)"},
+ )
+ thread_id: Mapped[str] = mapped_column(
+ sa.Text,
+ sa.ForeignKey("cubepi_threads.thread_id", ondelete="CASCADE"),
+ primary_key=True,
+ )
+ run_id: Mapped[str] = mapped_column(sa.Text, primary_key=True)
+ claimed_at: Mapped[_dt.datetime] = mapped_column(
+ sa.TIMESTAMP(timezone=True),
+ nullable=False,
+ server_default=sa.text("now()"),
+ )
+ completed_at: Mapped[_dt.datetime | None] = mapped_column(
+ sa.TIMESTAMP(timezone=True), nullable=True
+ )
+ completion_seq: Mapped[int | None] = mapped_column(
+ sa.BigInteger, nullable=True
+ )
+
+
class CubepiSchemaVersion(CubepiBase):
__tablename__ = "cubepi_schema_version"
diff --git a/tests/checkpointer/conftest.py b/tests/checkpointer/conftest.py
index d6af6bb..a06c431 100644
--- a/tests/checkpointer/conftest.py
+++ b/tests/checkpointer/conftest.py
@@ -61,6 +61,15 @@ async def clean_db(pg_dsn: str, _pg_available: bool):
await admin.close()
+@pytest_asyncio.fixture
+async def pg_v4_dsn(clean_db: str):
+ """Fresh Postgres DB with the v4 cubepi schema fully built."""
+ from tests.checkpointer.test_postgres import _setup_schema as _setup_pg_schema
+
+ await _setup_pg_schema(clean_db)
+ yield clean_db
+
+
# ---------------------------------------------------------------------------
# MySQL fixtures
# ---------------------------------------------------------------------------
diff --git a/tests/checkpointer/test_mysql.py b/tests/checkpointer/test_mysql.py
index 183b120..2caea0c 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 == 3
+ assert EXPECTED_SCHEMA_VERSION == 4
assert PARTITION_COUNT == 64
assert CubepiThread.__tablename__ == "cubepi_threads"
assert CubepiMessage.__tablename__ == "cubepi_messages"
diff --git a/tests/checkpointer/test_postgres.py b/tests/checkpointer/test_postgres.py
index f9dd308..157a075 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 == 3
+ assert EXPECTED_SCHEMA_VERSION == 4
assert PARTITION_COUNT == 64
# All three model classes are reachable via the public model module
assert CubepiThread.__tablename__ == "cubepi_threads"
@@ -203,6 +203,7 @@ async def _setup_schema(dsn: str) -> None:
add_pending_request_column_op,
add_run_id_column_op,
create_message_partitions_op,
+ upgrade_v3_to_v4_op,
write_schema_version_op,
)
@@ -219,6 +220,8 @@ async def _setup_schema(dsn: str) -> None:
version INTEGER PRIMARY KEY
);
""")
+ # Apply v3→v4 (run_id on messages + cubepi_runs partitioned table).
+ await conn.execute(upgrade_v3_to_v4_op())
await conn.execute(write_schema_version_op())
finally:
await conn.close()
@@ -327,7 +330,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 == 3
+ assert exc_info.value.expected == 4
assert exc_info.value.actual == 999
diff --git a/tests/checkpointer/test_postgres_schema.py b/tests/checkpointer/test_postgres_schema.py
new file mode 100644
index 0000000..672d5e1
--- /dev/null
+++ b/tests/checkpointer/test_postgres_schema.py
@@ -0,0 +1,41 @@
+import asyncpg
+import pytest
+
+from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION
+
+
+def test_expected_schema_version_is_4():
+ assert EXPECTED_SCHEMA_VERSION == 4
+
+
+async def test_cubepi_runs_table_present(pg_v4_dsn):
+ conn = await asyncpg.connect(pg_v4_dsn)
+ try:
+ rows = await conn.fetch(
+ "SELECT column_name FROM information_schema.columns "
+ "WHERE table_name = 'cubepi_runs'"
+ )
+ cols = {r["column_name"] for r in rows}
+ assert {
+ "thread_id",
+ "run_id",
+ "claimed_at",
+ "completed_at",
+ "completion_seq",
+ } <= cols
+ finally:
+ await conn.close()
+
+
+async def test_cubepi_messages_has_run_id_column(pg_v4_dsn):
+ conn = await asyncpg.connect(pg_v4_dsn)
+ try:
+ row = await conn.fetchrow(
+ "SELECT data_type FROM information_schema.columns "
+ "WHERE table_name = 'cubepi_messages' AND column_name = 'run_id'"
+ )
+ assert row is not None
+ finally:
+ await conn.close()