fix(gateway): allow edit replay after long runs (#8544)

* fix: 修复长回合编辑重跑

* fix: 解耦重跑查找与运行上限

* fix: 防止重跑选中旁支 checkpoint

* fix: 统一分支与重跑的 checkpoint 查找期限

* fix: 记录重跑查找超时并补全回归验证
This commit is contained in:
Hazenix 2026-11-24 11:24:16 +08:00 committed by GitHub
parent 624a64a152
commit fc2b5b257f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 250 additions and 73 deletions

View File

@ -2,9 +2,21 @@
from __future__ import annotations
import asyncio
import logging
from collections.abc import Sequence
from itertools import count
from typing import Any
from fastapi import HTTPException
from app.gateway.utils import sanitize_log_param
logger = logging.getLogger(__name__)
_REPLAY_LINEAGE_LOOKUP_TIMEOUT_SECONDS = 30
_REPLAY_LINEAGE_TIMEOUT_DETAIL = "Timed out resolving the checkpoint before the target user message"
def task_interrupts_by_id(snapshot: Any) -> dict[str, list[Any]]:
"""Group non-empty task interrupts of one snapshot by task id."""
@ -31,13 +43,23 @@ class CheckpointLineageError(RuntimeError):
class CheckpointParentMissingError(CheckpointLineageError):
"""Raised when a legacy checkpoint does not record its parent link."""
"""Raised when a legacy checkpoint head does not record a parent link."""
class CheckpointLineageIntegrityError(CheckpointLineageError):
"""Raised when recorded checkpoint lineage is present but unsafe to use."""
class CheckpointLineageTimeoutError(CheckpointLineageError):
"""Raised when the replay lineage lookup exceeds its own deadline."""
def replay_lineage_timeout_http_error(thread_id: str, exc: CheckpointLineageTimeoutError) -> HTTPException:
"""Log a replay lookup deadline expiry and return its fixed client error."""
logger.warning("Replay checkpoint lookup timed out for thread %s", sanitize_log_param(thread_id), exc_info=exc)
return HTTPException(status_code=504, detail=_REPLAY_LINEAGE_TIMEOUT_DETAIL)
def checkpoint_messages(checkpoint_tuple: Any) -> list[Any]:
values = getattr(checkpoint_tuple, "values", None)
if isinstance(values, dict):
@ -342,6 +364,8 @@ def _message_id(message: Any) -> str | None:
def _config_identity(config: dict[str, Any]) -> tuple[str, str, str] | None:
configurable = config.get("configurable", {})
if not isinstance(configurable, dict):
return None
thread_id = configurable.get("thread_id")
checkpoint_ns = configurable.get("checkpoint_ns", "")
checkpoint_id = configurable.get("checkpoint_id")
@ -372,12 +396,28 @@ def _checkpoint_exists(checkpoint_tuple: Any) -> bool:
return isinstance(getattr(checkpoint_tuple, "checkpoint", None), dict)
async def find_replay_checkpoint_before_message(
accessor: Any,
head_checkpoint: Any,
message_id: str,
) -> Any:
"""Resolve the replay base for branching, regeneration, or edit replay."""
deadline = asyncio.timeout(_REPLAY_LINEAGE_LOOKUP_TIMEOUT_SECONDS)
try:
async with deadline:
return await find_checkpoint_before_message(accessor, head_checkpoint, message_id, max_depth=None)
except TimeoutError as exc:
if not deadline.expired():
raise # The checkpoint store raised its own timeout.
raise CheckpointLineageTimeoutError(_REPLAY_LINEAGE_TIMEOUT_DETAIL) from exc
async def find_checkpoint_before_message(
accessor: Any,
head_checkpoint: Any,
message_id: str,
*,
max_depth: int,
max_depth: int | None,
) -> Any:
"""Walk one parent lineage and return the first checkpoint before ``message_id``.
@ -386,6 +426,7 @@ async def find_checkpoint_before_message(
a checkpoint from the wrong branch. Duration-only metadata checkpoints do not
represent an addressable conversation state and are skipped, and so are
checkpoints that still have pending tasks (see :func:`has_pending_tasks`).
With ``max_depth=None``, the caller must bound the lookup with a deadline.
"""
if message_id not in {_message_id(message) for message in checkpoint_messages(head_checkpoint)}:
@ -397,13 +438,9 @@ async def find_checkpoint_before_message(
if current_identity is not None:
visited.add(current_identity)
# Each distinct ancestor is read once: a Postgres stamp candidate also
# needs its grandparent for the shape check, and a candidate the shape
# check refuses re-reads that grandparent as the next iteration's parent,
# so reads are memoized by config identity instead of carried by hand.
# Normal branch/regenerate histories cross the target boundary within
# 1–3 reads. Keep max_depth as a conservative safety cap for valid
# histories with many intermediate or duration-only checkpoints.
# A Postgres stamp candidate may read its grandparent for the shape
# check. That snapshot is the next iteration's parent, so keep the last
# read only. A long walk does not need to retain every materialized state.
read_cache: dict[tuple[str, str, str], Any] = {}
async def read(config: dict[str, Any]) -> Any:
@ -412,23 +449,29 @@ async def find_checkpoint_before_message(
return read_cache[identity]
checkpoint_tuple = await accessor.aget(config)
if identity is not None:
read_cache.clear()
read_cache[identity] = checkpoint_tuple
return checkpoint_tuple
for _ in range(max_depth):
depths = count() if max_depth is None else range(max_depth)
for depth in depths:
if max_depth is None and depth % 64 == 0:
# In-memory reads can finish inline. Yield so the deadline can fire.
await asyncio.sleep(0)
parent_config = getattr(current, "parent_config", None)
if not isinstance(parent_config, dict):
raise CheckpointParentMissingError("Checkpoint lineage ended before the target message")
if parent_config is None:
if depth == 0:
raise CheckpointParentMissingError("Checkpoint head has no recorded parent link")
raise CheckpointLineageIntegrityError("Checkpoint lineage ended before the target message")
parent = await read(parent_config)
parent_identity = _checkpoint_identity(parent)
requested_parent_identity = _config_identity(parent_config)
if parent_identity is None or not _checkpoint_exists(parent) or (requested_parent_identity is not None and parent_identity != requested_parent_identity):
if not isinstance(parent_config, dict) or (parent_identity := _config_identity(parent_config)) is None:
raise CheckpointLineageIntegrityError("Checkpoint parent link is not addressable")
if parent_identity is not None:
if parent_identity in visited:
raise CheckpointLineageIntegrityError("Checkpoint lineage contains a cycle")
visited.add(parent_identity)
parent = await read(parent_config)
if _checkpoint_identity(parent) != parent_identity or not _checkpoint_exists(parent):
raise CheckpointLineageIntegrityError("Checkpoint parent link is not addressable")
if parent_identity in visited:
raise CheckpointLineageIntegrityError("Checkpoint lineage contains a cycle")
visited.add(parent_identity)
grandparent = None
versions = None

View File

@ -31,14 +31,16 @@ from app.gateway.artifact_archive import ArtifactArchiveError, ArtifactArchiveRe
from app.gateway.authz import require_cancel_permission_if, require_permission
from app.gateway.checkpoint_lineage import (
CheckpointLineageError,
CheckpointLineageTimeoutError,
CheckpointParentMissingError,
checkpoint_configurable,
checkpoint_messages,
find_checkpoint_before_message,
find_checkpoint_before_message_chronologically,
find_replay_checkpoint_before_message,
history_parent_index,
is_duration_only_checkpoint,
parent_from_history_index,
replay_lineage_timeout_http_error,
resolve_history_versions,
resolve_stamp_candidate_versions,
)
@ -758,15 +760,12 @@ async def _find_base_checkpoint_before_human(
raise _checkpoint_mode_http_error(exc, thread_id) from exc
if head_checkpoint is not None:
try:
return await find_checkpoint_before_message(
accessor,
head_checkpoint,
human_message_id,
max_depth=REGENERATE_HISTORY_RAW_SCAN_LIMIT,
)
return await find_replay_checkpoint_before_message(accessor, head_checkpoint, human_message_id)
except CheckpointLineageTimeoutError as exc:
raise replay_lineage_timeout_http_error(thread_id, exc) from exc
except CheckpointParentMissingError:
# Old checkpoints and imported histories may not have parent links.
# Preserve the bounded chronological fallback for those records.
# Some legacy or imported heads have no recorded parent link.
# Only those heads can use the chronological compatibility scan.
logger.debug(
"Could not resolve parent lineage for regenerate thread %s; falling back to history scan",
sanitize_log_param(thread_id),

View File

@ -29,12 +29,14 @@ from sqlalchemy.exc import IntegrityError
from app.gateway.authz import _is_internal_caller, authorize_model_use, require_permission
from app.gateway.checkpoint_lineage import (
CheckpointLineageError,
CheckpointLineageTimeoutError,
CheckpointParentMissingError,
find_checkpoint_before_message,
find_checkpoint_before_message_chronologically,
find_replay_checkpoint_before_message,
history_parent_index,
is_duration_only_checkpoint,
parent_from_history_index,
replay_lineage_timeout_http_error,
resolve_history_versions,
resolve_stamp_candidate_versions,
)
@ -305,22 +307,18 @@ async def _find_branch_replay_base(
) -> Any | None:
"""Resolve a replay base while preserving unlinked legacy histories."""
thread_id = config.get("configurable", {}).get("thread_id", "")
try:
return await find_checkpoint_before_message(
accessor,
snapshot,
target_human_id,
max_depth=_BRANCH_HISTORY_RAW_SCAN_LIMIT,
)
return await find_replay_checkpoint_before_message(accessor, snapshot, target_human_id)
except CheckpointLineageTimeoutError as exc:
raise replay_lineage_timeout_http_error(thread_id, exc) from exc
except CheckpointParentMissingError:
thread_id = config.get("configurable", {}).get("thread_id", "")
logger.debug(
"Could not resolve parent lineage for branch thread %s; falling back to history scan",
sanitize_log_param(thread_id),
exc_info=True,
)
except CheckpointLineageError as exc:
thread_id = config.get("configurable", {}).get("thread_id", "")
logger.warning(
"Rejected unsafe checkpoint lineage for branch thread %s",
sanitize_log_param(thread_id),
@ -331,10 +329,8 @@ async def _find_branch_replay_base(
try:
history = await accessor.ahistory(config, limit=_BRANCH_HISTORY_RAW_SCAN_LIMIT)
except _CHECKPOINT_MODE_ERRORS as exc:
thread_id = config.get("configurable", {}).get("thread_id", "")
raise _checkpoint_mode_http_error(exc, thread_id) from exc
except Exception as exc:
thread_id = config.get("configurable", {}).get("thread_id", "")
logger.exception("Failed to scan replay checkpoint history for thread %s", sanitize_log_param(thread_id))
raise HTTPException(status_code=500, detail="Failed to inspect checkpoint history") from exc
@ -343,7 +339,7 @@ async def _find_branch_replay_base(
logger.warning(
"Could not locate branch user message %s in chronological history for thread %s",
sanitize_log_param(target_human_id),
sanitize_log_param(config.get("configurable", {}).get("thread_id", "")),
sanitize_log_param(thread_id),
)
return replay_base

View File

@ -295,6 +295,15 @@ is not restored from history. A valid goal explicitly supplied in run input
still replaces it. Historical replay clears the old `goal_outcome`, because
the previous answer's verdict does not certify the replacement answer.
#### Branch and Replay Lookup
`POST /api/threads/{thread_id}/branches`,
`POST /api/threads/{thread_id}/runs/regenerate/prepare`, and
`POST /api/threads/{thread_id}/runs/edit-regenerate/prepare` share a deadline
for finding the replay base on the checkpoint lineage. If that lookup expires,
the response is HTTP 504 with detail
`Timed out resolving the checkpoint before the target user message`.
### Runs
#### Create Run

View File

@ -8,10 +8,11 @@ walks `parent_config` rather than globally ordered checkpoint history so replay
anchors stay on the selected lineage after regenerations create sibling branches.
New conversation branches persist the pre-user replay anchor before their visible
head through the state mutation graph, which preserves materialized state in both
full and delta checkpoint modes. Only an explicitly absent legacy parent link may
use chronological compatibility lookup; cycles, dangling links, and depth-limit
exhaustion fail closed. Existing single-checkpoint branches are never repaired by
copying a raw checkpoint because delta state is not self-contained in one tuple.
full and delta checkpoint modes. Chronological compatibility lookup is available
only when the checkpoint head has no recorded parent link. An explicit lineage
that ends before a replay base or contains a cycle or invalid link fails closed.
Existing single-checkpoint branches are never repaired by copying a raw
checkpoint because delta state is not self-contained in one tuple.
Both lookups additionally require the replay base to be a **settled** checkpoint
(`has_pending_tasks` — no scheduled `next` tasks). A checkpoint with pending tasks
is a mid-run snapshot: resuming from it replays the writes of the node that was
@ -25,7 +26,13 @@ edited one, and the model answered the question the edit was replacing (#4531).
tasks; absence of evidence stays permissive there rather than failing closed.
Edit replay resolves its base through the same lineage-first path as regenerate;
it must pass `head_checkpoint` or it silently degrades to the chronological scan
that cannot tell sibling branches apart.
that cannot tell sibling branches apart. Branch, regenerate, and edit replay
share a deadline for the linked lookup of the replay base. Changing
`max_recursion_limit` for future runs does not affect that lookup. The Gateway
logs lookup deadline expiry and returns HTTP 504. A `TimeoutError` raised by
the checkpoint store before the deadline propagates to the generic HTTP 500
handler. The chronological compatibility lookup retains its fixed checkpoint
window.
An edit replay that pauses for tool approval stays the current attempt: the edit
remains in thread state and replaces the source turn in history. Only a failed,
timed-out or cancelled attempt restores the pre-edit checkpoint; once the pause is

View File

@ -346,7 +346,7 @@ Checkpointer storage runs in one of two channel modes, selected by `checkpoint_c
**Never bypass `CheckpointStateAccessor` (`runtime/checkpoint_state.py`) for thread-state access.** It is the single choke point binding graph + checkpointer + mode: it injects the mode marker into configs, runs the compatibility check before every `get`/`update`/`history`, and returns materialized state (delta checkpoints lack `channel_values.messages` — raw `get_tuple` reads see a sentinel). An async unpinned delta read verifies that its resolved checkpoint still exists after materialization and retries once from the new head when retention removed that target mid-read; explicit historical selections never silently move. For metadata-only reads, use `get_metadata` / `aget_metadata` to retain the mode gate without materialization. Thread-owned reads must use `build_thread_checkpoint_state_accessor` so the recorded assistant schema materializes every channel. Sync checkpoint mutations must drain off-thread commits before cancellation propagates; sync `get_tuple` reads remain cancellable. `history(limit)` semantics: `0` means zero items (explicit empty), `None` means unlimited — do not pass `limit=0` through to `graph.get_state_history`. Assistant metadata lookup is fail-closed for mutation accessors so a store outage cannot silently select the default schema and discard extension channels. In `full` mode the read path degrades to a raw checkpointer read (`_RawCheckpointReadAccessor`) when the agent factory cannot build the graph (bad model config, MCP outage) — full checkpoints carry complete `channel_values`, so reads don't need the graph; degraded snapshots take `created_at` from the standard checkpoint `ts` field, falling back to metadata only for compatibility. The delta gate still applies on the degraded path; `next`/`tasks` degrade to empty and thread status falls back to the stored status because task presence is not derivable, while delta mode has no fallback (materialization needs the channel table).
**Replay checkpoint lookup prefers lineage and degrades only for an explicitly missing legacy parent link.** Branch and regenerate paths first walk `parent_config`, which prevents a global chronological scan from selecting a sibling created by regeneration. `CheckpointParentMissingError` alone enables the bounded newest-first history fallback in `app/gateway/checkpoint_lineage.py`; cycles, dangling/non-addressable parents, target mismatches, and depth exhaustion raise `CheckpointLineageIntegrityError` and fail closed instead of selecting a sibling. The compatibility scans request 400 raw checkpoints so up to 200 duration-only entries do not consume the effective branch-history budget; the fallback scans oldest-to-newest internally, skips duration-only checkpoints, and accepts only checkpoints with an addressable id as the replay base. A source history with no discoverable pre-user checkpoint preserves the historical single-checkpoint branch behavior instead of rejecting the branch; regeneration remains unavailable for that inherited response. Existing single-checkpoint branches are not mutated by regenerate preparation, and no raw checkpoint tuple is copied across threads because delta state depends on ancestry and pending writes. Regenerate source-run lookup uses the current thread's exact event, then the server-stamped `run_id` on the copied human message, then verified RunManager content matching; it does not read parent-thread events. When an interrupted response was streamed but never checkpointed, regeneration accepts only the latest visible human message's server-stamped `run_id` after verifying that it belongs to the same thread and still has `interrupted` status. Storage or checkpoint-mode failures are not treated as a missing base and still fail closed.
**Replay checkpoint lookup prefers lineage and degrades only for an explicitly missing legacy parent link.** Branch, regenerate, and edit replay first walk `parent_config` to stay on the selected lineage. The linked walk shares a lookup deadline. Expiry is logged and returns HTTP 504. `CheckpointParentMissingError` enables the bounded newest-first history fallback only when the selected checkpoint has no recorded parent link. A linked walk that ends before finding the replay base, encounters a cycle or invalid parent, or starts at a checkpoint without the target message raises `CheckpointLineageIntegrityError`. The compatibility scans request 400 raw checkpoints so up to 200 duration-only entries do not consume the effective branch-history budget; the fallback scans oldest-to-newest internally, skips duration-only checkpoints, and accepts only checkpoints with an addressable id as the replay base. A source history with no discoverable pre-user checkpoint preserves the historical single-checkpoint branch behavior instead of rejecting the branch; regeneration remains unavailable for that inherited response. Existing single-checkpoint branches are not mutated by regenerate preparation, and no raw checkpoint tuple is copied across threads because delta state depends on ancestry and pending writes. Regenerate source-run lookup uses the current thread's exact event, then the server-stamped `run_id` on the copied human message, then verified RunManager content matching; it does not read parent-thread events. When an interrupted response was streamed but never checkpointed, regeneration accepts only the latest visible human message's server-stamped `run_id` after verifying that it belongs to the same thread and still has `interrupted` status. Storage or checkpoint-mode failures are not treated as a missing base and still fail closed.
**A delta-mode run cannot fork; `runtime/runs/worker.py` linearizes the resume instead.** An older-checkpoint resume creates siblings whose pending writes can replay into the fork, retaining a superseded answer. Write-to-child ownership belongs to the upstream delta contract, so DeerFlow does not reimplement the walk: `_linearize_delta_checkpoint_resume` materializes the requested checkpoint's complete state and writes every channel onto the **current head** (which has no siblings) through the state mutation graph, using `Overwrite` for reducer channels and resetting newer head-only channels to their schema default (or `None` when no constructible default exists); it then drops the `checkpoint_id` selector and lets the run proceed linearly, while the abandoned turn stays in history as the rewritten head's ancestry. The worker holds `_checkpoint_thread_lock` across `_capture_rollback_point` and the optional linear rewrite, making the rollback snapshot and rewrite atomic with graph streaming and the preceding run's duration-metadata checkpoint write. Capture preserves the complete real pre-run state; cancel-with-rollback then linearly replaces the current delta head with that captured state rather than forking the now-shared pre-run checkpoint, so the abandoned turn is restored without replaying the resume sibling's writes. The worker also recomputes the current-run message boundary from the rewritten state and fails closed (an unreadable resume checkpoint raises rather than falling back to the corrupt fork). `full` mode keeps forking — its checkpoints carry complete `channel_values` and need no replay — so LangGraph branching semantics are unchanged there. Root namespace only; subgraph namespaces are left alone.

View File

@ -14,6 +14,7 @@ import pytest
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from app.gateway.checkpoint_lineage import (
CheckpointLineageIntegrityError,
CheckpointParentMissingError,
find_checkpoint_before_message,
find_checkpoint_before_message_chronologically,
@ -133,16 +134,25 @@ def test_chronological_scan_prefers_the_previous_turn_boundary():
assert base.config["configurable"]["checkpoint_id"] == "ckpt-turn1-tail"
def test_lineage_walk_reports_missing_parent_when_no_settled_ancestor_exists():
"""Fail closed rather than fork a mid-run checkpoint."""
@pytest.mark.parametrize(
("parent_config", "expected_error"),
[
(None, CheckpointParentMissingError),
({"configurable": {"thread_id": THREAD_ID, "checkpoint_id": "ckpt-mid"}}, CheckpointLineageIntegrityError),
({"configurable": None}, CheckpointLineageIntegrityError),
],
ids=["unlinked-head", "linked-exhaustion", "malformed-link"],
)
def test_lineage_walk_only_reports_missing_parent_for_unlinked_head(parent_config, expected_error):
human = HumanMessage(id="h1__user", content="question")
history = [
_snapshot("ckpt-head", [human, AIMessage(id="ai-1", content="answer")], parent_id="ckpt-mid"),
_snapshot("ckpt-head", [human, AIMessage(id="ai-1", content="answer")]),
_snapshot("ckpt-mid", [HumanMessage(id="h1", content="question")], next_tasks=("DynamicContextMiddleware.before_agent",)),
]
history[0].parent_config = parent_config
accessor = _Accessor(history)
with pytest.raises(CheckpointParentMissingError):
with pytest.raises(expected_error):
asyncio.run(find_checkpoint_before_message(accessor, history[0], "h1__user", max_depth=10))

View File

@ -1066,6 +1066,106 @@ def test_prepare_edit_regenerate_payload_skips_mid_run_replay_base_on_first_turn
assert response.metadata["regenerate_checkpoint_id"] == "ckpt-empty"
def test_prepare_edit_regenerate_payload_resolves_a_long_first_turn():
from app.gateway.routers import thread_runs
event_store, run_manager = _answer_run_fixtures()
checkpointer = _first_turn_checkpointer()
messages = checkpointer.history[1].checkpoint["channel_values"]["messages"]
checkpointer.history[1:1] = [_checkpoint(f"ckpt-middle-{index}", messages, next_tasks=("model",)) for index in range(468)]
for checkpoint, parent in zip(checkpointer.history, checkpointer.history[1:]):
checkpoint.parent_config = parent.config
response = asyncio.run(
thread_runs._prepare_edit_regenerate_payload(
"thread-1",
"human-1__user",
"edited question",
_request(checkpointer, event_store, run_manager=run_manager),
)
)
assert response.checkpoint["checkpoint_id"] == "ckpt-empty"
assert response.metadata["regenerate_checkpoint_id"] == "ckpt-empty"
assert checkpointer.alist_limits == []
def test_prepare_edit_regenerate_rejects_sibling_after_exhausting_linked_history():
from app.gateway.routers import thread_runs
event_store, run_manager = _answer_run_fixtures()
checkpointer = _first_turn_checkpointer()
for checkpoint, parent in zip(checkpointer.history, checkpointer.history[1:]):
checkpoint.parent_config = parent.config
root = checkpointer.history[-1]
root.checkpoint["channel_values"]["messages"] = [HumanMessage(id="human-1__user", content="original question")]
# The chronological scan would mistake this older sibling for the replay base.
checkpointer.history.append(_checkpoint("unrelated-sibling", []))
with pytest.raises(HTTPException) as exc:
asyncio.run(
thread_runs._prepare_edit_regenerate_payload(
"thread-1",
"human-1__user",
"edited question",
_request(checkpointer, event_store, run_manager=run_manager),
)
)
assert exc.value.status_code == 409
assert exc.value.detail == "Could not safely resolve the checkpoint before the target user message"
assert checkpointer.alist_limits == []
def test_replay_lineage_timeout_does_not_scan_chronological_history(monkeypatch):
from app.gateway import checkpoint_lineage
from app.gateway.routers import thread_runs
monkeypatch.setattr(checkpoint_lineage, "_REPLAY_LINEAGE_LOOKUP_TIMEOUT_SECONDS", 0)
checkpointer = _first_turn_checkpointer()
checkpointer.history[0].parent_config = checkpointer.history[1].config
head = FakeAccessor._from_raw(checkpointer.history[0])
with pytest.raises(HTTPException) as exc:
asyncio.run(
thread_runs._find_base_checkpoint_before_human(
"thread-1",
"human-1__user",
_request(checkpointer, FakeEventStore([])),
head_checkpoint=head,
)
)
assert exc.value.status_code == 504
assert exc.value.detail == "Timed out resolving the checkpoint before the target user message"
assert checkpointer.alist_limits == []
def test_replay_lineage_preserves_checkpoint_store_timeout(monkeypatch):
from app.gateway.routers import thread_runs
checkpointer = _first_turn_checkpointer()
checkpointer.history[0].parent_config = checkpointer.history[1].config
head = FakeAccessor._from_raw(checkpointer.history[0])
store_timeout = TimeoutError("checkpoint store timed out")
get_tuple = AsyncMock(side_effect=store_timeout)
monkeypatch.setattr(checkpointer, "aget_tuple", get_tuple)
with pytest.raises(TimeoutError) as exc:
asyncio.run(
thread_runs._find_base_checkpoint_before_human(
"thread-1",
"human-1__user",
_request(checkpointer, FakeEventStore([])),
head_checkpoint=head,
)
)
assert exc.value is store_timeout
get_tuple.assert_awaited_once_with(head.parent_config)
assert checkpointer.alist_limits == []
def test_prepare_edit_regenerate_payload_prefers_checkpoint_lineage():
"""Edit replay must resolve its base the same lineage-first way regenerate does.
@ -1080,7 +1180,7 @@ def test_prepare_edit_regenerate_payload_prefers_checkpoint_lineage():
walk = AsyncMock(side_effect=CheckpointParentMissingError("no parent link"))
with patch.object(thread_runs, "find_checkpoint_before_message", walk):
with patch.object(thread_runs, "find_replay_checkpoint_before_message", walk):
response = asyncio.run(
thread_runs._prepare_edit_regenerate_payload(
"thread-1",

View File

@ -3103,7 +3103,8 @@ def test_stamp_turn_duration_recovers_from_non_mapping_additional_kwargs(caplog)
# ── branch threads from completed assistant turns ─────────────────────────────
def test_branch_thread_can_prepare_regenerate_without_branch_run_events() -> None:
@pytest.mark.parametrize("source_checkpoint_count", [3, 473], ids=["short-turn", "long-turn"])
def test_branch_thread_can_prepare_regenerate_without_branch_run_events(source_checkpoint_count: int) -> None:
app, _store, checkpointer = _build_thread_app()
app.include_router(thread_runs.router)
source_thread_id = "source-regenerate"
@ -3122,32 +3123,26 @@ def test_branch_thread_can_prepare_regenerate_without_branch_run_events() -> Non
human = HumanMessage(id="human-1", content="Question", additional_kwargs={"run_id": source_run_id})
ai = AIMessage(id="ai-1", content="Answer")
async def seed_turn(parent_config: dict) -> None:
for step in range(1, source_checkpoint_count):
messages = [human, ai] if step == source_checkpoint_count - 1 else [human]
parent_config = await _write_checkpoint(
checkpointer,
source_thread_id,
str(uuid6()),
messages,
step=step,
metadata={"created_at": "2026-07-05T00:00:00+00:00"},
parent_config=parent_config,
)
with TestClient(app) as client:
created = client.post("/api/threads", json={"thread_id": source_thread_id, "metadata": {}})
assert created.status_code == 200, created.text
initial = asyncio.run(checkpointer.aget_tuple({"configurable": {"thread_id": source_thread_id, "checkpoint_ns": ""}}))
assert initial is not None
after_human = asyncio.run(
_write_checkpoint(
checkpointer,
source_thread_id,
str(uuid6()),
[human],
step=1,
parent_config=initial.config,
)
)
asyncio.run(
_write_checkpoint(
checkpointer,
source_thread_id,
str(uuid6()),
[human, ai],
step=2,
parent_config=after_human,
)
)
asyncio.run(seed_turn(initial.config))
branch_response = client.post(
f"/api/threads/{source_thread_id}/branches",
@ -3183,6 +3178,24 @@ def test_branch_thread_can_prepare_regenerate_without_branch_run_events() -> Non
assert branch_base.checkpoint.get("channel_values", {}).get("messages", []) == []
def test_branch_replay_deadline_returns_504_and_logs_exception(monkeypatch, caplog) -> None:
from app.gateway import checkpoint_lineage
app, _store, _checkpointer = _build_thread_app()
thread_id = "source-replay-deadline"
monkeypatch.setattr(checkpoint_lineage, "_REPLAY_LINEAGE_LOOKUP_TIMEOUT_SECONDS", 0)
with TestClient(app) as client:
created = client.post("/api/threads", json={"thread_id": thread_id})
assert created.status_code == 200, created.text
_seed_branchable_thread(app, thread_id)
response = client.post(f"/api/threads/{thread_id}/branches", json={"message_id": "ai-1"})
assert response.status_code == 504, response.text
assert response.json()["detail"] == "Timed out resolving the checkpoint before the target user message"
assert any(thread_id in record.message and record.exc_info for record in caplog.records)
def test_branch_thread_from_older_assistant_turn_creates_truncated_thread() -> None:
app, store, checkpointer = _build_thread_app()
source_thread_id = "source-thread"