Skip to content

Don't retry a failed read while recovering from a parse error in the Values format - #121916

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/values-format-no-retry-after-failed-read
Oct 6, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/values-format-no-retry-after-failed-read

Conversation

@groeneai

@groeneai groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

INSERT ... VALUES over a stream that fails mid-row now reports that read failure directly, instead of retrying the failed read while recovering from a parse error. This affects an HTTP request body that is shorter than its declared Content-Length and is streamed to the input format.

Description

Related: #109708

ValuesBlockInputFormat::tryReadValue classifies a failed value read with isParseError and, on a match, rolls back to the checkpoint and re-walks the row through the expression parser. CANNOT_READ_ALL_DATA is on that allowlist, so a read that failed inside the stream is swallowed like a failure to parse a value. A throwing read cancels its buffer for good, and PeekableReadBuffer::rollbackToCheckpoint clears only the wrapper's flag, never the sub-buffer's, so the re-walk refills a canceled buffer and trips the assertion in ReadBuffer::next().

I complete the existing gate with the buffer's own cancellation state, so recovery runs only for a parse error not raised inside the stream. This is the shape @ Avogar prescribed for the same assertion in IRowInputFormat (#109708).

Not a Bug Fix: the assertion is active only in debug and sanitizer builds. In a stable build it is compiled out and the failed read is reported either way, so no released version misbehaves.

Reachability: an HTTP INSERT ... VALUES whose body is shorter than its declared Content-Length and is streamed to the format rather than read as query text. Two default-settings forms qualify: a bulk body over max_query_size (256 KiB), or a client sending X-ClickHouse-100-Continue: defer. A truncated body alone is inert.

One site, not several: readUntilTheEndOfRowAndReTokenize puts the whole row into the buffer's own memory before any template or retry path reads it, so those cannot refill or cancel; the schema reader sets no checkpoint; TemplateRowInputFormat is covered by #109708.

CIDB shows no occurrence of this frame chain in 120 days, so I have no failing job to link. The substitute is the new test, which aborts the server on the unpatched build and passes with the fix.

Alternatives not taken: propagating cancellation through PeekableReadBuffer, which reverses schema-detection behaviour added in 5c6c629bfc4e8, and weakening the assertion, which #109785 owns.


Workflow [PR]
Sync PR [sync-upstream/pr/121916]

Version info

  • Merged into: 26.10.1.1686-master (included in 26.10 and later)

…Values format

`ValuesBlockInputFormat::tryReadValue` classifies a failed value read with
`isParseError` and, on a match, rolls back to the value's checkpoint and re-walks
the row through the expression parser. `CANNOT_READ_ALL_DATA` is on that
allowlist, so a read that failed inside the stream is swallowed exactly like a
failure to parse a value.

That swallow is the defect. A read that throws cancels its buffer for good
(`ReadBuffer::next` catches, cancels and rethrows, and the assertion at
ReadBuffer.cpp:107 makes the state terminal), while
`PeekableReadBuffer::rollbackToCheckpoint` clears only the wrapper's own flag and
never the sub-buffer's. After the rollback the wrapper therefore reads as clean
while the object it delegates to is canceled, and the re-walk's first refill trips
the assertion.

The wrapper's own `isCanceled()` is the right predicate at that point, rather than
the sub-buffer's: the sub-buffer can only be canceled inside `sub_buf->next()`,
reachable only from `PeekableReadBuffer::nextImpl`, reachable only from the
wrapper's own `ReadBuffer::next`, whose catch cancels the wrapper on the same
unwind. The two flags diverge only after a rollback, and this gate runs before it.

Completing the existing gate is what @ Avogar asked for when the same assertion
was fixed for `IRowInputFormat` in ClickHouse#109708: reach the skip-bad-lines logic only
for a parse error that was not thrown in the buffer itself. It also continues the
narrowing f188894 applied to this same allowlist, where only a genuine parse
error should be reported as an unparsed value.

One site is enough. `readUntilTheEndOfRowAndReTokenize` runs `skipToNextRow` and
then `makeContinuousMemoryFromCheckpointToPos`, so every template and retry path
afterwards reads the row out of the buffer's own memory and cannot refill, hence
cannot cancel. `ValuesSchemaReader` sets no checkpoint at all, and
`TemplateRowInputFormat` is already covered by ClickHouse#109708, whose read buffer is the
peekable one.

Reachable from an HTTP `INSERT ... VALUES` whose body is shorter than its declared
`Content-Length` and is streamed to the input format rather than drained for
query-text extraction, which `executeQuery.cpp:4180` decides; a truncated body
alone is inert. Measured on a debug build: the abort reproduces 3/3 through the
`X-ClickHouse-100-Continue: defer` form and 3/3 through a bulk body over
`max_query_size`, and the new test aborts the server on the unpatched build while
passing with this change.
The test's assertions so far were that the read failure is reported, that the
request does not hang, that the server is still alive and that no row landed.
Every one of those also holds on the path where the body never reaches a data
format at all: without the `X-ClickHouse-100-Continue: defer` header the request
is drained for query-text extraction instead, the decision `executeQuery.cpp:4180`
makes, and the short read is then reported from `copyData` with the server alive.
So the test distinguished the two builds only because the header happens to be
there, not because it checked that it mattered, and a later change to that
decision would leave the test green while covering nothing.

Assert the precondition instead of assuming it. A parse-classified error picks up
the row context in `ValuesBlockInputFormat::read`'s own catch, so its presence in
the response says the row really was handed to the Values format. Removing the
header now flips that one assertion and nothing else, which is the measurement the
test was missing.

Also give the table the cleanup shape of the test this one is modelled on,
`04826_handler_lengthless_body_keep_alive`, so a local re-run starts from a known
state instead of relying on each invocation getting a fresh database.

Test only, no change to the fix.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex). Two passes: a full review of the
first head (1 finding) and a delta re-review of the fix round (0 findings). My own cold review of the
resulting code ran first in each round, without the implementation notes, and added 3 nits.

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test asserts only that Code: 33 came back, that nothing timed out, that the server is alive and that no row landed, and every one of those is also true of the path where the request body never reaches a format at all (tests/queries/0_stateless/05243_values_truncated_http_body.sh) AGREE, fixed Correct: without the X-ClickHouse-100-Continue: defer header the request falls into the else branch of src/Interpreters/executeQuery.cpp:4180 and fails in copyData, answering Code: 33 with the server alive and no ValuesBlockInputFormat frame, so the oracle was satisfiable by a path that never reached a format. Both truncated arms now also assert the row context that only ValuesBlockInputFormat::read appends, and only for a parse-classified code (:147). Verified rather than accepted: with the guard reverted both assertions go false and the server exits 134; with the header removed the four original assertions stay green while the new one alone goes false
2 💡 The test creates its table with no DROP TABLE IF EXISTS and no cleanup, unlike the test it is modelled on AGREE, fixed Hygiene only: each invocation gets its own generated database. The committed shape is the model's (04826_handler_lengthless_body_keep_alive.sh:22-26)
3 💡 The test can only discriminate in debug and sanitizer builds DISAGREE Raised and refuted by me. The assertion is compiled out unless !defined(NDEBUG) or a sanitizer is on (base/base/defines.h:84-104), so this is inherent to the defect and matches the merged sibling #109708. Post-fix the observable result is Code: 33 on every build type, so there is no false failure in release. No action
4 💡 The new assertion matches at row rather than the exact " at row ", which would also match the parenthesised form the row-based formats use DISAGREE Raised and refuted by me. The request's own query text fixes the format, so no IRowInputFormat instance is in this pipeline, and no other producer of that substring is reachable from a UInt64 VALUES insert over HTTP. No action

I also re-derived the two claims the original report got wrong, and both corrections hold:
buf->isCanceled() is the right predicate with no need for getSubBuffer() (the only route to a
sub-buffer refill is PeekableReadBuffer::nextImpl, reached only through the wrapper's own
ReadBuffer::next(), whose handler cancels the wrapper on the same unwind), and this is one site
rather than five (every other gate of the same shape runs after readUntilTheEndOfRowAndReTokenize
has put the whole row in the buffer's own memory, so it cannot refill).

What keeps the fix from being over-broad: the third arm (INSERT INTO t VALUES (1+1) returning 2)
drives the same catch with the buffer not cancelled, so the rollback-and-reparse recovery must still
run. A guard that fired spuriously would redden it.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260924-075100

@clickhouse-gh clickhouse-gh Bot closed this Sep 24, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One raw HTTP request: POST /?query=INSERT+INTO+t+VALUES&async_insert=0 with X-ClickHouse-100-Continue: defer, Content-Length: 1000, a 6-byte body (12345, then a half-close. Aborts 3/3 on the unpatched build (exit 134). The committed test reproduces it on demand; not a rate.
b Root cause explained? Yes. tryReadValue swallows any isParseError code, including CANNOT_READ_ALL_DATA raised inside the stream, then rolls back and re-walks the row. A throwing read cancels its buffer for good, and PeekableReadBuffer::rollbackToCheckpoint clears only the wrapper's flag, not the sub-buffer's, so the re-walk refills a canceled buffer. Confirmed at instruction level: the abort's frame 8 is ValuesBlockInputFormat.cpp:383, the parseExpression call at the end of that same catch.
c Fix matches root cause? Yes. The defect is that the swallow classifies by error code alone; the fix adds the missing "where did it come from" term at that same swallow site. Not a widened bound, not a no-random-* tag, and not a guard at the read site, which @ Avogar explicitly refused on #109708.
d Test intent preserved / new tests added? New stateless test 05243_values_truncated_http_body, with two controls that pass identically on both builds so the expression fallback cannot be silently disabled. The oracle also asserts that the request actually reached the Values format, keyed on the row context that only ValuesBlockInputFormat::read adds to a parse-classified error, so the test cannot go green-and-empty if such a request is ever answered before any format runs. Verified by a negative control: removing the load-bearing defer header flips that one assertion to False while every other assertion stays satisfied. No existing test weakened; the 4 gtests over this code still pass, including the sibling RowInputFormatDiagnostics.CanceledBufferDoesNotAbort from #109708.
e Both directions demonstrated? Yes, at the same base with Build IDs asserted on both sides. Unpatched: abort 3/3, and the new test fails with the server exiting 134. Patched: 4/4 pass, Code: 33 reported, server alive. 50 randomized runs: 50/50.
f Fix is general across code paths? Yes, and deliberately one site. 14 candidate carriers were enumerated against a three-part discriminator and 13 discharged with evidence: readUntilTheEndOfRowAndReTokenize puts the whole row into the buffer's own memory before any template or retry path reads it, so those cannot refill or cancel; the schema reader sets no checkpoint at all; TemplateRowInputFormat is already covered by #109708, whose read buffer is the peekable one.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, type-independent by construction: the gate keys on the exception's origin, not on the value's type, so no Nullable / LowCardinality / Array / Map / Const combination can evade it, and the existing wrapper stripping in tryReadValue is untouched. Boundary shapes measured: a row cut mid-value, and a complete row followed by a failing read.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No new or changed setting, no format change, no version gate, so no SettingsChangesHistory.cpp entry. The set of reported error codes is unchanged, pinned by the control arm; only whether recovery is attempted changes, and only for an error raised inside the stream.
i Invariants and contracts preserved? Yes. The invariant is "the Values format never enters parse-error recovery on a buffer whose read has already failed". On the new path the function rethrows through the pre-existing branch, so recordToSystemErrors() still runs exactly as for the other rethrow case, and popBack(1) / rollbackToCheckpoint() are simply not reached. No lock, allocation or data-structure invariant is involved; the widened contract is on the error path only, and the control arm pins that error reporting is unchanged.

Session id: cron:clickhouse-impl-slot-5:20260924-073300

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7c7d144]

Summary: ✅


AI Review

Summary

This PR teaches ValuesBlockInputFormat::tryReadValue to rethrow a parse-classified exception when the underlying ReadBuffer has already canceled itself, so the Values fallback does not retry a failed stream read on the same row. The added shell test also now proves the request body actually reaches the Values format before asserting on the error shape. I did not find a remaining correctness, compatibility, or test-oracle problem in the changed paths.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 7c7d144.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). labels Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 7c7d144215e93c9a4e9521237644f100c99e2a04 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR changes one branch in the Values input format: it now rethrows a parse exception when the read buffer was canceled, plus a new stateless test. Only INSERT ... VALUES error recovery runs that code. One ClickBench query was flagged: Q16 is +10.4% (585 ms vs 530 ms). It is a read-only SELECT that never runs the changed code, and its time falls inside the range master itself currently varies over, so the suppression holds and nothing in this PR explains it. No performance impact from this PR is expected or shown on clickbench or tpch_adapted_1_official.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 530 585 +10.4% <0.0001 This SELECT never reaches the Values input format error-recovery branch the PR changes. The +10.4% sits inside master's current band of 519-669 ms, so the suppression stands.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 42a9ef97-e764-45d9-a591-b1284efd5c50
  • MIRAI run: 65f64b9a-6b50-417d-bcb8-6f109b5d07b6
  • PR check IDs:
    • clickbench_10343_1791293085
    • clickbench_10349_1791293084
    • clickbench_10355_1791293084
    • tpch_adapted_1_official_10366_1791293085
    • tpch_adapted_1_official_10376_1791293085
    • tpch_adapted_1_official_10414_1791293085

@PedroTadim PedroTadim self-assigned this Oct 6, 2026
@PedroTadim
PedroTadim enabled auto-merge October 6, 2026 12:02
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 6, 2026
Merged via the queue into ClickHouse:master with commit 350fd22 Oct 6, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-improvement Pull request with some product improvements 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.

3 participants