Skip to content

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

fix(agent): codex P1/P2 — claim under run-lock + forward fork_once options

xf gonge8e36b769eef
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 2a58e75..0d75a50 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -376,14 +376,9 @@ class Agent(Generic[TMessage]):
)
effective_run_id = run_id or uuid.uuid4().hex
# Reject mismatched caller-supplied Message.run_id BEFORE any state
- # mutation so the supplied run_id remains reusable (Task 25 will add
- # claim_run, which must not be called for a rejected prompt).
+ # mutation so the supplied run_id remains reusable (claim_run must
+ # not be called for a rejected prompt).
self._validate_input_run_ids(message, effective_run_id)
- if self._run_aware and self.thread_id is not None:
- assert self.checkpointer is not None # narrowed by _run_aware
- await self.checkpointer.claim_run(self.thread_id, effective_run_id)
- self._state.active_run_id = effective_run_id
- self._state.last_outcome = None
try:
async with self._run_lock:
# Re-check under the lock in case streaming flipped during acquire.
@@ -392,6 +387,16 @@ class Agent(Generic[TMessage]):
"Agent is already processing a prompt. "
"Use steer() or follow_up() to queue messages."
)
+ # Claim the run UNDER the lock: this serializes concurrent cold
+ # prompt() calls against the checkpointer. With the fail-fast
+ # `.locked()` guard above, the second concurrent caller raises
+ # immediately instead of awaiting claim_run + queueing on the
+ # lock.
+ if self._run_aware and self.thread_id is not None:
+ assert self.checkpointer is not None # narrowed by _run_aware
+ await self.checkpointer.claim_run(self.thread_id, effective_run_id)
+ self._state.active_run_id = effective_run_id
+ self._state.last_outcome = None
if isinstance(message, str):
messages: list[Message] = [
@@ -485,13 +490,30 @@ class Agent(Generic[TMessage]):
snapshot = await self.checkpointer.snapshot(
src_thread_id, after_run_id=after_run_id
)
- # Build transient agent
+ # Build transient agent. Forward the parent's resolved execution
+ # options + middleware-composed hooks so the probe behaves like the
+ # parent would (tool_execution, thinking, transform/response hooks,
+ # on_payload/on_response, queue modes). Passing the resolved hooks
+ # as explicit args means we pass middleware=[] to avoid composing
+ # middleware twice — the parent's composed result already lives on
+ # self.transform_context etc.
child: Agent = Agent(
model=self._model,
system_prompt=self._state.system_prompt,
tools=list(self._state.tools),
- middleware=list(self._middleware),
+ thinking=self._state.thinking,
convert_to_llm=self.convert_to_llm,
+ transform_context=self.transform_context,
+ transform_system_prompt=self.transform_system_prompt,
+ after_model_response=self.after_model_response,
+ before_tool_call=self.before_tool_call,
+ after_tool_call=self.after_tool_call,
+ should_stop_after_turn=self.should_stop_after_turn,
+ on_run_end=self.on_run_end,
+ on_payload=self.on_payload,
+ on_response=self.on_response,
+ tool_execution=self.tool_execution,
+ middleware=[],
messages=snapshot,
)
pre_len = len(child.state.messages)
diff --git a/tests/agent/test_agent_claim_run.py b/tests/agent/test_agent_claim_run.py
index 0c240d0..e538a78 100644
--- a/tests/agent/test_agent_claim_run.py
+++ b/tests/agent/test_agent_claim_run.py
@@ -1,3 +1,5 @@
+import asyncio
+
import pytest
from cubepi.agent.agent import Agent
@@ -81,3 +83,37 @@ async def test_degraded_mode_v3_only_checkpointer():
# Vanilla prompt works (degraded mode skips claim).
got = await a.prompt("hi")
assert isinstance(got, str)
+
+
+async def test_concurrent_cold_prompts_second_raises_fast():
+ """Two concurrent cold prompt() calls — the second must raise immediately
+ instead of serializing on the run-lock behind the first's claim_run I/O.
+
+ Regression for codex P1: claim_run used to run BEFORE the lock was
+ acquired, so two callers could both pass the fail-fast `.locked()` check
+ while the first was awaiting claim_run.
+ """
+
+ class _SlowClaimCheckpointer(MemoryCheckpointer):
+ async def claim_run(self, thread_id, run_id): # type: ignore[override]
+ await asyncio.sleep(0.05)
+ return await super().claim_run(thread_id, run_id)
+
+ cp = _SlowClaimCheckpointer()
+ a = _agent(checkpointer=cp, thread_id="t")
+
+ results = await asyncio.gather(
+ a.prompt("first", run_id="R1"),
+ a.prompt("second", run_id="R2"),
+ return_exceptions=True,
+ )
+ # Exactly one succeeded; the other raised "already processing".
+ runtime_errs = [r for r in results if isinstance(r, RuntimeError)]
+ successes = [r for r in results if isinstance(r, str)]
+ assert len(runtime_errs) == 1
+ assert len(successes) == 1
+ assert "already processing" in str(runtime_errs[0]).lower()
+ # The loser's run_id was NOT claimed (claim_run only runs inside the lock).
+ claimed = set(cp._runs.get("t", {}).keys())
+ assert claimed == {successes[0]}
diff --git a/tests/agent/test_agent_fork_once.py b/tests/agent/test_agent_fork_once.py
index b15c547..84e3374 100644
--- a/tests/agent/test_agent_fork_once.py
+++ b/tests/agent/test_agent_fork_once.py
@@ -211,3 +211,83 @@ async def test_fork_once_source_thread_byte_identical():
assert dict(after.extra) == before_extra
# Source thread's run state untouched.
assert dict(cp._runs.get("src", {})) == before_runs
+
+
+async def test_fork_once_forwards_parent_execution_options():
+ """fork_once() child must inherit the parent's execution options
+ (tool_execution, thinking, response hook) — not silently fall back
+ to defaults.
+
+ Regression for codex P2: the child was only receiving
+ {model, system_prompt, tools, middleware, convert_to_llm, messages}.
+ """
+ cp = MemoryCheckpointer()
+ hook_calls: list[str] = []
+
+ async def _after_response(response, ctx, *, signal=None):
+ # Proves the parent's after_model_response was forwarded to the child.
+ hook_calls.append("after_response")
+ return None
+
+ seed_agent = Agent(
+ model=_ok_faux().model("faux-model"),
+ checkpointer=cp,
+ thread_id="src",
+ )
+ await seed_agent.prompt("hello", run_id="R1")
+
+ parent = Agent(
+ model=_ok_faux().model("faux-model"),
+ checkpointer=cp,
+ thread_id="src",
+ tool_execution="sequential",
+ thinking="medium",
+ after_model_response=_after_response,
+ )
+ await parent.fork_once("src", "probe", after_run_id="R1")
+
+ # The hook ran in the child (proves the parent's hook was forwarded).
+ assert hook_calls == ["after_response"]
+
+
+async def test_fork_once_forwards_tool_execution_and_thinking():
+ """fork_once() child must inherit tool_execution and thinking settings."""
+ cp = MemoryCheckpointer()
+ captured: dict[str, object] = {}
+
+ # Patch Agent.__init__ briefly to capture the child's kwargs.
+ real_init = Agent.__init__
+
+ def _spy_init(self, *args, **kwargs):
+ # Skip the parent constructor call: only capture the second Agent()
+ # (the child built by fork_once).
+ captured.setdefault("calls", 0)
+ captured["calls"] = captured["calls"] + 1 # type: ignore[operator]
+ if captured["calls"] >= 3: # 1=seed, 2=parent, 3=child
+ captured["thinking"] = kwargs.get("thinking")
+ captured["tool_execution"] = kwargs.get("tool_execution")
+ return real_init(self, *args, **kwargs)
+
+ Agent.__init__ = _spy_init # type: ignore[method-assign]
+ try:
+ seed_agent = Agent(
+ model=_ok_faux().model("faux-model"),
+ checkpointer=cp,
+ thread_id="src",
+ )
+ await seed_agent.prompt("hello", run_id="R1")
+ parent = Agent(
+ model=_ok_faux().model("faux-model"),
+ checkpointer=cp,
+ thread_id="src",
+ tool_execution="sequential",
+ thinking="medium",
+ )
+ await parent.fork_once("src", "probe", after_run_id="R1")
+ finally:
+ Agent.__init__ = real_init # type: ignore[method-assign]
+
+ assert captured["thinking"] == "medium"
+ assert captured["tool_execution"] == "sequential"
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.md
index 155aa6e..6b7c627 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.md
@@ -147,6 +147,45 @@ cubepi_schema_version
`save_extra` 执行浅层顶级合并,而非替换——与 Postgres 和 SQLite 的行为相同。先写入 `{"foo": 1}` 再写入 `{"bar": 2}` 后,结果为 `{"foo": 1, "bar": 2}`。(内部实现是在行锁保护下读取当前 `extra`,然后写入合并后的字典,而非使用 `JSON_MERGE_PATCH`——后者的 null 删除和深度合并语义与 `dict.update` 不同。)
+## Forks
+
+`MySQLCheckpointer` 实现了 v4 的 `snapshot` / `fork` /
+`claim_run` / `mark_run_complete` / `load_pending` 协议方法,
+因此同时支持 `Agent.fork(...)` 和 `Agent.fork_once(...)`。
+`cubepi_threads` 上的 `parent_thread_id` / `forked_at_seq` 列
+用于记录 fork 谱系;v4 新增的 `cubepi_runs` 表用于追踪每个 run
+的 claim/completion 状态。
+
+用户层 API 与语义详见
+[会话 Fork 指南](./forking)。
+
+## Schema v3 → v4 migration {#schema-v3--v4-migration}
+
+Fork 功能将 `EXPECTED_SCHEMA_VERSION` 从 3 升到 4。升级会向
+`cubepi_messages` 添加 `run_id` 列 + 复合索引,并创建
+`cubepi_runs` 表。使用提供的 alembic helper —— MySQL/pymysql
+每次调用只执行一条语句,因此需要先拆分再执行:
+
+```python
+# 在迁移的 upgrade() 中:
+from cubepi.checkpointer.mysql.alembic_helpers import (
+ upgrade_v3_to_v4_op,
+ write_schema_version_op,
+)
+
+def upgrade():
+ for stmt in upgrade_v3_to_v4_op().split(";"):
+ if stmt.strip():
+ op.execute(stmt)
+ for stmt in write_schema_version_op().split(";"):
+ if stmt.strip():
+ op.execute(stmt)
+```
+
+`upgrade_v3_to_v4_op()` 在重复执行下是幂等的。升级前的旧消息
+保留 `run_id = NULL`,仍然可读;关于混合数据的 fork 资格规则,
+请参阅 [旧数据行为](./forking#legacy-data-behaviour)。
+
## 常见陷阱
- **`CubepiSchemaUninitialized`** —— 数据库为空、迁移未执行,或 `cubepi_schema_version` 表结构有误。请先应用宿主的 alembic upgrade。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md
index 0747a36..62a16e1 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md
@@ -157,9 +157,36 @@ extra = cubepi_threads.extra || EXCLUDED.extra
## Fork
-`parent_thread_id` + `forked_at_seq` 列是为将来的 fork 支持预留的。
-CubePi v0.3 尚未暴露 fork API——现在写入它们是为了保持 schema
-的前向兼容性。
+`parent_thread_id` + `forked_at_seq` 列用于支持
+[会话 Fork](./forking):fork 会创建一个新的 thread,并在其
+`cubepi_threads` 行中写入指向源 thread 的 `parent_thread_id`,
+以及拷贝时源 thread 末尾的 `forked_at_seq`(最后一条已拷贝消息的
+`seq`)。
+
+## Schema v3 → v4 migration {#schema-v3--v4-migration}
+
+Fork 功能将 `EXPECTED_SCHEMA_VERSION` 从 3 升到 4。升级会向
+`cubepi_messages` 添加 `run_id` 列 + 索引,并创建分区父表
+`cubepi_runs` 及其子分区。使用 alembic helper:
+
+```python
+# 在迁移的 upgrade() 中:
+from cubepi.checkpointer.postgres.alembic_helpers import (
+ upgrade_v3_to_v4_op,
+ write_schema_version_op,
+)
+
+def upgrade():
+ op.execute(upgrade_v3_to_v4_op())
+ op.execute(write_schema_version_op()) # 将 cubepi_schema_version 升到 4
+```
+
+`upgrade_v3_to_v4_op()` 在重复执行下是幂等的(所有 DDL 都带
+`IF NOT EXISTS`)。
+
+升级前的旧消息保留 `run_id = NULL`,仍然可读;
+关于混合数据的 fork 资格规则,请参阅
+[旧数据行为](./forking#legacy-data-behaviour)。
## 常见坑