Skip to content

Framing formats: multiplex data, totals, extremes, progress, logs, and profile events in the HTTP response stream - #110127

Merged
alexey-milovidov merged 99 commits into
masterfrom
framing-formats
Aug 13, 2026
Merged

alexey-milovidov merged 99 commits into
masterfrom
framing-formats

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

A framing format multiplexes different response parts of the query in a single stream: chunks of data, totals and extremes, progress packets, profile events (metrics), and server logs — everything that the native protocol supports. This allows rich data exchange in the HTTP protocol.

Framing formats are independent of output formats: they encapsulate bytes produced by any output format, by separating and potentially encoding these chunks of bytes. The concatenation of the payloads of all data, totals, and extremes packets is exactly what the output format would have produced without framing. Auxiliary packets (progress, logs, profile events, exceptions) are represented as JSON.

The framing format is selected by the new query setting framing_output_format (BETA tier). It currently applies to the HTTP protocol and is ignored for other interfaces. The implemented framing formats:

  • None — transparently routes everything applicable (data, totals, extremes, progress) to the output format, and ignores everything that is not applicable (metrics, logs), so everything works as it is by default.
  • EventStream — frames packets as HTTP server-sent events (text/event-stream). It integrates with the HTTP protocol and throws an exception when not applicable.
  • JSONEachPacketBase64 — every packet is a JSON object on a separate line; the formatted data is base64-encoded (suitable for binary output formats).
  • JSONEachPacketString — every packet is a JSON object on a separate line; the formatted data is put into a string.

Example:

$ curl "http://localhost:8123/?framing_output_format=EventStream" -d "SELECT number FROM numbers(3) FORMAT JSONEachRow"
event: progress
data: {"read_rows":"3","read_bytes":"24","total_rows_to_read":"3","elapsed_ns":"684907"}

event: data
data: {"number":0}
data: {"number":1}
data: {"number":2}

event: profile_events
data: {"host_name":"localhost","current_time":"2026-07-11 22:38:21","thread_id":"0","type":"increment","name":"SelectedRows","value":"3"}
...

Implementation: a framing format works as a multiplexor. The output format writes into the framing format's payload buffer, and IOutputFormat notifies the framing format on packet boundaries (under its writing mutex), which wraps everything accumulated since the previous boundary into a packet of the corresponding kind. Progress is routed through the existing throttled concurrent-progress path. Server logs (with the send_logs_level setting) and profile events reuse InternalTextLogsQueue and ProfileEvents::getProfileEvents — the same mechanisms as the native protocol — newly attached for HTTP queries. Exceptions are always written as the last packet of the stream (regardless of http_write_exception_in_output_format), so the client can always parse the response as a stream of packets. Parallel formatting is not used when framing is enabled, because the framing format needs to know the packet boundaries.

Processing of multiple queries at once is out of scope of the first implementation, but the design allows it: every packet can be extended with the information about the query index along multiple queries.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add framing formats, selected by the new setting framing_output_format: they multiplex different response parts of the query in a single HTTP response stream — chunks of data, totals and extremes, progress packets, profile events, server logs, and exceptions. Implemented framing formats: None (default, everything works as before), EventStream (HTTP server-sent events), JSONEachPacketBase64, and JSONEachPacketString (a JSON object per packet with base64-encoded or string data).

  • Documentation entry for user-facing changes: docs/en/interfaces/framing-formats.md

…, logs, and profile events in the HTTP response stream

A framing format multiplexes different response parts of the query in a single
stream - chunks of data, totals and extremes, progress packets, profile events
(metrics), and server logs - everything that the native protocol supports.
Framing formats are independent of output formats: they encapsulate bytes
produced by any output format. The framing format is selected by the new query
setting `framing_output_format` and currently applies to the HTTP protocol.

Implemented framing formats:
- `None` - transparently routes everything applicable to the output format,
  so everything works as it is by default.
- `EventStream` - frames packets as HTTP server-sent events (`text/event-stream`).
- `JSONEachPacketBase64` - every packet is a JSON object; the formatted data
  is base64-encoded.
- `JSONEachPacketString` - every packet is a JSON object; the formatted data
  is put into a string.

The framing format works as a multiplexor: the output format writes into the
framing format's payload buffer, and `IOutputFormat` notifies it on packet
boundaries, which wraps everything accumulated since the previous boundary
into a packet. The concatenation of the payloads of all `data`, `totals`,
and `extremes` packets is exactly what the output format would have produced
without framing. Auxiliary packets (progress, logs, profile events,
exceptions) are represented as JSON. Server logs and profile events reuse
`InternalTextLogsQueue` and `ProfileEvents::getProfileEvents` - the same
mechanisms as the native protocol - newly attached for HTTP queries.
Exceptions are always written as the last packet of the stream, so the client
can parse the response as a stream of packets.

Processing of multiple queries at once is out of scope of the first
implementation, but the design allows extending every packet with the
information about the query index.

Co-Authored-By: Claude Fable 5 <[email protected]>
@mintlify

mintlify Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 11, 2026, 11:03 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d47153c]

Summary: ✅


AI Review

Summary

This PR adds framed HTTP response formats that multiplex data, totals, extremes, progress, logs, profile events, and exceptions. After checking the current head and prior discussion, I still see one blocker, and it is broader than the single remaining open thread: the raw-bytes gate still misses type-driven Enum labels on several text output paths, so JSONEachPacketString can still emit invalid UTF-8/JSON from bytes that are already fixed by the header type.

Findings

❌ Blockers

  • [src/Formats/EscapingRuleUtils.cpp:178-210; src/Processors/Formats/Impl/SQLInsertRowOutputFormat.cpp:117-134; src/Processors/Formats/Impl/MarkdownRowOutputFormat.cpp:91-98; src/Processors/Formats/Impl/PrettyBlockOutputFormat.cpp:907-916; src/Processors/Formats/Impl/VerticalRowOutputFormat.cpp:224-229] The framing contract is that JSONEachPacketString must reject payloads whose non-UTF-8 bytes are knowable before execution, but the current may_produce_raw_bytes logic still misses type-driven Enum labels across several escaping rules. SerializationEnum writes the label bytes from the type definition verbatim through the plain, Escaped, Quoted, CSV, and JSON serializers (src/DataTypes/Serializations/SerializationEnum.cpp:20-29,67-74,137-145,183-186), and DataTypeEnum::textCanContainOnlyValidUTF8() already exposes whether those labels are valid (src/DataTypes/DataTypeEnum.cpp:135-150). The already-open hole in TSV / CSV / TSKV / CustomSeparated / JSONEachRow / JSONColumns is still present, and the new SQLInsert, Markdown, Pretty*, and Vertical registrations repeat it for the Quoted, Escaped, and plain serializeText value paths. So queries like SELECT CAST(1 AS Enum8('x\\xFFy' = 1)) AS x FORMAT SQLInsert SETTINGS framing_output_format='JSONEachPacketString' or the analogous Markdown / Vertical cases are still accepted and can emit invalid NDJSON even though the bad bytes are fixed by the header type. Suggested fix: add one shared helper that walks wrapped Enum carriers per escaping rule (Quoted, Escaped, CSV, JSON, plain text), wire it into every affected checker, and add focused regressions for at least one format in each rule family.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: close the remaining type-driven Enum raw-bytes gap for JSONEachPacketString across all affected escaping-rule families and add regressions that prove framed output no longer emits invalid UTF-8 for non-UTF-8 Enum labels.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 1029/1070 (96.17%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 11, 2026
alexey-milovidov and others added 5 commits July 12, 2026 00:48
When the last payload line has no trailing `\n` (for example `FORMAT JSON`),
`find_first_symbols<'\n'>` returns `end`, and `pos = line_end + 1` formed a
pointer past the one-past-the-end position - undefined behavior, even though
the loop exited immediately afterwards. Stop when `line_end == end` instead.

Addresses a review comment on #110127

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…treaming

`IFramingFormat` wrote each packet to `out` and called `out.next()`, which only
flushes the outermost buffer. When the HTTP output is wrapped in compression
(`wrapWriteBufferWithCompressionMethod` / a `WriteBufferWithOwnMemoryDecorator`),
`next` leaves the compressed bytes in the nested buffer, so `data`, `progress`,
and `log` packets could sit there until the end of the query instead of being
delivered interactively.

Add a `flushOut` helper that also flushes the nested buffer - mirroring
`IOutputFormat::flushImpl` - and use it at every packet boundary and on finalize.

Addresses a review comment on #110127

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`IOutputFormat` notifies the framing format of a `Totals` / `Extremes` packet
right after `consumeTotals` / `consumeExtremes`. That assumes the bytes are
already in the payload buffer, which holds for row formats but not for
`Template` (`areTotalsAndExtremesUsedInFinalize` is true): it stores totals and
extremes and emits them later from `finalizeImpl`, where the framing format can
no longer tell them apart from the main data and would mislabel them as `data`
packets.

Reject such formats in `setFraming` with a clear exception instead of producing
wrong output.

Addresses a review comment on #110127

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… rejection

The `GROUP BY ... WITH TOTALS` queries in `04512_framing_formats` emitted a
nondeterministic number of `data` packets: a `data` packet follows every output
block boundary, and the number of blocks depends on the number of threads,
two-level aggregation, the output block size, and external sorting - all of
which the CI settings randomizer varies. This made the test fail in the
`arm_asan_ubsan` targeted run and in the `amd_debug` / `amd_asan_ubsan` /
`amd_tsan` / `amd_msan` flaky checks.

Pin the settings that determine the block boundaries for those queries so the
result is a single block. Also add a case asserting that a framing format is
rejected for `Template`, which defers totals and extremes to finalize.

CI report: #110127

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… and HTTP compression

Cover the two remaining test suggestions from the review:
- `EventStream` with a payload whose last line has no trailing newline
  (`FORMAT Values` produces `(0),(1),(2)`), exercising the end-of-buffer fix.
- Framing over an `enable_http_compression` response, so a regression in the
  nested-buffer flush that leaves packets stuck in the compression buffer is
  caught.

Related to #110127

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 2 commits July 12, 2026 06:23
The `EventStream` and `JSONEachPacketString` framing formats embed the raw
output bytes into the response as UTF-8 text: `EventStream` writes them into
`data:` fields of a `text/event-stream` response, and `JSONEachPacketString`
passes them through `writeJSONString`, which does not sanitize invalid UTF-8.

A binary output format such as `Native` or `RowBinary` would therefore produce
invalid SSE / JSON instead of a byte-preserving stream. Reject such
combinations at framing selection time (mirroring the existing rejection of
formats that defer totals and extremes) and point the user to
`JSONEachPacketBase64`, which encodes arbitrary bytes safely.

The output format is classified as text via its content type: text formats
declare a charset (e.g. `text/tab-separated-values; charset=UTF-8`,
`application/json; charset=UTF-8`), while binary formats use types such as
`application/octet-stream` without a charset.

Addresses the AI review blocker on #110127

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The text framing formats (`EventStream`, `JSONEachPacketString`) embed the
output payload as UTF-8 text, so an output format that can emit arbitrary bytes
corrupts the stream. Binary formats (`Native`, `RowBinary`) were already
rejected via their `application/octet-stream` content type, but raw passthrough
formats slipped through: `RawBLOB` writes the column bytes verbatim while
inheriting the default `text/plain; charset=UTF-8` content type, and the
`TSVRaw` / `TabSeparatedRaw` / `LineAsString` / `Raw` family advertise a textual
content type while calling `serializeTextRaw` (no escaping). Both can produce
non-UTF-8 output, reproducing the invalid SSE / JSON stream the earlier review
flagged.

Content type alone is not a reliable signal for text-safety, so make it an
explicit output-format capability: add `may_produce_raw_bytes` to the format
registration (`markOutputFormatMayProduceRawBytes`) and mark the raw formats
with it. `outputFormatProducesText` now rejects any format marked this way in
addition to the content-type check. `JSONEachPacketBase64` is unaffected, since
it encodes arbitrary bytes safely.

Extended `04512_framing_formats` to cover rejecting `RawBLOB` (always raw),
`TSVRaw` and `LineAsString` (text-labeled raw) for text framings, and to confirm
`JSONEachPacketBase64` still carries `RawBLOB` output.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`FramingFormatEventStream::writeDataFields` emitted one SSE `data:` field per
`\n`-terminated line of the payload. The client reconstructs `event.data` by
joining the values of consecutive `data:` fields with `\n` and then stripping a
single trailing `\n` (per the server-sent events specification). For a payload
that ends with `\n` - the common case for line-based formats such as
`JSONEachRow`, `TSV`, or `CSV` - the stripped trailing `\n` was lost, so a
payload like `"row\n"` was reconstructed as `"row"`. That broke the central
framing contract that concatenating the payloads of the `data`, `totals`, and
`extremes` packets reproduces the output of the format without framing.

Emit an extra empty `data:` field when the payload ends with `\n`, so the
trailing newline survives the reconstruction. Payloads without a trailing
newline (for example `FORMAT JSON`) are unchanged.

Extended `04512_framing_formats` with a regression that rebuilds `event.data`
from a newline-terminated `EventStream` payload and compares it byte-for-byte
with the unframed output, and updated the existing `EventStream` reference and
the documentation example to reflect the trailing empty `data:` field.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 3 commits July 12, 2026 22:14
The `EventStream` (and other) framing formats sent fewer server log packets
than the native protocol: `clickhouse-client` receives log entries from the
start (parsing, planning, analysis - `executeQuery`, `Planner`, `SelectExecutor`,
"Reading approx N rows") and the end (`executeQuery: Read N rows`,
`MemoryTracker: Query peak memory usage`) of the query, while the framing
format captured only the logs emitted during pipeline execution.

Two causes:

- The logs and profile-events queues were attached to the thread only after
  the query had been interpreted, so the interpretation-phase logs were lost.
  Attach them before interpretation (in `attachQueuesForFramingIfApplicable`),
  as the native protocol does, and wire them into the framing format once it
  is created.

- The framing format was finalized during pipeline execution, before the
  query-finish logging ran, so the trailing logs were lost. Defer the framing
  finalization (`IOutputFormat::deferFramingFinalize`) until after `onFinish`,
  while the HTTP response stream is still open, and log the peak memory usage
  explicitly before the drain (mirroring `TCPHandler`). The exception path in
  `HTTPHandler` finalizes the deferred framing format explicitly.

With this change the framing format streams the same set of server logs as the
native protocol.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `EventStream` framing format previously rejected output formats that are not
guaranteed to produce valid UTF-8 text (binary formats such as `Native` or
`RowBinary`, and raw passthrough formats such as `RawBLOB` or `TSVRaw`), because
server-sent events is a text protocol. Instead of rejecting them, `EventStream`
now base64-encodes the `data`, `totals`, and `extremes` payloads (each into a
single `data:` field) so that arbitrary bytes survive the text transport, and
signals this by adding a `payload=base64` parameter to the `Content-Type`
(`text/event-stream; charset=UTF-8; payload=base64`). The client base64-decodes
those payloads; their concatenation is byte-for-byte what the output format would
have produced without framing. Text output formats are still embedded as plain
text, and the auxiliary JSON packets (progress, logs, profile events, exception)
are never encoded.

This lets progress, server logs, and profile events be streamed for any output
format over `EventStream`. `JSONEachPacketString` still requires a text output
format (it puts the bytes into a JSON string and cannot encode arbitrary bytes),
and `Template` is still rejected for all framings because it defers totals and
extremes to finalize.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
…and framed exceptions

Address the review findings on the framing formats
(#110127):

- `EventStream` now serializes a multi-row `profile_events` batch as a single
  JSON array in one `data:` field. An SSE client reconstructs `event.data` by
  joining consecutive `data:` fields with a newline, so emitting one field per
  row produced `{...}\n{...}`, which is not valid JSON and did not match the
  documented `profile_events` contract (an array of profile events as JSON).
  This mirrors the `profile_events` array of the `JSONEachPacket` framings.

- Raw-byte detection for text framings is now settings-aware. `CustomSeparated`
  with `format_custom_escaping_rule = 'Raw'` writes the column bytes verbatim
  (like `TSVRaw`), so it may produce non-UTF-8 output even though it advertises
  a textual content type. Since this depends on a setting rather than the format
  name, it cannot be marked statically with `markOutputFormatMayProduceRawBytes`;
  a settings-aware checker (`registerOutputFormatMayProduceRawBytesChecker`) is
  added alongside the static flag. `EventStream` now base64-encodes such output,
  and `JSONEachPacketString` rejects it, pointing to `JSONEachPacketBase64`.

- When the failure is the framing/output-format compatibility check itself
  (for example `JSONEachPacketString` with `FORMAT RowBinary`, or a framing with
  a format that defers totals/extremes such as `Template`), the error is now
  delivered as a framed `exception` packet instead of a plain HTTP error body.
  The exception packet is always JSON regardless of the output format, so the
  exception-recovery path creates the framing with a `for_exception` flag that
  skips the data-payload compatibility check and the deferred-totals check.

- The exception-recovery formatter now wires in the logs and profile-events
  queues attached before the query is interpreted, so `log` / `profile_events`
  packets accumulated during parsing and planning are drained on `finalize`
  instead of being dropped when the query fails before producing output.

- Update the `framing_output_format` setting description: `EventStream` no longer
  requires a text output format, it base64-encodes non-UTF-8 output.

Extend `04512_framing_formats` and `04513_framing_formats_logs_profile_events`
with regressions for each of the above.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Server/HTTPHandler.cpp Resolved
…xception path, document JSONEachPacketString UTF-8 contract

Addresses the AI review of `3a52d17a`.

`HTTPHandler` buffered exception path (`http_wait_end_of_query=1`): on an
exception the buffered output is discarded and the framing format is recreated
from `framing_name` alone, so the `log` and `profile_events` queues that
`executeQuery` attaches before parsing (and wires into the framing) were
dropped - `http_wait_end_of_query=1&framing_output_format=JSONEachPacketString&send_logs_level=trace`
lost the parsing/planning `log` packets that the streaming path and the docs
promise. The queues are now carried into the buffered exception writer: they are
captured by value (the original framing object goes out of scope before the
writer runs) and re-applied to the recreated framing via new `IFramingFormat`
accessors. Added a `wait_end_of_query` regression to
`04513_framing_formats_logs_profile_events`.

`JSONEachPacketString` UTF-8 contract: documented that it puts the payload
bytes into a JSON string without validating or re-encoding them, so text output
formats such as `JSONEachRow`, `TSV` or `CSV` may emit invalid UTF-8 for
`String` / `FixedString` values holding arbitrary bytes (just as ClickHouse's
own `JSONEachRow` does with the default `output_format_json_validate_utf8 = 0`),
in which case the NDJSON stream is not guaranteed to be valid UTF-8; pointed to
`JSONEachPacketBase64` for byte-exact transport.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…et_result_details`

Two review findings on the framed error paths.

1. `HTTPHandler`'s fail-close latch for framed responses (`used_output.framed`) was
   only set from the `set_query_result` callback. On the exception path
   `executeQuery` deliberately swallows a failure of that callback (see the
   `execute_query_calling_empty_set_result_func_on_exception` failpoint), so the
   callback may never run even though the response is then written through a
   framing format. A second failure - while delivering the exception packet or
   while closing the response - would then make `trySendExceptionToClient` miss
   the framed fast path and append the generic `__exception__` block after a
   partial packet stream. `handle_exception_in_output_format` now latches the flag
   itself whenever the output format has a framing.

2. The `JSONObjectEachRow` raw-bytes checker only looked at the header names,
   but the values of the column selected by
   `format_json_object_each_row_column_for_object_name` become the outer JSON
   keys and are written verbatim - `JSONUtils::writeCompactObjectStart` emits the
   title with `writeCString`, without escaping or UTF-8 validation. A value
   containing a quote, a newline or non-UTF-8 bytes therefore makes the output
   non-textual, which is data-dependent and not knowable from the header. The
   checker now fails close whenever such a column is selected, so the text
   framings reject it or switch to a base64 payload.

New test `04843_framed_fail_close_without_result_details` covers (1); `04512`
covers (2) - its previous "object-name column is not checked" case is replaced by
the rejection, a byte-exact base64 round trip of an output whose object name
breaks JSON, and the acceptance of the synthesized `row_N` object names.
…xception

The test now exercises the fail-close contract of a framed exception response
whose `set_result_details` callback never ran for both injectable secondary
failures: a throw while the terminal `exception` packet is delivered
(`framing_exception_packet_throw`, the response is cut before any bytes reach the
client) and a throw while the response is closed (`http_output_finalize_throw`,
the complete packet stream is on the wire). In both cases nothing may follow the
packet stream: no generic `__exception__` block, no second `exception` packet,
and the client observes an aborted connection.

The first section's earlier assertion that `log` packets are already on the wire
was wrong: with a query that fails during analysis, the auxiliary packets of the
recovery stream are still buffered when the injected failure hits, so the client
sees an empty response.
The style check (`ci/jobs/check_style.py`) rejects any changed test whose
file name contains `fail`. Rename
`04843_framed_fail_close_without_result_details` to
`04843_framed_secondary_error_without_result_details`, following the
naming of `04629_framing_exception_secondary_error`. No content change.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110127&sha=7039bf64e7bb2dc268d58df19017e9206072160b&name_0=PR&name_1=Style%20check
#110127

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 5 commits August 11, 2026 21:42
`trySendExceptionToClient` gated its framed fail-close branch on
`Output::isFinalized`, but `finalized` is latched at the very start of
`Output::finalize`, before `pushDelayedResults` moves anything out of the
delayed cascade. Under `http_wait_end_of_query` that push can throw before a
single delayed byte reaches `out_maybe_compressed` (finalizing the cascade,
reopening a temporary file to re-read it), and the response is then still
completely untouched - so cancelling it only turned a reportable error into an
aborted connection. Gate the branch on `response.sent()` and the byte
counters instead: by the time anything irreversible has happened, one of them
fires. Add the `http_push_delayed_results_throw` fail point and
`04848_framed_error_before_delayed_results` pinning the clean error response.

Addresses the review comment on #110210.

Co-Authored-By: Claude Fable 5 <[email protected]>
}
}

bool settingsLiteralsMayProduceRawBytes(const FormatSettings & format_settings, FormatSettings::EscapingRule escaping_rule)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still leaves a type-driven raw-bytes carrier uncovered: Enum labels. SerializationEnum::serializeText, serializeTextEscaped, serializeTextCSV, and serializeTextJSON write the label bytes from the type definition directly, so a query like SELECT CAST(1 AS Enum8('x\xFFy' = 1)) FORMAT TSV SETTINGS framing_output_format='JSONEachPacketString' (and the analogous JSONEachRow / JSONColumns cases) is still accepted and produces invalid NDJSON. This is different from the earlier dismissed arbitrary-String case: the possible bad bytes are fixed by the header type, and DataTypeEnum::textCanContainOnlyValidUTF8 already exposes that.

We need a companion helper for type-driven text carriers, at least for wrapped Enum types, and the relevant may_produce_raw_bytes checkers should include it.

…` packet

`IFramingFormat::finalize` flushed any buffered payload as
`FramedPacketKind::Data`, but the exception path can reach it after
`consumeTotals`/`consumeExtremes` (via `work` or `setTotals`/`setExtremes`)
buffered some bytes and then threw before the `totals`/`extremes` packet
boundary was taken. The concatenation of the `data` payloads is documented to
be exactly the format's main output, so a client concatenating them saw bytes
that never belonged to the main result set.

`IOutputFormat` now tells the framing what portion the format is about to
write (`beginPayload`), the boundary resets it back to `Data`, and the
exception path of `finalize` discards a pending `totals`/`extremes` fragment
instead of mislabeling it - a partial row is not usable under its own packet
kind either, and the stream is terminal (the `exception` packet follows).

Regression: `04870_framed_totals_extremes_error_discards_fragment` injects a
throw between the serialization and the boundary (new fail points
`framing_throw_before_totals_boundary`/`framing_throw_before_extremes_boundary`)
and asserts the fragment appears neither as a stray `data` packet nor under its
own kind, while the terminal `exception` packet is still delivered; a
fault-free section pins that the same bytes do arrive as `totals`/`extremes`
packets normally.
`JSONUtils::makeNamesValidJSONStrings` and the BSON name sanitizer relied on
the destructor of a scoped `WriteBufferValidUTF8` for the final flush into the
destination string. That destructor catches and suppresses a failure of the
flush, so the string stayed empty and the `substr` that strips the surrounding
quotes threw `std::out_of_range` - reported as `Logical error: 'std::exception.
Code: 1001, type: std::out_of_range` and an abort under a sanitizer build -
instead of the real error.

BuzzHouse hit exactly this on the framing branch by enabling the
`write_buffer_valid_utf8_finalize_throw` fail point at random (it picks from
`system.fail_points`): the injected fault was swallowed by the destructor and
resurfaced as the out-of-range exception in `JSONCompactRowOutputFormat`'s
constructor. Flush explicitly so a failure propagates as itself.

Regression: `04871_valid_utf8_names_finalize_error_propagates` arms the fail
point and asserts the injected fault is reported verbatim for `JSONCompact`
and `BSONEachRow` over HTTP, with no `out_of_range` degradation.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110210&sha=935a03ceb07790d1210f131ad6a1253950d02dd8&name_0=PR&name_1=BuzzHouse%20(amd_tsan)
Related: #110210
/// arbitrary bytes, so a column name is not guaranteed to be valid UTF-8 either. Both are knowable
/// before any row is written (from the settings and the header), so they are detected here and the
/// text framings reject or base64-encode the output accordingly.
factory.registerOutputFormatMayProduceRawBytesChecker("SQLInsert", [](const FormatSettings & settings, const Block & header)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This checker still only looks at the table/header bytes, but SQLInsert also serializes every row value through serializeTextQuoted (writeField -> SerializationEnum::serializeTextQuoted). For Enum columns that path writes the label bytes from the type definition verbatim, and writeQuotedString does not validate UTF-8, so a query like SELECT CAST(1 AS Enum8('x\\xFFy' = 1)) AS x FORMAT SQLInsert SETTINGS framing_output_format='JSONEachPacketString' is still accepted and emits invalid NDJSON even though the bad bytes are fixed by the header type and DataTypeEnum::textCanContainOnlyValidUTF8() already exposes that.

This wants the same type-driven raw-bytes helper as the already-open Enum issue, but for the Quoted path too. The same omission still exists in the new Markdown / Pretty* / Vertical registrations for their Escaped / None value paths.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed almost all the code.

The changes to detect if the format could produce invalid UTF-8 are excessive. We used to allow transparent encoding of binary data in JSON, leaving it the user's responsibility. But I don't mind these changes, so it is okay to have.

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 13, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

It's funny that with a framing format, we can even put our native TCP stream into HTTP. It does not make sense, though.

Merged via the queue into master with commit 3255cf7 Aug 13, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the framing-formats branch August 13, 2026 23:09
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 2026
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks

This branch was successfully deployed

1 active deployment
staging - docs — d47153ce Deployed Aug 12, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants