Repository navigation
fix(todos): keep an unusable stored todo list from failing every model call - #7803
Conversation
…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.
willem-bd
left a comment
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
🟡 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
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.
…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.
…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>

Why
POST /api/threads/{id}/stateturned out to validate caller-writtengoal(_normalize_external_goal) but pass any shape through fortodos— another reducer channel a client canOverwritedirectly, because the body isvalues: dict[str, Any].TodoMiddlewarereadsstate["todos"]in bothbefore_model(context-loss reminder) andafter_model(premature-exit guard) and callsentry.get(...)on every entry. One non-object entry, or a value that is not a list at all, therefore raisesAttributeErroron every model call for that thread. The failure happens before the model is invoked, so the UI cannot repair the thread either. Reproduced onmainat 3f86f07:What changed
app/gateway/services.py: new_normalize_external_todosvalidates the channel at both external boundaries —strip_server_owned_state_metadata(thread-state updates) andnormalize_input(run input). The value must be a list of objects whosecontentis a string and whosestatusispending/in_progress/completed(missing status defaults topending); anything else is HTTP 400 with the offending index, in the same per-entry style already used formessagesandgoal.Noneand[]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, directDeerFlowClientstate writes, and extension-written state therefore recover instead of failing, while valid entries behave exactly as before.backend/AGENTS.mdand middlewaresAGENTS.mddocument the boundary and the read-side tolerance.Surface area
POST /threads/{id}/stateand run inputBug fix verification
backend/tests/test_todo_input_validation.py(24 cases across both boundaries) andbackend/tests/test_todo_middleware.py::TestMalformedStoredTodos(6 cases).main(3f86f07), green here: on unmodifiedmainthe boundary calls raise nothing (noHTTPException) and the middleware hooks raiseAttributeError; with the fix the boundary returns 400 and the hooks ignore the unusable entries.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 passedpytest 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 passedruff checkandruff format --checkclean on the changed files.tests/test_agent_guidance_check.pycannot run in this sparse worktree (examples/is not checked out), so I verified the budgets directly withscripts/check_agent_guidance.py:backend/AGENTS.md25,071/32,768; middlewaresAGENTS.md40,788/49,152; effective chain 86,477/98,304.