Skip to content

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

fix: address final code review findings

xf gong535eef0e11b7
diff --git a/cubepi/checkpointer/sqlite.py b/cubepi/checkpointer/sqlite.py
index c425121..a6ecd49 100644
--- a/cubepi/checkpointer/sqlite.py
+++ b/cubepi/checkpointer/sqlite.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import json
from typing import Any
@@ -12,6 +13,7 @@ class SQLiteCheckpointer:
def __init__(self, db_path: str) -> None:
self._db_path = db_path
self._db: aiosqlite.Connection | None = None
+ self._lock = asyncio.Lock()
async def __aenter__(self) -> SQLiteCheckpointer:
self._db = await aiosqlite.connect(self._db_path)
@@ -39,64 +41,62 @@ class SQLiteCheckpointer:
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:
+ async with self._lock:
+ cursor = await self._db.execute(
+ "SELECT message_json FROM messages WHERE thread_id = ? ORDER BY id",
+ (thread_id,),
+ )
+ rows = await cursor.fetchall()
+
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))
+ if not rows and not extra_row:
+ return None
- 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 {}
+ messages = []
+ for row in rows:
+ msg_data = json.loads(row[0])
+ messages.append(_deserialize_message(msg_data))
- return CheckpointData(messages=messages, extra=extra)
+ 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 with self._lock:
+ 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)),
+ async with self._lock:
+ existing_cursor = await self._db.execute(
+ "SELECT extra_json FROM thread_extra WHERE thread_id = ?",
+ (thread_id,),
)
- await self._db.commit()
+ 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:
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.py
index ac860b6..31e15c9 100644
--- a/cubepi/providers/anthropic.py
+++ b/cubepi/providers/anthropic.py
@@ -93,7 +93,7 @@ class AnthropicProvider:
ms.push(StreamEvent(type="done"))
ms.set_result(result)
- except Exception as exc:
+ except BaseException as exc:
error_msg = AssistantMessage(
content=[],
stop_reason="error",
@@ -103,6 +103,8 @@ class AnthropicProvider:
)
ms.push(StreamEvent(type="error", error_message=str(exc)))
ms.set_result(error_msg)
+ if not isinstance(exc, Exception):
+ raise
asyncio.create_task(_produce())
return ms
diff --git a/cubepi/providers/faux.py b/cubepi/providers/faux.py
index a484ada..5256d1a 100644
--- a/cubepi/providers/faux.py
+++ b/cubepi/providers/faux.py
@@ -151,7 +151,7 @@ class FauxProvider:
resolved = step
await self._stream_with_deltas(ms, resolved, signal)
- except Exception as exc:
+ except BaseException as exc:
error_msg = AssistantMessage(
content=[],
stop_reason="error",
@@ -161,6 +161,8 @@ class FauxProvider:
)
ms.push(StreamEvent(type="error", error_message=str(exc)))
ms.set_result(error_msg)
+ if not isinstance(exc, Exception):
+ raise
asyncio.create_task(_produce())
return ms
diff --git a/cubepi/providers/openai.py b/cubepi/providers/openai.py
index 9d84264..c77f2b9 100644
--- a/cubepi/providers/openai.py
+++ b/cubepi/providers/openai.py
@@ -216,7 +216,7 @@ class OpenAIProvider:
ms.push(StreamEvent(type="done"))
ms.set_result(partial)
- except Exception as exc:
+ except BaseException as exc:
error_msg = AssistantMessage(
content=[],
stop_reason="error",
@@ -226,6 +226,8 @@ class OpenAIProvider:
)
ms.push(StreamEvent(type="error", error_message=str(exc)))
ms.set_result(error_msg)
+ if not isinstance(exc, Exception):
+ raise
asyncio.create_task(_produce())
return ms
@@ -241,8 +243,7 @@ class OpenAIProvider:
tool_calls = [c for c in msg.content if isinstance(c, ToolCall)]
result: dict[str, Any] = {"role": "assistant"}
- if text_parts:
- result["content"] = "\n".join(text_parts)
+ result["content"] = "\n".join(text_parts) if text_parts else None
if tool_calls:
result["tool_calls"] = [
{
diff --git a/tests/providers/test_openai.py b/tests/providers/test_openai.py
index b249f28..ee0725a 100644
--- a/tests/providers/test_openai.py
+++ b/tests/providers/test_openai.py
@@ -30,6 +30,7 @@ class TestOpenAIMessageConversion:
)
result = OpenAIProvider._convert_message(msg)
assert result["role"] == "assistant"
+ assert result["content"] is None
assert len(result["tool_calls"]) == 1
assert result["tool_calls"][0]["id"] == "tc-1"
assert result["tool_calls"][0]["function"]["name"] == "search"