Skip to content

fix(client-v2): throw on in-band server exception row in JSONEachRowFormatReader - #3313

Open
pcbeingused333 wants to merge 5 commits into
ClickHouse:mainfrom
pcbeingused333:c1800-jsoneachrow-inband-exception
Open

pcbeingused333 wants to merge 5 commits into
ClickHouse:mainfrom
pcbeingused333:c1800-jsoneachrow-inband-exception

Conversation

@pcbeingused333

@pcbeingused333 pcbeingused333 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3220

Cause: with http_write_exception_in_output_format (default on, 25.8), a query that fails after the response started makes the server append {"exception": "Code: ..."} as one more JSONEachRow row and end the body normally. JSONEachRowFormatReader handed it out as an ordinary data row, so the failure was silent (truncated result plus an all-null row).

Fix: when the prefetched row has exactly one key, exception, with a string value starting with Code: , it is turned into a ServerException (code parsed from Code: N., as the issue's expected behaviour asks) through the existing deferred-error path (the valid preceding rows are still returned, the error surfaces on the next next()). Rows with other columns are untouched, and so is a query whose whole result is a single exception column (detected from the schema inferred from the first row), even when its values start with Code: . A query that selects exception next to other columns (e.g. SELECT query_id, exception FROM system.query_log) is still protected, since JSONEachRow writes every column in every row and a one-key row cannot be data there.

Compatibility: previously such a row was returned as data; it now throws from next(). Queries whose only column is exception are unaffected. jdbc-v2 (StatementImpl) uses the same reader, so it gets the same behaviour. Added history/latest/3220.md and a line in docs/features.md.

Tests: JSONEachRowFormatReaderTest adds a case for the in-band error row (fails before, passes after), a case with a multi-column schema that includes exception, and ones confirming that queries with only an exception column (including values like Code: 60. DB::Exception...) are not treated as errors.

This change was prepared with the assistance of an AI tool (Claude) and reviewed before submission.


Note

Low Risk
Behavior change is opt-in and scoped to JSONEachRow reading; default callers (including jdbc-v2’s one-arg constructor) are unchanged.

Overview
Adds opt-in handling (new JSONEachRowFormatReader(parser, true), default unchanged) for ClickHouse’s streamed JSONEachRow failure row {"exception": "Code: ..."} when http_write_exception_in_output_format appends it after normal data rows.

When enabled, matching rows are not returned as data: next() throws ServerException with the parsed code via new ClientUtils.parseServerErrorCode / hasServerErrorCode, while rows already read are still delivered. Detection is skipped if the inferred schema is only a String column named exception, so legitimate single-column exception queries stay data.

Unit, integration (JSONEachRowServerExceptionIT), and documentation/changelog entries cover the behavior.

Reviewed by Cursor Bugbot for commit e7dc0e6. Bugbot is set up for automated code reviews on this repo. Configure here.

…ormatReader

With http_write_exception_in_output_format a query that fails after the
response started ends with an extra {"exception": "Code: ..."} row. The
reader now throws ServerException from next() for that row instead of
returning it as data.

Signed-off-by: Alex Castillo <alex.castillog33@gmail.com>

@chernser chernser left a comment

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.

thank you for the contribution!

please see comments.
It is better to have this handling on JSON library exception. May be remembering last raw line would help.

Current implementation will degrade performance.

@security-ai-gate-reviewer

security-ai-gate-reviewer Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

AI review gate — the gate never ran on this head

The org-required gate workflow has no run on 283b2df195e9: this pull request was open before the repository was enrolled, and GitHub starts that workflow only on opened, synchronize and reopened. Nothing here can merge until it runs.

What to do: a maintainer runs rollout kick-gate --repo ClickHouse/clickhouse-java --pr 3313 --apply from infra/github/conformance in security-integrations (dry run without --apply), or closes and reopens this pull request (auto-merge is turned off by the close; re-enable it after).

History (latest 5 heads, newest first)

  • 283b2df195e9 gate never ran — needs a kick

…wFormatReader

Address review: the check is off by default (new constructor flag), the
schema decision is made once, error code parsing moves to ClientUtils with
-1 for unreadable codes, and the key is a constant.
…body

hasServerErrorCode requires a Code: or Error: prefix, a numeric code, and
an Exception marker, so a value such as "Code: 1 is a value" stays data.
JSONEachRowServerExceptionIT reads a ClickHouse 25.8 HTTP 200 body (data
rows, then the exception object) with Gson and Jackson.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 5f4a7d4. Configure here.

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

AI review gate — AI review passed

Clean review from: Cursor Bugbot.

@pcbeingused333

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I pushed an update.

Detection is off by default. You have to use new JSONEachRowFormatReader(parser, true) to turn it on. The schema is decided from the first row, so the normal path doesn't do extra checks.

When the option is on, a row is treated as an error only if it has exactly one entry, the key is exception, and the value is a String that looks like a ClickHouse error (starts with Code: or Error: and has a numeric code).

JsonParser.nextRow() already returns a parsed map, so we can't look at the raw line. The row in the issue is valid JSON, so the parser doesn't fail. The check only looks at that map and doesn't change the parser.

If the result schema is a single String column named exception, we leave it as data. A body that is only the exception object has the same shape, so it also stays data; Client.query() already throws when the response is just the exception.

The one-argument constructor is unchanged and doesn't inspect rows. jdbc-v2 StatementImpl uses that constructor, so it keeps the old behavior.

Reproduction on ClickHouse 25.8:

SELECT toInt32(number) AS id FROM numbers(100)
WHERE throwIf(number = 50, 'in-band-boom') = 0
SETTINGS http_write_exception_in_output_format = 1, max_block_size = 1
FORMAT JSONEachRow

Tests:

  • JSONEachRowFormatReaderTest and ClientUtilsTest cover the opt-in flag, the schema exception, Code: / Error: parsing, and a Code: value that is not an exception text.
  • JSONEachRowServerExceptionIT runs on ClickHouse 25.8 with both Gson and Jackson. With the option on, it throws after the data rows. With the option off, the exception row comes back as data. A real exception column stays data.

This change was prepared with the assistance of an AI tool (Claude).

@connectorsec

Copy link
Copy Markdown

ConnectorSec security review — head 5f4a7d4

1. Cloud test password sent as Basic auth over plaintext HTTP — client-v2/src/test/java/com/clickhouse/client/api/data_formats/JSONEachRowServerExceptionIT.java:178

  • Scenario: cloud.yml (nightly on main, and on manual dispatch for a PR) runs mvn --projects client-v2 verify with TEST_CLICKHOUSE_SECURE=true and the shared Cloud test password in TEST_CLICKHOUSE_PASSWORD. Failsafe runs every integration-group class, this one included. In cloud mode getServer(ClickHouseProtocol.HTTP) resolves to the Cloud host on port 8443, but httpBody() always opens http://. The request, including the Authorization: Basic … header built at lines 180-182 from ClickHouseServerForTest.getPassword(), is written to the socket unencrypted before the TLS endpoint rejects it. That happens at least once for each of the four test invocations (2 tests × 2 parsers) on every cloud run, from a GitHub-hosted runner across the public internet. The rest of the suite uses TLS against Cloud (setUp() passes isCloud(); cloud.yml's own curl calls use https://…:8443). The Bugbot thread on these lines covers the correctness side (cloud runs never get a real body); this is the credential side.
  • Fix: build the URL with the scheme the suite already uses for Cloud (BaseIntegrationTest.getConnectionProtocol() returns https when isCloud()). Alternatively, skip the two raw-HTTP tests on Cloud with a SkipException, as HttpTransportTests does.
     private byte[] httpBody(String sql) throws Exception {
         ClickHouseNode node = getServer(ClickHouseProtocol.HTTP);
         HttpURLConnection conn = (HttpURLConnection) new URL(
-                "http://" + node.getHost() + ":" + node.getPort() + "/").openConnection();
+                getConnectionProtocol() + "://" + node.getHost() + ":" + node.getPort() + "/").openConnection();
         conn.setRequestMethod("POST");

Static review by ConnectorSec (ClickHouse Product Security); no PR code was executed.

@chernser chernser left a comment

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.

please resolve the issue #3313 (comment)

  • use client itself not an URLConnection
  • exclude test from cloud by throwing SkipException

…n IT

With a compressed response the server buffers the body and answers with an
HTTP 500, so no in-band exception row is streamed. Also drop a stale javadoc.
@pcbeingused333
pcbeingused333 requested a review from a team as a code owner November 18, 2026 10:08
@pcbeingused333

Copy link
Copy Markdown
Contributor Author

Thanks, both points addressed in 3c663ad: the integration test now reads the body through Client.query() instead of a raw HttpURLConnection (no hand-built Basic auth or plain-HTTP request), and setUp() throws SkipException when running on Cloud. Following a run against a real server (26.10), the test client also sets compressServerResponse(false): with a compressed response the server buffers the body and answers with HTTP 500 + X-ClickHouse-Exception-Code, so no in-band exception row is streamed. The latest commit (e7dc0e6) adds that and drops a stale javadoc; the IT passes 6/6.

This comment was drafted with Claude Code.

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.

[client-v2, jdbc-v2] JSONEachRow: a query that fails mid-stream on ClickHouse 25.8 returns the {"exception": ...} row as data and raises no error

3 participants