Skip to content

fix(gateway): store events with nul characters instead of looping - #476

Merged
nixuuu merged 1 commit into
devfrom
fix/event-nul-poison
Nov 10, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/event-nul-poison

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 10, 2026

Copy link
Copy Markdown
Member

Change

A worker event containing NUL could roll back an entire transcript batch. The gateway then drained the worker link, and journal replay sent the same event again. This fixes long-standing storage behavior exposed by Windows output.

The supplied logs show 448 PostgreSQL NUL storage failures for the same thread and 448 matching worker drains/reconnects, between 2026-11-09 22:06 UTC and 2026-11-10 08:50 UTC. Consecutive active retries were approximately 11 seconds apart. The logs establish the rejected character and replay cycle; they do not establish which command or source encoding produced it.

  • Normalize U+0000 and lone UTF-16 surrogates to U+FFFD at gateway persistence boundaries, before event projections. This covers raw JSON keys/values, item identifiers, messages, tool input/output, bot projections, command results and generated titles. Valid surrogate pairs and literal backslash-u text stay intact.
  • Isolate PostgreSQL data exceptions (22xxx) after the failed batch rolls back. Migration 0111_worker_event_quarantine stores the original protobuf as bytea; a visible warning and journal cursor commit atomically with it. The warning reuses the original event identity, so replay remains idempotent. Later events continue on the existing link.
  • Keep connection, deadlock and serialization failures on the existing unacked drain/redelivery path. Failure to save quarantine also rolls back the marker, cursor and preceding events in that recovery batch.
  • Existing journals recover automatically after updating the gateway. No journal deletion or worker protocol change is needed. Polish protocol, durability, transcript and data-model documentation explains the replacement and quarantine guarantees, including that quarantined events do not apply their original projections.

Normal event ingestion scans string values and skips numbers/bytes. Clean strings retain their value; ordinary events need no event clone or raw-JSON parse. The work is linear in the event's fields and string length. Only suspicious raw JSON is parsed, and only changed events are cloned. Savepoints and per-event fallback writes are restricted to a failed data batch; the normal batch path adds no SQL round trips.

Worker output decoding remains unchanged. Normal tool output reaches the adapters as text already decoded by the harness. Guessing UTF-16 from embedded NUL would risk altering valid output without access to its original encoding. The gateway remains the persistence guarantee.

Linked-computer inspection found no dependency that turns a local worker disconnect into a computer-link disconnect: peer presence uses its own connections and heartbeats. The logs contain 770 local and 89 linked thread-watch resubscriptions, rather than 770 linked resubscriptions. They begin at 19:30 UTC, before the first NUL failure, so they are not solely a consequence of this loop. Worker hello/heartbeat writes also advance shared metadata revisions and trigger watch refreshes even with stable links. Flapping adds refreshes; avoiding unrelated heartbeat-driven refreshes is a separate follow-up, outside this storage fix. This conclusion comes from logs and code inspection, not a live Windows/macOS reproduction.

Copy audit (§8): no recovery notice → “Some output could not be saved. Later output will still appear.” Two short English sentences explain the loss and automatic continuation; no new glossary terms, buttons, duplicated labels or humor. SQLSTATE stays in structured details and logs, without event payloads or secrets. The existing notice component renders the warning; no frontend layout changed.

Verification

  • bun install, bun run typecheck, bun run lint, bun run format:check, and git diff --check passed.
  • TMPDIR=/var/tmp bun test --rerun-each 5 tests/integration/event-storage.test.ts: 35 passed, no failures. Real PostgreSQL + gRPC + file-backed SQLite journal cover automatic replay, multiple NUL fields, raw JSON keys, lone surrogates, preserved emoji/literal escapes, later output, quarantine (22P02/22021), replay deduplication, transient serialization redelivery, bot projections, titles/results and rollback if quarantine persistence fails.
  • Focused files run separately: database schema/migrations 23 passed; durable threads 6 passed; journal delivery 2 passed.
  • Full suite, generated-code check and web build are left to CI under the requested shared-machine limits. No browser/E2E runs or protected services were used.

Related: #335

Normalize text at persistence boundaries and quarantine PostgreSQL data exceptions atomically with a warning and journal cursor. Keep transient failures unacked for redelivery.

Related: #335
@nixuuu
nixuuu merged commit 48223bd into dev Nov 10, 2026
9 checks passed
@nixuuu
nixuuu deleted the fix/event-nul-poison branch November 10, 2026 09:14
nixuuu added a commit that referenced this pull request Nov 10, 2026
Received agent-bus cards now preserve prose spaces, tabs and line breaks
while rendering Markdown lists and code. Web cards also offer Copy
message (the original Markdown source) and Quote message; mobile uses
the same long-press actions as agent answers, for both turn inputs and
steered messages.

### Cause and scope

The reproduced rendering issue was normal CSS whitespace collapsing
repeated ASCII spaces and tabs. Reports on web and received inputs on
mobile also omitted the Markdown single-line-break option. Preserve
whitespace on prose blocks only, so component layout whitespace does not
introduce gaps around list markers or code panels. Folded one-line
previews retain their existing whitespace normalization. The audited
preview helpers do not feed the full bodies of user, bot or agent
messages, or notice text; ordinary agent prose retains its Markdown
soft-line behavior.

**No tested Canopy transport layer loses whitespace.** The regression
exercises the real Codex app-server JSON-RPC dispatcher (dynamic
`item/tool/call`, native `mcpToolCall` item notifications) and Claude
SDK MCP schema plus `tool_use` mapping. Codex supplies complete argument
objects; Claude supplies complete SDK input. Canopy does not concatenate
partial tool-argument JSON. Claude partial `input_json_delta` envelopes
are covered and do not replace the complete input. Text streams include
whitespace-only deltas and tokens with leading/trailing spaces, such as
`" 4"` and `" views, overflow"`.

The gateway schema does not trim `prompt`; storage, gRPC delivery,
protobuf/JSON serialization, text reducers and client coalescing
preserve the exercised text byte for byte. This includes a real
child-to-parent bus message through both queue and steer delivery. The
#476 sanitizer only replaces NUL and lone surrogates with U+FFFD; it is
unchanged.

The screenshot's missing separators are **not reproduced** by these
paths. Upstream/model-provided text is the likely source if the affected
run used the same paths, but the original payload/transcript is still
needed to establish that. This change does not claim to repair
already-glued stored text. Copy now makes that original source available
for diagnosis.

### Validation

- `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run
lint`, `bun run format:check`, and the web production build.
- Four gateway–worker whitespace cases: Codex/Claude × queued/steered
child messages; PostgreSQL arguments and receiver input, delivery, UI
snapshot, and live coalesced replay. NBSP, narrow NBSP, thin/figure
spaces, ASCII spaces, tabs, LF, CRLF, lists and code are included.
- `TMPDIR=/var/tmp bun run check:tmp --max-concurrency 1`: **2,219
passed, 163 skipped, 0 failed** across 407 files (26,991 assertions);
temp-directory cleanup check passed. Opt-in live-model tests were
skipped.
- Real browser: light/dark, 1280 px desktop and 390 px phone; additional
320 px overflow and quote-dialog check. Expanded/folded cards,
short/long text, lists, code, original-source Copy handler,
whole-message/selection Quote, save/cancel, and focus restoration.
Clipboard reads are denied by the browser harness; the Copy handler's
exact argument was captured instead. Temporary fixture and server
removed; screenshots kept outside the repository.
- `bunx [email protected] fingerprint:generate --platform <ios|android>
--build-profile production --json --non-interactive`: unchanged iOS
`6ddec9ef559ee0095ac33e94ff9418a942053b17` and Android
`5f6eae3ab278f1cd543e9ed763f923a319b65ec9`. Mobile changes are JS only;
no device runtime verification was performed.

Copy audit (§8): bus cards had no actions → **Copy message** and **Quote
message**, both verb-first English labels with accessible names.
Existing mobile menu and quote-comment copy are reused; no new error or
empty-state text. Checked with short and long sender names at desktop
and phone widths. No new terminology or confirmation flow.

Related: #476
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.

1 participant