Skip to content

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

feat: add Checkpointer protocol with Memory and SQLite implementations

xf gonge8b70236cd7f
diff --git a/cubepi/checkpointer/__init__.py b/cubepi/checkpointer/__init__.py
index e69de29..6d1fd26 100644
--- a/cubepi/checkpointer/__init__.py
+++ b/cubepi/checkpointer/__init__.py
@@ -0,0 +1,4 @@
+from cubepi.checkpointer.base import Checkpointer, CheckpointData
+from cubepi.checkpointer.memory import MemoryCheckpointer
+
+__all__ = ["Checkpointer", "CheckpointData", "MemoryCheckpointer"]
diff --git a/cubepi/checkpointer/base.py b/cubepi/checkpointer/base.py
new file mode 100644
index 0000000..9d31643
--- /dev/null
+++ b/cubepi/checkpointer/base.py
@@ -0,0 +1,17 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Protocol, runtime_checkable
+
+
+@dataclass
+class CheckpointData:
+ messages: list[Any] = field(default_factory=list)
+ extra: dict[str, Any] = field(default_factory=dict)
+
+
+@runtime_checkable
+class Checkpointer(Protocol):
+ async def load(self, thread_id: str) -> CheckpointData | None: ...
+ async def append(self, thread_id: str, messages: list[Any]) -> None: ...
+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None: ...
diff --git a/cubepi/checkpointer/memory.py b/cubepi/checkpointer/memory.py
new file mode 100644
index 0000000..8a59c3d
--- /dev/null
+++ b/cubepi/checkpointer/memory.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+from typing import Any
+
+from cubepi.checkpointer.base import CheckpointData
+
+
+class MemoryCheckpointer:
+ def __init__(self) -> None:
+ self._store: dict[str, CheckpointData] = {}
+
+ async def load(self, thread_id: str) -> CheckpointData | None:
+ return self._store.get(thread_id)
+
+ async def append(self, thread_id: str, messages: list[Any]) -> None:
+ if thread_id not in self._store:
+ self._store[thread_id] = CheckpointData()
+ self._store[thread_id].messages.extend(messages)
+
+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:
+ if thread_id not in self._store:
+ self._store[thread_id] = CheckpointData()
+ self._store[thread_id].extra.update(extra)
diff --git a/cubepi/checkpointer/sqlite.py b/cubepi/checkpointer/sqlite.py
new file mode 100644
index 0000000..c425121
--- /dev/null
+++ b/cubepi/checkpointer/sqlite.py
@@ -0,0 +1,118 @@
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import aiosqlite
+
+from cubepi.checkpointer.base import CheckpointData
+
+
+class SQLiteCheckpointer:
+ def __init__(self, db_path: str) -> None:
+ self._db_path = db_path
+ self._db: aiosqlite.Connection | None = None
+
+ async def __aenter__(self) -> SQLiteCheckpointer:
+ self._db = await aiosqlite.connect(self._db_path)
+ await self._db.execute(
+ "CREATE TABLE IF NOT EXISTS messages ("
+ " id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " thread_id TEXT NOT NULL,"
+ " message_json TEXT NOT NULL,"
+ " created_at REAL NOT NULL DEFAULT (julianday('now'))"
+ ")"
+ )
+ await self._db.execute(
+ "CREATE TABLE IF NOT EXISTS thread_extra ("
+ " thread_id TEXT PRIMARY KEY,"
+ " extra_json TEXT NOT NULL DEFAULT '{}'"
+ ")"
+ )
+ await self._db.commit()
+ return self
+
+ async def __aexit__(self, *args: Any) -> None:
+ if self._db:
+ await self._db.close()
+ self._db = None
+
+ async def load(self, thread_id: str) -> CheckpointData | None:
+ assert self._db is not None
+ cursor = await self._db.execute(
+ "SELECT message_json FROM messages WHERE thread_id = ? ORDER BY id",
+ (thread_id,),
+ )
+ rows = await cursor.fetchall()
+ if not rows:
+ extra_cursor = await self._db.execute(
+ "SELECT extra_json FROM thread_extra WHERE thread_id = ?",
+ (thread_id,),
+ )
+ extra_row = await extra_cursor.fetchone()
+ if not extra_row:
+ return None
+
+ messages = []
+ for row in rows:
+ msg_data = json.loads(row[0])
+ messages.append(_deserialize_message(msg_data))
+
+ extra_cursor = await self._db.execute(
+ "SELECT extra_json FROM thread_extra WHERE thread_id = ?",
+ (thread_id,),
+ )
+ extra_row = await extra_cursor.fetchone()
+ extra = json.loads(extra_row[0]) if extra_row else {}
+
+ return CheckpointData(messages=messages, extra=extra)
+
+ async def append(self, thread_id: str, messages: list[Any]) -> None:
+ assert self._db is not None
+ for msg in messages:
+ msg_json = _serialize_message(msg)
+ await self._db.execute(
+ "INSERT INTO messages (thread_id, message_json) VALUES (?, ?)",
+ (thread_id, msg_json),
+ )
+ await self._db.commit()
+
+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:
+ assert self._db is not None
+ existing_cursor = await self._db.execute(
+ "SELECT extra_json FROM thread_extra WHERE thread_id = ?",
+ (thread_id,),
+ )
+ existing_row = await existing_cursor.fetchone()
+ if existing_row:
+ existing_extra = json.loads(existing_row[0])
+ existing_extra.update(extra)
+ await self._db.execute(
+ "UPDATE thread_extra SET extra_json = ? WHERE thread_id = ?",
+ (json.dumps(existing_extra), thread_id),
+ )
+ else:
+ await self._db.execute(
+ "INSERT INTO thread_extra (thread_id, extra_json) VALUES (?, ?)",
+ (thread_id, json.dumps(extra)),
+ )
+ await self._db.commit()
+
+
+def _serialize_message(msg: Any) -> str:
+ if hasattr(msg, "model_dump"):
+ return json.dumps(msg.model_dump())
+ return json.dumps(msg)
+
+
+def _deserialize_message(data: dict) -> Any:
+ from cubepi.providers.base import AssistantMessage, ToolResultMessage, UserMessage
+
+ role = data.get("role")
+ if role == "user":
+ return UserMessage.model_validate(data)
+ elif role == "assistant":
+ return AssistantMessage.model_validate(data)
+ elif role == "tool_result":
+ return ToolResultMessage.model_validate(data)
+ return data
diff --git a/tests/checkpointer/test_memory.py b/tests/checkpointer/test_memory.py
new file mode 100644
index 0000000..2cdf462
--- /dev/null
+++ b/tests/checkpointer/test_memory.py
@@ -0,0 +1,52 @@
+from cubepi.checkpointer.memory import MemoryCheckpointer
+from cubepi.providers.base import TextContent, UserMessage
+
+
+class TestMemoryCheckpointer:
+ async def test_load_empty_thread(self):
+ cp = MemoryCheckpointer()
+ data = await cp.load("thread-1")
+ assert data is None
+
+ async def test_append_and_load(self):
+ cp = MemoryCheckpointer()
+ msg1 = UserMessage(content=[TextContent(text="hello")])
+ msg2 = UserMessage(content=[TextContent(text="world")])
+
+ await cp.append("thread-1", [msg1])
+ await cp.append("thread-1", [msg2])
+
+ data = await cp.load("thread-1")
+ assert data is not None
+ assert len(data.messages) == 2
+ assert data.messages[0].content[0].text == "hello"
+ assert data.messages[1].content[0].text == "world"
+
+ async def test_save_extra(self):
+ cp = MemoryCheckpointer()
+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="hi")])])
+ await cp.save_extra("thread-1", {"compaction_index": 5})
+
+ data = await cp.load("thread-1")
+ assert data is not None
+ assert data.extra["compaction_index"] == 5
+
+ async def test_save_extra_merges(self):
+ cp = MemoryCheckpointer()
+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="hi")])])
+ await cp.save_extra("thread-1", {"a": 1})
+ await cp.save_extra("thread-1", {"b": 2})
+
+ data = await cp.load("thread-1")
+ assert data.extra == {"a": 1, "b": 2}
+
+ async def test_multiple_threads(self):
+ cp = MemoryCheckpointer()
+ await cp.append("t1", [UserMessage(content=[TextContent(text="t1")])])
+ await cp.append("t2", [UserMessage(content=[TextContent(text="t2")])])
+
+ d1 = await cp.load("t1")
+ d2 = await cp.load("t2")
+
+ assert d1.messages[0].content[0].text == "t1"
+ assert d2.messages[0].content[0].text == "t2"
diff --git a/tests/checkpointer/test_sqlite.py b/tests/checkpointer/test_sqlite.py
new file mode 100644
index 0000000..6931643
--- /dev/null
+++ b/tests/checkpointer/test_sqlite.py
@@ -0,0 +1,61 @@
+import os
+import tempfile
+
+import pytest
+
+from cubepi.checkpointer.sqlite import SQLiteCheckpointer
+from cubepi.providers.base import TextContent, UserMessage
+
+
+def db_path():
+ fd, path = tempfile.mkstemp(suffix=".db")
+ os.close(fd)
+ yield path
+ os.unlink(path)
+
+
+class TestSQLiteCheckpointer:
+ async def test_load_empty_thread(self, db_path):
+ async with SQLiteCheckpointer(db_path) as cp:
+ data = await cp.load("thread-1")
+ assert data is None
+
+ async def test_append_and_load(self, db_path):
+ async with SQLiteCheckpointer(db_path) as cp:
+ msg1 = UserMessage(content=[TextContent(text="hello")])
+ msg2 = UserMessage(content=[TextContent(text="world")])
+ await cp.append("thread-1", [msg1])
+ await cp.append("thread-1", [msg2])
+
+ data = await cp.load("thread-1")
+ assert data is not None
+ assert len(data.messages) == 2
+ assert data.messages[0].content[0].text == "hello"
+
+ async def test_save_extra(self, db_path):
+ async with SQLiteCheckpointer(db_path) as cp:
+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="hi")])])
+ await cp.save_extra("thread-1", {"index": 42})
+
+ data = await cp.load("thread-1")
+ assert data.extra["index"] == 42
+
+ async def test_persistence_across_instances(self, db_path):
+ async with SQLiteCheckpointer(db_path) as cp:
+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="persist")])])
+
+ async with SQLiteCheckpointer(db_path) as cp:
+ data = await cp.load("thread-1")
+ assert data is not None
+ assert data.messages[0].content[0].text == "persist"
+
+ async def test_multiple_threads(self, db_path):
+ async with SQLiteCheckpointer(db_path) as cp:
+ await cp.append("t1", [UserMessage(content=[TextContent(text="t1")])])
+ await cp.append("t2", [UserMessage(content=[TextContent(text="t2")])])
+
+ d1 = await cp.load("t1")
+ d2 = await cp.load("t2")
+ assert d1.messages[0].content[0].text == "t1"
+ assert d2.messages[0].content[0].text == "t2"