Skip to content

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

feat(mysql): snapshot + fork (threads-first, set-based)

xf gong683f5a986a8a
diff --git a/cubepi/checkpointer/mysql/checkpointer.py b/cubepi/checkpointer/mysql/checkpointer.py
index 9604458..fba605c 100644
--- a/cubepi/checkpointer/mysql/checkpointer.py
+++ b/cubepi/checkpointer/mysql/checkpointer.py
@@ -21,6 +21,9 @@ from cubepi.checkpointer.exceptions import (
RunAlreadyClaimedError,
RunAlreadyCompletedError,
RunNotClaimedError,
+ RunNotCompletedError,
+ ThreadAlreadyExistsError,
+ ThreadNotFoundError,
)
from cubepi.checkpointer.mysql.exceptions import (
CubepiSchemaMismatch,
@@ -179,7 +182,8 @@ class MySQLCheckpointer:
)
msg_rows = await cur.fetchall()
await cur.execute(
- "SELECT extra FROM cubepi_threads WHERE thread_id = %s",
+ "SELECT extra, parent_thread_id FROM cubepi_threads "
+ "WHERE thread_id = %s",
(thread_id,),
)
extra_row = await cur.fetchone()
@@ -196,8 +200,15 @@ class MySQLCheckpointer:
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)
+ parent_thread_id: str | None = None
+ if extra_row is not None:
+ extra = _decode_json(extra_row[0])
+ parent_thread_id = extra_row[1]
+ else:
+ extra = {}
+ return CheckpointData(
+ messages=messages, extra=extra, parent_thread_id=parent_thread_id
+ )
async def append(self, thread_id: str, messages: list[Message]) -> None:
if not messages:
@@ -401,6 +412,171 @@ class MySQLCheckpointer:
req = HitlRequest.model_validate(raw)
return req, row[1]
+ async def snapshot(self, thread_id: str, *, after_run_id: str) -> list[Message]:
+ """Return the message slice that fork() would copy, without writing.
+
+ Includes legacy messages with NULL ``run_id`` plus messages whose
+ ``run_id`` belongs to a completed run at or before
+ ``after_run_id``'s completion cutoff. Raises ``ThreadNotFoundError``
+ if the source thread row is absent, or ``RunNotCompletedError`` if
+ ``after_run_id`` has not yet been completion-marked.
+ """
+ assert self._pool is not None
+ async with self._pool.acquire() as conn:
+ async with conn.cursor() as cur:
+ await cur.execute(
+ "SELECT 1 FROM cubepi_threads WHERE thread_id = %s",
+ (thread_id,),
+ )
+ if await cur.fetchone() is None:
+ raise ThreadNotFoundError(f"thread={thread_id}")
+ await cur.execute(
+ "SELECT completion_seq FROM cubepi_runs "
+ "WHERE thread_id = %s AND run_id = %s",
+ (thread_id, after_run_id),
+ )
+ cutoff_row = await cur.fetchone()
+ if cutoff_row is None or cutoff_row[0] is None:
+ raise RunNotCompletedError(
+ f"thread={thread_id} run={after_run_id} not completed"
+ )
+ cutoff = cutoff_row[0]
+ await cur.execute(
+ "SELECT seq, role, metadata, payload FROM cubepi_messages "
+ "WHERE thread_id = %s AND ("
+ " run_id IS NULL OR run_id IN ("
+ " SELECT run_id FROM cubepi_runs "
+ " WHERE thread_id = %s "
+ " AND completion_seq IS NOT NULL "
+ " AND completion_seq <= %s"
+ " )"
+ ") ORDER BY seq",
+ (thread_id, thread_id, cutoff),
+ )
+ rows = await cur.fetchall()
+ messages: list[Message] = []
+ for _seq, role, metadata, payload in 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))
+ return messages
+
+ async def fork(
+ self,
+ src_thread_id: str,
+ new_thread_id: str,
+ *,
+ after_run_id: str,
+ metadata: JsonObject | None = None,
+ ) -> None:
+ """Copy completed prefix of ``src_thread_id`` into ``new_thread_id``.
+
+ Threads-row first: the destination ``cubepi_threads`` row is
+ inserted before the message + runs copies so callers see a
+ complete view if they probe mid-fork. There is no cubepi_runs ->
+ cubepi_threads FK on MySQL (partition limitation), but we keep
+ the same ordering for semantic parity with Postgres.
+
+ Per-thread serialization: a ``SELECT … FOR UPDATE`` on the source
+ thread row fences concurrent forks/appends — without it, an
+ append racing the fork could leak a partial in-flight run into
+ the destination.
+ """
+ assert self._pool is not None
+ async with self._pool.acquire() as conn:
+ await conn.begin()
+ try:
+ async with conn.cursor() as cur:
+ # Per-thread fence on the source thread.
+ await cur.execute(
+ "SELECT thread_id FROM cubepi_threads "
+ "WHERE thread_id = %s FOR UPDATE",
+ (src_thread_id,),
+ )
+ if await cur.fetchone() is None:
+ raise ThreadNotFoundError(f"thread={src_thread_id}")
+ # Destination must not exist.
+ await cur.execute(
+ "SELECT 1 FROM cubepi_threads WHERE thread_id = %s",
+ (new_thread_id,),
+ )
+ if await cur.fetchone() is not None:
+ raise ThreadAlreadyExistsError(f"thread={new_thread_id}")
+ # Cutoff: after_run_id must be completed on src.
+ await cur.execute(
+ "SELECT completion_seq FROM cubepi_runs "
+ "WHERE thread_id = %s AND run_id = %s",
+ (src_thread_id, after_run_id),
+ )
+ cutoff_row = await cur.fetchone()
+ if cutoff_row is None or cutoff_row[0] is None:
+ raise RunNotCompletedError(
+ f"thread={src_thread_id} run={after_run_id} not completed"
+ )
+ cutoff = cutoff_row[0]
+ # Build merged extra (carry parent's extra + fork metadata).
+ await cur.execute(
+ "SELECT extra FROM cubepi_threads WHERE thread_id = %s",
+ (src_thread_id,),
+ )
+ extra_row = await cur.fetchone()
+ base_extra = (
+ _decode_json(extra_row[0]) if extra_row is not None else {}
+ )
+ if metadata is not None:
+ # Round-trip through json to coerce to plain JSON types.
+ base_extra["fork"] = json.loads(json.dumps(metadata))
+ # INSERT destination threads row first (semantic parity
+ # with the Postgres FK-driven ordering, even though MySQL
+ # has no FK on the partitioned messages/runs tables).
+ await cur.execute(
+ "INSERT INTO cubepi_threads "
+ "(thread_id, parent_thread_id, forked_at_seq, extra) "
+ "VALUES (%s, %s, %s, %s)",
+ (
+ new_thread_id,
+ src_thread_id,
+ cutoff,
+ json.dumps(base_extra),
+ ),
+ )
+ # Copy messages: legacy NULL run_id OR completed-at-cutoff.
+ await cur.execute(
+ "INSERT INTO cubepi_messages "
+ "(thread_id, seq, role, metadata, payload, run_id) "
+ "SELECT %s, seq, role, metadata, payload, run_id "
+ "FROM cubepi_messages "
+ "WHERE thread_id = %s AND ("
+ " run_id IS NULL OR run_id IN ("
+ " SELECT run_id FROM cubepi_runs "
+ " WHERE thread_id = %s "
+ " AND completion_seq IS NOT NULL "
+ " AND completion_seq <= %s"
+ " )"
+ ") ORDER BY seq",
+ (new_thread_id, src_thread_id, src_thread_id, cutoff),
+ )
+ # Copy completed runs satisfying the cutoff.
+ await cur.execute(
+ "INSERT INTO cubepi_runs "
+ "(thread_id, run_id, claimed_at, completed_at, "
+ " completion_seq) "
+ "SELECT %s, run_id, claimed_at, completed_at, "
+ " completion_seq "
+ "FROM cubepi_runs "
+ "WHERE thread_id = %s "
+ "AND completion_seq IS NOT NULL "
+ "AND completion_seq <= %s",
+ (new_thread_id, src_thread_id, cutoff),
+ )
+ await conn.commit()
+ except BaseException:
+ await conn.rollback()
+ raise
+
async def save_extra(self, thread_id: str, extra: JsonObject) -> None:
assert self._pool is not None
async with self._pool.acquire() as conn:
diff --git a/examples/checkpointing_mysql.py b/examples/checkpointing_mysql.py
index 6aa56b4..9981f98 100644
--- a/examples/checkpointing_mysql.py
+++ b/examples/checkpointing_mysql.py
@@ -32,7 +32,9 @@ from cubepi.agent.agent import Agent
from cubepi.checkpointer.mysql import MySQLCheckpointer
from cubepi.checkpointer.mysql.alembic_helpers import (
add_pending_request_column_op,
+ add_run_id_column_op,
messages_partition_clause,
+ upgrade_v3_to_v4_op,
write_schema_version_op,
)
from cubepi.checkpointer.mysql.checkpointer import _parse_dsn
@@ -70,6 +72,7 @@ async def bootstrap_schema(dsn: str) -> None:
) ENGINE=InnoDB
""")
await cur.execute(add_pending_request_column_op()) # v1 -> v2 column
+ await cur.execute(add_run_id_column_op()) # v2 -> v3 column
await cur.execute(
"""
CREATE TABLE cubepi_messages (
@@ -87,6 +90,12 @@ async def bootstrap_schema(dsn: str) -> None:
"CREATE TABLE cubepi_schema_version (version INT PRIMARY KEY) "
"ENGINE=InnoDB"
)
+ # v3 -> v4: run_id on cubepi_messages + cubepi_runs partitioned table.
+ # upgrade_v3_to_v4_op() returns multiple ';'-separated statements;
+ # MySQL runs one per call, so split before executing.
+ for stmt in upgrade_v3_to_v4_op().split(";"):
+ if stmt.strip():
+ await cur.execute(stmt)
# write_schema_version_op() returns two ';'-separated statements;
# MySQL runs one per call, so split before executing.
for stmt in write_schema_version_op().split(";"):
diff --git a/tests/checkpointer/test_mysql_fork.py b/tests/checkpointer/test_mysql_fork.py
new file mode 100644
index 0000000..8c9c65b
--- /dev/null
+++ b/tests/checkpointer/test_mysql_fork.py
@@ -0,0 +1,131 @@
+"""MySQLCheckpointer snapshot/fork tests — mirrors test_postgres_fork.py."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from cubepi.checkpointer.exceptions import (
+ RunNotCompletedError,
+ ThreadAlreadyExistsError,
+ ThreadNotFoundError,
+)
+from cubepi.checkpointer.mysql import MySQLCheckpointer
+from cubepi.providers.base import TextContent, UserMessage
+
+
+def _msg(run_id: str | None, text: str) -> UserMessage:
+ return UserMessage(content=[TextContent(text=text)], run_id=run_id)
+
+
+async def test_fork_copies_completed_runs_only(mysql_v4_dsn) -> None:
+ async with MySQLCheckpointer(mysql_v4_dsn) as cp:
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1"), _msg("A", "a2")])
+ await cp.mark_run_complete("src", "A")
+ await cp.claim_run("src", "B")
+ await cp.append("src", [_msg("B", "b1")])
+ await cp.mark_run_complete("src", "B")
+ # An in-flight run C — must be excluded.
+ await cp.claim_run("src", "C")
+ await cp.append("src", [_msg("C", "c1")])
+ await cp.fork("src", "dst", after_run_id="B")
+ loaded = await cp.load("dst")
+ assert loaded is not None
+ texts = [m.content[0].text for m in loaded.messages]
+ assert texts == ["a1", "a2", "b1"]
+ assert loaded.parent_thread_id == "src"
+
+
+async def test_fork_includes_legacy_null_run_id_prefix(mysql_v4_dsn) -> None:
+ async with MySQLCheckpointer(mysql_v4_dsn) as cp:
+ await cp.append("src", [_msg(None, "legacy")])
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ await cp.mark_run_complete("src", "A")
+ await cp.fork("src", "dst", after_run_id="A")
+ loaded = await cp.load("dst")
+ assert loaded is not None
+ assert [m.content[0].text for m in loaded.messages] == ["legacy", "a1"]
+
+
+async def test_fork_unknown_src_raises_thread_not_found(mysql_v4_dsn) -> None:
+ async with MySQLCheckpointer(mysql_v4_dsn) as cp:
+ with pytest.raises(ThreadNotFoundError):
+ await cp.fork("missing", "dst", after_run_id="X")
+
+
+async def test_fork_unknown_run_id_raises_not_completed(mysql_v4_dsn) -> None:
+ async with MySQLCheckpointer(mysql_v4_dsn) as cp:
+ await cp.append("src", [_msg(None, "x")])
+ with pytest.raises(RunNotCompletedError):
+ await cp.fork("src", "dst", after_run_id="missing")
+
+
+async def test_fork_destination_collision_raises_already_exists(mysql_v4_dsn) -> None:
+ async with MySQLCheckpointer(mysql_v4_dsn) as cp:
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ await cp.mark_run_complete("src", "A")
+ await cp.fork("src", "dst", after_run_id="A")
+ with pytest.raises(ThreadAlreadyExistsError):
+ await cp.fork("src", "dst", after_run_id="A")
+
+
+async def test_fork_carries_extra_and_writes_metadata(mysql_v4_dsn) -> None:
+ async with MySQLCheckpointer(mysql_v4_dsn) as cp:
+ await cp.save_extra("src", {"original": "x"})
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ await cp.mark_run_complete("src", "A")
+ await cp.fork("src", "dst", after_run_id="A", metadata={"source": "test"})
+ loaded = await cp.load("dst")
+ assert loaded is not None
+ assert loaded.extra["original"] == "x"
+ assert loaded.extra["fork"] == {"source": "test"}
+
+
+async def test_snapshot_matches_fork_messages(mysql_v4_dsn) -> None:
+ async with MySQLCheckpointer(mysql_v4_dsn) as cp:
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ await cp.mark_run_complete("src", "A")
+ msgs = await cp.snapshot("src", after_run_id="A")
+ assert [m.content[0].text for m in msgs] == ["a1"]
+
+
+async def test_fork_serialized_with_concurrent_append(mysql_v4_dsn) -> None:
+ """The fork's per-thread SELECT FOR UPDATE must serialize with append.
+
+ Without it, an append racing the fork could leak a partial in-flight
+ run into the destination's messages. We assert the destination ONLY
+ contains the completed prefix regardless of who runs first.
+ """
+ async with MySQLCheckpointer(mysql_v4_dsn, min_pool_size=2, max_pool_size=4) as cp:
+ await cp.claim_run("src", "A")
+ await cp.append("src", [_msg("A", "a1")])
+ await cp.mark_run_complete("src", "A")
+ # Start an in-flight run B that an append targets.
+ await cp.claim_run("src", "B")
+
+ async def do_fork() -> None:
+ await cp.fork("src", "dst", after_run_id="A")
+
+ async def do_append() -> None:
+ await cp.append("src", [_msg("B", "b1")])
+
+ await asyncio.gather(do_fork(), do_append())
+ loaded = await cp.load("dst")
+ assert loaded is not None
+ # Destination must NOT contain b1 — only the completed prefix.
+ texts = [m.content[0].text for m in loaded.messages]
+ assert texts == ["a1"]