π€ perf: fix streaming content delay from ORPC schema validation #774
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
After the ORPC migration (commit
3ee72886), streaming message content appeared delayed:messagedelays.mp4
Root Cause: Zod Union Validation Order
ORPC validates every yielded event against
WorkspaceChatMessageSchema. The schema was defined as:The problem:
z.union()tries each schema in order until one passes.For every
stream-deltaevent (20+ per second during streaming):MuxMessageSchemais tried first β fails (wrong shape: hasid/role/parts, stream-delta hastype/messageId/delta)discriminatedUnionis checked β finds matchingtype: "stream-delta"β passesThis failed validation attempt on
MuxMessageSchemaruns for every single streaming event. With rapid deltas, the overhead accumulates and causes visible delay.Why Token Count Updated But Content Didn't
Both depend on the same event flow, but token counts are accumulated totals that remain stable once computed. Message content requires constructing new
DisplayedMessageobjects with accumulated text. The validation overhead delayed the entire pipeline, but cumulative metrics (tokens) appeared more responsive than the content itself.Solution
Reorder the union to put
discriminatedUnionfirst:Since streaming events have a
typefield,discriminatedUnionprovides O(1) lookup - no failed validation attempts.Also consolidated the two separate
discriminatedUnioncalls into one for cleaner code.Changes
src/common/orpc/schemas/stream.ts: Reordered union members, merged discriminated unions, added explanatory commentGenerated with
mux