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(checkpointer): add MySQLCheckpointer (#124)
Chris73f8f6c9b4af
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5cf4820..e4e84d2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -28,9 +28,22 @@ jobs:--health-interval 5s--health-timeout 5s--health-retries 10+ mysql:+ image: mysql:8.0+ env:+ MYSQL_ROOT_PASSWORD: root+ MYSQL_DATABASE: mysql+ ports:+ - 3306:3306+ options: >-+ --health-cmd "mysqladmin ping -h 127.0.0.1 -uroot -proot"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20env:CUBEPI_TEST_PG_DSN: postgresql://postgres:postgres@localhost:5432/postgres+ CUBEPI_TEST_MYSQL_DSN: mysql://root:root@localhost:3306/mysqlsteps:- uses: actions/checkout@v6diff --git a/cubepi/checkpointer/__init__.py b/cubepi/checkpointer/__init__.pyindex a149080..c2656a7 100644--- a/cubepi/checkpointer/__init__.py+++ b/cubepi/checkpointer/__init__.py@@ -11,6 +11,10 @@ def __getattr__(name: str) -> object:from cubepi.checkpointer.sqlite import SQLiteCheckpointerreturn SQLiteCheckpointer+ if name == "MySQLCheckpointer":+ from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer++ return MySQLCheckpointerraise AttributeError(f"module {__name__!r} has no attribute {name!r}")@@ -20,4 +24,5 @@ __all__ = ["MemoryCheckpointer","PostgresCheckpointer","SQLiteCheckpointer",+ "MySQLCheckpointer",]diff --git a/cubepi/checkpointer/exceptions.py b/cubepi/checkpointer/exceptions.pynew file mode 100644index 0000000..d939adf--- /dev/null+++ b/cubepi/checkpointer/exceptions.py@@ -0,0 +1,34 @@+"""Backend-agnostic schema exceptions for SQL checkpointers.++Shared by the Postgres and MySQL checkpointers so that ``except+CubepiSchemaError`` works across backends and neither backend's package+(and its driver) needs to be imported to obtain them.+"""+++class CubepiSchemaError(Exception):+ """Base class for cubepi SQL checkpointer schema errors."""+++class CubepiSchemaUninitialized(CubepiSchemaError):+ """The cubepi_schema_version table is empty or missing.++ Typically means the host application's alembic upgrade hasn't been+ run yet against this database.+ """+++class CubepiSchemaMismatch(CubepiSchemaError):+ """The DB schema version doesn't match cubepi's expected version.++ Typically means the cubepi library was upgraded but the host+ application's alembic is behind. Run a new alembic revision.+ """++ def __init__(self, *, expected: int, actual: int, hint: str = "") -> None:+ msg = f"cubepi schema mismatch: expected={expected} actual={actual}."+ if hint:+ msg += f" {hint}"+ super().__init__(msg)+ self.expected = expected+ self.actual = actualdiff --git a/cubepi/checkpointer/mysql/__init__.py b/cubepi/checkpointer/mysql/__init__.pynew file mode 100644index 0000000..7531aed--- /dev/null+++ b/cubepi/checkpointer/mysql/__init__.py@@ -0,0 +1,27 @@+"""MySQLCheckpointer package.++Exceptions are available immediately; ``MySQLCheckpointer`` and model symbols+are added below once their modules exist.+"""++from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer+from cubepi.checkpointer.mysql.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)+from cubepi.checkpointer.mysql.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ cubepi_metadata,+)++__all__ = [+ "MySQLCheckpointer",+ "CubepiSchemaError",+ "CubepiSchemaMismatch",+ "CubepiSchemaUninitialized",+ "EXPECTED_SCHEMA_VERSION",+ "PARTITION_COUNT",+ "cubepi_metadata",+]diff --git a/cubepi/checkpointer/mysql/alembic_helpers.py b/cubepi/checkpointer/mysql/alembic_helpers.pynew file mode 100644index 0000000..fe6efd1--- /dev/null+++ b/cubepi/checkpointer/mysql/alembic_helpers.py@@ -0,0 +1,42 @@+"""SQL helpers for host application alembic migrations (MySQL)."""++from cubepi.checkpointer.mysql.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+)+++def messages_partition_clause() -> str:+ """Return the KEY-partition clause for the cubepi_messages CREATE TABLE.++ Unlike Postgres (one child partition per modulus), MySQL declares all+ partitions inline. Append this to the messages table DDL, e.g.::++ op.execute("CREATE TABLE cubepi_messages (...) " + messages_partition_clause())++ KEY (not HASH) is required because thread_id is a VARCHAR; MySQL HASH+ partitioning only accepts integer expressions.+ """+ return f"PARTITION BY KEY (thread_id) PARTITIONS {PARTITION_COUNT}"+++def write_schema_version_op() -> str:+ """Return SQL setting cubepi_schema_version to the current version.++ Clears any stale rows from prior cubepi versions then inserts the current+ one. Idempotent. Call inside alembic upgrade() after CREATE TABLE+ cubepi_schema_version.++ Returns two ';'-separated statements (DELETE then INSERT). MySQL/pymysql+ executes a single statement per call, so split before executing::++ for stmt in write_schema_version_op().split(";"):+ if stmt.strip():+ op.execute(stmt)+ """+ return (+ f"DELETE FROM cubepi_schema_version "+ f"WHERE version <> {EXPECTED_SCHEMA_VERSION}; "+ f"INSERT IGNORE INTO cubepi_schema_version (version) "+ f"VALUES ({EXPECTED_SCHEMA_VERSION});"+ )diff --git a/cubepi/checkpointer/mysql/checkpointer.py b/cubepi/checkpointer/mysql/checkpointer.pynew file mode 100644index 0000000..9cc9ae4--- /dev/null+++ b/cubepi/checkpointer/mysql/checkpointer.py@@ -0,0 +1,276 @@+"""MySQLCheckpointer — Checkpointer protocol against MySQL.++Append-only message log + per-thread KV (extra). aiomysql pool + msgpack+payloads. Schema version verified on context entry. Mirrors+PostgresCheckpointer; see dev/specs/2026-05-27-mysql-checkpointer.md for the+list of deliberate MySQL divergences.+"""++from __future__ import annotations++import json+from typing import Any+from urllib.parse import unquote, urlparse++import aiomysql+import msgpack+import pymysql++from cubepi.checkpointer.base import CheckpointData+from cubepi.checkpointer.mysql.exceptions import (+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)+from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ ToolResultMessage,+ UserMessage,+)++_ER_NO_SUCH_TABLE = 1146+_ER_BAD_FIELD_ERROR = 1054+++def _role_of(msg: Message) -> str:+ if isinstance(msg, UserMessage):+ return "user"+ if isinstance(msg, AssistantMessage):+ return "assistant"+ if isinstance(msg, ToolResultMessage):+ return "tool"+ raise TypeError(f"unknown Message type: {type(msg).__name__}")+++_ROLE_TO_CLS: dict[str, type[Message]] = {+ "user": UserMessage,+ "assistant": AssistantMessage,+ "tool": ToolResultMessage,+}+++def _parse_dsn(dsn: str) -> dict[str, Any]:+ """Parse a mysql:// URL into aiomysql.create_pool kwargs."""+ u = urlparse(dsn)+ db = u.path.lstrip("/")+ return {+ "host": u.hostname or "localhost",+ "port": u.port or 3306,+ "user": unquote(u.username) if u.username else "",+ "password": unquote(u.password) if u.password else "",+ "db": db,+ }+++def _decode_json(value: Any) -> dict[str, Any]:+ """aiomysql returns JSON columns as str; tolerate already-parsed dicts."""+ if value is None:+ return {}+ if isinstance(value, str):+ return json.loads(value)+ return value+++class MySQLCheckpointer:+ """Checkpointer backed by MySQL (8.0.13+, InnoDB).++ Usage:+ cp = MySQLCheckpointer("mysql://user:pw@host:3306/db")+ async with cp:+ await cp.append(thread_id, [msg1, msg2])+ data = await cp.load(thread_id)+ await cp.save_extra(thread_id, {"k": "v"})++ Raises CubepiSchemaUninitialized / CubepiSchemaMismatch at __aenter__ if the+ DB schema isn't compatible with this cubepi version.+ """++ def __init__(+ self,+ dsn: str,+ *,+ min_pool_size: int = 1,+ max_pool_size: int = 10,+ ) -> None:+ self._cfg = _parse_dsn(dsn)+ self._min = min_pool_size+ self._max = max_pool_size+ self._pool: aiomysql.Pool | None = None++ async def __aenter__(self) -> "MySQLCheckpointer":+ self._pool = await aiomysql.create_pool(+ minsize=self._min,+ maxsize=self._max,+ autocommit=True,+ **self._cfg,+ )+ # If verification fails, __aexit__ won't run (the context was never+ # entered), so close the pool here to avoid leaking connections.+ try:+ await self._verify_schema()+ except BaseException:+ self._pool.close()+ await self._pool.wait_closed()+ self._pool = None+ raise+ return self++ async def __aexit__(self, *args: Any) -> None:+ if self._pool is not None:+ self._pool.close()+ await self._pool.wait_closed()+ self._pool = None++ async def _verify_schema(self) -> None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.cursor() as cur:+ try:+ await cur.execute(+ "SELECT version FROM cubepi_schema_version LIMIT 1"+ )+ row = await cur.fetchone()+ except pymysql.err.Error as e:+ # PyMySQL maps 1146 (ER_NO_SUCH_TABLE) to ProgrammingError but+ # 1054 (ER_BAD_FIELD_ERROR) to OperationalError, so catch the+ # common base and branch on the errno.+ code = e.args[0] if e.args else None+ if code in (_ER_NO_SUCH_TABLE, _ER_BAD_FIELD_ERROR):+ raise CubepiSchemaUninitialized(+ "cubepi tables not found or malformed. Run host "+ "application's alembic upgrade."+ ) from e+ raise # pragma: no cover - non-schema DB errors propagate+ if row is None:+ raise CubepiSchemaUninitialized(+ "cubepi_schema_version table is empty. Host alembic migration "+ "must INSERT the current version (use write_schema_version_op())."+ )+ actual = row[0]+ if actual != EXPECTED_SCHEMA_VERSION:+ raise CubepiSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=actual,+ hint="cubepi was upgraded but host alembic is behind. "+ "Generate a new revision and apply.",+ )++ async def load(self, thread_id: str) -> CheckpointData | None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.cursor() as cur:+ await cur.execute(+ "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "WHERE thread_id = %s ORDER BY seq",+ (thread_id,),+ )+ msg_rows = await cur.fetchall()+ await cur.execute(+ "SELECT extra FROM cubepi_threads WHERE thread_id = %s",+ (thread_id,),+ )+ extra_row = await cur.fetchone()++ if not msg_rows and extra_row is None:+ return None++ messages: list[Message] = []+ for _seq, role, metadata, payload in msg_rows:+ cls = _ROLE_TO_CLS.get(role)+ if cls is None:+ raise ValueError(f"unknown role in DB: {role!r}")+ data = msgpack.unpackb(bytes(payload), raw=False)+ data["metadata"] = _decode_json(metadata)+ messages.append(cls.model_validate(data))++ extra = _decode_json(extra_row[0]) if extra_row is not None else {}+ return CheckpointData(messages=messages, extra=extra)++ async def append(self, thread_id: str, messages: list[Message]) -> None:+ if not messages:+ return+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ await conn.begin()+ try:+ async with conn.cursor() as cur:+ # No-op upsert (idiomatic equivalent of Postgres+ # ON CONFLICT DO NOTHING); avoids INSERT IGNORE, which would+ # also swallow unrelated errors and emit a duplicate-key+ # warning when the row already exists.+ await cur.execute(+ "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "ON DUPLICATE KEY UPDATE thread_id = thread_id",+ (thread_id,),+ )+ await cur.execute(+ "SELECT thread_id FROM cubepi_threads "+ "WHERE thread_id = %s FOR UPDATE",+ (thread_id,),+ )+ await cur.execute(+ "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "+ "WHERE thread_id = %s",+ (thread_id,),+ )+ (last_seq,) = await cur.fetchone()+ rows = []+ for i, m in enumerate(messages):+ seq = last_seq + i + 1+ payload = msgpack.packb(+ m.model_dump(mode="json"), use_bin_type=True+ )+ rows.append(+ (+ thread_id,+ seq,+ _role_of(m),+ json.dumps(m.metadata),+ payload,+ )+ )+ await cur.executemany(+ "INSERT INTO cubepi_messages "+ "(thread_id, seq, role, metadata, payload) "+ "VALUES (%s, %s, %s, %s, %s)",+ rows,+ )+ await conn.commit()+ except BaseException: # pragma: no cover - defensive txn rollback+ await conn.rollback()+ raise++ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ await conn.begin()+ try:+ async with conn.cursor() as cur:+ # No-op upsert (idiomatic equivalent of Postgres+ # ON CONFLICT DO NOTHING); avoids INSERT IGNORE, which would+ # also swallow unrelated errors and emit a duplicate-key+ # warning when the row already exists.+ await cur.execute(+ "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "ON DUPLICATE KEY UPDATE thread_id = thread_id",+ (thread_id,),+ )+ await cur.execute(+ "SELECT extra FROM cubepi_threads "+ "WHERE thread_id = %s FOR UPDATE",+ (thread_id,),+ )+ row = await cur.fetchone()+ current = _decode_json(row[0]) if row is not None else {}+ merged = {**current, **extra}+ await cur.execute(+ "UPDATE cubepi_threads "+ "SET extra = %s, updated_at = CURRENT_TIMESTAMP "+ "WHERE thread_id = %s",+ (json.dumps(merged), thread_id),+ )+ await conn.commit()+ except BaseException: # pragma: no cover - defensive txn rollback+ await conn.rollback()+ raisediff --git a/cubepi/checkpointer/mysql/exceptions.py b/cubepi/checkpointer/mysql/exceptions.pynew file mode 100644index 0000000..d8834cf--- /dev/null+++ b/cubepi/checkpointer/mysql/exceptions.py@@ -0,0 +1,19 @@+"""Schema exceptions for MySQLCheckpointer.++Re-exported from the backend-agnostic ``cubepi.checkpointer.exceptions``.+Importing from there (rather than the Postgres package) keeps a single source+of truth without pulling in ``asyncpg``, so the ``cubepi[mysql]`` extra works+without the Postgres extra installed.+"""++from cubepi.checkpointer.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)++__all__ = [+ "CubepiSchemaError",+ "CubepiSchemaMismatch",+ "CubepiSchemaUninitialized",+]diff --git a/cubepi/checkpointer/mysql/models.py b/cubepi/checkpointer/mysql/models.pynew file mode 100644index 0000000..528f1e6--- /dev/null+++ b/cubepi/checkpointer/mysql/models.py@@ -0,0 +1,86 @@+"""SQLAlchemy table definitions for cubepi MySQLCheckpointer.++Mirrors the Postgres models with MySQL adaptations: VARCHAR(255) utf8mb4_bin+thread ids, JSON columns, no messages->threads FK (the messages table is+KEY-partitioned and MySQL forbids FKs on partitioned tables), self-FK on+parent_thread_id kept. KEY partitioning is NOT expressible in SQLAlchemy+declarative, so it lives only in alembic_helpers.messages_partition_clause().+"""++from __future__ import annotations++import datetime as _dt+from typing import Any++import sqlalchemy as sa+from sqlalchemy.dialects.mysql import JSON, LONGBLOB, VARCHAR+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column++EXPECTED_SCHEMA_VERSION = 1+PARTITION_COUNT = 64++cubepi_metadata = sa.MetaData()++_TID = VARCHAR(255, collation="utf8mb4_bin")+++class CubepiBase(DeclarativeBase):+ metadata = cubepi_metadata+++class CubepiThread(CubepiBase):+ __tablename__ = "cubepi_threads"+ __table_args__ = {"mysql_engine": "InnoDB"}++ thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)+ parent_thread_id: Mapped[str | None] = mapped_column(+ _TID,+ sa.ForeignKey("cubepi_threads.thread_id"),+ nullable=True,+ )+ forked_at_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)+ extra: Mapped[dict[str, Any]] = mapped_column(+ JSON,+ nullable=False,+ server_default=sa.text("(JSON_OBJECT())"),+ )+ created_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP,+ nullable=False,+ server_default=sa.text("CURRENT_TIMESTAMP"),+ )+ updated_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP,+ nullable=False,+ server_default=sa.text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),+ )+++class CubepiMessage(CubepiBase):+ __tablename__ = "cubepi_messages"+ __table_args__ = {"mysql_engine": "InnoDB"}++ thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)+ seq: Mapped[int] = mapped_column(sa.BigInteger, primary_key=True)+ role: Mapped[str] = mapped_column(sa.String(32), nullable=False)+ # Python attribute renamed to avoid DeclarativeBase's reserved `metadata`+ # ClassVar; DB column stays `metadata`.+ msg_metadata: Mapped[dict[str, Any]] = mapped_column(+ "metadata",+ JSON,+ nullable=False,+ server_default=sa.text("(JSON_OBJECT())"),+ )+ payload: Mapped[bytes] = mapped_column(LONGBLOB, nullable=False)+ created_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP,+ nullable=False,+ server_default=sa.text("CURRENT_TIMESTAMP"),+ )+++class CubepiSchemaVersion(CubepiBase):+ __tablename__ = "cubepi_schema_version"+ __table_args__ = {"mysql_engine": "InnoDB"}++ version: Mapped[int] = mapped_column(sa.Integer, primary_key=True)diff --git a/cubepi/checkpointer/postgres/exceptions.py b/cubepi/checkpointer/postgres/exceptions.pyindex 5a59cf2..cbd27b8 100644--- a/cubepi/checkpointer/postgres/exceptions.py+++ b/cubepi/checkpointer/postgres/exceptions.py@@ -1,29 +1,17 @@-"""Exceptions raised by PostgresCheckpointer schema verification."""---class CubepiSchemaError(Exception):- """Base class for cubepi Postgres schema errors."""---class CubepiSchemaUninitialized(CubepiSchemaError):- """The cubepi_schema_version table is empty or missing.-- Typically means the host application's alembic upgrade hasn't been- run yet against this database.- """---class CubepiSchemaMismatch(CubepiSchemaError):- """The DB schema version doesn't match cubepi's expected version.-- Typically means the cubepi library was upgraded but the host- application's alembic is behind. Run a new alembic revision.- """-- def __init__(self, *, expected: int, actual: int, hint: str = "") -> None:- msg = f"cubepi schema mismatch: expected={expected} actual={actual}."- if hint:- msg += f" {hint}"- super().__init__(msg)- self.expected = expected- self.actual = actual+"""Exceptions raised by PostgresCheckpointer schema verification.++Re-exported from the backend-agnostic ``cubepi.checkpointer.exceptions`` so+the same classes are shared with the MySQL checkpointer.+"""++from cubepi.checkpointer.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)++__all__ = [+ "CubepiSchemaError",+ "CubepiSchemaMismatch",+ "CubepiSchemaUninitialized",+]diff --git a/dev/plans/2026-05-27-mysql-checkpointer.md b/dev/plans/2026-05-27-mysql-checkpointer.mdnew file mode 100644index 0000000..c0e3dba--- /dev/null+++ b/dev/plans/2026-05-27-mysql-checkpointer.md@@ -0,0 +1,1253 @@+# MySQLCheckpointer Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Add a production-grade `MySQLCheckpointer` implementing the cubepi+`Checkpointer` protocol against MySQL, mirroring `PostgresCheckpointer`.++**Architecture:** New package `cubepi/checkpointer/mysql/` (checkpointer / models+/ alembic_helpers / exceptions / __init__) following the Postgres package layout.+Connection pool via aiomysql, msgpack message payloads, JSON `metadata`/`extra`+columns, `KEY(thread_id)` partitioned messages table, host-managed schema+verified on entry. Schema exceptions are re-exported from the Postgres module+(single source of truth). Ships as optional `mysql` extra.++**Tech Stack:** Python 3.11+, aiomysql, SQLAlchemy 2.0 (table defs only), msgpack,+pymysql (error codes, transitive via aiomysql), pytest/pytest-asyncio.++Spec: `dev/specs/2026-05-27-mysql-checkpointer.md`.++---++## File Structure++- Create `cubepi/checkpointer/mysql/__init__.py` — public exports + lazy nothing+ (eager, since importing it already implies the extra is installed).+- Create `cubepi/checkpointer/mysql/exceptions.py` — re-export schema exceptions+ from `cubepi.checkpointer.postgres.exceptions`.+- Create `cubepi/checkpointer/mysql/models.py` — SQLAlchemy table defs on a+ private `cubepi_metadata`; constants `EXPECTED_SCHEMA_VERSION`,+ `PARTITION_COUNT`.+- Create `cubepi/checkpointer/mysql/alembic_helpers.py` —+ `messages_partition_clause()`, `write_schema_version_op()`.+- Create `cubepi/checkpointer/mysql/checkpointer.py` — `MySQLCheckpointer` ++ `_parse_dsn`, `_role_of`, `_ROLE_TO_CLS`, `_decode_json`.+- Modify `cubepi/checkpointer/__init__.py` — add `MySQLCheckpointer` to+ `__getattr__` and `__all__`.+- Modify `pyproject.toml` — add `mysql` optional-dependency extra + dev group dep.+- Create `tests/checkpointer/test_mysql.py` — unit + E2E tests.+- Modify `tests/checkpointer/conftest.py` — add MySQL fixtures alongside PG ones.+- Create/modify docs page under `website/docs/` — MySQL checkpointer section.++---++## Task 1: Dependency + package skeleton + exceptions++**Files:**+- Modify: `pyproject.toml`+- Create: `cubepi/checkpointer/mysql/__init__.py`+- Create: `cubepi/checkpointer/mysql/exceptions.py`+- Test: `tests/checkpointer/test_mysql.py`++- [ ] **Step 0: Add the `mysql` extra and dev dep (must precede any aiomysql import)**++In `pyproject.toml`, under `[project.optional-dependencies]` add after the+`postgres` block:++```toml+mysql = [+ "sqlalchemy>=2.0",+ "aiomysql>=0.2",+ "msgpack>=1.0",+]+```++In `[dependency-groups]` `dev = [ ... ]`, add near the other DB drivers:++```toml+ "aiomysql>=0.2",+```++Then run: `uv sync --all-extras --dev`+Expected: resolves and installs aiomysql (which pulls in PyMySQL).++- [ ] **Step 1: Write the failing test**++```python+# tests/checkpointer/test_mysql.py+"""MySQLCheckpointer tests — mirrors test_postgres.py."""++import pytest+++def test_exceptions_are_postgres_aliases() -> None:+ from cubepi.checkpointer.mysql.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+ )+ from cubepi.checkpointer.postgres import exceptions as pg_exc++ assert CubepiSchemaError is pg_exc.CubepiSchemaError+ assert CubepiSchemaMismatch is pg_exc.CubepiSchemaMismatch+ assert CubepiSchemaUninitialized is pg_exc.CubepiSchemaUninitialized+```++- [ ] **Step 2: Run test to verify it fails**++Run: `uv run pytest tests/checkpointer/test_mysql.py::test_exceptions_are_postgres_aliases -v`+Expected: FAIL — `ModuleNotFoundError: cubepi.checkpointer.mysql`++- [ ] **Step 3: Write minimal implementation**++```python+# cubepi/checkpointer/mysql/exceptions.py+"""Schema exceptions for MySQLCheckpointer.++These are backend-agnostic schema errors; re-exported from the Postgres+module so there is a single source of truth.+"""++from cubepi.checkpointer.postgres.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)++__all__ = [+ "CubepiSchemaError",+ "CubepiSchemaMismatch",+ "CubepiSchemaUninitialized",+]+```++```python+# cubepi/checkpointer/mysql/__init__.py+"""MySQLCheckpointer package.++Exports are built up incrementally across the plan. Exceptions are available+immediately; MySQLCheckpointer and model symbols are added once their modules+exist (Task 5), to avoid importing not-yet-written submodules.+"""++from cubepi.checkpointer.mysql.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)++__all__ = [+ "CubepiSchemaError",+ "CubepiSchemaMismatch",+ "CubepiSchemaUninitialized",+]+```++**Critical:** importing the package runs `__init__.py` first, so it must NOT+import `checkpointer`/`models` until those modules exist. The full export list+(adding `MySQLCheckpointer`, `EXPECTED_SCHEMA_VERSION`, `PARTITION_COUNT`,+`cubepi_metadata`) is written in Task 5 Step 2, after all submodules exist.++- [ ] **Step 4: Run test to verify it passes**++Run: `uv run pytest tests/checkpointer/test_mysql.py::test_exceptions_are_postgres_aliases -v`+Expected: PASS++- [ ] **Step 5: Commit**++```bash+git add pyproject.toml uv.lock cubepi/checkpointer/mysql/__init__.py cubepi/checkpointer/mysql/exceptions.py tests/checkpointer/test_mysql.py+git commit -m "feat(checkpointer): mysql package skeleton, exception aliases, mysql extra"+```++---++## Task 2: SQLAlchemy models++**Files:**+- Create: `cubepi/checkpointer/mysql/models.py`+- Test: `tests/checkpointer/test_mysql.py`++- [ ] **Step 1: Write the failing tests**++```python+# append to tests/checkpointer/test_mysql.py+def test_models_import() -> None:+ from cubepi.checkpointer.mysql.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ CubepiMessage,+ CubepiSchemaVersion,+ CubepiThread,+ cubepi_metadata,+ )++ assert EXPECTED_SCHEMA_VERSION == 1+ assert PARTITION_COUNT == 64+ assert CubepiThread.__tablename__ == "cubepi_threads"+ assert CubepiMessage.__tablename__ == "cubepi_messages"+ assert CubepiSchemaVersion.__tablename__ == "cubepi_schema_version"+ assert "cubepi_threads" in cubepi_metadata.tables+ assert "cubepi_messages" in cubepi_metadata.tables+ assert "cubepi_schema_version" in cubepi_metadata.tables+++def test_threads_parent_self_fk_present() -> None:+ """parent_thread_id keeps a self-FK (threads table is not partitioned)."""+ from cubepi.checkpointer.mysql.models import cubepi_metadata++ threads = cubepi_metadata.tables["cubepi_threads"]+ fk_targets = {+ fk.column.table.name+ for col in threads.columns+ for fk in col.foreign_keys+ }+ # parent_thread_id references cubepi_threads+ assert "cubepi_threads" in fk_targets+++def test_messages_has_no_foreign_keys() -> None:+ """messages table is partitioned, so no FK is allowed."""+ from cubepi.checkpointer.mysql.models import cubepi_metadata++ msgs = cubepi_metadata.tables["cubepi_messages"]+ assert msgs.foreign_keys == set()+++def test_messages_has_no_metadata_index() -> None:+ from cubepi.checkpointer.mysql.models import cubepi_metadata++ msgs = cubepi_metadata.tables["cubepi_messages"]+ assert msgs.indexes == set()+```++- [ ] **Step 2: Run tests to verify they fail**++Run: `uv run pytest tests/checkpointer/test_mysql.py -k "models_import or self_fk or foreign_keys or metadata_index" -v`+Expected: FAIL — `ModuleNotFoundError` / attribute errors.++- [ ] **Step 3: Write minimal implementation**++```python+# cubepi/checkpointer/mysql/models.py+"""SQLAlchemy table definitions for cubepi MySQLCheckpointer.++Mirrors the Postgres models with MySQL adaptations: VARCHAR(255) utf8mb4_bin+thread ids, JSON columns, no messages->threads FK (the messages table is+KEY-partitioned and MySQL forbids FKs on partitioned tables), self-FK on+parent_thread_id kept. KEY partitioning is NOT expressible in SQLAlchemy+declarative, so it lives only in alembic_helpers.messages_partition_clause().+"""++from __future__ import annotations++import datetime as _dt+from typing import Any++import sqlalchemy as sa+from sqlalchemy.dialects.mysql import JSON, LONGBLOB, VARCHAR+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column++EXPECTED_SCHEMA_VERSION = 1+PARTITION_COUNT = 64++cubepi_metadata = sa.MetaData()++_TID = VARCHAR(255, collation="utf8mb4_bin")+++class CubepiBase(DeclarativeBase):+ metadata = cubepi_metadata+++class CubepiThread(CubepiBase):+ __tablename__ = "cubepi_threads"+ __table_args__ = {"mysql_engine": "InnoDB"}++ thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)+ parent_thread_id: Mapped[str | None] = mapped_column(+ _TID,+ sa.ForeignKey("cubepi_threads.thread_id"),+ nullable=True,+ )+ forked_at_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)+ extra: Mapped[dict[str, Any]] = mapped_column(+ JSON,+ nullable=False,+ server_default=sa.text("(JSON_OBJECT())"),+ )+ created_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP,+ nullable=False,+ server_default=sa.text("CURRENT_TIMESTAMP"),+ )+ updated_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP,+ nullable=False,+ server_default=sa.text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),+ )+++class CubepiMessage(CubepiBase):+ __tablename__ = "cubepi_messages"+ __table_args__ = {"mysql_engine": "InnoDB"}++ thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)+ seq: Mapped[int] = mapped_column(sa.BigInteger, primary_key=True)+ role: Mapped[str] = mapped_column(sa.String(32), nullable=False)+ # Python attribute renamed to avoid DeclarativeBase's reserved `metadata`+ # ClassVar; DB column stays `metadata`.+ msg_metadata: Mapped[dict[str, Any]] = mapped_column(+ "metadata",+ JSON,+ nullable=False,+ server_default=sa.text("(JSON_OBJECT())"),+ )+ payload: Mapped[bytes] = mapped_column(LONGBLOB, nullable=False)+ created_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP,+ nullable=False,+ server_default=sa.text("CURRENT_TIMESTAMP"),+ )+++class CubepiSchemaVersion(CubepiBase):+ __tablename__ = "cubepi_schema_version"+ __table_args__ = {"mysql_engine": "InnoDB"}++ version: Mapped[int] = mapped_column(sa.Integer, primary_key=True)+```++- [ ] **Step 4: Run tests to verify they pass**++Run: `uv run pytest tests/checkpointer/test_mysql.py -k "models_import or self_fk or foreign_keys or metadata_index" -v`+Expected: PASS (4 tests)++- [ ] **Step 5: Commit**++```bash+git add cubepi/checkpointer/mysql/models.py tests/checkpointer/test_mysql.py+git commit -m "feat(checkpointer): mysql SQLAlchemy models"+```++---++## Task 3: alembic helpers++**Files:**+- Create: `cubepi/checkpointer/mysql/alembic_helpers.py`+- Test: `tests/checkpointer/test_mysql.py`++- [ ] **Step 1: Write the failing tests**++```python+# append to tests/checkpointer/test_mysql.py+def test_messages_partition_clause() -> None:+ from cubepi.checkpointer.mysql.alembic_helpers import messages_partition_clause++ clause = messages_partition_clause()+ assert clause == "PARTITION BY KEY (thread_id) PARTITIONS 64"+++def test_write_schema_version_op_clears_stale_then_inserts() -> None:+ from cubepi.checkpointer.mysql.alembic_helpers import write_schema_version_op++ sql = write_schema_version_op()+ assert "DELETE FROM cubepi_schema_version" in sql+ assert "WHERE version <> 1" in sql+ assert "INSERT IGNORE INTO cubepi_schema_version" in sql+ assert "VALUES (1)" in sql+ assert sql.index("DELETE") < sql.index("INSERT")+```++- [ ] **Step 2: Run tests to verify they fail**++Run: `uv run pytest tests/checkpointer/test_mysql.py -k "partition_clause or schema_version_op" -v`+Expected: FAIL — `ModuleNotFoundError`.++- [ ] **Step 3: Write minimal implementation**++```python+# cubepi/checkpointer/mysql/alembic_helpers.py+"""SQL helpers for host application alembic migrations (MySQL)."""++from cubepi.checkpointer.mysql.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+)+++def messages_partition_clause() -> str:+ """Return the KEY-partition clause for the cubepi_messages CREATE TABLE.++ Unlike Postgres (one child partition per modulus), MySQL declares all+ partitions inline. Append this to the messages table DDL, e.g.::++ op.execute("CREATE TABLE cubepi_messages (...) " + messages_partition_clause())++ KEY (not HASH) is required because thread_id is a VARCHAR; MySQL HASH+ partitioning only accepts integer expressions.+ """+ return f"PARTITION BY KEY (thread_id) PARTITIONS {PARTITION_COUNT}"+++def write_schema_version_op() -> str:+ """Return SQL setting cubepi_schema_version to the current version.++ Clears any stale rows from prior cubepi versions then inserts the current+ one. Idempotent. Call inside alembic upgrade() after CREATE TABLE+ cubepi_schema_version.+ """+ return (+ f"DELETE FROM cubepi_schema_version "+ f"WHERE version <> {EXPECTED_SCHEMA_VERSION}; "+ f"INSERT IGNORE INTO cubepi_schema_version (version) "+ f"VALUES ({EXPECTED_SCHEMA_VERSION});"+ )+```++- [ ] **Step 4: Run tests to verify they pass**++Run: `uv run pytest tests/checkpointer/test_mysql.py -k "partition_clause or schema_version_op" -v`+Expected: PASS++- [ ] **Step 5: Commit**++```bash+git add cubepi/checkpointer/mysql/alembic_helpers.py tests/checkpointer/test_mysql.py+git commit -m "feat(checkpointer): mysql alembic helpers"+```++---++## Task 4: Checkpointer — helpers, DSN, role mapping, empty-append no-op++**Files:**+- Create: `cubepi/checkpointer/mysql/checkpointer.py`+- Test: `tests/checkpointer/test_mysql.py`++- [ ] **Step 1: Write the failing tests**++```python+# append to tests/checkpointer/test_mysql.py+def test_role_of_known_message_types() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _role_of+ from cubepi.providers.base import (+ AssistantMessage,+ TextContent,+ ToolResultMessage,+ Usage,+ UserMessage,+ )++ assert _role_of(UserMessage(content=[TextContent(text="x")])) == "user"+ assert (+ _role_of(AssistantMessage(content=[TextContent(text="x")], usage=Usage()))+ == "assistant"+ )+ tr = ToolResultMessage(+ tool_call_id="tc-1", tool_name="t", content=[TextContent(text="ok")]+ )+ assert _role_of(tr) == "tool"+++def test_role_of_rejects_unknown_message_type() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _role_of++ class FakeMessage:+ pass++ with pytest.raises(TypeError, match="unknown Message type"):+ _role_of(FakeMessage()) # type: ignore[arg-type]+++def test_parse_dsn_full() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ cfg = _parse_dsn("mysql://user:[email protected]:3307/mydb")+ assert cfg == {+ "host": "db.example.com",+ "port": 3307,+ "user": "user",+ "password": "pw",+ "db": "mydb",+ }+++def test_parse_dsn_defaults_port_3306() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ cfg = _parse_dsn("mysql://root@localhost/x")+ assert cfg["port"] == 3306+ assert cfg["password"] == ""+++def test_decode_json_handles_str_and_dict() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _decode_json++ assert _decode_json('{"a": 1}') == {"a": 1}+ assert _decode_json({"a": 1}) == {"a": 1}+ assert _decode_json(None) == {}+++async def test_append_empty_messages_is_noop() -> None:+ # Import from the submodule, not the package: the package __init__ does not+ # export MySQLCheckpointer until Task 5.+ from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer++ cp = MySQLCheckpointer("mysql://root@unreachable-host/none")+ assert cp._pool is None+ await cp.append("thread-x", [])+ assert cp._pool is None+```++- [ ] **Step 2: Run tests to verify they fail**++Run: `uv run pytest tests/checkpointer/test_mysql.py -k "role_of or parse_dsn or decode_json or append_empty" -v`+Expected: FAIL — module/attr missing.++- [ ] **Step 3: Write minimal implementation**++```python+# cubepi/checkpointer/mysql/checkpointer.py+"""MySQLCheckpointer — Checkpointer protocol against MySQL.++Append-only message log + per-thread KV (extra). aiomysql pool + msgpack+payloads. Schema version verified on context entry. Mirrors+PostgresCheckpointer; see dev/specs/2026-05-27-mysql-checkpointer.md for the+list of deliberate MySQL divergences.+"""++from __future__ import annotations++import json+from typing import Any+from urllib.parse import unquote, urlparse++import aiomysql+import msgpack+import pymysql++from cubepi.checkpointer.base import CheckpointData+from cubepi.checkpointer.mysql.exceptions import (+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)+from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ ToolResultMessage,+ UserMessage,+)++_ER_NO_SUCH_TABLE = 1146+_ER_BAD_FIELD_ERROR = 1054+++def _role_of(msg: Message) -> str:+ if isinstance(msg, UserMessage):+ return "user"+ if isinstance(msg, AssistantMessage):+ return "assistant"+ if isinstance(msg, ToolResultMessage):+ return "tool"+ raise TypeError(f"unknown Message type: {type(msg).__name__}")+++_ROLE_TO_CLS: dict[str, type[Message]] = {+ "user": UserMessage,+ "assistant": AssistantMessage,+ "tool": ToolResultMessage,+}+++def _parse_dsn(dsn: str) -> dict[str, Any]:+ """Parse a mysql:// URL into aiomysql.create_pool kwargs."""+ u = urlparse(dsn)+ db = u.path.lstrip("/")+ return {+ "host": u.hostname or "localhost",+ "port": u.port or 3306,+ "user": unquote(u.username) if u.username else "",+ "password": unquote(u.password) if u.password else "",+ "db": db,+ }+++def _decode_json(value: Any) -> dict[str, Any]:+ """aiomysql returns JSON columns as str; tolerate already-parsed dicts."""+ if value is None:+ return {}+ if isinstance(value, str):+ return json.loads(value)+ return value+++class MySQLCheckpointer:+ """Checkpointer backed by MySQL (8.0.13+, InnoDB).++ Usage:+ cp = MySQLCheckpointer("mysql://user:pw@host:3306/db")+ async with cp:+ await cp.append(thread_id, [msg1, msg2])+ data = await cp.load(thread_id)+ await cp.save_extra(thread_id, {"k": "v"})++ Raises CubepiSchemaUninitialized / CubepiSchemaMismatch at __aenter__ if the+ DB schema isn't compatible with this cubepi version.+ """++ def __init__(+ self,+ dsn: str,+ *,+ min_pool_size: int = 1,+ max_pool_size: int = 10,+ ) -> None:+ self._cfg = _parse_dsn(dsn)+ self._min = min_pool_size+ self._max = max_pool_size+ self._pool: aiomysql.Pool | None = None++ async def append(self, thread_id: str, messages: list[Message]) -> None:+ if not messages:+ return+ raise NotImplementedError # completed in Task 6+```++- [ ] **Step 4: Run tests to verify they pass**++Run: `uv run pytest tests/checkpointer/test_mysql.py -k "role_of or parse_dsn or decode_json or append_empty" -v`+Expected: PASS++- [ ] **Step 5: Commit**++```bash+git add cubepi/checkpointer/mysql/checkpointer.py tests/checkpointer/test_mysql.py+git commit -m "feat(checkpointer): mysql checkpointer helpers + dsn parsing"+```++---++## Task 5: Pool lifecycle + schema verification + package wiring++**Files:**+- Modify: `cubepi/checkpointer/mysql/checkpointer.py`+- Modify: `cubepi/checkpointer/mysql/__init__.py`+- Modify: `cubepi/checkpointer/__init__.py`+- Test: `tests/checkpointer/test_mysql.py`++(The `mysql` extra and dev dep were already added in Task 1 Step 0.)++- [ ] **Step 1: Complete the mysql package `__init__.py`**++Now that all submodules exist, replace `cubepi/checkpointer/mysql/__init__.py`+with the full export surface:++```python+# cubepi/checkpointer/mysql/__init__.py+from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer+from cubepi.checkpointer.mysql.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)+from cubepi.checkpointer.mysql.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ cubepi_metadata,+)++__all__ = [+ "MySQLCheckpointer",+ "CubepiSchemaError",+ "CubepiSchemaMismatch",+ "CubepiSchemaUninitialized",+ "EXPECTED_SCHEMA_VERSION",+ "PARTITION_COUNT",+ "cubepi_metadata",+]+```++- [ ] **Step 2: Wire lazy import in the checkpointer package**++Edit `cubepi/checkpointer/__init__.py` `__getattr__` to add, before the final+`raise AttributeError`:++```python+ if name == "MySQLCheckpointer":+ from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer++ return MySQLCheckpointer+```++And add `"MySQLCheckpointer"` to `__all__`.++- [ ] **Step 3: Write the test for the top-level lazy import**++```python+# append to tests/checkpointer/test_mysql.py+def test_top_level_lazy_import() -> None:+ import cubepi.checkpointer as cp_pkg++ assert cp_pkg.MySQLCheckpointer is not None+ assert "MySQLCheckpointer" in cp_pkg.__all__+```++- [ ] **Step 4: Run it (verifies the wiring; the class exists from Task 4)**++Run: `uv run pytest tests/checkpointer/test_mysql.py::test_top_level_lazy_import -v`+Expected: PASS. A failure here means an import error in the wiring — fix it+before continuing. (This step verifies wiring rather than following strict+red→green, because the class already exists from Task 4.)++- [ ] **Step 5: Implement `__aenter__`/`__aexit__`/`_verify_schema`**++Add these methods to `MySQLCheckpointer` (after `__init__`, before `append`):++```python+ async def __aenter__(self) -> "MySQLCheckpointer":+ self._pool = await aiomysql.create_pool(+ minsize=self._min,+ maxsize=self._max,+ autocommit=True,+ **self._cfg,+ )+ await self._verify_schema()+ return self++ async def __aexit__(self, *args: Any) -> None:+ if self._pool is not None:+ self._pool.close()+ await self._pool.wait_closed()+ self._pool = None++ async def _verify_schema(self) -> None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.cursor() as cur:+ try:+ await cur.execute(+ "SELECT version FROM cubepi_schema_version LIMIT 1"+ )+ row = await cur.fetchone()+ except pymysql.err.Error as e:+ # PyMySQL maps 1146 (ER_NO_SUCH_TABLE) to ProgrammingError but+ # 1054 (ER_BAD_FIELD_ERROR) to OperationalError, so catch the+ # common base and branch on the errno.+ code = e.args[0] if e.args else None+ if code in (_ER_NO_SUCH_TABLE, _ER_BAD_FIELD_ERROR):+ raise CubepiSchemaUninitialized(+ "cubepi tables not found or malformed. Run host "+ "application's alembic upgrade."+ ) from e+ raise+ if row is None:+ raise CubepiSchemaUninitialized(+ "cubepi_schema_version table is empty. Host alembic migration "+ "must INSERT the current version (use write_schema_version_op())."+ )+ actual = row[0]+ if actual != EXPECTED_SCHEMA_VERSION:+ raise CubepiSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=actual,+ hint="cubepi was upgraded but host alembic is behind. "+ "Generate a new revision and apply.",+ )+```++- [ ] **Step 6: Run the full unit-test subset to verify nothing broke**++Run: `uv run pytest tests/checkpointer/test_mysql.py -v`+Expected: PASS for all non-E2E tests (E2E tests not written yet).++- [ ] **Step 7: Commit**++```bash+git add cubepi/checkpointer/__init__.py cubepi/checkpointer/mysql/__init__.py cubepi/checkpointer/mysql/checkpointer.py tests/checkpointer/test_mysql.py+git commit -m "feat(checkpointer): mysql pool lifecycle + schema verification + package wiring"+```++---++## Task 6: load / append / save_extra++**Files:**+- Modify: `cubepi/checkpointer/mysql/checkpointer.py`+- Test: `tests/checkpointer/test_mysql.py` (E2E, added in Task 7)++This task has no standalone unit test (the logic needs a DB; E2E tests in Task 7+cover it). Implement, then run the existing unit subset to confirm no import or+syntax regressions.++- [ ] **Step 1: Implement `load`**++Replace the `append` stub region by first adding `load` above it:++```python+ async def load(self, thread_id: str) -> CheckpointData | None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.cursor() as cur:+ await cur.execute(+ "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "WHERE thread_id = %s ORDER BY seq",+ (thread_id,),+ )+ msg_rows = await cur.fetchall()+ await cur.execute(+ "SELECT extra FROM cubepi_threads WHERE thread_id = %s",+ (thread_id,),+ )+ extra_row = await cur.fetchone()++ if not msg_rows and extra_row is None:+ return None++ messages: list[Message] = []+ for _seq, role, metadata, payload in msg_rows:+ cls = _ROLE_TO_CLS.get(role)+ if cls is None:+ raise ValueError(f"unknown role in DB: {role!r}")+ data = msgpack.unpackb(bytes(payload), raw=False)+ data["metadata"] = _decode_json(metadata)+ messages.append(cls.model_validate(data))++ extra = _decode_json(extra_row[0]) if extra_row is not None else {}+ return CheckpointData(messages=messages, extra=extra)+```++- [ ] **Step 2: Implement `append` (replace the `NotImplementedError` stub)**++```python+ async def append(self, thread_id: str, messages: list[Message]) -> None:+ if not messages:+ return+ 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 IGNORE INTO cubepi_threads (thread_id) "+ "VALUES (%s)",+ (thread_id,),+ )+ await cur.execute(+ "SELECT thread_id FROM cubepi_threads "+ "WHERE thread_id = %s FOR UPDATE",+ (thread_id,),+ )+ await cur.execute(+ "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "+ "WHERE thread_id = %s",+ (thread_id,),+ )+ (last_seq,) = await cur.fetchone()+ rows = []+ for i, m in enumerate(messages):+ seq = last_seq + i + 1+ payload = msgpack.packb(+ m.model_dump(mode="json"), use_bin_type=True+ )+ rows.append(+ (+ thread_id,+ seq,+ _role_of(m),+ json.dumps(m.metadata),+ payload,+ )+ )+ await cur.executemany(+ "INSERT INTO cubepi_messages "+ "(thread_id, seq, role, metadata, payload) "+ "VALUES (%s, %s, %s, %s, %s)",+ rows,+ )+ await conn.commit()+ except BaseException:+ await conn.rollback()+ raise+```++- [ ] **Step 3: Implement `save_extra` (read-modify-write shallow merge)**++```python+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:+ 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 IGNORE INTO cubepi_threads (thread_id) "+ "VALUES (%s)",+ (thread_id,),+ )+ await cur.execute(+ "SELECT extra FROM cubepi_threads "+ "WHERE thread_id = %s FOR UPDATE",+ (thread_id,),+ )+ row = await cur.fetchone()+ current = _decode_json(row[0]) if row is not None else {}+ merged = {**current, **extra}+ await cur.execute(+ "UPDATE cubepi_threads "+ "SET extra = %s, updated_at = CURRENT_TIMESTAMP "+ "WHERE thread_id = %s",+ (json.dumps(merged), thread_id),+ )+ await conn.commit()+ except BaseException:+ await conn.rollback()+ raise+```++- [ ] **Step 4: Run the unit subset to verify no regressions**++Run: `uv run pytest tests/checkpointer/test_mysql.py -v`+Expected: PASS (unit tests; E2E added next task).+Also: `uv run ruff check cubepi/ tests/` and `uv run ruff format --check cubepi/ tests/`+Expected: clean.++- [ ] **Step 5: Commit**++```bash+git add cubepi/checkpointer/mysql/checkpointer.py+git commit -m "feat(checkpointer): mysql load/append/save_extra"+```++---++## Task 7: E2E tests + conftest fixtures++**Files:**+- Modify: `tests/checkpointer/conftest.py`+- Modify: `tests/checkpointer/test_mysql.py`++E2E tests skip automatically when no MySQL is reachable (mirrors the Postgres+ones). They run when `CUBEPI_TEST_MYSQL_DSN` points at a live server.++- [ ] **Step 1: Add MySQL fixtures to conftest**++Append to `tests/checkpointer/conftest.py`:++```python+import aiomysql # add near the asyncpg import at top of file++[email protected](scope="session")+def mysql_dsn() -> str:+ """MySQL DSN for tests. Override via CUBEPI_TEST_MYSQL_DSN env."""+ return os.environ.get(+ "CUBEPI_TEST_MYSQL_DSN",+ "mysql://root:root@localhost:3306/mysql",+ )+++def _mysql_cfg(dsn: str) -> dict:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ return _parse_dsn(dsn)+++@pytest_asyncio.fixture(scope="session")+async def _mysql_available(mysql_dsn: str) -> bool:+ """Quick probe — connection refused → skip MySQL tests."""+ try:+ conn = await aiomysql.connect(connect_timeout=2, **_mysql_cfg(mysql_dsn))+ conn.close()+ return True+ except (aiomysql.Error, OSError, ConnectionError):+ return False+++@pytest_asyncio.fixture+async def clean_mysql_db(mysql_dsn: str, _mysql_available: bool):+ """Create a fresh database for each test; drop after."""+ if not _mysql_available:+ pytest.skip(+ "MySQL not available for E2E tests; set CUBEPI_TEST_MYSQL_DSN "+ "to a working DSN to enable."+ )++ db_name = f"cubepi_test_{secrets.token_hex(6)}"+ admin_cfg = _mysql_cfg(mysql_dsn)+ admin = await aiomysql.connect(autocommit=True, **admin_cfg)+ try:+ async with admin.cursor() as cur:+ await cur.execute(f"CREATE DATABASE `{db_name}`")+ finally:+ admin.close()++ base = mysql_dsn.rsplit("/", 1)[0]+ test_dsn = f"{base}/{db_name}"+ yield test_dsn++ admin = await aiomysql.connect(autocommit=True, **admin_cfg)+ try:+ async with admin.cursor() as cur:+ await cur.execute(f"DROP DATABASE IF EXISTS `{db_name}`")+ finally:+ admin.close()+```++(`os`, `secrets`, `pytest`, `pytest_asyncio` are already imported in this file.)++- [ ] **Step 2: Add `_setup_schema` + E2E tests to test_mysql.py**++```python+# append to tests/checkpointer/test_mysql.py+import aiomysql++from cubepi.checkpointer.mysql.alembic_helpers import (+ messages_partition_clause,+ write_schema_version_op,+)+++async def _setup_schema(dsn: str) -> None:+ """Build the cubepi schema (matching what host alembic would generate)."""+ 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(+ """+ 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:+ conn.close()+++async def test_mysql_checkpointer_round_trip(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import (+ AssistantMessage,+ TextContent,+ Usage,+ UserMessage,+ )++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ msg1 = UserMessage(+ content=[TextContent(text="hello")],+ metadata={"memory_snapshot": {"id": "m1"}},+ )+ msg2 = AssistantMessage(+ content=[TextContent(text="hi back")],+ usage=Usage(),+ metadata={"cost_cents": 5},+ )+ await cp.append("t-1", [msg1, msg2])+ data = await cp.load("t-1")++ assert data is not None+ assert len(data.messages) == 2+ assert isinstance(data.messages[0], UserMessage)+ assert isinstance(data.messages[1], AssistantMessage)+ assert data.messages[0].metadata == {"memory_snapshot": {"id": "m1"}}+ assert data.messages[1].metadata == {"cost_cents": 5}+ assert data.messages[0].content[0].text == "hello"+ assert data.messages[1].content[0].text == "hi back"+++async def test_mysql_checkpointer_save_extra_merges(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import TextContent, UserMessage++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ await cp.append("t-2", [UserMessage(content=[TextContent(text="x")])])+ await cp.save_extra("t-2", {"a": 1})+ await cp.save_extra("t-2", {"b": 2})+ data = await cp.load("t-2")++ assert data is not None+ assert data.extra == {"a": 1, "b": 2}+++async def test_mysql_checkpointer_seq_monotonic(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import TextContent, UserMessage++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ msgs1 = [UserMessage(content=[TextContent(text=str(i))]) for i in range(5)]+ await cp.append("t-3", msgs1)+ msgs2 = [+ UserMessage(content=[TextContent(text=str(i))]) for i in range(5, 10)+ ]+ await cp.append("t-3", msgs2)+ data = await cp.load("t-3")++ assert data is not None+ assert len(data.messages) == 10+ texts = [m.content[0].text for m in data.messages]+ assert texts == [str(i) for i in range(10)]+++async def test_uninitialized_schema_raises(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import (+ CubepiSchemaUninitialized,+ MySQLCheckpointer,+ )++ with pytest.raises(CubepiSchemaUninitialized):+ async with MySQLCheckpointer(clean_mysql_db):+ pass+++async def test_version_mismatch_raises(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import CubepiSchemaMismatch, MySQLCheckpointer+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ await _setup_schema(clean_mysql_db)+ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))+ try:+ async with conn.cursor() as cur:+ await cur.execute("UPDATE cubepi_schema_version SET version = 999")+ finally:+ conn.close()++ with pytest.raises(CubepiSchemaMismatch) as exc_info:+ async with MySQLCheckpointer(clean_mysql_db):+ pass+ assert exc_info.value.expected == 1+ assert exc_info.value.actual == 999+++async def test_empty_thread_load_returns_none(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ data = await cp.load("nonexistent-thread")+ assert data is None+```++- [ ] **Step 3: Run the full test file**++Run: `uv run pytest tests/checkpointer/test_mysql.py -v`+Expected: unit tests PASS; E2E tests PASS if `CUBEPI_TEST_MYSQL_DSN` is set to a+live 8.0.13+ server, otherwise SKIPPED. Run with a real DB before considering+the feature done:+`CUBEPI_TEST_MYSQL_DSN=mysql://root:root@localhost:3306/mysql uv run pytest tests/checkpointer/test_mysql.py -v`++- [ ] **Step 4: Lint**++Run: `uv run ruff check cubepi/ tests/ && uv run ruff format --check cubepi/ tests/`+Expected: clean.++- [ ] **Step 5: Commit**++```bash+git add tests/checkpointer/conftest.py tests/checkpointer/test_mysql.py+git commit -m "test(checkpointer): mysql unit + E2E tests"+```++---++## Task 8: Documentation++**Files:**+- Modify: the checkpointer docs page under `website/docs/` (locate the page that+ documents `PostgresCheckpointer`; add a MySQL section there). If Postgres is+ documented in e.g. `website/docs/guides/checkpointing.md` or similar, edit that+ file. Use `grep -rl PostgresCheckpointer website/docs` to find it.++- [ ] **Step 1: Locate the existing checkpointer doc**++Run: `grep -rl "PostgresCheckpointer" website/docs`+Use the returned path as the doc to extend.++- [ ] **Step 2: Add a MySQL section**++Mirror the Postgres section. Content must cover:+- Install: `pip install "cubepi[mysql]"` (driver: aiomysql).+- Minimum MySQL **8.0.13+**, InnoDB engine.+- Host-managed schema: cubepi ships SQLAlchemy models+ (`cubepi.checkpointer.mysql.models.cubepi_metadata`) and alembic helpers+ (`messages_partition_clause()`, `write_schema_version_op()`). The host's+ alembic migration creates the tables; the checkpointer verifies the schema+ version on connect and raises `CubepiSchemaUninitialized` / `CubepiSchemaMismatch`.+- Usage example:++```python+from cubepi.checkpointer import MySQLCheckpointer++cp = MySQLCheckpointer("mysql://user:pw@localhost:3306/mydb")+async with cp:+ await cp.append(thread_id, [msg])+ data = await cp.load(thread_id)+```++- Divergences worth flagging to users: messages table is `KEY(thread_id)`+ partitioned with no FK (integrity from lazy thread insert); `metadata` JSON+ column is **not** indexed (add a generated-column index host-side if you need+ to query by metadata); thread IDs are case-sensitive (`utf8mb4_bin`).++- [ ] **Step 3: Build/verify docs (if a build step exists)**++Run (if present): `grep -q "\"build\"" website/package.json && (cd website && npm run build)` — otherwise skip; verify the markdown renders by eye.++- [ ] **Step 4: Commit**++```bash+git add website/docs+git commit -m "docs: document MySQLCheckpointer"+```++---++## Final verification before PR++- [ ] `uv run pytest tests/ -v` (whole suite; MySQL E2E skipped without DB).+- [ ] With a live MySQL 8.0.13+: `CUBEPI_TEST_MYSQL_DSN=... uv run pytest tests/checkpointer/test_mysql.py -v` — all E2E pass.+- [ ] `uv run ruff check cubepi/ tests/` clean.+- [ ] `uv run ruff format --check cubepi/ tests/` clean.+- [ ] Spec divergences all reflected in code.+- [ ] Docs page updated.diff --git a/dev/specs/2026-05-27-mysql-checkpointer.md b/dev/specs/2026-05-27-mysql-checkpointer.mdnew file mode 100644index 0000000..6bb6a3b--- /dev/null+++ b/dev/specs/2026-05-27-mysql-checkpointer.md@@ -0,0 +1,265 @@+# MySQLCheckpointer Design++**Date:** 2026-05-27+**Status:** Spec+**Topic:** Add a production-grade MySQL `Checkpointer` implementation, mirroring+`PostgresCheckpointer`.++## Motivation++cubepi ships memory / sqlite / postgres checkpointers. Deployments standardized+on MySQL (e.g. cubemanus, whose async stack is `aiomysql`) currently have no+first-class option. This adds `MySQLCheckpointer` with the same production+characteristics as `PostgresCheckpointer`: connection pool, msgpack payloads,+queryable JSON `metadata` column, host-managed schema with startup version+verification.++## Goals / Non-goals++**Goals**+- Implement the `Checkpointer` protocol (`load` / `append` / `save_extra`)+ against MySQL with feature parity to `PostgresCheckpointer`.+- Host-managed schema: ship SQLAlchemy models + alembic helpers; verify+ `cubepi_schema_version` on context entry.+- Monotonic per-thread `seq` allocation under concurrency.+- Ship as an optional `mysql` extra; keep core deps lean.+- User-facing docs in `website/docs/`.++**Non-goals**+- No automatic schema creation by the checkpointer (host owns DDL, like+ Postgres). MySQL JSON metadata indexing is left to the host.+- No thread forking logic beyond the columns the Postgres schema already+ carries (`parent_thread_id`, `forked_at_seq`) — they exist for schema parity+ but are not exercised by this checkpointer.++## Driver++`aiomysql` (matches cubemanus, which depends on+`langgraph-checkpoint-mysql[aiomysql]`). Pool via `aiomysql.create_pool`.+Connection is configured from a `mysql://user:pw@host:port/db` DSN URL (parsed+into `aiomysql.create_pool` kwargs), matching `PostgresCheckpointer`'s+DSN-only constructor — no separate explicit-kwargs path (YAGNI; a DSN covers the+cases). Placeholders are `%s` (PyMySQL paramstyle).++## Module layout++Mirror `cubepi/checkpointer/postgres/`:++```+cubepi/checkpointer/mysql/+ __init__.py # exports MySQLCheckpointer, schema symbols, exceptions+ checkpointer.py # MySQLCheckpointer+ models.py # SQLAlchemy table defs on a private cubepi_metadata+ alembic_helpers.py # host alembic migration helpers+ exceptions.py # CubepiSchemaError / Uninitialized / Mismatch+```++Exceptions are structurally identical to the Postgres ones. To avoid drift they+are **re-exported from the Postgres exceptions module** rather than redefined:+`from cubepi.checkpointer.postgres.exceptions import (...)`. (They are+backend-agnostic schema errors; this keeps a single source of truth.)++## Schema++Host creates these via alembic; the checkpointer only verifies on entry.++**Minimum MySQL version: 8.0.13+** — required for expression defaults on JSON+columns (`DEFAULT (JSON_OBJECT())`). Engine: InnoDB (row locks, transactions).++`thread_id` columns use collation **`utf8mb4_bin`** so thread IDs are+case-sensitive and byte-exact, matching Postgres `TEXT`. (MySQL's default+`utf8mb4_0900_ai_ci` is case- and accent-insensitive, which would collide+distinct IDs like `UserA` / `usera`.) The 255-char limit is documented; cubepi+thread IDs are short (UUIDs / slugs) so this is not a practical constraint.++### `cubepi_threads`+| column | type | notes |+|---|---|---|+| `thread_id` | `VARCHAR(255) utf8mb4_bin` | PK |+| `parent_thread_id` | `VARCHAR(255) utf8mb4_bin NULL` | self-FK → `cubepi_threads.thread_id` (kept; this table is not partitioned) |+| `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` |++### `cubepi_messages`+| column | type | notes |+|---|---|---|+| `thread_id` | `VARCHAR(255) utf8mb4_bin NOT NULL` | part of PK |+| `seq` | `BIGINT NOT NULL` | part of PK |+| `role` | `VARCHAR(32) NOT NULL` | `user`/`assistant`/`tool` |+| `metadata` | `JSON NOT NULL` | `DEFAULT (JSON_OBJECT())`, no index |+| `payload` | `LONGBLOB NOT NULL` | msgpack |+| `created_at` | `TIMESTAMP NOT NULL` | default `CURRENT_TIMESTAMP` |++PK `(thread_id, seq)`. Table is `PARTITION BY KEY (thread_id) PARTITIONS 64`.+**`KEY`, not `HASH`** — MySQL `HASH` partitioning requires an integer expression,+whereas `KEY` applies MySQL's internal hash to any column type including+`VARCHAR`. No foreign key on this table (see divergence). MySQL requires every+unique key to contain the partition column — satisfied since `thread_id` leads+the PK.++### `cubepi_schema_version`+| column | type | notes |+|---|---|---|+| `version` | `INT` | PK |++`EXPECTED_SCHEMA_VERSION = 1`, `PARTITION_COUNT = 64` (constants in `models.py`,+parity with Postgres).++**Note on partitioning in the model:** SQLAlchemy has no `mysql_partition_by`+dialect kwarg analogous to Postgres's `postgresql_partition_by`. The `KEY`+partition clause therefore cannot live on the declarative model; it is emitted+only by the `messages_partition_clause()` alembic helper, which the host appends+to the `CREATE TABLE` DDL. The model defines columns/PK/self-FK; the partition+clause is a helper concern. Unit tests assert on the helper output, not model+kwargs.++## Divergences from PostgresCheckpointer++Each is a deliberate MySQL adaptation; called out per project convention.++| Aspect | Postgres | MySQL | Why |+|---|---|---|---|+| Driver | asyncpg | aiomysql | Matches cubemanus stack |+| Placeholder | `$1` | `%s` | PyMySQL paramstyle |+| `seq` lock | `pg_advisory_xact_lock(hashtext(tid))` | `SELECT … FROM cubepi_threads WHERE thread_id=%s FOR UPDATE` | MySQL has no advisory xact lock; lock the (lazily-created) thread row via InnoDB row lock, auto-released at txn end |+| Upsert | `INSERT … ON CONFLICT DO …` | `INSERT … ON DUPLICATE KEY UPDATE …` | MySQL syntax |+| `extra` merge | `extra \|\| EXCLUDED.extra` (shallow, top-level) | read-modify-write under `FOR UPDATE` (Python `dict.update`) | `JSON_MERGE_PATCH` is **not** equivalent — it deletes keys whose value is JSON `null` and deep-merges nested objects. PG `\|\|` and sqlite `.update()` are shallow top-level replace; RMW reproduces that exactly |+| Lazy thread insert | `INSERT … ON CONFLICT DO NOTHING` | `INSERT … ON DUPLICATE KEY UPDATE thread_id = thread_id` (no-op) | Precise equivalent of `ON CONFLICT DO NOTHING`. `INSERT IGNORE` was rejected: it also swallows unrelated errors (e.g. data truncation) and emits a duplicate-key warning when the row exists |+| JSON type | `JSONB` | `JSON` | MySQL has no JSONB |+| JSON readback | native dict | `str` → `json.loads` (both `metadata` and `extra`) | aiomysql returns JSON columns as text |+| JSON default | `'{}'::jsonb` | `DEFAULT (JSON_OBJECT())` | MySQL needs an expression default (8.0.13+) |+| metadata index | GIN (`jsonb_path_ops`) | none | MySQL can't index JSON directly; host adds generated-column index if needed |+| Partition | `HASH (thread_id)` | `KEY (thread_id)` | HASH needs an integer expr; KEY hashes any type |+| messages FK | `→ cubepi_threads` | dropped | MySQL partitioned tables disallow FKs |+| threads self-FK | `parent_thread_id →` | **kept** | this table is not partitioned, so MySQL allows it; preserves parity |+| `thread_id` collation | `TEXT` (case-sensitive) | `VARCHAR(255) utf8mb4_bin` | match PG case-sensitivity/byte-exactness |+| `now()` | `now()` | `CURRENT_TIMESTAMP` | MySQL spelling |++Only the `cubepi_messages → cubepi_threads` FK is dropped (because that table is+partitioned). The `cubepi_threads.parent_thread_id` self-FK is **kept**, matching+Postgres. Referential integrity for messages is guaranteed by the lazy+thread-row insert in `append`.++## Behavior++### `__aenter__` / `__aexit__`+Create pool (`min_pool_size`/`max_pool_size`), run `_verify_schema`, return self.+If `_verify_schema` raises, `__aenter__` closes the pool before propagating —+the context was never entered, so `__aexit__` would not run and the pool (and+its connections) would leak. Exit closes the pool. Pool is created with+**`autocommit=True`**; write methods+(`append`, `save_extra`) wrap their work in an explicit transaction+(`conn.begin()` / `commit` / rollback on error). This avoids the InnoDB pitfall+where, under `autocommit=False`, a read-only `load` would open a transaction that+never commits and return the connection to the pool holding a stale REPEATABLE+READ snapshot.++### `_verify_schema`+`SELECT version FROM cubepi_schema_version LIMIT 1`.+- Table missing (PyMySQL error code `1146 ER_NO_SUCH_TABLE`) →+ `CubepiSchemaUninitialized`.+- `version` column missing (`1054 ER_BAD_FIELD_ERROR`, a malformed/stale table) →+ `CubepiSchemaUninitialized` (MySQL-specific defensive handling; Postgres has no+ analogous catch).+- No row → `CubepiSchemaUninitialized`.+- `version != EXPECTED_SCHEMA_VERSION` → `CubepiSchemaMismatch(expected, actual)`.++Error codes are read from `pymysql.err.*` / `e.args[0]` rather than matched on+message text.++### `load(thread_id)`+Fetch messages `WHERE thread_id=%s ORDER BY seq` and the thread's `extra`.+Return `None` if no messages **and** no thread row. Decode each `payload` with+msgpack; the `metadata` column is the source of truth for `Message.metadata`.+**Both** JSON columns (`metadata` and `extra`) come back from aiomysql as `str`+and are decoded with `json.loads` (guard against an already-parsed value for+driver-version robustness). Reconstruct via `_ROLE_TO_CLS` (shared mapping+identical to Postgres).++### `append(thread_id, messages)`+Early-return on empty list (no pool touch — testable without a DB). Otherwise, in+one transaction:+1. `INSERT INTO cubepi_threads (thread_id) VALUES (%s) ON DUPLICATE KEY UPDATE thread_id = thread_id`+ (no-op upsert; lazy create).+2. `SELECT thread_id FROM cubepi_threads WHERE thread_id=%s FOR UPDATE` (row+ lock serializes concurrent appends to this thread).+3. `SELECT COALESCE(MAX(seq),0) FROM cubepi_messages WHERE thread_id=%s`.+4. `executemany` insert of `(thread_id, seq, role, metadata_json, payload)` with+ `seq = last + i + 1`.+Commit. msgpack uses `model_dump(mode="json")`; metadata column gets+`json.dumps(m.metadata)`.++### `save_extra(thread_id, extra)`+Shallow top-level merge matching Postgres `||` / sqlite `dict.update`. Because+`JSON_MERGE_PATCH` has different semantics (null-key deletion, deep merge), do a+read-modify-write inside one transaction:+1. `INSERT INTO cubepi_threads (thread_id) VALUES (%s) ON DUPLICATE KEY UPDATE thread_id = thread_id`+ (no-op upsert; lazy create).+2. `SELECT extra FROM cubepi_threads WHERE thread_id=%s FOR UPDATE` (row lock).+3. In Python: `merged = {**current, **extra}`.+4. `UPDATE cubepi_threads SET extra=%s, updated_at=CURRENT_TIMESTAMP WHERE thread_id=%s`+ with `json.dumps(merged)`.+Commit. The `FOR UPDATE` serializes concurrent `save_extra` on the same thread.++## alembic_helpers.py++- `messages_partition_clause() -> str` — unlike Postgres (which needs a 64-row+ per-partition DDL loop), MySQL `PARTITION BY KEY (thread_id) PARTITIONS 64` is a+ single inline clause on the `CREATE TABLE`. The helper returns that clause for+ the host to append to its messages-table DDL.+- `write_schema_version_op() -> str` — same intent as Postgres: clear stale rows+ then insert current version, idempotent:+ `DELETE FROM cubepi_schema_version WHERE version <> 1; INSERT IGNORE INTO cubepi_schema_version (version) VALUES (1);`++Exact helper surface finalized in the plan; the principle is parity with the+Postgres helpers adjusted for MySQL's single-statement partitioning.++## Packaging++`pyproject.toml`:+```toml+mysql = [+ "sqlalchemy>=2.0",+ "aiomysql>=0.2",+ "msgpack>=1.0",+]+```+Add `aiomysql>=0.2` to the dev dependency-group. Add `MySQLCheckpointer` lazy+import to `cubepi/checkpointer/__init__.py` `__getattr__` and `__all__`.++## Testing++Mirror `tests/checkpointer/test_postgres.py` + its conftest exactly:++**Unit (no DB):** models import & registration on `cubepi_metadata`; partition+clause present (`PARTITION BY KEY (thread_id) PARTITIONS 64`); no metadata index;+self-FK on `parent_thread_id` present while no FK on `cubepi_messages`; alembic+helper SQL (schema-version op clears stale + inserts 1); exceptions; `_role_of`+mapping + rejects unknown; `append([])` is a no-op without a pool.++**E2E (real MySQL, skipped if unavailable):** add+`tests/checkpointer/conftest.py` fixtures `mysql_dsn`+(`CUBEPI_TEST_MYSQL_DSN`, default `mysql://root:root@localhost:3306/mysql`),+`_mysql_available` probe (connect with short timeout, skip on failure),+`clean_mysql_db` (create fresh `cubepi_test_<hex>` database per test via aiomysql,+drop after). A `_setup_schema(dsn)` in the test file issues the CREATE TABLE ++partition + schema-version DDL (mirroring what host alembic generates). Tests:+round-trip with metadata, `save_extra` merges, `seq` monotonic across batches,+uninitialized schema raises, version mismatch raises, empty-thread load → None.++The existing postgres conftest fixtures are not disturbed; MySQL fixtures are+added alongside.++## Docs++Add a MySQL section to the checkpointer docs under `website/docs/` (same page /+guide that documents the Postgres checkpointer): install extra, host alembic+setup, usage example, and the divergence notes (no metadata index, host-managed+schema).++## Open questions++None blocking. Helper function names in `alembic_helpers.py` will be settled in+the implementation plan.diff --git a/pyproject.toml b/pyproject.tomlindex 351b0f2..7512f25 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -31,6 +31,14 @@ postgres = ["asyncpg>=0.29","msgpack>=1.0",]+mysql = [+ "sqlalchemy>=2.0",+ "aiomysql>=0.2",+ "msgpack>=1.0",+ # Required by PyMySQL/aiomysql for MySQL 8's default caching_sha2_password+ # RSA password exchange over a non-TLS connection.+ "cryptography>=42",+]mcp = ["mcp>=1.0",]@@ -52,6 +60,7 @@ cubepi = "cubepi.cli.__main__:main"[dependency-groups]dev = [+ "aiomysql>=0.2","aiosqlite>=0.22.1","asyncpg>=0.29","msgpack>=1.0",diff --git a/tests/checkpointer/conftest.py b/tests/checkpointer/conftest.pyindex 25778e1..d6af6bb 100644--- a/tests/checkpointer/conftest.py+++ b/tests/checkpointer/conftest.py@@ -1,8 +1,9 @@-"""Postgres test fixtures for D1.3+ tests."""+"""Database test fixtures (Postgres + MySQL E2E)."""import osimport secrets+import aiomysqlimport asyncpgimport pytestimport pytest_asyncio@@ -58,3 +59,64 @@ async def clean_db(pg_dsn: str, _pg_available: bool):await admin.execute(f'DROP DATABASE IF EXISTS "{db_name}"')finally:await admin.close()+++# ---------------------------------------------------------------------------+# MySQL fixtures+# ---------------------------------------------------------------------------++[email protected](scope="session")+def mysql_dsn() -> str:+ """MySQL DSN for tests. Override via CUBEPI_TEST_MYSQL_DSN env."""+ return os.environ.get(+ "CUBEPI_TEST_MYSQL_DSN",+ "mysql://root:root@localhost:3306/mysql",+ )+++def _mysql_cfg(dsn: str) -> dict:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ return _parse_dsn(dsn)+++@pytest_asyncio.fixture(scope="session")+async def _mysql_available(mysql_dsn: str) -> bool:+ """Quick probe — connection refused → skip MySQL tests."""+ try:+ conn = await aiomysql.connect(connect_timeout=2, **_mysql_cfg(mysql_dsn))+ await conn.ensure_closed()+ return True+ except (aiomysql.Error, OSError, ConnectionError):+ return False+++@pytest_asyncio.fixture+async def clean_mysql_db(mysql_dsn: str, _mysql_available: bool):+ """Create a fresh database for each test; drop after."""+ if not _mysql_available:+ pytest.skip(+ "MySQL not available for E2E tests; set CUBEPI_TEST_MYSQL_DSN "+ "to a working DSN to enable."+ )++ db_name = f"cubepi_test_{secrets.token_hex(6)}"+ admin_cfg = _mysql_cfg(mysql_dsn)+ admin = await aiomysql.connect(autocommit=True, **admin_cfg)+ try:+ async with admin.cursor() as cur:+ await cur.execute(f"CREATE DATABASE `{db_name}`")+ finally:+ await admin.ensure_closed()++ base = mysql_dsn.rsplit("/", 1)[0]+ test_dsn = f"{base}/{db_name}"+ yield test_dsn++ admin = await aiomysql.connect(autocommit=True, **admin_cfg)+ try:+ async with admin.cursor() as cur:+ await cur.execute(f"DROP DATABASE IF EXISTS `{db_name}`")+ finally:+ await admin.ensure_closed()diff --git a/tests/checkpointer/test_mysql.py b/tests/checkpointer/test_mysql.pynew file mode 100644index 0000000..767f3bc--- /dev/null+++ b/tests/checkpointer/test_mysql.py@@ -0,0 +1,531 @@+"""MySQLCheckpointer tests — mirrors test_postgres.py."""++import aiomysql+import pytest++from cubepi.checkpointer.mysql.alembic_helpers import (+ messages_partition_clause,+ write_schema_version_op,+)++# ---------------------------------------------------------------------------+# Unit tests (no DB)+# ---------------------------------------------------------------------------+++def test_exceptions_are_postgres_aliases() -> None:+ from cubepi.checkpointer.mysql.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+ )+ from cubepi.checkpointer.postgres import exceptions as pg_exc++ assert CubepiSchemaError is pg_exc.CubepiSchemaError+ assert CubepiSchemaMismatch is pg_exc.CubepiSchemaMismatch+ assert CubepiSchemaUninitialized is pg_exc.CubepiSchemaUninitialized+++def test_models_import() -> None:+ from cubepi.checkpointer.mysql.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ CubepiMessage,+ CubepiSchemaVersion,+ CubepiThread,+ cubepi_metadata,+ )++ assert EXPECTED_SCHEMA_VERSION == 1+ assert PARTITION_COUNT == 64+ assert CubepiThread.__tablename__ == "cubepi_threads"+ assert CubepiMessage.__tablename__ == "cubepi_messages"+ assert CubepiSchemaVersion.__tablename__ == "cubepi_schema_version"+ assert "cubepi_threads" in cubepi_metadata.tables+ assert "cubepi_messages" in cubepi_metadata.tables+ assert "cubepi_schema_version" in cubepi_metadata.tables+++def test_threads_parent_self_fk_present() -> None:+ """parent_thread_id keeps a self-FK (threads table is not partitioned)."""+ from cubepi.checkpointer.mysql.models import cubepi_metadata++ threads = cubepi_metadata.tables["cubepi_threads"]+ fk_targets = {+ fk.column.table.name for col in threads.columns for fk in col.foreign_keys+ }+ assert "cubepi_threads" in fk_targets+++def test_messages_has_no_foreign_keys() -> None:+ """messages table is partitioned, so no FK is allowed."""+ from cubepi.checkpointer.mysql.models import cubepi_metadata++ msgs = cubepi_metadata.tables["cubepi_messages"]+ assert msgs.foreign_keys == set()+++def test_messages_has_no_metadata_index() -> None:+ from cubepi.checkpointer.mysql.models import cubepi_metadata++ msgs = cubepi_metadata.tables["cubepi_messages"]+ assert msgs.indexes == set()+++def test_messages_partition_clause() -> None:+ clause = messages_partition_clause()+ assert clause == "PARTITION BY KEY (thread_id) PARTITIONS 64"+++def test_write_schema_version_op_clears_stale_then_inserts() -> None:+ sql = write_schema_version_op()+ assert "DELETE FROM cubepi_schema_version" in sql+ assert "WHERE version <> 1" in sql+ assert "INSERT IGNORE INTO cubepi_schema_version" in sql+ assert "VALUES (1)" in sql+ assert sql.index("DELETE") < sql.index("INSERT")+++def test_role_of_known_message_types() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _role_of+ from cubepi.providers.base import (+ AssistantMessage,+ TextContent,+ ToolResultMessage,+ Usage,+ UserMessage,+ )++ assert _role_of(UserMessage(content=[TextContent(text="x")])) == "user"+ assert (+ _role_of(AssistantMessage(content=[TextContent(text="x")], usage=Usage()))+ == "assistant"+ )+ tr = ToolResultMessage(+ tool_call_id="tc-1", tool_name="t", content=[TextContent(text="ok")]+ )+ assert _role_of(tr) == "tool"+++def test_role_of_rejects_unknown_message_type() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _role_of++ class FakeMessage:+ pass++ with pytest.raises(TypeError, match="unknown Message type"):+ _role_of(FakeMessage()) # type: ignore[arg-type]+++def test_parse_dsn_full() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ cfg = _parse_dsn("mysql://user:[email protected]:3307/mydb")+ assert cfg == {+ "host": "db.example.com",+ "port": 3307,+ "user": "user",+ "password": "pw",+ "db": "mydb",+ }+++def test_parse_dsn_defaults_port_3306() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ cfg = _parse_dsn("mysql://root@localhost/x")+ assert cfg["port"] == 3306+ assert cfg["password"] == ""+++def test_decode_json_handles_str_and_dict() -> None:+ from cubepi.checkpointer.mysql.checkpointer import _decode_json++ assert _decode_json('{"a": 1}') == {"a": 1}+ assert _decode_json({"a": 1}) == {"a": 1}+ assert _decode_json(None) == {}+++async def test_append_empty_messages_is_noop() -> None:+ from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer++ cp = MySQLCheckpointer("mysql://root@unreachable-host/none")+ assert cp._pool is None+ await cp.append("thread-x", [])+ assert cp._pool is None+++def test_top_level_lazy_import() -> None:+ import cubepi.checkpointer as cp_pkg++ assert cp_pkg.MySQLCheckpointer is not None+ assert "MySQLCheckpointer" in cp_pkg.__all__+++def test_mysql_import_does_not_require_asyncpg() -> None:+ """The cubepi[mysql] extra must not pull in asyncpg (the Postgres driver).++ Run in a fresh interpreter with asyncpg import forced to fail, to catch any+ transitive import into the Postgres package.+ """+ import subprocess+ import sys+ import textwrap++ code = textwrap.dedent(+ """+ import builtins+ real = builtins.__import__+ def fake(name, *a, **k):+ if name == "asyncpg" or name.startswith("asyncpg."):+ raise ModuleNotFoundError("No module named asyncpg")+ return real(name, *a, **k)+ builtins.__import__ = fake+ from cubepi.checkpointer import MySQLCheckpointer+ assert MySQLCheckpointer is not None+ print("OK")+ """+ )+ result = subprocess.run(+ [sys.executable, "-c", code], capture_output=True, text=True+ )+ assert result.returncode == 0, result.stderr+ assert "OK" in result.stdout+++# ---------------------------------------------------------------------------+# E2E tests — require a real MySQL instance (8.0.13+)+# ---------------------------------------------------------------------------+++async def _setup_schema(dsn: str) -> None:+ """Build the cubepi schema (matching what host alembic would generate)."""+ 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(+ """+ 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_checkpointer_round_trip(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import (+ AssistantMessage,+ TextContent,+ Usage,+ UserMessage,+ )++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ msg1 = UserMessage(+ content=[TextContent(text="hello")],+ metadata={"memory_snapshot": {"id": "m1"}},+ )+ msg2 = AssistantMessage(+ content=[TextContent(text="hi back")],+ usage=Usage(),+ metadata={"cost_cents": 5},+ )+ await cp.append("t-1", [msg1, msg2])+ data = await cp.load("t-1")++ assert data is not None+ assert len(data.messages) == 2+ assert isinstance(data.messages[0], UserMessage)+ assert isinstance(data.messages[1], AssistantMessage)+ assert data.messages[0].metadata == {"memory_snapshot": {"id": "m1"}}+ assert data.messages[1].metadata == {"cost_cents": 5}+ assert data.messages[0].content[0].text == "hello"+ assert data.messages[1].content[0].text == "hi back"+++async def test_mysql_checkpointer_save_extra_merges(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import TextContent, UserMessage++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ await cp.append("t-2", [UserMessage(content=[TextContent(text="x")])])+ await cp.save_extra("t-2", {"a": 1})+ await cp.save_extra("t-2", {"b": 2})+ data = await cp.load("t-2")++ assert data is not None+ assert data.extra == {"a": 1, "b": 2}+++async def test_mysql_checkpointer_save_extra_shallow_merge_semantics(+ clean_mysql_db,+) -> None:+ """Shallow top-level merge (dict.update), NOT JSON_MERGE_PATCH.++ JSON_MERGE_PATCH would (a) delete keys whose value is null and+ (b) deep-merge nested objects. dict.update overwrites top-level keys,+ keeps null values, and replaces nested objects wholesale.+ """+ from cubepi.checkpointer.mysql import MySQLCheckpointer++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ await cp.save_extra("t-sem", {"a": 1, "nested": {"x": 1}, "keep": "v"})+ await cp.save_extra("t-sem", {"a": 2, "nested": {"y": 2}, "z": None})+ data = await cp.load("t-sem")++ assert data is not None+ assert data.extra == {+ "a": 2, # overwritten+ "nested": {"y": 2}, # replaced wholesale, not deep-merged+ "keep": "v", # untouched+ "z": None, # null preserved, not deleted+ }+++async def test_mysql_checkpointer_seq_monotonic(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import TextContent, UserMessage++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ msgs1 = [UserMessage(content=[TextContent(text=str(i))]) for i in range(5)]+ await cp.append("t-3", msgs1)+ msgs2 = [UserMessage(content=[TextContent(text=str(i))]) for i in range(5, 10)]+ await cp.append("t-3", msgs2)+ data = await cp.load("t-3")++ assert data is not None+ assert len(data.messages) == 10+ texts = [m.content[0].text for m in data.messages]+ assert texts == [str(i) for i in range(10)]+++async def test_uninitialized_schema_raises(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import (+ CubepiSchemaUninitialized,+ MySQLCheckpointer,+ )++ with pytest.raises(CubepiSchemaUninitialized):+ async with MySQLCheckpointer(clean_mysql_db):+ pass+++async def test_version_mismatch_raises(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import CubepiSchemaMismatch, MySQLCheckpointer+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ await _setup_schema(clean_mysql_db)+ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))+ try:+ async with conn.cursor() as cur:+ await cur.execute("UPDATE cubepi_schema_version SET version = 999")+ finally:+ await conn.ensure_closed()++ with pytest.raises(CubepiSchemaMismatch) as exc_info:+ async with MySQLCheckpointer(clean_mysql_db):+ pass+ assert exc_info.value.expected == 1+ assert exc_info.value.actual == 999+++async def test_empty_thread_load_returns_none(clean_mysql_db) -> None:+ from cubepi.checkpointer.mysql import MySQLCheckpointer++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ data = await cp.load("nonexistent-thread")+ assert data is None+++async def test_mysql_checkpointer_rich_content_round_trip(clean_mysql_db) -> None:+ """Round-trip thinking + tool-call + tool-result content types."""+ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import (+ AssistantMessage,+ TextContent,+ ThinkingContent,+ ToolCall,+ ToolResultMessage,+ Usage,+ )++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db) as cp:+ assistant = AssistantMessage(+ content=[+ ThinkingContent(thinking="let me think"),+ TextContent(text="calling a tool"),+ ToolCall(id="call-1", name="search", arguments={"q": "cubepi"}),+ ],+ usage=Usage(),+ )+ tool_result = ToolResultMessage(+ tool_call_id="call-1",+ tool_name="search",+ content=[TextContent(text="result text")],+ )+ await cp.append("t-rich", [assistant, tool_result])+ data = await cp.load("t-rich")++ assert data is not None+ assert len(data.messages) == 2+ am, tr = data.messages+ assert isinstance(am, AssistantMessage)+ assert isinstance(am.content[0], ThinkingContent)+ assert am.content[0].thinking == "let me think"+ assert isinstance(am.content[2], ToolCall)+ assert am.content[2].id == "call-1"+ assert am.content[2].arguments == {"q": "cubepi"}+ assert isinstance(tr, ToolResultMessage)+ assert tr.tool_call_id == "call-1"+ assert tr.content[0].text == "result text"+++async def test_mysql_checkpointer_concurrent_append_seq_unique(+ clean_mysql_db,+) -> None:+ """Concurrent appends to one thread serialize via FOR UPDATE.++ Two appends race on the same thread; the row lock must give every+ message a unique, contiguous seq with no gaps or collisions.+ """+ import asyncio++ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.providers.base import TextContent, UserMessage++ await _setup_schema(clean_mysql_db)+ async with MySQLCheckpointer(clean_mysql_db, max_pool_size=4) as cp:+ batch_a = [UserMessage(content=[TextContent(text=f"a{i}")]) for i in range(10)]+ batch_b = [UserMessage(content=[TextContent(text=f"b{i}")]) for i in range(10)]+ await asyncio.gather(+ cp.append("t-conc", batch_a),+ cp.append("t-conc", batch_b),+ )+ data = await cp.load("t-conc")++ assert data is not None+ assert len(data.messages) == 20+ texts = {m.content[0].text for m in data.messages}+ assert texts == {f"a{i}" for i in range(10)} | {f"b{i}" for i in range(10)}+++async def test_empty_version_table_raises_uninitialized(clean_mysql_db) -> None:+ """Schema present but cubepi_schema_version has no row → Uninitialized."""+ from cubepi.checkpointer.mysql import (+ CubepiSchemaUninitialized,+ MySQLCheckpointer,+ )+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ await _setup_schema(clean_mysql_db)+ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))+ try:+ async with conn.cursor() as cur:+ await cur.execute("DELETE FROM cubepi_schema_version")+ finally:+ await conn.ensure_closed()++ with pytest.raises(CubepiSchemaUninitialized):+ async with MySQLCheckpointer(clean_mysql_db):+ pass+++async def test_load_unknown_role_raises(clean_mysql_db) -> None:+ """A message row with an unrecognized role string → ValueError on load."""+ import msgpack++ from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ await _setup_schema(clean_mysql_db)+ payload = msgpack.packb({"content": []}, use_bin_type=True)+ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))+ try:+ async with conn.cursor() as cur:+ await cur.execute("INSERT INTO cubepi_threads (thread_id) VALUES ('t-bad')")+ await cur.execute(+ "INSERT INTO cubepi_messages "+ "(thread_id, seq, role, metadata, payload) "+ "VALUES ('t-bad', 1, 'bogus', '{}', %s)",+ (payload,),+ )+ finally:+ await conn.ensure_closed()++ async with MySQLCheckpointer(clean_mysql_db) as cp:+ with pytest.raises(ValueError, match="unknown role in DB"):+ await cp.load("t-bad")+++async def test_missing_version_column_raises_uninitialized(clean_mysql_db) -> None:+ """A malformed cubepi_schema_version table (no `version` column) → 1054 path."""+ from cubepi.checkpointer.mysql import (+ CubepiSchemaUninitialized,+ MySQLCheckpointer,+ )+ from cubepi.checkpointer.mysql.checkpointer import _parse_dsn++ 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 (wrong_col INT PRIMARY KEY) "+ "ENGINE=InnoDB"+ )+ finally:+ await conn.ensure_closed()++ with pytest.raises(CubepiSchemaUninitialized):+ async with MySQLCheckpointer(clean_mysql_db):+ passdiff --git a/uv.lock b/uv.lockindex b7e0468..19a0e73 100644--- a/uv.lock+++ b/uv.lock@@ -2,6 +2,18 @@ version = 1revision = 3requires-python = ">=3.11"+[[package]]+name = "aiomysql"+version = "0.3.2"+source = { registry = "https://pypi.org/simple/" }+dependencies = [+ { name = "pymysql" },+]+sdist = { url = "https://files.pythonhosted.org/packages/29/e0/302aeffe8d90853556f47f3106b89c16cc2ec2a4d269bdfd82e3f4ae12cc/aiomysql-0.3.2.tar.gz", hash = "sha256:72d15ef5cfc34c03468eb41e1b90adb9fd9347b0b589114bd23ead569a02ac1a", size = 108311, upload-time = "2025-10-22T00:15:21.278Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/4c/af/aae0153c3e28712adaf462328f6c7a3c196a1c1c27b491de4377dd3e6b52/aiomysql-0.3.2-py3-none-any.whl", hash = "sha256:c82c5ba04137d7afd5c693a258bea8ead2aad77101668044143a991e04632eb2", size = 71834, upload-time = "2025-10-22T00:15:15.905Z" },+]+[[package]]name = "aiosqlite"version = "0.22.1"@@ -479,6 +491,12 @@ docs = [mcp = [{ name = "mcp" },]+mysql = [+ { name = "aiomysql" },+ { name = "cryptography" },+ { name = "msgpack" },+ { name = "sqlalchemy" },+]postgres = [{ name = "asyncpg" },{ name = "msgpack" },@@ -499,6 +517,7 @@ tracing-otlp = [[package.dev-dependencies]dev = [+ { name = "aiomysql" },{ name = "aiosqlite" },{ name = "asyncpg" },{ name = "mcp" },@@ -513,11 +532,14 @@ dev = [[package.metadata]requires-dist = [+ { name = "aiomysql", marker = "extra == 'mysql'", specifier = ">=0.2" },{ name = "aiosqlite", marker = "extra == 'sqlite'", specifier = ">=0.22.1" },{ name = "anthropic", specifier = ">=0.100.0" },{ name = "asyncpg", marker = "extra == 'postgres'", specifier = ">=0.29" },+ { name = "cryptography", marker = "extra == 'mysql'", specifier = ">=42" },{ name = "griffe", marker = "extra == 'docs'", specifier = ">=0.45" },{ name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.0" },+ { name = "msgpack", marker = "extra == 'mysql'", specifier = ">=1.0" },{ name = "msgpack", marker = "extra == 'postgres'", specifier = ">=1.0" },{ name = "openai", specifier = ">=2.36.0" },{ name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'tracing-otlp'", specifier = ">=1.30" },@@ -525,12 +547,14 @@ requires-dist = [{ name = "pydantic", specifier = ">=2.13.4" },{ name = "pyyaml", specifier = ">=6.0.3" },{ name = "rich", marker = "extra == 'trace-cli'", specifier = ">=13.0" },+ { name = "sqlalchemy", marker = "extra == 'mysql'", specifier = ">=2.0" },{ name = "sqlalchemy", marker = "extra == 'postgres'", specifier = ">=2.0" },]-provides-extras = ["sqlite", "postgres", "mcp", "docs", "tracing", "tracing-otlp", "trace-cli"]+provides-extras = ["sqlite", "postgres", "mysql", "mcp", "docs", "tracing", "tracing-otlp", "trace-cli"][package.metadata.requires-dev]dev = [+ { name = "aiomysql", specifier = ">=0.2" },{ name = "aiosqlite", specifier = ">=0.22.1" },{ name = "asyncpg", specifier = ">=0.29" },{ name = "mcp", specifier = ">=1.0" },@@ -1244,6 +1268,15 @@ crypto = [{ name = "cryptography" },]+[[package]]+name = "pymysql"+version = "1.2.0"+source = { registry = "https://pypi.org/simple/" }+sdist = { url = "https://files.pythonhosted.org/packages/c9/bc/1c6a92f385940f727daeecf3bacaf186e03875dff57197801046c583bcf0/pymysql-1.2.0.tar.gz", hash = "sha256:6c7b17ca686988104d7426c27895b455cdeea3e9d3ceb1270f0c3704fead8c33", size = 49021, upload-time = "2026-05-19T08:26:22.302Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c4/bd/2534e130295c8cfd4f0a2e31623baab7502278f1e97bcfe61db75656a77f/pymysql-1.2.0-py3-none-any.whl", hash = "sha256:62169ce6d5510f08e140c5e7990ee884a9764024e4a9a27b2cc11f1099322ae0", size = 45716, upload-time = "2026-05-19T08:26:20.974Z" },+]+[[package]]name = "pytest"version = "9.0.3"diff --git a/website/docs/guides/checkpointing/mysql.md b/website/docs/guides/checkpointing/mysql.mdnew file mode 100644index 0000000..42fbce4--- /dev/null+++ b/website/docs/guides/checkpointing/mysql.md@@ -0,0 +1,197 @@+---+title: MySQL Checkpointing+---++# MySQL Checkpointing++`MySQLCheckpointer` is a production-grade persistence backend for+deployments standardized on MySQL. It mirrors+[`PostgresCheckpointer`](./postgres): `aiomysql` connection pool,+`msgpack` payloads, a queryable JSON `metadata` column, and a+host-managed schema verified on connect. Per-thread `seq` allocation is+serialized with a `SELECT … FOR UPDATE` row lock so multiple processes+can append to the same `thread_id` safely.++**Requires MySQL 8.0.13+** (for JSON expression defaults) on the InnoDB+engine.++Install the extra:++```bash+pip install "cubepi[mysql]"+```++This pulls in `aiomysql`, `sqlalchemy`, and `msgpack`.++## Basic usage++```python+import asyncio+from cubepi import Agent, Model+from cubepi.checkpointer import MySQLCheckpointer+from cubepi.providers.anthropic import AnthropicProvider+++async def main():+ provider = AnthropicProvider(api_key="…")+ async with MySQLCheckpointer("mysql://user:pass@host:3306/dbname") as cp:+ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ checkpointer=cp,+ thread_id="user-42",+ )+ await agent.prompt("hello")+++asyncio.run(main())+```++The connection is configured from a `mysql://user:pass@host:port/db`+DSN. Pool sizing:++```python+async with MySQLCheckpointer(+ "mysql://…",+ min_pool_size=2,+ max_pool_size=20,+) as cp:+ …+```++## Schema++The checkpointer expects three tables: `cubepi_threads`,+`cubepi_messages`, and `cubepi_schema_version`. Like Postgres (and+unlike SQLite), CubePi **does not create these for you** — it verifies+on `__aenter__` that they exist with the expected `schema_version`.++If they're missing, you get `CubepiSchemaUninitialized`. If the version+doesn't match this cubepi release, you get `CubepiSchemaMismatch`. A+production database belongs to the host application's migration system+(Alembic, …), not to a third-party library.++### Bootstrapping via Alembic++CubePi exposes the SQLAlchemy `MetaData` so your migrations can adopt+the schema:++```python+# alembic/env.py+from cubepi.checkpointer.mysql import cubepi_metadata, EXPECTED_SCHEMA_VERSION++target_metadata = [my_app_metadata, cubepi_metadata]+```++The `cubepi_messages` table is `KEY`-partitioned, which SQLAlchemy's+autogenerate cannot express, so append the partition clause and the+schema-version write with the provided helpers:++```python+# In a migration's upgrade():+from cubepi.checkpointer.mysql.alembic_helpers import (+ messages_partition_clause,+ write_schema_version_op,+)++def upgrade():+ op.create_table("cubepi_threads", ...)+ op.create_table(+ "cubepi_messages", ...,+ mysql_engine="InnoDB",+ )+ # KEY(thread_id) partitioning is not autogenerated — apply it explicitly:+ op.execute(+ "ALTER TABLE cubepi_messages " + messages_partition_clause()+ )+ op.create_table("cubepi_schema_version", ...)+ # write_schema_version_op() returns two ';'-separated statements+ # (DELETE then INSERT). MySQL/pymysql runs one statement per execute,+ # so split and execute each:+ for stmt in write_schema_version_op().split(";"):+ if stmt.strip():+ op.execute(stmt)+```++`write_schema_version_op()` is idempotent: it deletes any rows from a+prior cubepi version and inserts the current one. When CubePi later+bumps `EXPECTED_SCHEMA_VERSION`, generate a new revision and run it+again.++## Data model++```+cubepi_threads+ thread_id (PK) -- VARCHAR(255) utf8mb4_bin (case-sensitive)+ parent_thread_id -- self-FK, for forks+ forked_at_seq -- seq number at fork point+ extra -- JSON+ created_at / updated_at++cubepi_messages+ thread_id, seq -- composite PK; partitioned by KEY(thread_id) into 64+ role -- "user" | "assistant" | "tool"+ metadata -- JSON (not indexed; see below)+ payload -- LONGBLOB (msgpack)+ created_at++cubepi_schema_version+ version (PK)+```++Important properties:++- **`(thread_id, seq)` is the message identity.** `seq` is monotonic+ per thread, allocated under a `SELECT … FOR UPDATE` row lock on the+ thread row. Two concurrent writers on the same thread serialize+ cleanly.+- **`payload` is msgpack-encoded `model.model_dump(mode="json")`.**+ CubePi reconstructs the Pydantic model on read.+- **`metadata` is JSON, queryable** via MySQL JSON functions. It is+ **not** indexed — MySQL can't index a JSON column directly. If you+ need to query messages by metadata, add a generated-column index+ host-side.+- **Messages are partitioned by `KEY(thread_id)` into 64 partitions.**+ Even distribution, no per-thread bottleneck. The table has **no+ foreign key** to `cubepi_threads` (MySQL forbids FKs on partitioned+ tables); integrity is preserved by the lazy thread-row insert on+ `append`.++## Differences from the Postgres backend++| | Postgres | MySQL |+|---|---|---|+| Driver | `asyncpg` | `aiomysql` |+| `seq` lock | `pg_advisory_xact_lock` | `SELECT … FOR UPDATE` |+| Messages partitioning | `HASH(thread_id)` + FK | `KEY(thread_id)`, no FK |+| `metadata` index | GIN | none (add a generated column) |+| Thread IDs | `TEXT` | `VARCHAR(255) utf8mb4_bin` |+| Min version | — | MySQL 8.0.13+, InnoDB |++## `save_extra` semantics++`save_extra` does a shallow top-level merge, not a replace — the same+behavior as Postgres and SQLite. Writing `{"foo": 1}` then `{"bar": 2}`+leaves `{"foo": 1, "bar": 2}`. (Internally it reads the current `extra`+under a row lock and writes the merged dict, rather than using+`JSON_MERGE_PATCH`, whose null-deletion and deep-merge semantics differ+from `dict.update`.)++## Common pitfalls++- **`CubepiSchemaUninitialized`** — Your DB is empty, your migrations+ didn't run, or the `cubepi_schema_version` table is malformed. Apply+ the host alembic upgrade first.+- **`CubepiSchemaMismatch`** — You upgraded cubepi but didn't generate a+ new migration. Generate one, apply it, and CubePi will start.+- **JSON default errors on older MySQL** — JSON columns use+ `DEFAULT (JSON_OBJECT())`, which requires MySQL 8.0.13+.+- **Case-insensitive thread-ID collisions** — Thread IDs use the+ `utf8mb4_bin` collation so `UserA` and `usera` stay distinct. If you+ hand-roll the DDL, keep that collation.++## See also++- [Postgres Checkpointing](./postgres) — the Postgres-backed sibling.+- [SQLite Checkpointing](./sqlite) — single-process alternative.+- [Custom Backends](./custom) — Protocol details.diff --git a/website/sidebars.ts b/website/sidebars.tsindex 1a1571c..b957c36 100644--- a/website/sidebars.ts+++ b/website/sidebars.ts@@ -32,6 +32,7 @@ const sidebars: SidebarsConfig = {{ type: 'category', label: 'Checkpointing', items: ['guides/checkpointing/sqlite','guides/checkpointing/postgres',+ 'guides/checkpointing/mysql','guides/checkpointing/custom',]},{ type: 'category', label: 'Middleware', items: [