diff --git a/backend/app/gateway/routers/threads.py b/backend/app/gateway/routers/threads.py index 16b79b2a59..e228818e26 100644 --- a/backend/app/gateway/routers/threads.py +++ b/backend/app/gateway/routers/threads.py @@ -60,7 +60,7 @@ from deerflow.config.summarization_config import ContextSize from deerflow.persistence.thread_meta import PROJECT_FILTER_UNSET, THREAD_ARCHIVED_METADATA_KEY, THREAD_PINNED_METADATA_KEY, THREAD_PROJECT_METADATA_KEY, ThreadOwnershipConflictError from deerflow.runtime import ThreadOperationKind, serialize_channel_values_for_api from deerflow.runtime.checkpoint_mode import CheckpointModeMismatchError, CheckpointModeReconfigurationError -from deerflow.runtime.checkpoint_state import graph_reducer_channels, graph_state_schema, graph_writable_channels +from deerflow.runtime.checkpoint_state import graph_reducer_channels, graph_state_schema, graph_writable_channels, validate_state_mutation_node from deerflow.runtime.context_compaction import ( ContextCompactionDisabled, ContextCompactionFailed, @@ -598,6 +598,16 @@ class ThreadStateUpdateRequest(BaseModel): checkpoint: dict[str, Any] | None = Field(default=None, description="Full checkpoint object") as_node: str | None = Field(default=None, description="Node identity for the update") + @field_validator("as_node") + @classmethod + def _as_node_is_a_graph_node_name(cls, value: str | None) -> str | None: + # The name becomes the mutation graph's node; reject what LangGraph + # cannot compile as a 422 instead of an unhandled 500. An empty value + # keeps falling back to the default node in the route. + if value: + validate_state_mutation_node(value) + return value + class ThreadGoalRequest(BaseModel): """Request body for setting a thread-scoped goal.""" diff --git a/backend/docs/API.md b/backend/docs/API.md index 0cd5b732cd..515f66f12f 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -248,6 +248,11 @@ external boundaries. Ordinary `type`/`value` fields remain compatible. `goal: null` retains its existing semantics: it clears a state update's goal, but does not replace a goal through run input. +A state update's optional `as_node` names the graph node recorded as the +writer, and defaults to `manual_state_update`. It must be a name LangGraph can +register as a node: `__start__`, `__end__`, LangGraph's other reserved names and +names containing `:` or `|` are rejected with 422 before anything is written. + Replaying messages from an earlier root checkpoint, including response regeneration, preserves the thread's current goal and continuation budget. A cleared or achieved goal is not restored from history. A valid goal explicitly supplied in run input diff --git a/backend/packages/harness/deerflow/runtime/checkpoint_state.py b/backend/packages/harness/deerflow/runtime/checkpoint_state.py index 920bfd18b5..4d902dec20 100644 --- a/backend/packages/harness/deerflow/runtime/checkpoint_state.py +++ b/backend/packages/harness/deerflow/runtime/checkpoint_state.py @@ -34,6 +34,28 @@ def _finish_state_mutation(_state: dict[str, Any]) -> dict[str, Any]: return {} +def validate_state_mutation_node(as_node: str) -> str: + """Return *as_node*, or raise ``ValueError`` when LangGraph refuses it as a node name. + + :func:`build_state_mutation_graph` registers ``as_node`` as the graph's + only node, and LangGraph refuses ``__start__``, ``__end__``, its other + reserved names and any name containing a namespace separator (``|``) or + task separator (``:``). Callers that take the name from a client check it + here first, so a bad name is an input error and not a failed compile. + The reserved set is private to LangGraph; recheck this import when + upgrading LangGraph (verified against 1.2.9 and 1.2.14). + """ + from langgraph._internal._constants import NS_END, NS_SEP, RESERVED + from langgraph.constants import END, START + + if as_node in (START, END) or as_node in RESERVED: + raise ValueError(f"Node name {as_node!r} is reserved by LangGraph") + for character in (NS_SEP, NS_END): + if character in as_node: + raise ValueError(f"Node name must not contain {character!r}") + return as_node + + def build_state_mutation_graph( as_node: str, mode: CheckpointChannelMode, diff --git a/backend/tests/test_checkpoint_state.py b/backend/tests/test_checkpoint_state.py index c2433ca1b2..cad030e2b9 100644 --- a/backend/tests/test_checkpoint_state.py +++ b/backend/tests/test_checkpoint_state.py @@ -96,6 +96,33 @@ def test_mutation_graph_bakes_snapshot_frequency_into_fallback_schema() -> None: assert low_cadence.channels["messages"].snapshot_frequency == 250 +def _langgraph_refused_node_names() -> list[str]: + from langgraph._internal._constants import RESERVED + from langgraph.constants import END, START + + return sorted({START, END, *RESERVED, "a|b", "a:b", "branch:x"}) + + +@pytest.mark.parametrize("as_node", _langgraph_refused_node_names()) +def test_validate_state_mutation_node_rejects_every_name_langgraph_refuses(as_node: str) -> None: + """The client check and LangGraph's compile must refuse the same names.""" + from deerflow.runtime.checkpoint_state import build_state_mutation_graph, validate_state_mutation_node + + with pytest.raises(ValueError): + build_state_mutation_graph(as_node, "full") + with pytest.raises(ValueError): + validate_state_mutation_node(as_node) + + +@pytest.mark.parametrize("as_node", ["manual_state_update", "agent", "messages", "__start", "start", "a b", "é", "x" * 5000]) +def test_validate_state_mutation_node_accepts_names_langgraph_compiles(as_node: str) -> None: + """Names LangGraph compiles stay accepted, so the check never rejects a working update.""" + from deerflow.runtime.checkpoint_state import build_state_mutation_graph, validate_state_mutation_node + + assert as_node in build_state_mutation_graph(as_node, "full").nodes + assert validate_state_mutation_node(as_node) == as_node + + def test_sync_accessor_binds_persistence_guards_operations_and_preserves_input() -> None: graph = FakeGraph() saver = FakeCheckpointer() diff --git a/backend/tests/test_threads_router.py b/backend/tests/test_threads_router.py index c26c82c583..c0dcf9d532 100644 --- a/backend/tests/test_threads_router.py +++ b/backend/tests/test_threads_router.py @@ -4809,6 +4809,65 @@ def test_update_thread_state_real_mutation_graph_finishes_without_scheduling(mon assert body["next"] == [] +def _use_real_mutation_graph(monkeypatch) -> None: + real_mutation_builder = gateway_services.build_checkpoint_state_mutation_accessor + + async def mutation_boundary(request, *, thread_id, as_node, checkpoint_id=None): + return real_mutation_builder(request, thread_id=thread_id, as_node=as_node, checkpoint_id=checkpoint_id) + + monkeypatch.setattr(threads, "build_thread_checkpoint_state_mutation_accessor", mutation_boundary) + + +@pytest.mark.parametrize("mode", ["full", "delta"]) +@pytest.mark.parametrize("as_node", ["__start__", "__end__", "__interrupt__", "a:b", "a|b"]) +def test_update_thread_state_rejects_an_as_node_langgraph_cannot_compile(monkeypatch, mode, as_node) -> None: + """A node name the mutation graph cannot register is the client's input error, not a 500.""" + import asyncio + + app, _store, checkpointer = _build_thread_app() + app.state.checkpoint_channel_mode = mode + _use_real_mutation_graph(monkeypatch) + + with TestClient(app, raise_server_exceptions=False) as client: + created = client.post("/api/threads", json={"thread_id": "state-bad-node", "metadata": {}}) + assert created.status_code == 200, created.text + response = client.post("/api/threads/state-bad-node/state", json={"values": {"title": "Renamed"}, "as_node": as_node}) + state = client.get("/api/threads/state-bad-node/state") + + assert response.status_code == 422, response.text + assert response.json()["detail"][0]["loc"] == ["body", "as_node"] + assert state.status_code == 200, state.text + assert state.json()["values"].get("title") != "Renamed" + + async def _count() -> int: + return len([item async for item in checkpointer.alist({"configurable": {"thread_id": "state-bad-node"}})]) + + assert asyncio.run(_count()) == 1 + + +@pytest.mark.parametrize(("as_node", "expected_writer"), [("custom_editor", "custom_editor"), ("", "manual_state_update"), (None, "manual_state_update")]) +def test_update_thread_state_keeps_accepting_compilable_as_node_values(monkeypatch, as_node, expected_writer) -> None: + app, _store, _checkpointer = _build_thread_app() + _use_real_mutation_graph(monkeypatch) + recorded: list[str] = [] + real_boundary = threads.build_thread_checkpoint_state_mutation_accessor + + async def recording_boundary(request, *, thread_id, as_node, checkpoint_id=None): + recorded.append(as_node) + return await real_boundary(request, thread_id=thread_id, as_node=as_node, checkpoint_id=checkpoint_id) + + monkeypatch.setattr(threads, "build_thread_checkpoint_state_mutation_accessor", recording_boundary) + + with TestClient(app) as client: + created = client.post("/api/threads", json={"thread_id": "state-good-node", "metadata": {}}) + assert created.status_code == 200, created.text + response = client.post("/api/threads/state-good-node/state", json={"values": {"title": "Renamed"}, "as_node": as_node}) + + assert response.status_code == 200, response.text + assert response.json()["values"]["title"] == "Renamed" + assert recorded == [expected_writer] + + def test_update_thread_state_forks_from_checkpoint_object(monkeypatch) -> None: app, _store, _checkpointer = _build_thread_app() thread_id = "state-checkpoint-object" diff --git a/frontend/src/content/en/harness/checkpoints/reference.mdx b/frontend/src/content/en/harness/checkpoints/reference.mdx index 0bcb2ac77b..7c6865f5c1 100644 --- a/frontend/src/content/en/harness/checkpoints/reference.mdx +++ b/frontend/src/content/en/harness/checkpoints/reference.mdx @@ -233,8 +233,9 @@ Import paths a consumer may rely on. Everything listed here is a Python import; | `create_deerflow_agent(..., checkpoint_channel_mode="full", checkpoint_snapshot_frequency=None, ...)` | `deerflow.agents.factory` | public agent factory; delta plus a checkpointer is rejected | `factory:66-77`, `factory:135-141` | | `CheckpointStateAccessor`, `build_state_mutation_graph` | `deerflow.runtime` (package re-export) | accessor choke point and mutation graph | `deerflow/runtime/__init__.py:8,21-22` | | `ThreadState`, `DeltaThreadState`, `SandboxState` | `deerflow.agents` (package re-export) | lazily exported state schemas | `agents/__init__.py:14-16,40-47` | -| `CheckpointStateAccessor.bind(graph, checkpointer, *, store=None, mode="full")` | `deerflow.runtime.checkpoint_state` | bind graph, saver, and mode | `cstate:112-134` | -| `build_state_mutation_graph(as_node, mode, state_schema=None, *, snapshot_frequency=None)` | `deerflow.runtime.checkpoint_state` | state-only writer graph for `Overwrite`-style writes | `cstate:39-65` | +| `CheckpointStateAccessor.bind(graph, checkpointer, *, store=None, mode="full")` | `deerflow.runtime.checkpoint_state` | bind graph, saver, and mode | `cstate:134-154` | +| `build_state_mutation_graph(as_node, mode, state_schema=None, *, snapshot_frequency=None)` | `deerflow.runtime.checkpoint_state` | state-only writer graph for `Overwrite`-style writes | `cstate:59-89` | +| `validate_state_mutation_node(as_node)` | `deerflow.runtime.checkpoint_state` | refuses a node name LangGraph cannot compile; the request model of `POST /api/threads/{thread_id}/state` runs it on `as_node` | `cstate:37-56`, `threads:601-609` | In delta mode a raw saver read sees sentinels, not messages. Consumers must read diff --git a/frontend/src/content/zh/harness/checkpoints/reference.mdx b/frontend/src/content/zh/harness/checkpoints/reference.mdx index 98e50bac04..61f5ba3128 100644 --- a/frontend/src/content/zh/harness/checkpoints/reference.mdx +++ b/frontend/src/content/zh/harness/checkpoints/reference.mdx @@ -233,8 +233,9 @@ wait 响应仍为 HTTP `200`。Python SDK 默认使用 `raise_error=True`,识 | `create_deerflow_agent(..., checkpoint_channel_mode="full", checkpoint_snapshot_frequency=None, ...)` | `deerflow.agents.factory` | 对外 agent 工厂;delta 加 checkpointer 会被拒绝 | `factory:66-77`、`factory:135-141` | | `CheckpointStateAccessor`、`build_state_mutation_graph` | `deerflow.runtime`(包级再导出) | 访问器收口点与变更图 | `deerflow/runtime/__init__.py:8,21-22` | | `ThreadState`、`DeltaThreadState`、`SandboxState` | `deerflow.agents`(包级再导出) | 惰性导出的状态 schema | `agents/__init__.py:14-16,40-47` | -| `CheckpointStateAccessor.bind(graph, checkpointer, *, store=None, mode="full")` | `deerflow.runtime.checkpoint_state` | 绑定 graph、saver 与模式 | `cstate:112-134` | -| `build_state_mutation_graph(as_node, mode, state_schema=None, *, snapshot_frequency=None)` | `deerflow.runtime.checkpoint_state` | 面向 `Overwrite` 式写入的纯状态写入图 | `cstate:39-65` | +| `CheckpointStateAccessor.bind(graph, checkpointer, *, store=None, mode="full")` | `deerflow.runtime.checkpoint_state` | 绑定 graph、saver 与模式 | `cstate:134-154` | +| `build_state_mutation_graph(as_node, mode, state_schema=None, *, snapshot_frequency=None)` | `deerflow.runtime.checkpoint_state` | 面向 `Overwrite` 式写入的纯状态写入图 | `cstate:59-89` | +| `validate_state_mutation_node(as_node)` | `deerflow.runtime.checkpoint_state` | 拒绝 LangGraph 无法编译的节点名;`POST /api/threads/{thread_id}/state` 的请求模型用它校验 `as_node` | `cstate:37-56`、`threads:601-609` | delta 模式下裸读 saver 看到的是哨兵而不是消息。消费者必须通过