clickhouse-js icon indicating copy to clipboard operation
clickhouse-js copied to clipboard

Fix streaming: make mid-stream exception detection sound (no false positives, no event-loop hang)

Open polyglotAI-bot opened this issue 4 months ago • 1 comments

Description

Fixes https://github.com/ClickHouse/clickhouse-js/issues/974.

ClickHouse 25.11+ appends an in-band __exception__ trailer to a 200 response when a query errors after streaming has begun, and echoes a random per-response token in the x-clickhouse-exception-tag header. That header is a leading header sent on successful responses too, so the detector in ResultSet.stream() is armed on every streaming query. The detector then treated any \r\n in the body as an exception trailer — extractErrorAtTheEndOfChunk only uses EXCEPTION_MARKER.length and never compares the marker bytes — so a stray 0d 0a aborted a successful query with a bogus error. Separately, its trailer-length backward scan (do { --i } while (chunk[i] !== NEWLINE)) had no floor, so a trailer with no interior newline ran the index negative forever, blocking the Node.js event loop (a busy loop, so the surrounding try/catch could not rescue it).

Verified against a real ClickHouse 26.5.1.882 server: the real trailer ends the body with the exact bytes <tag>\r\n__exception__\r\n.

Changes

  • packages/client-common/src/utils/stream.ts
    • Add endsWithExceptionMarker(chunk, exceptionTag) — a sound discriminator that returns true only when the chunk ends with the exact <tag>\r\n__exception__\r\n bytes. Requiring both the fixed __exception__ marker and the random per-response tag makes a stray \r\n in a successful body (binary Parquet, CRLF-terminated CSV/TSV) no longer a false positive. Guards the empty-tag precondition and does a byte-exact, allocation-free comparison.
    • Floor the backward scan in extractErrorAtTheEndOfChunk so a malformed / proxy-truncated trailer returns an error instead of spinning forever.
  • packages/client-node/src/result_set.ts and packages/client-web/src/result_set.ts — gate the exception path on endsWithExceptionMarker(...) (the existing \r-before-\n check is kept as a cheap pre-filter). The two ResultSet implementations are intentionally duplicated, so the change is applied identically to both.
  • packages/client-common/src/index.ts — export the new helper.
  • CHANGELOGs for @clickhouse/client and @clickhouse/client-web (shared common-module change affects both).

The cross-chunk trailer-split robustness (a trailer split across two chunks) is a larger change and is intentionally out of scope here; it is noted in the issue for separate tracking.

Test

  • packages/client-common/__tests__/unit/stream_utils.test.ts — parametrized unit tests for endsWithExceptionMarker (real trailer → true; CRLF CSV/TSV, embedded-\r\n binary, too-short chunk, exact-length-minus-one boundary, wrong tag, empty tag → false), plus a regression that extractErrorAtTheEndOfChunk returns an error instead of hanging on a trailer with no length delimiter.
  • packages/client-node/__tests__/unit/node_exception_tag.test.ts and packages/client-web/__tests__/unit/web_exception_tag.test.ts — live-path regressions through the real ResultSet.stream() transform: a successful CRLF CSV stream completes, a binary body containing \r\n completes, and a genuine mid-stream exception still surfaces the real server message (no-regression guard).

The Node and common suites are green (test:node:unit), plus typecheck and lint --max-warnings=0. The Node live-path tests fail on unpatched main for the right reason (the detector aborts the CRLF/binary stream); they pass with the fix. The Web live path was verified equivalently in Node against the built @clickhouse/client-web (the Web browser test runner needs a browser image not available in the dev sandbox).

Pre-PR validation gate

  • [x] Deterministic repro confirmed (real 26.5.1.882 server + unit repro)
  • [x] Root cause documented above
  • [x] Fix targets the root cause (sound marker match + bounded scan)
  • [x] Tests fail without fix, pass with fix
  • [x] No existing tests weakened or edited (new tests only)
  • [x] Convention compliance verified per packages/AGENTS.md (CHANGELOG in both affected packages, prettier, lint)
  • [x] Fix on the live runtime path (proven via ResultSet.stream() end-to-end tests)

polyglotAI-bot avatar Jul 30 '26 09:07 polyglotAI-bot

Codecov Report

:x: Patch coverage is 95.86207% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
packages/client-node/src/result_set.ts 92.68% 2 Missing and 1 partial :warning:
packages/client-web/src/result_set.ts 95.16% 2 Missing and 1 partial :warning:

:loudspeaker: Thoughts on this report? Let us know!

codecov[bot] avatar Jul 30 '26 09:07 codecov[bot]

@peter-leonov-ch Thanks, you are right. The detector looked only at the current chunk. ClickHouse writes the exception block (up to 16 KiB) at the end of the response, but the client can receive it split across chunks.

I reproduced this against a live 26.9 server (2 KiB to 15 KiB messages, no compression). In 2 of 16 runs the block was split. The previous head then emitted \r, __exception__\r, and <tag>\r as rows, followed by a wrong error message.

Pushed aa33dcf (Node and Web):

  • Detection now uses the block opening \r\n__exception__\r\n<tag>, also when the opening is split across chunks. If a chunk ends before it is possible to decide, the bytes from the start of that row are kept and scanned again with the next chunk. This applies only after a \r\n, so JSON formats are not delayed.
  • From the opening on, the block is buffered until its closing <tag>\r\n__exception__\r\n arrives (capped at the server's 16 KiB), then parsed. Block bytes are never emitted as rows.
  • At the end of the response, an incomplete block is an error.
  • New tests split the response at every byte, and deliver it one byte at a time, for LF and CRLF rows. They also cover a 16 KiB block in 4 KiB chunks and successful CRLF/binary bodies. These tests fail on the previous head and pass now.
  • Against the live server: 48 of 48 runs now give the real error and 0 block rows.

I also moved the CHANGELOG entry to a new # 1.24.1 heading, because 1.24.0 is released.

polyglotAI-bot avatar Oct 05 '26 18:10 polyglotAI-bot