Skip to content

fix: normalize invalid UTF-8 before protobuf streaming (#402) - #418

Merged
jhrozek merged 4 commits into
mainfrom
invalid-utf8
Aug 9, 2026
Merged

jhrozek merged 4 commits into
mainfrom
invalid-utf8

Conversation

@jhrozek

@jhrozek jhrozek commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Fixes the crash in #402 — a tool result carrying invalid UTF-8 killed the live
Converse stream with codes.Internal: string field contains invalid UTF-8 —
and then closes the same bug class everywhere else it was reachable.

Three commits: the original fix, a panel-review follow-up that found the same
bug on surfaces the first two layers structurally cannot reach, and the last
open acceptance criterion.

The bug

A protobuf string field rejects invalid UTF-8 at marshal time. Tools hand back
arbitrary bytes — BSD cat -t mangles an em dash into an orphaned \xe2 lead
byte — so stream.Send failed and the relay cancelled the run. The durable JSON
log survived because encoding/json already substitutes U+FFFD, which is why
replay looked healthy while the live stream died.

What landed

Two defense layers (840a54f). A semantic repair — session.RepairToolResult
at the loop's effective-payload choke point in engine/agent execute, after
PostToolUse and before recorder/emit/record, so the recorded == streamed ==
model-view invariant holds with the same repaired text — plus a mechanical
backstop in the protobuf mapper for every producer that never crosses execute.
Both layers are load-bearing: clampPreview returns its input unchanged when
nothing was truncated, so a subagent/team preview built from a child's tool
output reaches the mapper still malformed and is repaired only there.

Sibling surfaces (ba18f72). Skill, agent-def, soul and command content is
os.ReadFile→string off the workspace with no JSON decode to launder it,
unlike MCP and provider text. A Latin-1 SOUL.md made GetSoul fail with
codes.Internal exactly as the em dash killed Converse. Repaired at the proto
construction sites in internal/app and internal/adapter/grpcdriver.
AgentDef.Hooks uses validMap because proto3 validates map keys too.
AgentMCPServer.Headers is the one deliberate exemption — secret-shaped, and
repairing a credential corrupts it — pinned byte-exact by a test.

PreToolUse hook output (ba18f72). A hook is an operator-deployed subprocess
whose Message is its raw stdout and whose Mutated is rewritten args JSON —
and json.Valid accepts invalid UTF-8 inside a string literal. A block becomes
a NewToolError at four sites, none of which call execute. Both values are now
repaired once in preHook where they arrive, not at the four consumers.

The command-output cap (023a9e3). cappedBuffer was a producer, not just
a conduit: its cap is a byte cap, so cuts landed mid-rune for two of every three
offsets in 3-byte-rune output, manufacturing invalid UTF-8 from well-formed
command output. Not synthetic — maxCommandOutput is 1 MiB and
1048576 mod 3 == 1. It now cuts on a rune boundary in the truncating branch
only; output that fits still crosses byte-for-byte, because bounding and
sanitizing are different jobs.

The test that was lying

TestToProtoNeverFailsMarshalOnInvalidUTF8 hand-seeds its payloads, so a field
nobody remembers to seed is never exercised — it was green with ToolName
unwrapped at three sites. Its comment, AGENTS.md and IMPLEMENTATION-NOTES all
claimed it "fails if a future payload field is added unrepaired". It does not.

TestToProtoStructuralUTF8Guard now reflects over session.Event, seeds every
bare-string field (named typedefs are the closed kind/stop vocabularies), and
protoreflect-walks the output asserting utf8.ValidString on every populated
string and map key. That inverts the failure mode from "remember to add
coverage" (invisible when forgotten) to "justify an exemption" in
harnessTokenFields (visible in review). It found ParallelPayload.Join on its
first run. Both tests are kept, with their roles now stated.

Two doc comments also asserted false premises and are corrected: ToValidUTF8
claimed byte-for-byte agreement with encoding/json (json substitutes one U+FFFD
per invalid byte, this one per invalid run), and RepairToolResult credited
validateMIME for MIMEType's safety when the real guarantee is the JSON
transport.

Verification

Every repair is mutation-verified: each was blanked and the corresponding test
confirmed to fail with string field contains invalid UTF-8, then restored.

All seven acceptance criteria on #402 are met. task lint 0 issues both modules,
task test 119 packages green, task api:check ok, docs citation lint ok,
task tidy no diff, engine standalone (GOWORK=off) clean, mecademo runs a
full offline session.

Note for reviewers running the suite on macOS: the path-escape and
mecatui/embed tests need a TMPDIR that is both fully resolved and short —
/var and /tmp are symlinks (osfs EvalSymlinks-resolves the workspace root),
and sun_path caps at ~104 bytes. TMPDIR=/private/tmp/mt satisfies both. CI on
Linux hits neither.

Scope beyond the issue

The issue text covers the tool-result path. This branch also fixes the
soul/skills/agent-def snapshots, the grpcdriver server wrappers, the PreToolUse
hook path, and the command-output cap — all the same bug class, none named in
#402.

🤖 Generated with Claude Code

jhrozek and others added 4 commits August 6, 2026 23:53
A tool can hand back arbitrary bytes (Bash stdout, file contents, MCP
text), and providers reject requests containing invalid UTF-8. One
binary-in-output tool result poisoned the session: every subsequent turn
replayed it and the provider 400'd until the session was abandoned.

Add session.RepairUTF8 / RepairUTF8Messages as the single repair
chokepoint (strings.ToValidUTF8 -> U+FFFD, allocation-free on the
already-valid path). Apply it at every tool-result ingress so poisoned
bytes never enter persisted history:
- engine/agent dispatch funnel (recorded history + model view)
- server wire projections (toProto*) as defense-in-depth so a poisoned
  event can never break the SSE/gRPC stream

New exported funcs -> engine/api/session.txt + CHANGELOG (Added/minor).

Co-Authored-By: mecatl <[email protected]>
…review)

Follow-up to 840a54f. A panel review of that fix found the same
stream/RPC-killing bug on surfaces the two original layers structurally
cannot reach, plus three doc comments asserting guarantees the code did
not provide.

Sibling producers (the crash, on other RPCs). Skill/agent/soul/command
content is os.ReadFile->string off the workspace with NO JSON decode to
launder it, unlike MCP and provider text. A Latin-1 SOUL.md made GetSoul
fail with codes.Internal exactly as the em-dash Bash output killed
Converse. Repaired at the proto construction sites in internal/app
(soulSnapshotWith, agentSnapshot, skillSnapshot, UserModelEntry) and
internal/adapter/grpcdriver (skill/soul/command bodies, agent defs).
AgentDef.Hooks uses validMap because proto3 validates map KEYS too;
AgentMCPServer.Headers is the ONE deliberate exemption (secret-shaped --
repairing a credential corrupts it) and is pinned byte-exact.
AgentInfo.Tools is left alone: scopedToolNames intersects with the
catalog, so only harness names survive.

PreToolUse hook output. A hook is an operator-deployed SUBPROCESS whose
Message is its raw stdout and whose Mutated is rewritten args JSON --
and json.Valid ACCEPTS invalid UTF-8 inside a string literal. A block
becomes a NewToolError at four sites, none of which call execute, so
RepairToolResult never saw either value. Both are now repaired ONCE in
preHook where they arrive, not at the four consumers.

Mapper symmetry. ToolCall.Name and three ToolName sites were unwrapped
while the same value was wrapped at toProtoApproval/toProtoHook; also
ScheduleFire.Err (its event twin was repaired), Session.Workspace,
contentToProto.Url, and ParallelPayload.Join -- a model-authored arg
that normalizeJoin passes through unvalidated.

The oracle. TestToProtoNeverFailsMarshalOnInvalidUTF8 hand-seeds its
payloads, so a field nobody remembers to seed is never exercised: it was
GREEN with ToolName unwrapped at three sites. Its comment (and AGENTS.md
and IMPLEMENTATION-NOTES) claimed it "fails if a future payload field is
added unrepaired". It does not. TestToProtoStructuralUTF8Guard now
reflects over session.Event, seeds every bare-string field (named
typedefs are the closed kind/stop vocabularies), and protoreflect-walks
the output asserting utf8.ValidString on every populated string and map
key. That inverts the failure mode from "remember to add coverage"
(invisible when forgotten) to "justify an exemption" in
harnessTokenFields (visible in review). It found Join on its first run.
Both tests are kept, with their roles now stated.

Doc accuracy. ToValidUTF8 claimed to apply "the SAME repair
encoding/json applies ... byte-for-byte": json substitutes one U+FFFD
per invalid BYTE, this one per invalid RUN ("\xe2\x80" -> two vs one).
The conclusion holds post-repair, the stated premise did not.
RepairToolResult claimed MIMEType is safe because "validateMIME already
constrains it upstream": validateMIME's only caller is NewContent, and
the MCP block constructors do not validate it -- the real guarantee is
the JSON transport.

Every repair is mutation-verified: each was blanked and the
corresponding test confirmed to fail with "string field contains invalid
UTF-8", then restored.

Refs #402

Co-Authored-By: Claude Opus 5 <[email protected]>
The last open acceptance criterion: "Output truncated at a multibyte
boundary remains valid UTF-8."

cappedBuffer was a PRODUCER of the #402 bug, not just a conduit for it.
Its cap is a BYTE cap, so the cut landed mid-rune for two of every three
offsets in 3-byte-rune output -- manufacturing invalid UTF-8 out of a
command whose own output was perfectly well-formed. Not synthetic:
maxCommandOutput is 1 MiB and 1048576 mod 3 == 1, so any CJK or emoji
stream long enough to hit the cap really does split there.

The truncating branch now backs the cut up to a rune boundary. The tail
past the cap is discarded anyway, so dropping the partial rune's lead
bytes loses nothing, and it mirrors engine/adapter/fstools truncate,
which already cut this way.

The trim is CAP-ONLY. Output that fits crosses byte-for-byte even when
it is already malformed -- bounding and sanitizing are different jobs,
and the loop's choke point (RepairToolResult) owns the second. That is
why this is a correctness fix rather than a crash fix: the repair would
have rewritten the half-rune to U+FFFD regardless, but the model would
have seen a replacement character the harness itself invented in place
of the command's real last character.

Pinned by internal/adapter/osfs/cappedbuffer_utf8_test.go: every cap
offset across several runes (covering all three alignments, including
the aligned one that must NOT be trimmed), the under-cap byte-exactness
case, and the pre-existing discard-past-cap bound. Mutation-verified --
disabling the boundary walk fails with `cap=1: cap produced invalid
UTF-8 from valid input: "\xe6"`.

Closes #402

Co-Authored-By: Claude Opus 5 <[email protected]>
Caught by TestToProtoStructuralUTF8Guard while rebasing onto main:
TeamPayload.Cause landed from #332 (the failure-cause work) after this
branch was cut, and toProtoTeam copied it to the proto verbatim while
its identical sibling SubagentPayload.Cause was already wrapped.

Cause is the child's failure detail -- composed by subagentErrorBody
from a child's last assistant text and the real error, both
producer-influenced -- so it is squarely in the class that killed the
Converse stream.

This is the guard doing exactly the job it was added for, on a field no
fixture test would have covered: the hand-seeded
TestToProtoNeverFailsMarshalOnInvalidUTF8 stayed green, because nobody
seeds a field they do not know exists yet. The structural guard seeds
every bare-string field by reflection, so a field arriving from ANOTHER
branch is covered the moment the two meet.

Refs #402

Co-Authored-By: Claude Opus 5 <[email protected]>
@jhrozek jhrozek closed this Aug 6, 2026
@jhrozek jhrozek reopened this Aug 6, 2026

@JAORMX JAORMX 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.

Panel review — Approve.

Correctly layered fix. The semantic repair runs at the loop's effective-payload point (engine/agent execute, after PostToolUse, before recorder/emit/record) so recorded == streamed == model-view all carry identical text; a PreToolUse hook's block Message/Mutated is repaired at the one arrival point, closing the four non-execute sites. A mechanical backstop in the protobuf mapper (valid() on every producer-influenced string, skipping harness tokens) plus peer helpers in grpcdriver and internal/app cover the surfaces the loop can't reach (replay, child previews, disk-sourced bodies).

Verified specifically: the domain primitive (session.ToValidUTF8) is stdlib-only so both layers import it without breaking inward-only layering; valid input is a no-op fast path; RepairToolResult copies (immutable value object) leaving binary Data/MIMEType byte-exact; and the structural guard (TestToProtoStructuralUTF8Guard) reflects over session.Event, seeds 77 bare-string fields with invalid UTF-8, and protoreflect-walks the output — it fails closed when a new field skips valid(), inverting the old fixture-based failure mode. FuzzRepairToolResult ran 800k+ execs clean; the e2e gRPC test fails on codes.Internal and asserts U+FFFD repair + terminal result. api gate updated, CHANGELOG classified Added/minor.

Non-blocking notes (acknowledged in the PR, no action needed): PostToolUse EvHook.Text is only mapper-backstopped (durable log per-byte vs wire per-run can diverge in U+FFFD count on a non-model-facing observability event); the structural guard covers only session.Event (non-event mappers are fixture-covered only); MIMEType is a documented residual safe today because MCP/provider text arrives JSON-decoded. Good to merge.

@jhrozek
jhrozek merged commit e196901 into main Aug 9, 2026
1 check passed
@jhrozek
jhrozek deleted the invalid-utf8 branch August 9, 2026 18:37
jhrozek added a commit that referenced this pull request Aug 10, 2026
The prior sandbox couldn't resolve the matlatl Go module (no network
egress); this environment does, so the fix from the handover doc lands
here directly instead of waiting on a separate follow-up. Regenerated
via `task docs:llms` (drift was PR #418 editing
docs/design/IMPLEMENTATION-NOTES.md without a llms.txt regen).
Matches this repo's own convention (see the deleted
HANDOVER-reasoning-item-id-replay.md precedent): the handover doc is
removed once its fix lands in the same effort.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
jhrozek added a commit that referenced this pull request Aug 10, 2026
* docs: handover for stale llms.txt (CI Docs/matlatl failing on main)

The Docs (matlatl) CI check fails on main's own tip, unrelated to any
single PR: PR #418 (invalid-utf8) edited docs/design/IMPLEMENTATION-NOTES.md
across several commits without regenerating llms.txt (the AGENTS.md
"changed any Markdown -> task generate" rule). Diagnosed but not fixed
here: this sandbox has no network egress to resolve the matlatl Go
module, so the actual regen + commit needs a network-connected
environment. See the handover doc for root cause and the exact fix
command.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* docs: regenerate stale llms.txt, drop the handover doc

The prior sandbox couldn't resolve the matlatl Go module (no network
egress); this environment does, so the fix from the handover doc lands
here directly instead of waiting on a separate follow-up. Regenerated
via `task docs:llms` (drift was PR #418 editing
docs/design/IMPLEMENTATION-NOTES.md without a llms.txt regen).
Matches this repo's own convention (see the deleted
HANDOVER-reasoning-item-id-replay.md precedent): the handover doc is
removed once its fix lands in the same effort.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[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.

2 participants