Skip to content

fix(agent-events): bound the per-client SSE backlog - #997

Merged
agegr merged 3 commits into
agegr:mainfrom
HoloNova:pr/sse-backlog
Sep 30, 2026
Merged

agegr merged 3 commits into
agegr:mainfrom
HoloNova:pr/sse-backlog

Conversation

@HoloNova

Copy link
Copy Markdown
Contributor

What

A client that stops reading let its per-client event queue grow without limit:
one 24 MB command with an unread stream buffered 22.7 MB on the server, and a
stalled tab could hold that for as long as it stayed connected.

Cap the queued bytes per client (PI_WEB_SSE_BACKLOG_LIMIT_BYTES, default 4 MB,
minimum 64 KB). Past the cap the stream prefers to stay alive — it drops events
the client can rebuild from session state — and only closes when what is left
cannot be rebuilt, so the client reconnects and re-snapshots instead of the
server holding the memory. Either case is logged once per stream.

Scope

Server-side only: one file (lib/agent-event-stream.ts) plus its test. No
client change, no config change, no new route. A client that keeps reading sees
exactly what it saw before — that is one of the new tests, and the existing
stream suite passes unchanged.

Verified

node --experimental-strip-types --test lib/agent-event-stream.test.mjs app/api/agent/events-route.test.mjs

11 tests pass, including the new backlog cases: an unread, non-rebuildable
backlog terminates the stream; rebuildable deltas are dropped instead of
disconnecting the client; a prompt reader still receives every event.
tsc --noEmit and eslint clean.

Notes

Extracted from #984, which bundled this fix together with a Lite-mode prototype.
That PR is being split into smaller ones — this is the independent, Lite-free
part, on its own branch off current main.

Related: #923 — its second hypothesis (per-client backlog growth).

A client that stops reading let its event queue grow without limit: one 24 MB
command with an unread stream buffered 22.7 MB on the server.

Cap the queued bytes per client (PI_WEB_SSE_BACKLOG_LIMIT_BYTES, default 4 MB).
Past the cap, drop events the client can rebuild from session state, and close
the stream for backlog that cannot be rebuilt so the client reconnects and
re-snapshots instead of holding memory.
agegr and others added 2 commits September 30, 2026 21:22
…or images

- Only `*_delta` message updates and `tool_execution_update` are dropped.
  `*_start` / `*_end` create and finalize blocks in the client's stream
  reducer, and `text_end` carries the authoritative text, so keeping them lets
  a block repair the deltas it lost. Dropping every `message_update` also
  dropped those.
- Default the backlog limit to 16 MB. One image `read` emits its base64
  three times, and on a slow link those queue up while the first is still
  being written, so 4 MB disconnected healthy clients.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@agegr

agegr commented Sep 30, 2026

Copy link
Copy Markdown
Owner

Thanks @HoloNova! The bug is real: enqueue() ignored backpressure, so a client that stopped reading (backgrounded phone tab, stalled link) grew the stream's queue without bound. Measuring with desiredSize against a byte-sized highWaterMark, and erroring the stream so EventSource reconnects and re-snapshots, is a contained, server-only fix.

I pushed two changes:

  • Drop only deltas. The droppable set was every message_update, which includes text_start / text_end, thinking_*, and toolcall_start / toolcall_end. The client's streamReducer creates blocks from *_start and replaces them with the authoritative content on *_end. Dropping those left the streaming bubble missing blocks, or holding gapped text, until message_end. Now only *_delta updates and tool_execution_update (a full partial result that the next one supersedes) are dropped, so a block repairs its lost deltas at its own *_end. There's a new test for this; it fails on the previous version, where text_end is dropped.
  • Default limit 16 MB instead of 4 MB. The queue doesn't count the chunk Next is currently writing to the socket. One image read emits its base64 three times (tool_execution_end, then the result's message_start and message_end), so on a slow link a ~1.5 MB PNG alone leaves ~5 MB queued behind a client that is reading fine, and 4 MB would disconnect it. 16 MB still bounds the 22.7 MB stalled-client case, and PI_WEB_SSE_BACKLOG_LIMIT_BYTES still overrides it.

Also merged main. tsc --noEmit, eslint, and the full unit suite pass (the one failure, worktree.test.mjs force removal, also fails on main in my macOS temp dir). LGTM 👍

Minor: the description says the backpressure log fires once per stream, but lastBackpressureLogAt is module-wide (once a minute across all streams). That's fine as a rate limit, just worth knowing.


Generated by Claude Code

@agegr
agegr merged commit 6b0c6a5 into agegr:main Sep 30, 2026
2 checks passed
Kano-u pushed a commit to Kano-u/pi-web that referenced this pull request Oct 2, 2026
解开 agegr#981 的 DirectoryPicker 冲突后,这一段(390e70f..f52fd84)实测 0 冲突:

- agegr#992 移动端输入框停在键盘上方并给打字更多空间
- agegr#997 限制每客户端 SSE 积压
- agegr#1001 可配置发送键(Enter / Ctrl+Enter)
- agegr#1006 从 pi 的 provider catalog 解析 discovery endpoint
- agegr#1017 空闲关闭被禁用时回收 Stop 无法解除的运行
- agegr#1016 Stop 结束输出被幸存进程持住的命令
- agegr#1015 保留用户消息里输入的换行
- agegr#1019 在 Safari / iOS 16.2 上可加载(新增 browserslist,无新依赖)
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 6, 2026
* fix(agent-events): bound the per-client SSE backlog

A client that stops reading let its event queue grow without limit: one 24 MB
command with an unread stream buffered 22.7 MB on the server.

Cap the queued bytes per client (PI_WEB_SSE_BACKLOG_LIMIT_BYTES, default 4 MB).
Past the cap, drop events the client can rebuild from session state, and close
the stream for backlog that cannot be rebuilt so the client reconnects and
re-snapshots instead of holding memory.

* fix(agent-events): drop only deltas when behind, and size the limit for images

- Only `*_delta` message updates and `tool_execution_update` are dropped.
  `*_start` / `*_end` create and finalize blocks in the client's stream
  reducer, and `text_end` carries the authoritative text, so keeping them lets
  a block repair the deltas it lost. Dropping every `message_update` also
  dropped those.
- Default the backlog limit to 16 MB. One image `read` emits its base64
  three times, and on a slow link those queue up while the first is still
  being written, so 4 MB disconnected healthy clients.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Alex Yang <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
windli2018 pushed a commit to aiti-ai/aiti-ai that referenced this pull request Nov 8, 2026
* fix(agent-events): bound the per-client SSE backlog

A client that stops reading let its event queue grow without limit: one 24 MB
command with an unread stream buffered 22.7 MB on the server.

Cap the queued bytes per client (PI_WEB_SSE_BACKLOG_LIMIT_BYTES, default 4 MB).
Past the cap, drop events the client can rebuild from session state, and close
the stream for backlog that cannot be rebuilt so the client reconnects and
re-snapshots instead of holding memory.

* fix(agent-events): drop only deltas when behind, and size the limit for images

- Only `*_delta` message updates and `tool_execution_update` are dropped.
  `*_start` / `*_end` create and finalize blocks in the client's stream
  reducer, and `text_end` carries the authoritative text, so keeping them lets
  a block repair the deltas it lost. Dropping every `message_update` also
  dropped those.
- Default the backlog limit to 16 MB. One image `read` emits its base64
  three times, and on a slow link those queue up while the first is still
  being written, so 4 MB disconnected healthy clients.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Alex Yang <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
lclichen added a commit to lclichen/pi-web that referenced this pull request Nov 9, 2026
…ze-once fan-out, crash guards, file log, process debug metrics

Batch 1 of the multi-user performance workstream (docs/dev/performance-optimization-2026-11.md):
- lib/sse-backpressure.ts + wiring in agent-event-stream/sse-stream/batch task-event-stream:
  512KB high-water mark with byte-counted queuing strategies, droppable deltas above the
  mark, hard error-close past PI_WEB_SSE_BACKLOG_LIMIT_BYTES (16MB default); slow clients
  reconnect and re-snapshot instead of pinning unbounded memory
- tool_execution_update coalescing (150ms) and per-event serialize-once caches in
  agent-event-wire (projection + JSON shared across a session's listeners)
- instrumentation-node: unhandledRejection/uncaughtException handlers (log + keep serving),
  SDK prewarm import (upstream 6425d0d), server-log tee, event-loop monitor
- lib/server-log.ts: daily rotating file log under <dataDir>/logs with retention/size caps
  and a failure circuit breaker; lib/perf-stats.ts counters for restore/scan + loop delay
- /api/agent/debug + DebugPanel: memory usage, heap limit, event-loop p95, restore/scan stats
- i18n: debug.heap / debug.rss / debug.loopDelay (files also carry pre-existing uncommitted
  sessions.* keys from parallel work — key sets stay consistent per registry test)
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