mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(runtime): keep replayed fallback from failing a successful run (#8324)
* fix(runtime): scope fallback detection when pre-run capture fails A failed pre-run snapshot capture leaves the message-id boundary empty, but values-mode chunks still replay prior history. A stale deerflow_error_fallback marker can therefore flip a successful current run to error. When capture failed, attribute only the newest values message to this run; incremental modes and journal fallback detection stay unchanged. Parametrize the stale-history regression over capture success and failure. * fix(runtime): establish fallback boundary on uncaptured values frames An initial values frame can be entirely replayed history, so latching its newest fallback still misclassifies the run. When the pre-run snapshot was not captured, record the first values frame as the message-ID baseline and accept only later IDs; only then can a fallback be attributed to the current run. Update the regression to emit the initial replay frame, and keep the fresh-fallback control with an empty initial frame. * test(runtime): cover replay boundaries in both values modes Emit the initial replayed values frame as a separate frame and assert both values-only and values+updates streams ignore its stale fallback. Keep the fresh-fallback control on the same two mode shapes. * fix(runtime): keep no-checkpointer runs as current fallback sources An in-memory run has no replayed history, so a values frame is current even when snapshot capture is unavailable. Only a thread with a checkpointer needs the first-frame replay baseline; preserve fallback detection for checkpointer-less runs. * fix(runtime): filter replayed fallbacks from updates frames too ThreadDataMiddleware.before_agent returns full history in an updates frame. When the pre-run snapshot capture failed, the message-ID boundary now covers values and updates frames and collects nested update messages; values and updates-only requests skip replayed fallback markers while fresh updates remain eligible. Add a regression that builds the history update with the real middleware and covers updates-only and values+updates. * fix(runtime): bound fallback on empty frames and checkpoint streams Set the replay boundary on the first values or updates frame even when it has no messages, so a new thread's first fallback is not mistaken for history. Treat checkpoints and debug snapshots as replay sources: they seed the message-ID boundary and never latch a fallback. Add regressions for empty boundary frames in values, updates and mixed mode, and for checkpoints/debug history before values. --------- Co-authored-by: Tong-bit-art <Tong-bit-art@users.noreply.github.com>
This commit is contained in:
parent
ec2c881c6b
commit
cd518c347b
@ -42,6 +42,10 @@ make test-blocking-io
|
||||
mode rejects a `delta` checkpoint; it does not guess.
|
||||
- **Read and change state through `CheckpointStateAccessor`** with the thread's
|
||||
effective schema. It preserves mode gates, parentage and pending writes.
|
||||
- **A failed pre-run snapshot leaves no message-ID boundary.** When a
|
||||
checkpointer exists but the pre-run capture fails, the first `values` frame
|
||||
establishes a replay baseline; only later message IDs can decide this run's
|
||||
LLM error fallback.
|
||||
- **Delta resume and rollback rewrite the current head.** They do not fork.
|
||||
Reject a missing tuple or pending sends before the first write.
|
||||
|
||||
|
||||
@ -1084,6 +1084,10 @@ async def run_agent(
|
||||
# earlier runs on the same thread — without it, one stale fallback in
|
||||
# history would mark every subsequent run on this thread as ``error``.
|
||||
pre_existing_message_ids: set[str] = set()
|
||||
# First values frame replayed when the pre-run capture failed. It is an
|
||||
# emission boundary, not current output: only later message IDs can decide
|
||||
# this run's fallback.
|
||||
fallback_boundary_ids: set[str] | None = None
|
||||
|
||||
# Bound agent graph accessor + captured pre-run rollback point; assigned
|
||||
# inside the try block so the finally rollback path can fork the pre-run
|
||||
@ -1715,6 +1719,31 @@ async def run_agent(
|
||||
pending_pause = True
|
||||
remember_approval(streamed_interrupts)
|
||||
|
||||
def _fallback_scope(chunk: Any, mode: str) -> set[str] | None:
|
||||
"""Message IDs allowed to decide this run's fallback for one frame.
|
||||
|
||||
``None`` means this frame only establishes the boundary and must not
|
||||
latch a fallback. Without a captured pre-run snapshot, the first values
|
||||
frame can be entirely replayed history; later frames are compared
|
||||
against that baseline.
|
||||
"""
|
||||
nonlocal fallback_boundary_ids
|
||||
if not snapshot_capture_failed or checkpointer is None:
|
||||
return pre_existing_message_ids
|
||||
if mode in {"checkpoints", "debug"}:
|
||||
# Introspection snapshots can contain the full pre-run state.
|
||||
# They seed the boundary but never decide the current status.
|
||||
fallback_boundary_ids = (fallback_boundary_ids or set()) | _collect_message_ids_deep(chunk)
|
||||
return None
|
||||
if mode not in {"values", "updates"}:
|
||||
return pre_existing_message_ids
|
||||
if fallback_boundary_ids is None:
|
||||
# Establish the boundary even when the frame is empty: a new
|
||||
# thread's first message-bearing frame can be the current fallback.
|
||||
fallback_boundary_ids = _collect_message_ids_deep(chunk)
|
||||
return None
|
||||
return pre_existing_message_ids | fallback_boundary_ids
|
||||
|
||||
async def _stream_once(input_payload: Any, stream_config: RunnableConfig) -> None:
|
||||
nonlocal llm_error_fallback_message
|
||||
if input_control is not None:
|
||||
@ -1736,7 +1765,9 @@ async def run_agent(
|
||||
if single_mode != "custom":
|
||||
# Custom frames carry task_* events whose payload can hold a delegated
|
||||
# subagent's messages; see the multi-mode branch below.
|
||||
llm_error_fallback_message = llm_error_fallback_message or _extract_llm_error_fallback_message(chunk, pre_existing_message_ids)
|
||||
scope_ids = _fallback_scope(chunk, single_mode)
|
||||
if scope_ids is not None:
|
||||
llm_error_fallback_message = llm_error_fallback_message or _extract_llm_error_fallback_message(chunk, scope_ids)
|
||||
sse_event = _lg_mode_to_sse_event(single_mode)
|
||||
single_payload = serialize(chunk, mode=single_mode)
|
||||
if single_mode == "values" and seq_stamper is not None:
|
||||
@ -1792,7 +1823,9 @@ async def run_agent(
|
||||
# executor's to map (task_failed), not this run's. That
|
||||
# includes the child messages task_running custom events
|
||||
# carry, which are root frames too.
|
||||
llm_error_fallback_message = llm_error_fallback_message or _extract_llm_error_fallback_message(chunk, pre_existing_message_ids)
|
||||
scope_ids = _fallback_scope(chunk, mode)
|
||||
if scope_ids is not None:
|
||||
llm_error_fallback_message = llm_error_fallback_message or _extract_llm_error_fallback_message(chunk, scope_ids)
|
||||
observe_stream_pause(mode, chunk, namespace)
|
||||
await _publish_stream_item(
|
||||
bridge=bridge,
|
||||
@ -4012,6 +4045,34 @@ def _collect_pre_existing_message_ids(values: Any) -> set[str]:
|
||||
return {message_id for message in messages if (message_id := _message_id(message)) is not None}
|
||||
|
||||
|
||||
def _collect_message_ids_deep(value: Any) -> set[str]:
|
||||
"""Collect message IDs from values or nested updates frames."""
|
||||
ids: set[str] = set()
|
||||
seen: set[int] = set()
|
||||
|
||||
def walk(obj: Any) -> None:
|
||||
oid = id(obj)
|
||||
if oid in seen:
|
||||
return
|
||||
seen.add(oid)
|
||||
if isinstance(obj, dict):
|
||||
message_id = _message_id(obj)
|
||||
if message_id is not None:
|
||||
ids.add(message_id)
|
||||
for item in obj.values():
|
||||
walk(item)
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
for item in obj:
|
||||
walk(item)
|
||||
else:
|
||||
message_id = _message_id(obj)
|
||||
if message_id is not None:
|
||||
ids.add(message_id)
|
||||
|
||||
walk(value)
|
||||
return ids
|
||||
|
||||
|
||||
def _unpack_stream_item(
|
||||
item: Any,
|
||||
lg_modes: list[str],
|
||||
|
||||
@ -1926,8 +1926,9 @@ async def test_run_agent_overrides_spoofed_pre_existing_message_ids_without_snap
|
||||
assert captured["pre_existing_message_ids"] == frozenset()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream_modes", [["values"], ["values", "updates"]], ids=["values-only", "values+updates"])
|
||||
@pytest.mark.anyio
|
||||
async def test_run_agent_marks_llm_error_fallback_as_error_status():
|
||||
async def test_run_agent_marks_llm_error_fallback_as_error_status(stream_modes):
|
||||
run_manager = RunManager()
|
||||
record = await run_manager.create("thread-1")
|
||||
bridge = SimpleNamespace(
|
||||
@ -1938,19 +1939,28 @@ async def test_run_agent_marks_llm_error_fallback_as_error_status():
|
||||
|
||||
class DummyAgent:
|
||||
async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False):
|
||||
yield {
|
||||
"messages": [
|
||||
AIMessage(
|
||||
content="The configured LLM provider is temporarily unavailable after multiple retries.",
|
||||
additional_kwargs={
|
||||
"deerflow_error_fallback": True,
|
||||
"error_type": "APIConnectionError",
|
||||
"error_reason": "transient",
|
||||
"error_detail": "Connection error.",
|
||||
},
|
||||
)
|
||||
]
|
||||
}
|
||||
frames = [
|
||||
{"messages": []},
|
||||
{
|
||||
"messages": [
|
||||
AIMessage(
|
||||
content="The configured LLM provider is temporarily unavailable after multiple retries.",
|
||||
additional_kwargs={
|
||||
"deerflow_error_fallback": True,
|
||||
"error_type": "APIConnectionError",
|
||||
"error_reason": "transient",
|
||||
"error_detail": "Connection error.",
|
||||
},
|
||||
)
|
||||
]
|
||||
},
|
||||
]
|
||||
if isinstance(stream_mode, (list, tuple)):
|
||||
for frame in frames:
|
||||
yield ("values", frame)
|
||||
else:
|
||||
for frame in frames:
|
||||
yield frame
|
||||
|
||||
def factory(*, config):
|
||||
return DummyAgent()
|
||||
@ -1963,6 +1973,7 @@ async def test_run_agent_marks_llm_error_fallback_as_error_status():
|
||||
agent_factory=factory,
|
||||
graph_input={},
|
||||
config={},
|
||||
stream_modes=stream_modes,
|
||||
)
|
||||
|
||||
fetched = await run_manager.get(record.run_id)
|
||||
@ -3408,8 +3419,10 @@ def test_collect_pre_existing_message_ids_handles_missing_pieces():
|
||||
assert _collect_pre_existing_message_ids({"messages": None}) == set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("capture_fails", [False, True], ids=["capture-ok", "capture-failed"])
|
||||
@pytest.mark.parametrize("stream_modes", [["values"], ["values", "updates"]], ids=["values-only", "values+updates"])
|
||||
@pytest.mark.anyio
|
||||
async def test_run_agent_ignores_stale_llm_error_fallback_from_prior_run():
|
||||
async def test_run_agent_ignores_stale_llm_error_fallback_from_prior_run(capture_fails, stream_modes):
|
||||
"""A stale fallback marker checkpointed by an earlier run on the same thread
|
||||
must NOT cause a successful current run to be reported as ``error``.
|
||||
|
||||
@ -3451,6 +3464,8 @@ async def test_run_agent_ignores_stale_llm_error_fallback_from_prior_run():
|
||||
|
||||
class DummyAgent:
|
||||
async def aget_state(self, _config):
|
||||
if capture_fails:
|
||||
raise RuntimeError("snapshot capture failed")
|
||||
return SimpleNamespace(
|
||||
values={"messages": [stale_fallback]},
|
||||
config={
|
||||
@ -3469,13 +3484,23 @@ async def test_run_agent_ignores_stale_llm_error_fallback_from_prior_run():
|
||||
|
||||
async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False):
|
||||
# Replay the prior fallback message (as LangGraph would when using
|
||||
# stream_mode="values") and then yield a fresh successful AIMessage.
|
||||
yield {
|
||||
"messages": [
|
||||
stale_fallback,
|
||||
AIMessage(id="fresh-ok", content="Hello — the run succeeded."),
|
||||
]
|
||||
}
|
||||
# stream_mode="values") as an initial boundary frame, then emit a
|
||||
# fresh successful AIMessage.
|
||||
frames = [
|
||||
{"messages": [stale_fallback]},
|
||||
{
|
||||
"messages": [
|
||||
stale_fallback,
|
||||
AIMessage(id="fresh-ok", content="Hello — the run succeeded."),
|
||||
]
|
||||
},
|
||||
]
|
||||
if isinstance(stream_mode, (list, tuple)):
|
||||
for frame in frames:
|
||||
yield ("values", frame)
|
||||
else:
|
||||
for frame in frames:
|
||||
yield frame
|
||||
|
||||
def factory(*, config):
|
||||
return DummyAgent()
|
||||
@ -3488,6 +3513,7 @@ async def test_run_agent_ignores_stale_llm_error_fallback_from_prior_run():
|
||||
agent_factory=factory,
|
||||
graph_input={},
|
||||
config={},
|
||||
stream_modes=stream_modes,
|
||||
)
|
||||
|
||||
fetched = await run_manager.get(record.run_id)
|
||||
@ -3496,6 +3522,184 @@ async def test_run_agent_ignores_stale_llm_error_fallback_from_prior_run():
|
||||
bridge.publish_end.assert_awaited_once_with(record.run_id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream_modes", [["updates"], ["values", "updates"]], ids=["updates-only", "values+updates"])
|
||||
@pytest.mark.anyio
|
||||
async def test_run_agent_ignores_replayed_fallback_in_updates_frame(tmp_path, stream_modes):
|
||||
from deerflow.agents.middlewares.thread_data_middleware import ThreadDataMiddleware
|
||||
|
||||
run_manager = RunManager()
|
||||
record = await run_manager.create("thread-1")
|
||||
bridge = SimpleNamespace(
|
||||
publish=AsyncMock(),
|
||||
publish_end=AsyncMock(),
|
||||
cleanup=AsyncMock(),
|
||||
)
|
||||
stale_fallback = AIMessage(
|
||||
id="stale-update-fallback",
|
||||
content="Old failure.",
|
||||
additional_kwargs={
|
||||
"deerflow_error_fallback": True,
|
||||
"error_type": "IndexError",
|
||||
"error_reason": "transient",
|
||||
"error_detail": "list index out of range",
|
||||
},
|
||||
)
|
||||
|
||||
class MinimalCheckpointer:
|
||||
async def aget_tuple(self, _config):
|
||||
return None
|
||||
|
||||
class DummyAgent:
|
||||
async def aget_state(self, _config):
|
||||
raise RuntimeError("snapshot capture failed")
|
||||
|
||||
async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False):
|
||||
history = ThreadDataMiddleware(base_dir=str(tmp_path)).before_agent(
|
||||
{"messages": [stale_fallback]},
|
||||
SimpleNamespace(context={"thread_id": "thread-1", "user_id": "user-1"}),
|
||||
)
|
||||
frames = [
|
||||
("updates", {"ThreadDataMiddleware.before_agent": history}),
|
||||
(
|
||||
"updates",
|
||||
{"model": {"messages": [AIMessage(id="fresh-update", content="The run succeeded.")]}},
|
||||
),
|
||||
]
|
||||
if "values" in stream_modes:
|
||||
frames.insert(
|
||||
1,
|
||||
(
|
||||
"values",
|
||||
{"messages": [stale_fallback, AIMessage(id="fresh-value", content="The run succeeded.")]},
|
||||
),
|
||||
)
|
||||
for mode, frame in frames:
|
||||
if isinstance(stream_mode, (list, tuple)):
|
||||
yield (mode, frame)
|
||||
elif mode == "updates":
|
||||
yield frame
|
||||
|
||||
await run_agent(
|
||||
bridge,
|
||||
run_manager,
|
||||
record,
|
||||
ctx=RunContext(checkpointer=MinimalCheckpointer()),
|
||||
agent_factory=lambda *, config: DummyAgent(),
|
||||
graph_input={},
|
||||
config={},
|
||||
stream_modes=stream_modes,
|
||||
)
|
||||
|
||||
fetched = await run_manager.get(record.run_id)
|
||||
assert fetched is not None
|
||||
assert fetched.status == RunStatus.success
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream_modes", [["values"], ["updates"], ["values", "updates"]], ids=["values-only", "updates-only", "values+updates"])
|
||||
@pytest.mark.anyio
|
||||
async def test_run_agent_keeps_fresh_fallback_after_empty_boundary_frame(stream_modes):
|
||||
run_manager = RunManager()
|
||||
record = await run_manager.create("thread-1")
|
||||
bridge = SimpleNamespace(
|
||||
publish=AsyncMock(),
|
||||
publish_end=AsyncMock(),
|
||||
cleanup=AsyncMock(),
|
||||
)
|
||||
fallback = AIMessage(
|
||||
id="fresh-boundary-fallback",
|
||||
content="Provider unavailable.",
|
||||
additional_kwargs={"deerflow_error_fallback": True, "error_detail": "Connection error."},
|
||||
)
|
||||
|
||||
class MinimalCheckpointer:
|
||||
async def aget_tuple(self, _config):
|
||||
return None
|
||||
|
||||
class DummyAgent:
|
||||
async def aget_state(self, _config):
|
||||
raise RuntimeError("snapshot capture failed")
|
||||
|
||||
async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False):
|
||||
frames = []
|
||||
if "values" in stream_modes:
|
||||
frames.append(("values", {"messages": []}))
|
||||
else:
|
||||
frames.append(("updates", {}))
|
||||
if "updates" in stream_modes:
|
||||
frames.append(("updates", {"model": {"messages": [fallback]}}))
|
||||
else:
|
||||
frames.append(("values", {"messages": [fallback]}))
|
||||
for mode, frame in frames:
|
||||
if isinstance(stream_mode, (list, tuple)):
|
||||
yield (mode, frame)
|
||||
elif mode == stream_mode:
|
||||
yield frame
|
||||
|
||||
await run_agent(
|
||||
bridge,
|
||||
run_manager,
|
||||
record,
|
||||
ctx=RunContext(checkpointer=MinimalCheckpointer()),
|
||||
agent_factory=lambda *, config: DummyAgent(),
|
||||
graph_input={},
|
||||
config={},
|
||||
stream_modes=stream_modes,
|
||||
)
|
||||
|
||||
fetched = await run_manager.get(record.run_id)
|
||||
assert fetched is not None
|
||||
assert fetched.status == RunStatus.error
|
||||
assert fetched.error == "Connection error."
|
||||
|
||||
|
||||
@pytest.mark.parametrize("inspect_mode", ["checkpoints", "debug"], ids=["checkpoints", "debug"])
|
||||
@pytest.mark.anyio
|
||||
async def test_run_agent_filters_checkpoint_history_before_values(inspect_mode):
|
||||
run_manager = RunManager()
|
||||
record = await run_manager.create("thread-1")
|
||||
bridge = SimpleNamespace(
|
||||
publish=AsyncMock(),
|
||||
publish_end=AsyncMock(),
|
||||
cleanup=AsyncMock(),
|
||||
)
|
||||
stale_fallback = AIMessage(
|
||||
id="checkpoint-stale-fallback",
|
||||
content="Old failure.",
|
||||
additional_kwargs={"deerflow_error_fallback": True, "error_detail": "old"},
|
||||
)
|
||||
|
||||
class MinimalCheckpointer:
|
||||
async def aget_tuple(self, _config):
|
||||
return None
|
||||
|
||||
class DummyAgent:
|
||||
async def aget_state(self, _config):
|
||||
raise RuntimeError("snapshot capture failed")
|
||||
|
||||
async def astream(self, graph_input, config=None, stream_mode=None, subgraphs=False):
|
||||
frames = [
|
||||
(inspect_mode, {"values": {"messages": [stale_fallback]}}),
|
||||
("values", {"messages": [stale_fallback, AIMessage(id="fresh-ok", content="The run succeeded.")]}),
|
||||
]
|
||||
for mode, frame in frames:
|
||||
yield (mode, frame)
|
||||
|
||||
await run_agent(
|
||||
bridge,
|
||||
run_manager,
|
||||
record,
|
||||
ctx=RunContext(checkpointer=MinimalCheckpointer()),
|
||||
agent_factory=lambda *, config: DummyAgent(),
|
||||
graph_input={},
|
||||
config={},
|
||||
stream_modes=[inspect_mode, "values"],
|
||||
)
|
||||
|
||||
fetched = await run_manager.get(record.run_id)
|
||||
assert fetched is not None
|
||||
assert fetched.status == RunStatus.success
|
||||
|
||||
|
||||
class _FakeCheckpointTuple:
|
||||
"""Minimal stand-in for ``CheckpointTuple`` used by ``_ensure_interrupted_title``."""
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user