Ray's Knowledge Base
Unlock

serde's Cow<str> always copies, and an internally tagged enum buffers every event

PitfallVerified 17 Oct 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

A dhat test of one streamed text delta shows several blocks per delta (here 4 or 5) even after the parser writes into a caller-owned buffer. Most of them are serde's: a String per Cow<str> field and a Vec per internally tagged event.

Cause#

serde's generic impl Deserialize for Cow<'a, T> deserializes T::Owned and wraps it in Cow::Owned (serde 1.0.229 src/de/impls.rs), so Cow<'a, str> copies every string even when serde_json could lend it. An internally tagged enum (#[serde(tag = "type")]) deserializes the whole event into a buffered Content map first and reads the fields back out, which allocates a map per event and a nested map per object field.

Fix#

Use a small type that borrows on visit_borrowed_str and owns on visit_str instead of Cow (a Deserialize impl over an enum { Borrowed(&'a str), Owned(String) }). Replace each #[serde(tag = "...")] enum with one flat struct that carries all the fields as Option, and match on the type string. Keep &'a str for enum-like fields such as a tag or a stop reason, where an escape is impossible. A #[serde(default)] on a Vec field allocates nothing when the key is absent, but a one-element Vec array still allocates capacity 4: hold the first element inline in a custom Seq type when the common case is one element.

Evidence#

reagent-ai (2026-10-17): crates/ai/tests/allocs.rs with dhat, a 1000-delta text stream per provider through the splitter and parser. Before: anthropic 5.000, openai-responses 4.000, openai-chat 5.000 blocks per delta. With Cow replaced by a custom borrowed-or-owned string (visit_borrowed_str borrows, visit_str owns) and each event flattened to a struct dispatched on the type string: 1.001 blocks per delta for all three. The cargo bench -p reagent-ai --features testing --bench providers parse benches are 2.13 ms / 1.55 ms / 1.89 ms per 10k deltas (anthropic, responses, chat).

Later case: Option<Cow> is also never borrowed by serde derive: a dhat test still showed one block per loop until the field used the same borrowed-or-owned newtype instead of Option<Cow>. After the newtype, an ordinary read or edit call allocated zero extra blocks.

Later case: Replacing the tagged enum with one flat struct cut the TUI line decode from 1 heap block to 0. The TUI binary on Linux got 65 KB smaller, from 8,074,632 to 8,009,256 bytes.