Skip to content

fix: reject incomplete and malformed Messages streams - #345

Merged
franciscojavierarceo merged 3 commits into
mainfrom
codex/messages-stream-validation
Sep 29, 2026
Merged

franciscojavierarceo merged 3 commits into
mainfrom
codex/messages-stream-validation

Conversation

@franciscojavierarceo

@franciscojavierarceo franciscojavierarceo commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Reject incomplete or malformed upstream Messages streams before built-in tool dispatch or successful completion. Every round now requires message_stop and a content_block_stop for every started block, including hidden built-in tool blocks; EOF or [DONE] without it produces an Anthropic SSE api_error instead of synthetic completion. Invalid JSON in an SSE data payload also terminates the loop with a fixed error that does not echo upstream content. Previously, malformed events were silently ignored and could be followed by tool execution.

Block events require unsigned integer indexes. Index reuse, duplicate completion, and deltas or stops outside an open block fail before tool dispatch or completion.

Duplicate message starts within one upstream round fail before usage updates or dispatch. Valid starts in later tool rounds remain supported.

Message-start IDs and tool-use IDs/names must be non-empty strings; malformed identifiers fail before dispatch or completion.

Part of #313 and Enterprise Readiness #316. The existing accumulator remains the single ingestion path. Move unchanged content-block reconstruction into a private module and remove the now-unneeded file-size baseline exception. Well-formed unknown events, SSE comments, upstream error forwarding, named-tool compatibility, and valid completion before HTTP EOF retain their behavior. Pass-through requests are unchanged.

Remaining event-schema/message-level lifecycle validation, aggregate retained-data budgets, and bounded tool scheduling remain open. The branch includes main's terminal hidden-call fix (#346).

Test Plan

  • Regression tests failed before each fix: premature EOF reported success, and malformed JSON or an unclosed block still dispatched a search.
  • Core library: 753 passed, 5 ignored. Messages stream integration: 15 passed, covering ten incomplete-stream scenarios, malformed data before a tool dispatch and after a completed tool round, no upstream-data echo, well-formed unknown events, and individually omitted block-closing events in both recorded rounds. Tests count actual search and inference requests. An additional 18-case matrix rejects missing/invalid indexes, index reuse, duplicate starts/stops, and deltas or stops outside an open block.
  • Identifier regression coverage includes 12 cases for missing, null, numeric, and empty message IDs, tool IDs, and tool names. The missing-message-ID case reproduced tool execution before the fix.
  • Duplicate-start regression covers early and pre-terminal duplicates in both recorded rounds; the early duplicate reproduced tool execution before the fix.
  • HTTP Messages completion: 12 passed, including immediate malformed-data rejection, fragmented UTF-8, and completion without HTTP EOF. HTTP tool choice: 13 passed.
  • Workspace all-target clippy with warnings denied, all-files pre-commit hooks, formatting, and diff checks passed.
  • Validation uses deterministic local servers and existing cassette replay, not live inference. Linux builds used an existing local static OpenSSL installation. GitHub CI reruns for the updated head.

@franciscojavierarceo franciscojavierarceo changed the title fix: reject incomplete Messages tool-loop streams fix: reject incomplete and malformed Messages streams Sep 21, 2026
@franciscojavierarceo
franciscojavierarceo force-pushed the codex/messages-stream-validation branch from 3acc3c4 to 0d6220a Compare September 23, 2026 01:47

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot review overview

🟢 Approval recommended

The implementation is localized, consistent with the documented scope, and thoroughly covered by targeted regressions.

Review effort: Balanced
Findings: None

What changed in this PR

Strengthens Messages SSE ingestion so malformed or incomplete upstream rounds cannot trigger tools or report success.

Changes:

  • Validates round completion, block lifecycle, indexes, identifiers, and JSON.
  • Adds comprehensive streaming and HTTP regression tests.
  • Extracts block reconstruction and removes the obsolete file-size exception.
File Description
.rust-file-sizes.json Removes the resolved size exception.
docs/​design/​claude-code-integration.md Documents stream validation behavior.
crates/​agentic-server/​tests/​messages_stop_test.rs Tests HTTP completion and malformed payload handling.
crates/​agentic-server-core/​tests/​messages_stream_test.rs Adds lifecycle and dispatch-prevention coverage.
crates/​agentic-server-core/​src/​executor/​messages_stream/​block.rs Encapsulates buffered block reconstruction.
crates/​agentic-server-core/​src/​executor/​messages_stream.rs Implements strict per-round stream validation.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@franciscojavierarceo
franciscojavierarceo marked this pull request as ready for review September 23, 2026 13:04
@franciscojavierarceo
franciscojavierarceo merged commit 1fc1696 into main Sep 29, 2026
14 of 15 checks passed
haoshan98 pushed a commit that referenced this pull request Sep 29, 2026
## Summary

Remove the unnecessary semicolon after the Messages block-index
validation branch. The final resolution of #345 introduced it, causing
the Rust job to fail at Clippy on both the PR and `main` (5ce142f).

Follow-up to #345, part of #313. No runtime behavior changes.

## Test Plan

- `cargo clippy --all-targets -- -D warnings`.
- `pre-commit run --all-files`, including formatting and Rust file-size
checks.
- Inspected the one-character diff; no additional behavioral test is
needed for this lint-only correction.

Signed-off-by: Francisco Javier Arceo <[email protected]>
franciscojavierarceo added a commit that referenced this pull request Sep 30, 2026
## Summary

An upstream Messages round without `message_start` can currently
dispatch a built-in tool or report completion. Require a start in each
round before accepting content-block events or terminal message events.
Invalid order produces a fixed `api_error` before dispatch or
completion; upstream errors and harmless unknown events retain their
handling.

Follow-up to #345, part of #313 and #316. Move the accumulator's
existing ingestion methods into a private module to keep the single
parsing/validation path within the file-size limit, and remove the old
exception. Four existing unit fixtures now include their required round
starts. Broader schema validation and resource budgets remain open;
search-budget accounting is separate work in #391.

## Test Plan

- New regression failed on current main: omitting a round's start still
dispatched search. It removes the start from both recorded rounds and
separately checks content deltas/stops and message deltas/stops before a
start.
- Core library: 914 passed, 5 ignored. Messages streaming integration:
16 passed. HTTP Messages completion/tool choice: 25 passed (955 total).
- Workspace all-target Clippy with warnings denied and all-files
pre-commit checks passed, including formatting and file sizes.
- Compared extracted ingestion methods with the original: unchanged
except for the ordering guard and private module visibility.
Deterministic local fixtures; no live inference.

Signed-off-by: Francisco Javier Arceo <[email protected]>
haoshan98 added a commit that referenced this pull request Sep 30, 2026
## Summary

Several user-facing docs had fallen behind `main` or contradicted each
other and the code. This PR brings them in line with what has shipped.
It changes documentation only.


**Corrected claims**
- README listed the Messages API as "🚧 Planned" while another README
section documents `/v1/messages`. It is now listed as shipped; only
stateful Messages stays planned.
- README and `docs/index.md` advertised "Background execution" and
gateway-executed file search. Neither exists yet: background mode is
#357, and `file_search` declarations parse but are dropped before
inference (`tool/normalize.rs`). Both claims are removed.
- `docs/api/index.md` quoted fixed WebSocket and executor limits (256
KiB SSE lines, 1 MiB events and response budget). These now come from
the configurable `[responses]` settings, which default to 16 MiB and 8
MiB.
- `docs/api/index.md` listed only some of the conditions that route a
Responses request through the executor. The list now also includes
non-function tools, `multi_agent.enabled`, and tool-search state,
matching `handler/http/responses.rs`.
- CHANGELOG listed Tavily under 0.8.0, but it merged on Sep 28, after
the Sep 19 release. The two Tavily entries move to `[Unreleased]`.

**Newly documented features**
- README: a multi-agent Responses section with an example and the
gateway's limits (`store: true`, HTTP/SSE only, default of 3 concurrent
subagents, no `max_tool_calls` or reasoning summaries). Also new rows in
the API table for `/v1/responses/compact`, the full Conversations
routes, `/v1/messages` with `/v1/messages/count_tokens`, and
Swagger/OpenAPI (`ENABLE_OPENAPI_DOCS`). The features list, diagram, and
tool ownership table now include MCP, the code interpreter, Claude Code,
compaction, and OpenTelemetry.
- `docs/api/index.md`: new sections for `GET
/v1/responses/{response_id}`, multi-agent, Conversations, and Messages.
- CHANGELOG `[Unreleased]` was empty. It now has entries for #345, #347,
#349, #351/#370, #354, #368, #369, #372/#373, #380, and #387.

**Roadmap**
- ROADMAP.md marks multi-agent HTTP execution as shipped, with WebSocket
injection (#300) and stateless requests (#393) still open. It adds a
status note for Messages, a code interpreter entry, and a file search
item linking #34 and #356.
- README "Roadmap at a Glance" checks off Messages and Conversations and
adds unchecked items for multi-agent, file search, and stateful
Messages.

**Smaller fixes**
- The repository layout in README and AGENTS.md now lists
`agentic-llm-d`, `agentic-cli-docs`, and `python/agentic_api/`.
- ARCHITECTURE.md's list of multi-agent rejections now includes
`max_tool_calls`, matching `executor/rehydrate.rs`.
- `mkdocs.yaml` adds the existing but unlinked `design/shell-tool.md` to
the nav.

**Not changed:** the README's "Rust 1.85+" badge is wrong (1.85 cannot
build the lockfile, see #377), but #379 already updates it to 1.88 along
with `rust-version` and a CI check, so this PR leaves it alone to avoid
a conflict.

Signed-off-by: haoshan98 <[email protected]>
franciscojavierarceo pushed a commit that referenced this pull request Nov 22, 2026
## Summary

Part of #313. On a premature HTTP EOF (no `message_stop`), the Messages
stream already sends the client an `event: error` frame and no
successful terminal (`finish()` refuses to synthesize one). However,
`messages_stream_body` unconditionally called
`execution.completed_with_stop_reason(...)`, so the `agentic.execute`
span was recorded as `completed` with `Status::Unset` — telemetry
reported a successful turn the client never saw.

This adds `record_terminal_outcome`, which derives the span outcome from
the same `has_completed_round()` gate `finish()` uses to emit the error:

- completed round → keeps its stop-reason outcome (`completed` /
`incomplete`);
- no completed round (clean EOF) → `failed` with
`FailureCategory::Stream` (`error.type=stream`, `Status::Error`), with
delivery still `delivered` since the error frame reached the client.

This does not change client-visible frames or tool dispatch. The
intentional `max_tokens` mid-call tolerance from #345 is untouched.

## Test Plan

- `cargo fmt -- --check` — passed.
- `cargo clippy --workspace --all-targets -- -D warnings` — passed, 0
warnings.
- `cargo test -p agentic-server-core --test execution_trace_test
messages_stream` — 5 passed, including new
`messages_stream_clean_eof_without_message_stop_is_failed` asserting the
error frame plus a failed/error-status span with `error.type=stream`.
- `cargo test -p agentic-server-core --test messages_stream_test` — 29
passed (existing EOF/incomplete-stream cases unchanged).
- `cargo test --workspace --no-fail-fast` — all targets pass except two
pre-existing environment-dependent tests
(`messages_returns_anthropic_error_for_unreachable_upstream` and
`messages_gateway_loop_returns_anthropic_error_for_unreachable_upstream`,
expected 502 / got 504 on this host; reproduced on pristine
`origin/main`, unrelated to this change).

---------

Signed-off-by: Jack Wei <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants