mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-23 14:04:41 +00:00
fix(gateway): reject unusable artifact state at the input boundary (#8409)
artifacts and tool_artifact_processed are caller-writable reducer channels whose values the thread-state route persists with Overwrite. A non-list value was stored before any reducer saw it, and the next artifact-producing run failed on existing + new; unhashable entries crashed the dedupe. Validate the declared list-of-strings shape on both boundaries and let merge_artifacts ignore a non-list side or non-string entry so an already-poisoned checkpoint heals instead of failing every later run.
This commit is contained in:
parent
018a8d814d
commit
0ed5743832
@ -774,6 +774,28 @@ def _normalize_external_tool_artifacts(value: Any, *, location: str) -> list[dic
|
||||
return normalized
|
||||
|
||||
|
||||
def _normalize_external_artifacts(value: Any, *, location: str) -> list[str] | None:
|
||||
"""Reject artifact lists the reducer cannot merge.
|
||||
|
||||
``artifacts`` and ``tool_artifact_processed`` are checkpointed reducer
|
||||
channels a caller may Overwrite. ``merge_artifacts`` concatenates the stored
|
||||
list with the new one, so a caller-supplied non-list value fails the next
|
||||
artifact-producing run with an unhandled ``TypeError``. The thread-state
|
||||
route persists the value with ``Overwrite`` before any reducer sees it, so
|
||||
without this boundary the thread stays broken across runs. Require the
|
||||
declared ``list[str]`` shape; the reducer also tolerates an already-poisoned
|
||||
checkpoint.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, list):
|
||||
raise HTTPException(status_code=400, detail=f"{location} must be a list of strings")
|
||||
for index, entry in enumerate(value):
|
||||
if not isinstance(entry, str):
|
||||
raise HTTPException(status_code=400, detail=f"{location}[{index}] must be a string")
|
||||
return list(value)
|
||||
|
||||
|
||||
def _normalize_external_goal(value: Any, *, location: str) -> dict[str, Any] | None:
|
||||
"""Require usable goal text without rebuilding caller-supplied goal state."""
|
||||
if value is None:
|
||||
@ -896,6 +918,11 @@ def strip_server_owned_state_metadata(values: Mapping[str, Any]) -> dict[str, An
|
||||
# strip the generic list branch applied: a caller-crafted entry must
|
||||
# not smuggle server-owned message metadata into the checkpoint.
|
||||
stripped[channel] = None if normalized_tool_artifacts is None else [_strip_external_metadata_from_message_like(item) for item in normalized_tool_artifacts]
|
||||
elif channel in ("artifacts", "tool_artifact_processed"):
|
||||
# Entries are display paths, so the generic list branch's
|
||||
# message-metadata strip is a no-op for them; the shape check
|
||||
# replaces that pass rather than skipping a real sanitizer.
|
||||
stripped[channel] = _normalize_external_artifacts(value, location=f"values.{channel}")
|
||||
elif isinstance(value, list):
|
||||
stripped[channel] = [_strip_external_metadata_from_message_like(item) for item in value]
|
||||
else:
|
||||
@ -971,6 +998,9 @@ def normalize_input(raw_input: dict[str, Any] | None, *, trusted_internal: bool
|
||||
result = {**result, "promoted": _normalize_external_promoted(result["promoted"], location="input.promoted")}
|
||||
if "tool_artifacts" in result:
|
||||
result = {**result, "tool_artifacts": _normalize_external_tool_artifacts(result["tool_artifacts"], location="input.tool_artifacts")}
|
||||
for artifact_channel in ("artifacts", "tool_artifact_processed"):
|
||||
if artifact_channel in result:
|
||||
result = {**result, artifact_channel: _normalize_external_artifacts(result[artifact_channel], location=f"input.{artifact_channel}")}
|
||||
# merge_goal ignores None, so only a goal value replaces the goal.
|
||||
if result.get("goal") is not None:
|
||||
normalized_goal = _normalize_external_goal(result["goal"], location="input.goal")
|
||||
|
||||
@ -101,13 +101,20 @@ SandboxStateField = Annotated[NotRequired[SandboxState | None], merge_sandbox]
|
||||
|
||||
|
||||
def merge_artifacts(existing: list[str] | None, new: list[str] | None) -> list[str]:
|
||||
"""Reducer for artifacts list - merges and deduplicates artifacts."""
|
||||
if existing is None:
|
||||
return new or []
|
||||
if new is None:
|
||||
return existing
|
||||
"""Reducer for artifacts list - merges and deduplicates artifacts.
|
||||
|
||||
The thread-state route writes reducer channels with ``Overwrite``, so a
|
||||
caller-supplied non-list value can be persisted without ever reaching this
|
||||
reducer, and a checkpoint written before the boundary validation can carry
|
||||
one. Ignore a non-list side and non-string entries instead of raising on
|
||||
``existing + new`` or on an unhashable entry: one bad write must not fail
|
||||
every later run that produces an artifact. Entries are display paths, so
|
||||
only strings survive.
|
||||
"""
|
||||
existing_items = [item for item in existing if isinstance(item, str)] if isinstance(existing, list) else []
|
||||
new_items = [item for item in new if isinstance(item, str)] if isinstance(new, list) else []
|
||||
# Use dict.fromkeys to deduplicate while preserving order
|
||||
return list(dict.fromkeys(existing + new))
|
||||
return list(dict.fromkeys(existing_items + new_items))
|
||||
|
||||
|
||||
def merge_viewed_images(existing: dict[str, ViewedImageData] | None, new: dict[str, ViewedImageData] | None) -> dict[str, ViewedImageData]:
|
||||
|
||||
@ -945,6 +945,51 @@ def test_normalize_input_rejects_malformed_message_with_400():
|
||||
assert "input.messages[1]" in excinfo.value.detail
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["artifacts", "tool_artifact_processed"])
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
["oops", [["nested"]], ["ok", 3], {"type": "__overwrite__", "value": ["ok"]}],
|
||||
ids=["non-list", "unhashable-entry", "non-string-entry", "overwrite-shaped"],
|
||||
)
|
||||
def test_normalize_input_rejects_unusable_artifact_state_with_400(channel, value):
|
||||
"""A value ``merge_artifacts`` cannot concatenate must be a 400 here.
|
||||
|
||||
The thread-state route persists reducer values with ``Overwrite``, so a
|
||||
non-list shape would be stored before any reducer sees it and the next
|
||||
artifact-producing run would fail on ``existing + new``.
|
||||
"""
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.gateway.services import normalize_input
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
normalize_input({channel: value})
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert f"input.{channel}" in excinfo.value.detail
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["artifacts", "tool_artifact_processed"])
|
||||
def test_normalize_input_keeps_usable_artifact_lists(channel):
|
||||
from app.gateway.services import normalize_input
|
||||
|
||||
assert normalize_input({channel: ["out/report.md", "out/data.csv"]})[channel] == ["out/report.md", "out/data.csv"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", ["artifacts", "tool_artifact_processed"])
|
||||
def test_state_values_reject_unusable_artifact_state_with_400(channel):
|
||||
"""The thread-state update route shares the artifact-list boundary."""
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.gateway.services import strip_server_owned_state_metadata
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
strip_server_owned_state_metadata({channel: "oops"})
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert f"values.{channel}" in excinfo.value.detail
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tool_artifacts",
|
||||
[
|
||||
|
||||
@ -119,6 +119,18 @@ class TestMergeArtifacts:
|
||||
def test_none_existing_accepts_new(self):
|
||||
assert merge_artifacts(None, ["a"]) == ["a"]
|
||||
|
||||
def test_poisoned_existing_value_is_ignored(self):
|
||||
"""A non-list value persisted through the state route must not fail the
|
||||
next artifact write with ``TypeError``."""
|
||||
assert merge_artifacts("oops", ["a"]) == ["a"]
|
||||
|
||||
def test_non_list_new_value_is_ignored(self):
|
||||
assert merge_artifacts(["a"], "oops") == ["a"]
|
||||
|
||||
def test_non_string_entries_are_dropped(self):
|
||||
"""Unhashable entries from a poisoned list must not break deduplication."""
|
||||
assert merge_artifacts(["a", ["b"]], ["c", {"d": 1}]) == ["a", "c"]
|
||||
|
||||
|
||||
class TestMergeViewedImages:
|
||||
"""Sanity check for the existing viewed_images reducer."""
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user