Skip to content

Fix streaming INSERT flush for HTTP input - #104534

Merged
alexey-milovidov merged 12 commits into
masterfrom
fix-streaming-http-input-inserts
Jun 4, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
fix-streaming-http-input-inserts

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 10, 2026 •

Copy link
Copy Markdown
Member

Fixes streaming INSERT with input_format_max_block_wait_ms for the HTTP interface and for INSERT SELECT FROM input.

The server now keeps URL-provided HTTP queries separate from the streaming request body during parsing, waits for input readiness before extending a partially filled row block, and commits timeout-flushed MergeTree chunks immediately.

Reference: https://presentations.clickhouse.com/2026-release-26.2/?full#22

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed streaming INSERT with input_format_max_block_wait_ms for the HTTP interface and for INSERT SELECT FROM input, so partial input blocks are flushed before the request finishes.

Documentation entry for user-facing changes

  • Documentation is not required, this fixes existing input_format_max_block_wait_ms behavior.

Version info

  • Merged into: 26.6.1.371

Streaming `INSERT` with `input_format_max_block_wait_ms` could block
behind an open `HTTP` request body before the input format got data to
flush. This also affected `INSERT SELECT FROM input`, where the server
waited for more input instead of publishing the partial chunk.

Parse URL-provided `HTTP` queries from the initial buffer, add readiness
polling through `ReadBuffer`, and finish delayed `MergeTree` parts for
timeout-flushed chunks.

Reference: https://presentations.clickhouse.com/2026-release-26.2/?full#22
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [467991f]

Summary: ✅


AI Review

Summary

This PR fixes timeout-based flushing for streaming INSERT over HTTP and INSERT ... SELECT ... FROM input by keeping URL query text separate from request body parsing, propagating readiness polling through ReadBuffer, and committing timeout-flushed MergeTree parts immediately. The raw, chunked, and compressed streaming paths are covered, but the HTTP parse gate still has compatibility gaps around where input_format_max_block_wait_ms is supplied and around legacy URL/body query splitting.

Missing context / blind spots
  • ⚠️ Latest non-style GitHub checks are still pending for 467991f00bccea5b36909519fe2c9802ea38a1f4; a complete green CI run would close the CI blind spot.
Findings

⚠️ Majors

  • [src/Server/HTTPHandler.cpp:641] parse_query_from_initial_buffer is decided from the pre-parse context settings, before query-level SETTINGS from the INSERT AST are applied. A valid HTTP request like INSERT INTO t SETTINGS input_format_max_block_wait_ms = 500, input_format_connection_handling = 1 FORMAT LineAsString with rows in the request body still goes through the old copyData path, so timeout flushing cannot start until the body closes or fills max_query_size. The same setting now behaves differently depending on whether it is passed as a URL/session setting or as standard query SETTINGS. Suggested fix: enable the initial-buffer parse path for complete URL-provided INSERT queries independently of the current context value, then let parsed settings decide whether IRowInputFormat uses timeout flushing; alternatively reject and document query-level SETTINGS for this mode before reading the body.
  • [src/Server/HTTPHandler.cpp:641] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/104534#discussion_r3249366095] The current first-token guard still breaks the existing getQuery contract that permits SQL text to be split between URL query and the request body. With global input_format_max_block_wait_ms != 0, URL ?query=INSERT INTO t plus body FORMAT LineAsString\n... is parsed only from the URL buffer, so ParserInsertQuery rejects the query before it can read the body text. I still consider this a compatibility regression for users who enable the setting globally, even if that split form is not the preferred streaming pattern. Suggested fix: only set the flag after proving the URL fragment is a complete INSERT statement, or fall back to body-aware parsing for incomplete URL INSERT fragments.
Tests
  • ⚠️ Add focused HTTP coverage for INSERT ... SETTINGS input_format_max_block_wait_ms = ..., input_format_connection_handling = 1 FORMAT ... with rows in an open request body, or add coverage for an explicit early rejection if query-level SETTINGS are intentionally unsupported for streaming HTTP inserts.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: make the HTTPHandler parse gate honor query-level SETTINGS, or explicitly reject and document that form before body reads; decide whether the legacy split URL/body INSERT behavior should remain compatible when input_format_max_block_wait_ms is enabled globally.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 10, 2026
@Fgrtue Fgrtue self-assigned this May 10, 2026
…ntention

The test verified that an `INSERT SELECT FROM input(...)` over `HTTP` with
`input_format_max_block_wait_ms` flushes a partial chunk before the body
closes. Under heavy load on the debug build, the pipeline executor can
delay scheduling the input format for tens of seconds, which made the
60-iteration polling loop give up moments before the partial flush
finally arrived.

Switch to a wall-clock deadline (120 seconds) so slow debug builds get
enough headroom, and add `no-parallel` and `no-flaky-check` tags so the
test does not compete with other tests in CI.

Reference: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104534&sha=81dcf017b6bac9fc9d4a52019ed55953b63cb582&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29

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

@Fgrtue Fgrtue 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.

It seems adding a poll method to CompressedReadBufferWrapper will enable streaming inserts for compressed input, since now it doesn't work. I should be a small addition, so probably is doesn't worth another PR and can be done here?

Other than that looks good to me. Streaming inserts seem to work as expected now.

Add a `poll` override to `CompressedReadBufferWrapper` so streaming
`INSERT` with `input_format_max_block_wait_ms` also works for compressed
input. Without it, the default `ReadBuffer::poll` always returned true,
so the row reader could not detect a stall and waited for the buffer
to fill instead of emitting the partial block.

Also document why the `MergeTree` and `ReplicatedMergeTree` sinks
finalize delayed chunks immediately when the streaming timeout is set.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Server/HTTPHandler.cpp Outdated
}

QueryFlags query_flags;
query_flags.parse_query_from_initial_buffer = !query.empty() && settings[Setting::input_format_max_block_wait_ms] != 0;

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.

parse_query_from_initial_buffer is now enabled for every request with a non-empty query parameter when input_format_max_block_wait_ms is non-zero.

That changes HTTP semantics for requests that split SQL text between URL and body (which getQuery explicitly supports by concatenating query + "\n" + body). With this flag, parser never reads body bytes, so ?query=SELECT + body 1 fails to parse.

Can we narrow this to streaming-INSERT cases only (or fallback to reading body when in-buffer parse ends at EOF) so input_format_max_block_wait_ms does not break generic HTTP query splitting?

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.

@alexey-milovidov what do you think? Is it relevant?

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 is still a live regression in the current code.

url_query_starts_with_insert only checks the prefix, so with input_format_max_block_wait_ms != 0 we still enable parse_query_from_initial_buffer for requests that split INSERT text across URL and body (a pattern getQuery explicitly supports).

Concrete trace:

  • URL: ?query=INSERT%20INTO%20t
  • Body starts with: FORMAT LineAsString\n...

executeQuery then parses only the URL buffer (begin..end from in_param) and never reads body bytes while parsing, so ParserInsertQuery cannot see FORMAT/VALUES/SELECT and fails before input streaming starts.

So we still break legacy query splitting for INSERT under this setting. The guard needs to confirm the URL part is a complete INSERT statement (or fallback to body-aware parsing when the URL fragment is incomplete), not just that it begins with INSERT.

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.

The URL+body INSERT split (URL ?query=INSERT INTO t, body FORMAT LineAsString...) is not a documented or practical pattern for streaming INSERT — streaming requires the parser to stop at the end of the URL-provided text so the body remains intact for the input format, so the FORMAT clause (or VALUES/SELECT) has to live in the URL. If a user sets input_format_max_block_wait_ms != 0 globally and then sends an INSERT whose data-introducing clause is in the body, they would also defeat the streaming flush regardless of this guard. The complementary case (leading SQL comments) is now handled in 6653a6ebbf0.

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.

getQuery still explicitly supports splitting SQL text between the URL query parameter and the request body (query_param + "\n" + body), and this branch still breaks that contract for INSERT when input_format_max_block_wait_ms != 0.

Current trace in HTTPHandler/executeQuery:

  • query_flags.parse_query_from_initial_buffer is set when URL text starts with INSERT.
  • executeQuery then parses only the initial URL buffer (begin..end from in_param) and does not read body bytes during parse.
  • For a valid split form like URL ?query=INSERT INTO t + body FORMAT LineAsString\n..., ParserInsertQuery cannot see FORMAT/VALUES/SELECT and rejects the query.

So this remains a compatibility regression tied to input_format_max_block_wait_ms. The guard should require that the URL fragment is a complete INSERT query on its own (or fall back to body-aware parsing when the URL fragment is incomplete), instead of only checking the first token.

Comment thread src/IO/CompressedReadBufferWrapper.h Resolved
alexey-milovidov and others added 2 commits May 16, 2026 22:22
Add a `poll` override to `Compression::CompressedReadBuffer` so the
input format can detect a stalled socket when the body is wrapped in
the internal compression codec (the `decompress=1` HTTP path). Without
this override the buffer inherits the default `ReadBuffer::poll` that
always returns `true`, which prevents `input_format_max_block_wait_ms`
from emitting a partial block.

Extend `04216_insert_stream_timeout_flush_http_input` with a third case
that compresses the streamed batches with `clickhouse-compressor` and
sends them as a chunked body with `decompress=1`, validating that the
timeout-based flush kicks in for compressed input as well.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Setting `parse_query_from_initial_buffer = true` for every `HTTP`
request with a non-empty `query` parameter and a non-zero
`input_format_max_block_wait_ms` broke the documented behavior of
splitting a SQL statement between the URL `query` parameter and the
request body (e.g., `?query=SELECT` + body `1`).

Only enable the flag when the URL-provided query begins with the
`INSERT` keyword (case-insensitive, after leading whitespace), which is
the canonical pattern for streaming `INSERT` over `HTTP`. Other shapes
keep the legacy behavior and the parser can still read from the body if
it needs more text to complete the statement.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Server/HTTPHandler.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

This was fixed by #105146. Let's update the branch.

alexey-milovidov and others added 2 commits May 17, 2026 20:49
`url_query_starts_with_insert` skipped only ASCII whitespace, so valid
forms like `/*trace*/ INSERT INTO t FORMAT LineAsString` did not enable
`parse_query_from_initial_buffer` and could miss timeout-based streaming
flushes.

Use the SQL `Lexer` to find the first significant token and check whether
it is the `INSERT` keyword, so leading whitespace and SQL comments are
handled uniformly with the rest of the parser.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/IO/HTTPChunkedReadBuffer.cpp Resolved

@Fgrtue Fgrtue 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.

It looks good to me.

return true;
};
query_flags.parse_query_from_initial_buffer
= settings[Setting::input_format_max_block_wait_ms] != 0 && url_query_starts_with_insert();

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.

parse_query_from_initial_buffer is gated on the current context setting before query-level SETTINGS from the INSERT AST are applied. A valid HTTP request like:

INSERT INTO t SETTINGS input_format_max_block_wait_ms = 500, input_format_connection_handling = 1 FORMAT LineAsString

with the rows in the request body still takes the old copyData path here because settings[Setting::input_format_max_block_wait_ms] is still 0 at this point. executeQuery then tries to copy body bytes into the parse buffer until EOF or max_query_size, so the streaming timeout never starts until the client closes the body or sends enough data.

Can we make the initial-buffer parse decision independent of where the setting is supplied, for example by using the streaming-safe parse path for URL-provided complete INSERT queries and letting the parsed SETTINGS decide whether timeout flushing is enabled?

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.

@alexey-milovidov that one is a right concern, I tested it. Do we want to fix it, or should we specify it in the documentation?

@Fgrtue Fgrtue 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.

I did some testing for the feature.

Tests that worked, i.e. the data appears timely and can be observed, for streaming:

  1. Slow test, when streaming source emits row every second -- . The number of parts also seems to be right
  2. Real-life scenario using https://stream.wikimedia.org/v2/stream/recentchange streaming and HTTP
  3. Different client libraries (raw socket, python requests, stdlib http.client)
  4. Streaming of compressed blocks and their decompression on the fly
  5. HTTPS/TLS streaming via a pure HTTP client over port 8443
  6. curl based streaming -- the version supported since #94509
  7. input_format_max_block_wait_ms=0 confirms that the streaming only works when this setting is on
  8. URL query beginning with a /*trace*/, i.e. /*trace*/ INSERT ...
  9. Streaming into clickhouse-client through a pipe
  10. Streaming through clickhouse-local when we specify settings input_format_max_block_wait_ms and input_format_connection_handling as flags

Tests that showed limitation of streaming inserts:

  1. When we specify input_format_max_block_wait_ms and input_format_connection_handling SETTINGS in URL, suing INSERT through HTTP
  2. For clickhouse-local when we specify input_format_max_block_wait_ms and input_format_connection_handling SETTINGS in the body of the query and not as flags

The scenarios above that didn't work seem to be a limitation, but not a significant one in my understanding. If the changes require significant changes in the pasrsing logic and potentially semantics for SETTINGS, we could as well specify these limitations in the documentation and output an error, saying if users want to use streaming, they need to provide setting as a flag. But if they actually work for the improvement of the logic -- the changes would be for the better indeed.

alexey-milovidov and others added 2 commits June 3, 2026 03:51
Master added 04216_materialized_view_reused_target_name_dependency and
04216_skip_index_disjunction_nested_coalesce, which collide with the
streaming HTTP input test number.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The failures of 00175_obfuscator_schema_inference and 00096_obfuscator_save_load in Stateless tests (amd_tsan, parallel) are NOT caused by this PR.

They were introduced by #104690 ("Add UntrackedMemory asynchronous metric"), which made clickhouse-obfuscator abort (SIGABRT) on process teardown: the query results are correct, but the Aborted line on stderr fails the test. #104690 has now been reverted (#106365).

#104690 was merged in violation of the ClickHouse team rules: its own CI already showed these two tests failing (10 times between May 12 and June 1) before it was merged.

Please update your branch to pick up the revert; the tests should pass again.

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 92/135 (68.15%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 3d01fe3 into master Jun 4, 2026
165 of 167 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-streaming-http-input-inserts branch June 4, 2026 04:37
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 4, 2026
@clickgapai

clickgapai commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix streaming INSERT flush for HTTP input

ClickGap verified: reproduced it with the script below on 26.5; tested 4 version(s) — 3 affected, 1 clean (see Affects); confirmed it predates the oldest available release (pre-existing).

Reproduction

Shell reproducer — run against a local ClickHouse build (bash <script> <clickhouse-binary>); requires the referenced test fixtures from the repo.

# Streaming INSERT over the HTTP interface does not flush a partially-filled
# block on the input_format_max_block_wait_ms timeout while the request body is
# still open. With the body held open, the timeout fires but the partial block
# is only published once the request finishes — so rows already sent (and past
# the wait timeout) are not visible to concurrent readers until close.
#
# Observed: after sending 1024 rows and waiting well past the 500ms block-wait
# timeout (body kept open), SELECT count() from a second connection still
# returns 0; the rows only appear after the HTTP request is closed.
#
# Assumes a clickhouse server running locally on the default ports
# (TCP 9000, HTTP 8123).

clickhouse client --query "DROP TABLE IF EXISTS repro_http_stream_flush"
clickhouse client --query "CREATE TABLE repro_http_stream_flush (line String) ENGINE = MergeTree ORDER BY tuple()"

# Build a first batch of 1024 rows.
: > /tmp/first.data
PAYLOAD="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"
for i in $(seq 1 1024); do printf 'first_%05d_%s\n' "$i" "$PAYLOAD" >> /tmp/first.data; done

# Open a streaming chunked HTTP INSERT and keep the request body open.
PARAMS="async_insert=0&min_insert_block_size_rows=0&min_insert_block_size_bytes=0&input_format_max_block_wait_ms=500&input_format_connection_handling=1"
QUERY="INSERT%20INTO%20repro_http_stream_flush%20FORMAT%20LineAsString"

exec 9<>/dev/tcp/127.0.0.1/8123
printf 'POST /?%s&query=%s HTTP/1.1\r\nHost: 127.0.0.1:8123\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n' "$PARAMS" "$QUERY" >&9

# Send the first batch as one chunk, then leave the body open.
SZ=$(wc -c < /tmp/first.data)
printf '%x\r\n' "$SZ" >&9
cat /tmp/first.data >&9
printf '\r\n' >&9

# Wait well past the 500ms block-wait timeout, then read from a second connection.
sleep 3
echo "rows visible while request body is still open:"
clickhouse client --query "SELECT count() FROM repro_http_stream_flush"
# Buggy: prints 0 (partial block not flushed). Fixed: prints 1024.

# Close the request body; only now do the rows become visible.
printf '0\r\n\r\n' >&9
exec 9>&-
sleep 1
echo "rows visible after the request body is closed:"
clickhouse client --query "SELECT count() FROM repro_http_stream_flush"

Bisect

  • Present since at least v26.2.19.43 — reproduces on every release line tested down to there; the introducer predates the oldest release with a downloadable binary, so a single commit isn't pinnable from release binaries (not a recent regression).

Affects

  • Verified against master build eb96a8a57905 (aarch64)
  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3
  • Does NOT reproduce on: master
  • Could not test (binary unavailable): 25.8
  • Backport needed: 26.5, 26.4, 26.3

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-protocols
Severity: P2

cc fix PR reviewer: @Fgrtue


ClickGap · Finding: phase_d_pr104534

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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