Skip to content

fix(todos): keep an unusable stored todo list from failing every model call - #7803

Merged
WillemJiang merged 6 commits into
bytedance:mainfrom
gdut4140:fix/todo-state-shape
Nov 4, 2026
Merged

WillemJiang merged 6 commits into
bytedance:mainfrom
gdut4140:fix/todo-state-shape

Conversation

@gdut4140

@gdut4140 gdut4140 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Why

  • Trigger: while checking how much thread state the Gateway trusts, POST /api/threads/{id}/state turned out to validate caller-written goal (_normalize_external_goal) but pass any shape through for todos — another reducer channel a client can Overwrite directly, because the body is values: dict[str, Any].
  • Pain: TodoMiddleware reads state["todos"] in both before_model (context-loss reminder) and after_model (premature-exit guard) and calls entry.get(...) on every entry. One non-object entry, or a value that is not a list at all, therefore raises AttributeError on every model call for that thread. The failure happens before the model is invoked, so the UI cannot repair the thread either. Reproduced on main at 3f86f07:
from langchain_core.messages import AIMessage
from deerflow.agents.middlewares.todo_middleware import TodoMiddleware

TodoMiddleware().after_model(
    {"messages": [AIMessage(content="done")], "todos": ["oops"]}, runtime
)
# AttributeError: 'str' object has no attribute 'get'

What changed

  • app/gateway/services.py: new _normalize_external_todos validates the channel at both external boundaries — strip_server_owned_state_metadata (thread-state updates) and normalize_input (run input). The value must be a list of objects whose content is a string and whose status is pending / in_progress / completed (missing status defaults to pending); anything else is HTTP 400 with the offending index, in the same per-entry style already used for messages and goal. None and [] are preserved and an absent channel is untouched.
  • agents/middlewares/todo_middleware.py: both hooks read the channel through _usable_todos, which drops entries that are not mappings. Checkpoints written before this boundary, direct DeerFlowClient state writes, and extension-written state therefore recover instead of failing, while valid entries behave exactly as before.
  • README, backend/AGENTS.md and middlewares AGENTS.md document the boundary and the read-side tolerance.

Surface area

  • Backend API — request validation for POST /threads/{id}/state and run input
  • Agents / LangGraph — todo middleware hooks

Bug fix verification

  • Test paths: backend/tests/test_todo_input_validation.py (24 cases across both boundaries) and backend/tests/test_todo_middleware.py::TestMalformedStoredTodos (6 cases).
  • Red on main (3f86f07), green here: on unmodified main the boundary calls raise nothing (no HTTPException) and the middleware hooks raise AttributeError; with the fix the boundary returns 400 and the hooks ignore the unusable entries.
  • Valid shapes are unchanged: test_external_todos_accept_the_write_todos_shape, test_external_todos_preserve_null_and_empty, plus the entire pre-existing todo suite (test_todo_middleware.py, test_todo_compaction.py).

Validation

  • pytest tests/test_todo_input_validation.py tests/test_todo_middleware.py tests/test_todo_compaction.py — 115 passed
  • pytest tests/test_gateway_services.py tests/test_goal_input_validation.py tests/test_message_provenance.py tests/test_external_system_message_boundary.py tests/test_knowledge_contract.py tests/test_sandbox_reference_ownership.py — 561 passed
  • ruff check and ruff format --check clean on the changed files.
  • tests/test_agent_guidance_check.py cannot run in this sparse worktree (examples/ is not checked out), so I verified the budgets directly with scripts/check_agent_guidance.py: backend/AGENTS.md 25,071/32,768; middlewares AGENTS.md 40,788/49,152; effective chain 86,477/98,304.

…l call

`todos` is a reducer channel that `POST /threads/{id}/state` and run input can
Overwrite directly, but neither boundary validated its shape. The todo
middleware rendered it with `entry.get(...)` in both `before_model` and
`after_model`, so a non-object entry — or a value that is not a list — raised
AttributeError on every model call, permanently for that thread.

Validate caller-written todos beside `goal` in `_normalize_external_todos`: a
list of objects with string content and a known status, or HTTP 400. The
middleware now reads the channel through `_usable_todos` and ignores entries of
any other stored shape, so checkpoints and direct integrations written before
this boundary still run.
@github-actions github-actions Bot added area:agents Agents, subagents, graph wiring, prompts, langgraph.json area:backend Gateway / runtime / core backend under backend/ area:docs Documentation and Markdown only needs-validation Touches front/back contract surface; needs real-path validation risk:high High risk: backend API, agents, sandbox, auth, deps, CI size/M PR changes 100-300 lines labels Nov 2, 2026

@willem-bd willem-bd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The boundary + read-side tolerance approach is the right shape, and the new tests cover the two entry points and the middleware hooks well. One gap remains: todos has a second in-process reader that still assumes every stored entry is a mapping, so a thread carrying exactly the persisted value this PR is about can still abort a step (the default-enabled TokenUsageMiddleware). Also one small doc/test inconsistency around the missing-status default. Details inline.

Comment thread backend/app/gateway/services.py Resolved
gdut4140 and others added 3 commits November 2, 2026 16:08
TokenUsageMiddleware reads the same stored `todos` channel through
`_build_attribution` whenever the last AIMessage calls write_todos, and
`token_usage.enabled` defaults on, so a value the todo middleware now tolerates
still aborted the step here. Route the stored list through `_normalize_todos`
before reading entries.

Document that a caller-written todo without a status is accepted as pending and
cover that shape at both external boundaries.
@WillemJiang WillemJiang added this to the 2.3.0 milestone Nov 3, 2026
@ShenAC-SAC
ShenAC-SAC requested a balanced review from Copilot November 3, 2026 03:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical sanitizer bypass allows caller-supplied server-owned metadata in normalized todo entries to persist in checkpoints, so each entry must be sanitized while preserving None and empty lists.

1 open issue
What changed in this PR

This PR prevents malformed todo state from repeatedly failing DeerFlow model calls by validating incoming todo lists and making middleware readers tolerate unusable stored values.

Changes:

  • Validate todo shapes in Gateway state updates and run input.
  • Normalize stored todos before reminder generation, completion checks, and token-usage attribution.
  • Add regression tests and document the validation and recovery behavior.
File Description
README.md Documents todo validation and stored-state tolerance.
backend/​tests/​test_token_usage_middleware.py Tests attribution with malformed stored todos.
backend/​tests/​test_todo_middleware.py Tests reminder and completion behavior with unusable entries.
backend/​tests/​test_todo_input_validation.py Tests both input boundaries, defaults, and invalid shapes.
backend/​packages/​harness/​deerflow/​agents/​middlewares/​token_usage_middleware.py Normalizes stored todos before attribution.
backend/​packages/​harness/​deerflow/​agents/​middlewares/​todo_middleware.py Filters unusable stored entries in both hooks.
backend/​packages/​harness/​deerflow/​agents/​middlewares/​AGENTS.md Documents tolerant todo readers.
backend/​app/​gateway/​services.py Adds todo validation at external write boundaries.
backend/​AGENTS.md Documents the boundary and condenses existing guidance.

Review effort: Balanced

Comment thread backend/app/gateway/services.py Resolved
The dedicated todos branch in strip_server_owned_state_metadata replaced the
generic list branch, which stripped server-owned metadata from every entry. A
caller could therefore persist additional_kwargs.original_user_content,
untrusted_input, or artifact.knowledge_sources on a todo entry. Re-apply the
per-entry strip after normalization, keeping None and empty lists untouched.
@CLAassistant

CLAassistant commented Nov 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@WillemJiang
WillemJiang merged commit 459fc8c into bytedance:main Nov 4, 2026
17 checks passed
chauvuusvn added a commit to chauvuusvn/deer-flow that referenced this pull request Nov 5, 2026
…al (bytedance#7803 follow-up)

Commit 459fc8c introduced shape validation for caller-written todos in
both strip_server_owned_state_metadata and normalize_input, but only
applied _strip_external_metadata_from_message_like in
strip_server_owned_state_metadata.

External callers submitting POST /runs or POST /threads/{id}/runs with
input.todos or input.goal could supply forged server-owned metadata
(such as untrusted_input: False, original_user_content, or artifact
knowledge_sources) directly into the agent graph.

Apply _strip_external_metadata_from_message_like to both normalized
todos and goal in normalize_input when trusted_internal=False.
WillemJiang added a commit that referenced this pull request Nov 6, 2026
…al (#7803 follow-up) (#7904)

* fix(gateway): strip server-owned metadata from run input todos and goal (#7803 follow-up)

Commit 459fc8c introduced shape validation for caller-written todos in
both strip_server_owned_state_metadata and normalize_input, but only
applied _strip_external_metadata_from_message_like in
strip_server_owned_state_metadata.

External callers submitting POST /runs or POST /threads/{id}/runs with
input.todos or input.goal could supply forged server-owned metadata
(such as untrusted_input: False, original_user_content, or artifact
knowledge_sources) directly into the agent graph.

Apply _strip_external_metadata_from_message_like to both normalized
todos and goal in normalize_input when trusted_internal=False.

* fix(gateway): mirror normalized goal and todos into canonical run record input

* fix(gateway): replace non-dict additional_kwargs and cover edge cases

- Ensure non-dict additional_kwargs in message-like entries is replaced with an empty dict instead of surviving the strip
- Remove redundant None-check on normalized_goal in normalize_input
- Add regression tests covering non-dict additional_kwargs replacement and untrusted_input stamping on human-like entries

* test(gateway): format todo input validation cases

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agents Agents, subagents, graph wiring, prompts, langgraph.json area:backend Gateway / runtime / core backend under backend/ area:docs Documentation and Markdown only needs-validation Touches front/back contract surface; needs real-path validation risk:high High risk: backend API, agents, sandbox, auth, deps, CI size/M PR changes 100-300 lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants