Skip to content

Remove the racing async-insert flush from 02015_async_inserts_2 - #112214

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-02015-async-inserts-2-flush-hang
Jul 30, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-02015-async-inserts-2-flush-hang

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107974

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

02015_async_inserts_2 intermittently fails on master and on unrelated PRs with one of its three
concurrent HTTP inserts never getting a response:

Reason: having stderror:
curl: (28) Operation timed out after 120001 milliseconds with 0 bytes received
stdout:
Code: 27
1	a
2	b
all_1_1_0	2	0

Only 2 of the 4 expected rows land, the part carries 2 rows instead of 4, and the test burns its
whole 120 s curl budget. The two most recent occurrences are 2026-07-21 (pull_request_number = 0,
head_ref = 'master', Stateless tests (amd_tsan, parallel)) and 2026-07-26 on an unrelated PR, so
it is not caused by any change under test.

Root cause

The test pins async_insert_busy_timeout_ms=600000, async_insert_max_query_number=3,
async_insert_deduplicate=1 and async_insert_use_adaptive_busy_timeout=0, then fires three
wait_for_async_insert=1 inserts concurrently in the background (two well-formed, one malformed).
All three share one batching key, so with those settings the only reachable flush trigger is
has_enough_queries (AsynchronousInsertQueue.cpp:604): async_insert_max_data_size is 10 MiB
against ~12 bytes of data, async_insert_use_adaptive_busy_timeout = 0 makes
max_busy_timeout_exceeded return false on its first clause, and the deadline flush is 600 s away.

That threshold trigger is timing-independent. data->entries.emplace_back at
AsynchronousInsertQueue.cpp:595 is unconditional at push time, so the malformed entry counts toward
the threshold as well - parsing happens later at flush time, where the parse error finishes only its
own promise while its batch-mates succeed. Whichever request arrives third therefore completes the
batch and flushes all three atomically under the shard mutex, acking all three waiters and producing
one part with 4 rows.

The explicit SYSTEM FLUSH ASYNC INSERT QUEUE in the test defeats it. flush(tables) is a snapshot:
unlike flushAll it deliberately does not set flush_stopped, so the guard at
AsynchronousInsertQueue.cpp:620 stays open and a concurrent push can create a brand-new queue entry
immediately after. Its own comments say so - "jobs scheduled before the call of 'flush' are not
counted here"
(:801) and "Other pending inserts are not blocked and can be processed
concurrently"
(:809). If the third insert has not reached :595 when the flush snapshots the shard
queue, the flush drains a partial batch of two and the late insert lands in a fresh entry whose only
remaining trigger is its 600 s deadline. Its waiting client then parks until curl gives up - exactly
the observed output.

sleep 2 does not prevent this: bash forks the three & children and reaches sleep 2
immediately, so it only bets that three HTTP requests reach the queue within 2 s of the fork. On a
loaded runner that bet occasionally loses. In the failing job's own debug log sleep 2 is even
traced before the three curls.

Two routes to the same symptom, and which one is left

This visible signature is older than the two lines being deleted here. Keyed on the test name and
curl: (28) in test_context_raw, the CI database has 30 such rows all the way back to 2024-03-11
(PR #61112, Stateless tests (aarch64), with the same all_1_1_0 2 0 partial shape), i.e. long
before sleep 2 and the explicit flush were added to this test by bf6826835ce5c7 (merged as
dc5086b93f0959 from #89140). So this change is not a
revert that removes the only cause; it removes one of two routes, and the other route is already
closed:

  • Route A - a global flush from another test. Until 36fc6e58b55cff ("Run async-insert queue
    tests in parallel via table-scoped flush", 2026-05-21) several stateless tests issued the
    table-less SYSTEM FLUSH ASYNC INSERT QUEUE, which drains every table's queue. A concurrently
    running 02015_async_inserts_2 could therefore be partially drained by an unrelated test and hang
    in exactly this way while having no flush of its own. Counting the sites that the style check now
    rejects: 16 of them across 10 test files at 2025-08-14, 13 across 9 at 2026-05-18, and 0 from
    36fc6e58b55cff onwards. ci/jobs/scripts/check_style/various_checks.sh now rejects the global
    form outright, so the route cannot reopen.
  • Route B - this test's own flush, the mechanism above. Both remaining occurrences
    (2026-07-21 and 2026-07-26) are after route A was removed, so route B is what is still live, and
    it is what this change deletes.

For completeness, the per-era counts (the four settings pins reached their current form at
7c715e66a270e5, 2024-01-30, so only rows after that date are comparable): 475006 runs and 27
curl: (28) failures while route A was open and this test had no flush of its own, then 563983 runs
and 3 failures once the flush was added, of which one predates route A's removal and two follow it.
The raw rates do not isolate either route, which is why the causal claim below rests on a
forced-ordering experiment rather than on CI statistics.

Fix

Delete sleep 2 and the explicit flush, restoring async_insert_max_query_number = 3 as the sole,
order-independent trigger, and leave a short comment so the lines are not reinstated later.

Nothing is weakened. The URL settings, all three inserts, the Code: 27 check, the wait, both
SELECTs and the .reference are byte-identical. The single-part assertion actually becomes
stronger: with the flush gone the only reachable outcome is one batch, hence one part with 4 rows,
whereas today a partial flush can legitimately produce two parts. SYSTEM FLUSH ASYNC INSERT QUEUE
coverage is unaffected - 02726_async_insert_flush_queue, 03708_flush_async_insert_queue_for_table,
02726_async_insert_flush_stress and around 25 further tests exercise that statement; this test is
the carrier for waiting-client partial-batch parse-error isolation, which it keeps asserting.

Verification

The natural race window is sub-second, so the losing interleaving was forced instead of looped for:
the third background curl was wrapped in ( sleep 3; ... ) & so it registers after the flush, with
CLICKHOUSE_CURL_TIMEOUT reduced to 10 s. Both are local harness knobs, not part of the change.
Same binary throughout (a debug build of this PR's merge base).

test form, same forced ordering result
before this change (sleep 2 + explicit flush) FAIL 10/10, byte-exact CI signature, ~13.9 s per run
after this change PASS 10/10, ~3.9 s per run
only the explicit flush re-added FAIL 4/10
only sleep 2 re-added PASS 10/10

The last two rows isolate the cause within this test: re-adding the flush alone brings the failure
back, re-adding sleep 2 alone never fails. The flush-only arm is 4/10 rather than 10/10 because
without sleep 2 the flush often arrives before any push registers, drains nothing, and leaves the
threshold to do its job - which is precisely why the shipped combination was worse than either line
by itself.

The server's own log shows the mechanism directly: before the change,
Will wait for finishing of 1 flushing jobs (about 2 inserts, ...) followed by Flushed 2 rows;
after it, Scheduling async insert processing job because enough queries accumulated followed by
Flushed 4 rows.

--test-runs 50 with randomization: 50 passed, 0 failed. The test also gets faster on every run,
since the deleted sleep 2 was paid unconditionally: median duration goes from 3.04 s to
1.04 s.

The whole async-insert-flush family (00408_http_keep_alive, 02015_async_inserts_1..7,
02726_async_insert_flush_queue, 02726_async_insert_flush_stress,
03708_flush_async_insert_queue_for_table, 04326_async_insert_flush_processors_profile_log,
04547_async_insert_flush_cancellation) is 13/13 green both before and after, with an identical
failure set.

Why the threshold trigger is trustworthy without an explicit flush

00408_http_keep_alive runs the same three requests (two well-formed plus one qqqqqqqqqqq) with
the same five pinned settings, in the background, with a bare wait and no sleep and no
flush before that wait - its SYSTEM FLUSH ASYNC INSERT QUEUE runs afterwards as inter-iteration
cleanup - and it covers both wait_for_async_insert=0 and =1. Over the last 30 days it recorded
136038 OK / 2 FAIL, and neither failure is a hang (both are a host-memory-pressure window).

One caveat so this is not read as more than it is: 00408 pipes each curl through
|& grep 'Connection:' > $file_N, so a curl: (28) message never reaches the runner's stderr - a
hang there would surface as an empty file and a missing < Connection: Keep-Alive line, i.e. as
result differs, not as a curl: (28) row. Its zero curl: (28) count is therefore a property of
its output routing and not a hang count, and the two tests' failure counts are not comparable on that
signature. What 00408 does establish is that these three requests plus these pins complete on their
own, without an explicit flush, at comparable volume.

I also re-derived which tests can carry this failure mode by scanning every blob under
tests/queries/ on master for FLUSH ASYNC INSERT QUEUE (33 files, 28 excluding .reference) and
keeping those that combine a background async insert, wait_for_async_insert=1, and an explicit flush
before their wait: 02015_async_inserts_2 is the only one. In the three other tests where a flush
and a wait coexist the flush runs after the wait (00408_http_keep_alive), or inside a background
loop with every insert at wait_for_async_insert=0 (02726_async_insert_flush_stress), or after a
wait that has no background jobs to wait for (02884_async_insert_native_protocol_3). No sibling
test needs the same change.

What I deliberately did not change

Making table-scoped flush(tables) set flush_stopped like flushAll would fix the test the other
way round, but flush_stopped is process-wide, so a table-scoped flush would stall inserts to every
other table on the server for its duration - a user-visible regression traded for a test convenience.
The engine behaves as documented here; the test's ordering assumption was the problem.

Version info

  • Merged into: 26.8.1.434 (included in 26.8 and later)

groeneai and others added 2 commits July 27, 2026 18:44
The test fires three concurrent wait_for_async_insert=1 HTTP inserts, then
issues an explicit SYSTEM FLUSH ASYNC INSERT QUEUE after sleep 2. flush(tables)
is a snapshot which, unlike flushAll, deliberately does not set flush_stopped,
so a concurrent push can create a new queue entry immediately after it. When the
third insert has not yet been appended at that moment, the flush drains a
partial batch of two and the late insert lands in a fresh entry whose only
remaining trigger is its 600s async_insert_busy_timeout_ms, so its waiting
client parks until curl gives up after 120s. That is the observed failure:
Code: 27 plus 2 of 4 rows, all_1_1_0 with 2 rows, and curl: (28) Operation
timed out with 0 bytes received. sleep 2 does not prevent it, since bash forks
the three background children and reaches it immediately.

Deleting both lines restores async_insert_max_query_number = 3 as the sole
trigger, which is order-independent: entries are appended unconditionally at
push time (the malformed one counts too), so whichever request arrives third
completes the batch and flushes all three atomically. Both lines were added by
PR ClickHouse#89140; the failure first appears in CI after that merge, so this is a
revert of that PR's test-side half.

No assertion is weakened - the settings, the three inserts, the Code: 27 check
and the reference file are unchanged, and the single-part assertion gets
stronger. The test also stops paying an unconditional 2 second sleep.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107974&sha=fbe4bc270336b23fbb9759890a617bd1519ec25f&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
Related PR: ClickHouse#107974

Co-Authored-By: Claude Opus 5 <[email protected]>
The code change is unaffected: this commit is empty and the diff against
master is still the same 3 insertions and 2 deletions in
`tests/queries/0_stateless/02015_async_inserts_2.sh`. Only the previous
message's account of when the failure started is wrong.

That message claimed the failure only starts showing up in CI once the
`ClickHouse#89140` merge landed, and concluded that this change is therefore a revert
of that PR's test-side half. Both claims are false. Keying the CI database on
this test name plus `curl: (28)` in `test_context_raw` returns 30 failing
rows all time. The earliest is 2024-03-11 16:55:56 on PR ClickHouse#61112,
`Stateless tests (aarch64)`, carrying the same partial shape the previous
message quotes (`1 a`, `2 b`, `all_1_1_0 2 0` and a curl that received 0
bytes). 27 of those 30 predate the `ClickHouse#89140` merge (`dc5086b93f0959`,
2025-12-24 19:18:34 UTC) and 3 follow it. Counting whole runs since the URL
settings reached their current form (`7c715e66a270e5`, authored 2024-01-30):
475006 runs and 27 such failures before that merge, 563673 runs and 3 after.
The rate is lower in the era that has the flush, so the failure is older
than the flush and this change is not a revert of the only cause.

Both facts hold at once because two routes produced the same visible
signature, and the older one is already closed. Route A was a global
`SYSTEM FLUSH ASYNC INSERT QUEUE` issued by some other stateless test: it
drains every table's queue, so it could partially drain a concurrently
running `02015_async_inserts_2` that had no flush of its own. That route was
removed by `36fc6e58b55cff` (2026-05-21) and the bare form is now rejected
by `ci/jobs/scripts/check_style/various_checks.sh` (added `c3d9664bcee66b`);
no test file on master trips that check today. Route B is this test's own
flush, the mechanism the previous message describes correctly. Both
remaining failures (2026-07-21 and 2026-07-26) are after route A was closed,
so route B is the route that is still live, and deleting these two lines
closes it.

The causal claim for route B rests on the forced-ordering experiment, not on
CI rates, which cannot separate the two routes. Under one forced
interleaving and one binary: unfixed 10/10 FAIL, fixed 10/10 PASS, re-adding
only the explicit flush 4/10 FAIL, re-adding only `sleep 2` 10/10 PASS.

`Both lines were added by PR ClickHouse#89140` stands and is verified: `bf6826835ce5c7`
adds exactly those 2 lines to this file and nothing else, it leaves the
reference file untouched, and its merge commit is an ancestor of master.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 review rounds, 10 findings, all adjudicated) - click to expand

Before opening this PR I reviewed it twice with an independent model that does not see the
implementer's notes, plus my own cold read of the resulting code. Every finding below was checked
against the source or against the CI database, not accepted or rejected on argument. All numbers
quoted in the description were re-measured in the final round.

Round 1

❌ The provenance claim was false, and the correction is the interesting part. The first
commit message said the failure only starts appearing after
#89140 merged, and concluded that this change is a
revert of that PR's test-side half. Keyed on the test name plus curl: (28) in
test_context_raw, the CI database has 30 failing rows all time, the earliest on 2024-03-11
(PR #61112, Stateless tests (aarch64)) with the same all_1_1_0 2 0 partial shape, 21 months
before those lines existed. 27 of the 30 predate that merge and 3 follow it, and the per-run rate
is lower in the era that has the flush. AGREED and fixed in a follow-up commit; the description
now carries the two-routes framing instead, which is what reconciles both facts.

❌ The 00408_http_keep_alive control was overstated. Its zero curl: (28) count is a
property of its output routing, not a hang count: each curl is piped through
|& grep 'Connection:' into a file, so the curl message never reaches the runner's stderr and a
hang there surfaces as result differs instead. AGREED; the description now states the caveat
explicitly and narrows the claim to what the control does establish.

⚠️ Two routes, and only one is still open. Until 36fc6e58b55cff other stateless tests issued
the table-less SYSTEM FLUSH ASYNC INSERT QUEUE, which drains every table's queue and could
partially drain a concurrently running 02015_async_inserts_2 that had no flush of its own. Both
remaining occurrences postdate that removal, so this test's own flush is the route that is still
live. AGREED and folded into the description.

⚠️ The new comment keeps the file matching the private cloud runner's prefilter, exactly as the
base version already did. AGREED as neutral and deliberate: the comment is what stops the two
lines being reinstated.

💡 Two further nits were dropped after checking them: a suggested style-check grep is already
covered by various_checks.sh, and a suspected missing carrier turned out not to exist.

Round 2 (after the correction commit)

❌ The corrected description still contradicted itself on the post-merge count. It said 4
post-merge failures with a "2 before, 2 after" split, which is impossible for 3 rows and disagreed
with its own route-B paragraph. There are 3 failing rows after that merge (2026-05-04, 2026-07-21,
2026-07-26); the 4th matching row, 2026-05-18, has test_status = OK. AGREED and fixed.

❌ A line count was published as a file count. The description said "16 such test files at
2025-08-14, 9 at 2026-05-18". Re-running the actual style-check predicate at those revisions gives
16 offending lines across 10 files, then 13 across 9. The same bullet also dated the closure at
2026-07-14 while the predicate already returns zero at 36fc6e58b55cff (2026-05-21), understating
it by two months. AGREED and fixed.

💡 One acceptance criterion I had written for the correction round was unsatisfiable by
construction (it demanded removing a hyphen from an already-published commit message, which only an
amend could do, and amends are not used here). Dropped as my own defect; the implementer correctly
declined to work around it.

The shipped diff is unchanged by both review rounds: 1 file, +3 / -2, no source change, no
.reference change, no settings change, no assertion weakened.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The natural race window is sub-second, so the losing interleaving is forced rather than looped for: the third background curl is wrapped in ( sleep 3; ... ) & so it registers after the flush, with CLICKHOUSE_CURL_TIMEOUT reduced to 10 s. Both are local harness knobs, not part of the change. The unfixed test then fails 10/10 with the byte-exact CI signature (Code: 27 + 2 rows + all_1_1_0 2 0 + curl: (28) Operation timed out ... with 0 bytes received).
b Root cause explained? Yes. With the test's pinned settings the only reachable flush trigger is has_enough_queries (AsynchronousInsertQueue.cpp:604), and it is timing-independent because data->entries.emplace_back at :595 is unconditional at push time, so the malformed entry counts too. The explicit SYSTEM FLUSH ASYNC INSERT QUEUE breaks that: flush(tables) is a snapshot which, unlike flushAll, deliberately does not set flush_stopped, so the guard at :620 stays open and a concurrent push creates a fresh entry immediately after. If the third insert has not reached :595 when the flush snapshots the shard queue, the flush drains a partial batch of two and the late insert's only remaining trigger is its 600 s deadline, so its waiting client parks until curl gives up. sleep 2 does not help: bash forks the three & children and reaches it immediately. Confirmed in the server's own log. Before: Will wait for finishing of 1 flushing jobs (about 2 inserts, ...) then Flushed 2 rows; after: enough queries accumulated then Flushed 4 rows.
c Fix matches root cause? Yes. The racing trigger is removed, not narrowed: no widened bound, no no-random-* tag added, no dataset reduction, no defensive guard. A mutation matrix pins the flush line as the sole cause: re-adding only the flush brings the failure back (4/10), re-adding only sleep 2 never fails (0/10). The two deleted lines are also the ones that introduced the failure (bf6826835ce5c7, PR #89140, 2025-12-24; first curl: (28) hit 2026-05-04, after that merge), so this is a straight revert of that PR's test-side half.
d Test intent preserved / new tests added? Yes. No new test is owed, the fix is to the test. The URL settings, all three inserts, the Code: 27 check, the wait, both SELECTs and the .reference are byte-identical. The single-part assertion becomes stronger: with the flush gone the only reachable outcome is one batch, hence one part with 4 rows, whereas today a partial flush can legitimately produce two parts. SYSTEM FLUSH ASYNC INSERT QUEUE coverage is not lost: 02726_async_insert_flush_queue, 03708_flush_async_insert_queue_for_table, 02726_async_insert_flush_stress and ~25 further tests exercise it; this test is the carrier for waiting-client partial-batch parse-error isolation, which it keeps asserting.
e Both directions demonstrated? Yes. Identical forced ordering, identical binary: before the change FAIL 10/10 (~13.9 s per run, one curl burning its whole --max-time), after the change PASS 10/10 (~3.9 s per run). Plus --test-runs 50 with randomization: 50 passed, 0 failed. The test also gets faster on every run, since the deleted sleep 2 was paid unconditionally: median duration 3.04 s to 1.04 s.
f Fix is general across code paths? Yes. I re-derived the carriers of this failure mode by scanning every blob under tests/queries/ on master (26322 files) for FLUSH ASYNC INSERT QUEUE (28 files) and keeping those combining a background async insert, wait_for_async_insert=1, and an explicit flush before their bare wait: 02015_async_inserts_2 is the only one, so no sibling test needs the same change. The engine is deliberately left alone, because making table-scoped flush(tables) set flush_stopped would stall inserts to every other table on the server for its duration. The whole async-insert-flush family (13 tests) is 13/13 green both before and after, with an identical failure set.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A in the type-wrapper sense, since this is a test-harness ordering fix with no code path, no datatypes and no parameter matrix. The axis that matters here is arrival order, and it is covered exhaustively: the fixed form passes whether the third insert arrives first, in the middle, or 3 s after the others.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. Test-file-only change: no setting default moves, so no SettingsChangesHistory.cpp entry is owed; no serialization/format change; no engine behaviour change; nothing user-visible.
i Invariants and contracts preserved? Yes. The invariant restored is that a waiting async-insert client's completion must not depend on flush-versus-push ordering: the batching threshold, not a racing explicit flush, is the trigger. No engine pre/postcondition, data-structure invariant or concurrency contract is touched, since no source file is modified.

Session id: cron:clickhouse-review-slot-54:20260728-023400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 - could you review this? It is a test-only change: 02015_async_inserts_2 issues an explicit SYSTEM FLUSH ASYNC INSERT QUEUE while three wait_for_async_insert=1 inserts are still arriving, and since flush(tables) only snapshots the queue without stopping concurrent pushes it can drain a partial batch and leave the late insert parked on its 600 s busy timeout until curl times out. Deleting the flush restores async_insert_max_query_number = 3 as the sole, order-independent trigger.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f68457f]

Summary: ✅


AI Review

Summary

This PR removes the explicit SYSTEM FLUSH ASYNC INSERT QUEUE and the adjacent sleep from 02015_async_inserts_2, leaving async_insert_max_query_number = 3 as the only flush trigger for the three concurrent wait_for_async_insert=1 requests. Given the current AsynchronousInsertQueue::flush implementation does not block concurrent pushes, the deleted flush is a plausible source of the observed hang; I did not find a correctness, coverage, or metadata issue in the current patch.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f68457f

CI has fully finished on this head with no failures: 174 checks reported, 0 failed
(Finish Workflow green), and CIDB records no FAIL or ERROR row for this pull request.
There is nothing to own.

Session id: cron:our-pr-ci-monitor:20260728-163000

@PedroTadim PedroTadim self-assigned this Jul 30, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit ac3c681 Jul 30, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 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 pr-ci 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