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(mysql): schema v3→v4 — add run_id column + cubepi_runs table
xf gong99c77379c396
diff --git a/cubepi/checkpointer/mysql/alembic_helpers.py b/cubepi/checkpointer/mysql/alembic_helpers.pyindex ef33894..15c241d 100644--- a/cubepi/checkpointer/mysql/alembic_helpers.py+++ b/cubepi/checkpointer/mysql/alembic_helpers.py@@ -45,6 +45,90 @@ def add_run_id_column_op() -> str:return "ALTER TABLE cubepi_threads ADD COLUMN run_id VARCHAR(64) NULL"+def runs_partition_clause() -> str:+ """Return the KEY-partition clause for the cubepi_runs CREATE TABLE.++ Mirrors ``messages_partition_clause()``: KEY-partitioning the runs+ table by thread_id keeps each run's row colocated with its messages+ on the same partition shard. KEY (not HASH) because thread_id is a+ VARCHAR.+ """+ return f"PARTITION BY KEY (thread_id) PARTITIONS {PARTITION_COUNT}"+++def add_messages_run_id_column_op() -> str:+ """Return SQL adding the v4 `run_id` column + composite index to+ cubepi_messages.++ Call inside the host's alembic v3→v4 upgrade() via op.execute(). The+ helper returns two ';'-separated statements (ALTER then CREATE INDEX);+ MySQL/pymysql executes a single statement per call, so split before+ executing::++ for stmt in add_messages_run_id_column_op().split(";"):+ if stmt.strip():+ op.execute(stmt)++ MySQL does not support IF NOT EXISTS for ADD COLUMN; guard with a+ schema check in the alembic migration if idempotence is required.+ """+ return (+ "ALTER TABLE cubepi_messages ADD COLUMN run_id VARCHAR(255) NULL; "+ "CREATE INDEX ix_cubepi_messages_thread_run "+ "ON cubepi_messages (thread_id, run_id);"+ )+++def create_runs_table_op() -> str:+ """Return SQL creating the partitioned ``cubepi_runs`` parent table.++ Call inside the host's alembic v3→v4 upgrade() via op.execute(). The+ returned statement includes the KEY-partition clause inline. NO FK to+ ``cubepi_threads`` — MySQL forbids FKs on partitioned tables.+ """+ return (+ "CREATE TABLE cubepi_runs ("+ " thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,"+ " run_id VARCHAR(255) NOT NULL,"+ " claimed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,"+ " completed_at TIMESTAMP NULL,"+ " completion_seq BIGINT NULL,"+ " PRIMARY KEY (thread_id, run_id),"+ " KEY ix_cubepi_runs_thread_seq (thread_id, completion_seq)"+ ") ENGINE=InnoDB " + runs_partition_clause()+ )+++def create_runs_partitions_op() -> str:+ """Return SQL extending the runs table with KEY partitions.++ Provided for symmetry with the Postgres helper of the same name.+ For MySQL, partitions are declared inline by ``create_runs_table_op()``+ (the KEY clause specifies the partition count). This helper returns+ only the partition clause for callers that want to attach it+ separately, e.g. via ALTER.+ """+ return runs_partition_clause()+++def upgrade_v3_to_v4_op() -> str:+ """Return SQL applying the v3→v4 schema changes.++ Adds the ``run_id`` column + composite index to ``cubepi_messages``+ and creates the partitioned ``cubepi_runs`` table. Hosts must also+ bump ``cubepi_schema_version`` via ``write_schema_version_op()``+ (EXPECTED_SCHEMA_VERSION is now 4).++ Returns multiple ';'-separated statements; MySQL/pymysql executes one+ per call, so split before executing::++ for stmt in upgrade_v3_to_v4_op().split(";"):+ if stmt.strip():+ op.execute(stmt)+ """+ return f"{add_messages_run_id_column_op()} {create_runs_table_op()};"++def write_schema_version_op() -> str:"""Return SQL setting cubepi_schema_version to the current version.diff --git a/cubepi/checkpointer/mysql/models.py b/cubepi/checkpointer/mysql/models.pyindex 2fc3462..f666d53 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 = 3+EXPECTED_SCHEMA_VERSION = 4PARTITION_COUNT = 64cubepi_metadata = sa.MetaData()@@ -73,7 +73,10 @@ class CubepiThread(CubepiBase):class CubepiMessage(CubepiBase):__tablename__ = "cubepi_messages"- __table_args__ = {"mysql_engine": "InnoDB"}+ __table_args__ = (+ sa.Index("ix_cubepi_messages_thread_run", "thread_id", "run_id"),+ {"mysql_engine": "InnoDB"},+ )thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)seq: Mapped[int] = mapped_column(sa.BigInteger, primary_key=True)@@ -87,6 +90,14 @@ class CubepiMessage(CubepiBase):server_default=sa.text("(JSON_OBJECT())"),)payload: Mapped[bytes] = mapped_column(LONGBLOB, nullable=False)+ # v4: opaque host-side run identifier stamped on each message. Lets+ # fork/snapshot include only messages from completed runs. VARCHAR(255)+ # to match the cubepi_messages indexing convention (thread_id is also+ # VARCHAR(255) — keeps the composite index cardinality consistent).+ run_id: Mapped[str | None] = mapped_column(+ VARCHAR(255),+ nullable=True,+ )created_at: Mapped[_dt.datetime] = mapped_column(sa.TIMESTAMP,nullable=False,@@ -94,6 +105,36 @@ class CubepiMessage(CubepiBase):)+class CubepiRun(CubepiBase):+ """v4 per-run lifecycle row.++ Primary key (thread_id, run_id). KEY-partitioned by thread_id to match+ cubepi_messages. NO FK to cubepi_threads — MySQL forbids FKs on+ partitioned tables. The partition clause cannot be expressed in+ SQLAlchemy declarative and lives in+ ``alembic_helpers.runs_partition_clause()``.+ """++ __tablename__ = "cubepi_runs"+ __table_args__ = (+ sa.Index("ix_cubepi_runs_thread_seq", "thread_id", "completion_seq"),+ {"mysql_engine": "InnoDB"},+ )++ thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)+ run_id: Mapped[str] = mapped_column(VARCHAR(255), primary_key=True)+ claimed_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP,+ nullable=False,+ server_default=sa.text("CURRENT_TIMESTAMP"),+ )+ completed_at: Mapped[_dt.datetime | None] = mapped_column(+ sa.TIMESTAMP,+ nullable=True,+ )+ completion_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)++class CubepiSchemaVersion(CubepiBase):__tablename__ = "cubepi_schema_version"__table_args__ = {"mysql_engine": "InnoDB"}diff --git a/tests/checkpointer/conftest.py b/tests/checkpointer/conftest.pyindex a06c431..da5692b 100644--- a/tests/checkpointer/conftest.py+++ b/tests/checkpointer/conftest.py@@ -129,3 +129,12 @@ async def clean_mysql_db(mysql_dsn: str, _mysql_available: bool):await cur.execute(f"DROP DATABASE IF EXISTS `{db_name}`")finally:await admin.ensure_closed()+++@pytest_asyncio.fixture+async def mysql_v4_dsn(clean_mysql_db: str):+ """Fresh MySQL DB with the v4 cubepi schema fully built."""+ from tests.checkpointer.test_mysql import _setup_schema as _setup_mysql_schema++ await _setup_mysql_schema(clean_mysql_db)+ yield clean_mysql_dbdiff --git a/tests/checkpointer/test_mysql.py b/tests/checkpointer/test_mysql.pyindex 2caea0c..f2c5fee 100644--- a/tests/checkpointer/test_mysql.py+++ b/tests/checkpointer/test_mysql.py@@ -66,10 +66,16 @@ def test_messages_has_no_foreign_keys() -> None:def test_messages_has_no_metadata_index() -> None:+ """Only the v4 (thread_id, run_id) composite index is allowed.++ The MySQL backend never indexes the JSON ``metadata`` column (Postgres+ has a GIN index there; MySQL has no equivalent for the host-app cost).+ """from cubepi.checkpointer.mysql.models import cubepi_metadatamsgs = cubepi_metadata.tables["cubepi_messages"]- assert msgs.indexes == set()+ idx_names = {idx.name for idx in msgs.indexes}+ assert idx_names == {"ix_cubepi_messages_thread_run"}def test_messages_partition_clause() -> None:@@ -225,6 +231,7 @@ async def _setup_schema(dsn: str) -> None:from cubepi.checkpointer.mysql.alembic_helpers import (add_pending_request_column_op,add_run_id_column_op,+ upgrade_v3_to_v4_op,)await cur.execute(add_pending_request_column_op())@@ -247,6 +254,10 @@ async def _setup_schema(dsn: str) -> None:version INT PRIMARY KEY) ENGINE=InnoDB""")+ # v3 → v4: run_id on cubepi_messages + cubepi_runs partitioned table.+ for stmt in upgrade_v3_to_v4_op().split(";"):+ if stmt.strip():+ await cur.execute(stmt)for stmt in write_schema_version_op().split(";"):if stmt.strip():await cur.execute(stmt)@@ -378,7 +389,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 == 3+ assert exc_info.value.expected == 4assert exc_info.value.actual == 999diff --git a/tests/checkpointer/test_mysql_schema.py b/tests/checkpointer/test_mysql_schema.pynew file mode 100644index 0000000..aad1892--- /dev/null+++ b/tests/checkpointer/test_mysql_schema.py@@ -0,0 +1,56 @@+"""MySQLCheckpointer v4 schema tests — mirrors test_postgres_schema.py."""++import aiomysql+import pytest++from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+++def test_expected_schema_version_is_4() -> None:+ assert EXPECTED_SCHEMA_VERSION == 4+++async def test_cubepi_runs_table_present(mysql_v4_dsn) -> None:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ cfg = _parse_dsn(mysql_v4_dsn)+ conn = await aiomysql.connect(autocommit=True, **cfg)+ try:+ async with conn.cursor() as cur:+ await cur.execute(+ "SELECT column_name FROM information_schema.columns "+ "WHERE table_schema = %s AND table_name = 'cubepi_runs'",+ (cfg["db"],),+ )+ rows = await cur.fetchall()+ finally:+ await conn.ensure_closed()+ cols = {r[0].lower() for r in rows}+ assert {+ "thread_id",+ "run_id",+ "claimed_at",+ "completed_at",+ "completion_seq",+ } <= cols+++async def test_cubepi_messages_has_run_id_column(mysql_v4_dsn) -> None:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ cfg = _parse_dsn(mysql_v4_dsn)+ conn = await aiomysql.connect(autocommit=True, **cfg)+ try:+ async with conn.cursor() as cur:+ await cur.execute(+ "SELECT data_type FROM information_schema.columns "+ "WHERE table_schema = %s AND table_name = 'cubepi_messages' "+ "AND column_name = 'run_id'",+ (cfg["db"],),+ )+ row = await cur.fetchone()+ finally:+ await conn.ensure_closed()+ assert row is not None