Skip to content

Make the query_id of 03652_threads_count_insert unique - #112853

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-03652-query-id-collision
Aug 1, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-03652-query-id-collision

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Related: #106671

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

03652_threads_count_insert.sh built its query_id as 03652_query_id_$RANDOM, drawing 4
times per run from bash's 15-bit $RANDOM (0..32767). When two of the 4 loop iterations draw
the same number they share one query_id, and every predicate of the test's system.query_log
filter is true of both INSERTs, so the later SELECT returns two rows instead of one. order by ALL prints the smaller first, which is the extra 1 above a 7 seen in CI. This is a test bug,
not a query_log defect: query_id uniqueness is enforced only among concurrently running
queries and the log is append-only history, so several rows per query_id are by design.

There is a second collision axis: current_database = currentDatabase() isolates executions
only when each gets a fresh database, while the stress arms pass a fixed --database. The fix
composes the id from the per-iteration loop variables (closing the within-run axis by
construction, with no randomness) plus a server generateUUIDv4 (closing the across-execution
axis).

Validation. The natural failure is roughly 1 in 11,000, so it was proven by forcing the
collision rather than by repetition: replacing $RANDOM with a constant makes the test fail
deterministically with the same diff class in maximal form, and adding only the loop-variable
component makes it pass again with zero randomness involved. The second axis reproduces with a
fixed --database and passes 5/5 with the fix. Randomized 50/50 run: 50 OK, 0 FAIL. No blanket
no-random-settings tag was added, since the mechanism is independent of the randomizer.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112680&sha=fa21e1fb571139f9ca1c573fd38bd6232eb50aa5&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29

Of the 13 CI failures in the last 90 days, 11 have this collision shape. One (#110015) is a
thread-count shortfall (7 becoming 4, not an extra line) and one is a server died during
cleanup, so the residual rate should fall to about 1 per 90 days rather than to zero.

The test built its query_id as 03652_query_id_$RANDOM, drawing 4 times per
run from bash's 15-bit $RANDOM (0..32767). When two of the 4 loop iterations
draw the same number they share one query_id, and every predicate of the
test's system.query_log filter is true of both INSERTs, so the later SELECT
returns two rows instead of one. order by ALL prints the smaller first, which
is the extra 1 above a 7 seen in CI: 11 of the 13 failures recorded in the
last 90 days have that shape, spread over 11 unrelated pull requests.

This is a test bug and not a query_log defect. query_id uniqueness is
enforced only among concurrently running queries, in ProcessList::insert, and
system.query_log is append-only history, so several rows for one query_id are
by design. My earlier fix in ClickHouse#106671 tightened this same filter, which lowered
the rate but could not help, because each predicate it added is also true of
both colliding rows.

There is a second collision axis. current_database = currentDatabase()
isolates executions only when each execution gets a fresh database, whereas
the stress arms pass a fixed --database, so one database serves many
executions and a repeat draw from an earlier execution matches as well.

The id is now composed from the per-iteration loop variables, which closes
the within-run axis by construction with no randomness involved, plus a
server-generated UUIDv4, which closes the across-execution axis.

The natural failure rate is roughly 1 in 11,000, so the mechanism was proven
by forcing the collision rather than by repetition: replacing $RANDOM with a
constant makes the test fail deterministically with the same diff class in
maximal form, and adding only the loop-variable component makes it pass again.
The second axis reproduces with a fixed --database, 1 pass and 2 failures in 3
runs, and passes 5 of 5 with the fix. Two mutations confirm each component is
load-bearing. Randomized 50/50 run: 50 OK, 0 FAIL. No blanket
no-random-settings tag was added, since the mechanism is independent of the
randomizer.

One of the 13 failures, on ClickHouse#110015, is a different mechanism: a thread-count
shortfall printing 4 instead of 7, with the same line count rather than an
extra line. It is deliberately not addressed here and is tracked separately,
so the residual rate should fall to about 1 per 90 days rather than to zero.

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

groeneai commented Aug 1, 2026

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

An independent reviewer read the resulting code cold, without the author's write-up, and a
second model re-reviewed the diff separately. Findings and verdicts:

# Finding Verdict
⚠️ The only provenance link to the superseded fix #106671 sat inside the leading HTML comment block, which GitHub does not render, so a reader of the rendered body saw the claim "my earlier fix lowered the rate but could not help" with no link to check it. Agreed, fixed. The link is now a rendered Related: line. Headers re-diffed against a freshly fetched upstream template and left byte-identical.
💡 The fix adds a fourth client round trip per iteration to obtain the UUID, and the test is not tagged long, so the 180s flaky-check cap applies to it. Agreed, noted, not changed. Measured cost 3.00s to 3.16s. The flaky-check jobs run this test in about 43s against the 180s cap, so the four extra spawns are roughly 1% of the cap. Adding long would be worse: it would exempt the test from a cap it comfortably passes and halve its flaky-check iterations.
💡 The internal note recorded the in-tree precedent for deriving a query_id from generateUUIDv4 as 7 sibling tests; re-derivation finds 11. Agreed, corrected internally. The figure appears in no published text and is load-bearing only as "the idiom is established", which 11 supports more strongly than 7.

The second model returned no findings on the diff.

Claims re-derived independently rather than taken from the author's notes, all confirmed:

  • Failure-shape census. Projecting the diff hunk out of every CI failure context for this
    test over 90 days gives 11 rows @@ -1,8 +1,9 @@ (the collision), 1 row @@ -1,8 +1,8 @@
    (Make stateless tests parallel-safe with per-test isolation #110015, the thread-count shortfall, a different mechanism), and 1 row with no hunk
    (Add OptimizeTrivialGroupByLimitPass #104473, server died in cleanup). This is what supports the statement that the residual
    rate falls to about 1 per 90 days rather than to zero.
  • The $RANDOM adjacency property the mechanism rests on. Reproduced on bash 5.2.21 over
    2,000,000 draws: 0 repeats at distance 1, 60 at distance 2, 67 at distance 3, against about
    61 expected per distance. Bash suppresses immediately repeated values, so only iteration pairs
    at distance 2 or more can collide, which is why the observed rate matches 3 pairs rather
    than 6.
  • That this is not a query_log defect. ProcessList::insert rejects a duplicate
    query_id only for a concurrently running query, and system.query_log.query_id is a plain
    String column with no uniqueness property, so several rows per id are by design. Materialized
    view pushes are logged to system.query_views_log, never to query_log.
  • That both components of the new id are load-bearing. The loop variables close the
    within-run axis by construction, since the four iterations are the four distinct
    (max_threads, max_insert_threads) pairs, with no randomness involved. The UUID is required
    for the across-execution axis, because a fresh database is created per test only when
    --database is absent, and the stress arms pass a fixed --database.
  • No competing fix. The one open pull request whose text matches this test name changes no
    file matching it. No open issue tracks this test, so no Closes: line is owed.
  • The reference file is byte-identical, the query_log filter is untouched, and no tag was
    added or removed, so no assertion was weakened and the test still asserts the same
    thread-count contract.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The natural collision is roughly 1 in 11,000, so it is forced instead: with :27 replaced by a constant query_id the test fails deterministically with the same diff class in maximal form (@@ -1,8 +1,14 @@, extra lines accumulating in the later blocks). The second axis reproduces deterministically as well, with a fixed --database over 3 runs.
b Root cause explained? Yes. :27 drew query_id from bash's 15-bit $RANDOM, 4 times per run. Two iterations drawing the same number share one query_id; every predicate of the query_log filter at :44-52 is true of both INSERTs, so the later SELECT returns two rows and order by ALL prints the smaller first. Several rows per query_id are by design: uniqueness is enforced only among concurrently running queries and the log is append-only history.
c Fix matches root cause? Yes. It removes the ambiguity in the id rather than tolerating it. Rejected as masking: LIMIT 1 or argMax over the ambiguous id, $RANDOM$RANDOM (still probabilistic), and a blanket no-random-settings tag (the mechanism is independent of the randomizer).
d Test intent preserved / new tests added? Yes. The changed test is the regression test. All four iterations, both settings, the three materialized views and the >= 6 bucketing are untouched; .reference is unchanged; the no-object-storage, no-parallel and no-fasttest tags are unchanged. No new test file.
e Both directions demonstrated? Yes. Axis 1: constant id fails, loop-variable component alone passes with zero randomness involved. Axis 2 with a fixed --database: 1 pass and 2 failures in 3 runs before, 5 of 5 passing after. Two mutations confirm each component is load-bearing: dropping the loop variables fails, and dropping generateUUIDv4 fails 4 of 5 runs on a fixed database. Randomized 50/50: 50 OK, 0 FAIL.
f Fix is general across code paths? Yes for this concern. Carriers: the four loop iterations (closed by the loop-variable component), repeated executions in a reused database (closed by generateUUIDv4), --test-runs N (same as the previous), and concurrent copies, which cannot occur because of no-parallel and because a live duplicate id is rejected anyway. The engine side needs no change. 38 sibling shell tests derive a query_id from $RANDOM and are deliberately left out of scope, one concern per PR; each needs its own analysis of whether its filter carries another discriminator.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A: a test-only id-uniqueness fix, so there are no datatypes, type wrappers or boundary values involved. The four (max_threads, max_insert_threads) pairs are the whole input space and all four run every time.
h Backward compatible? (maintainer-approved exception only) N/A: no src/ change, no settings, no SettingsChangesHistory.cpp entry, no serialization format, no protocol, no docs.
i Invariants and contracts preserved? Yes. The invariant is that a query_log lookup must be keyed on an id unique across every query that can satisfy the rest of the filter; it now holds on both axes. bash -n is clean, and ${CLICKHOUSE_DATABASE} is always set by shell_config.sh, so the id can never be malformed. Runtime cost of the four extra client round trips measured at 3.00s to 3.16s, negligible against the 600s per-test budget.

Session id: cron:clickhouse-review-slot-52:20260801-031800

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @jkartseva, could you review this? The test built its query_id from bash $RANDOM, four draws per run from a 15-bit range, so two of its four loop iterations sometimes shared one id and the system.query_log lookup returned two rows instead of one. The id is now derived from the per-iteration loop variables plus a server generateUUIDv4.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@PedroTadim PedroTadim self-assigned this Aug 1, 2026
@PedroTadim
PedroTadim enabled auto-merge August 1, 2026 11:01
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d7f23be]

Summary: ✅


AI Review

Summary

This PR makes the 03652_threads_count_insert.sh test stop keying its system.query_log lookup on a 15-bit bash $RANDOM value and instead uses a query_id composed from the database name, loop variables, and a server-generated UUID. I reviewed the current diff, the full test, comparable query_id-based tests, prior PR discussion, and the current Praktika results; I did not find a remaining correctness, compatibility, or metadata issue that warrants an inline review comment.

Final Verdict

✅ No blocking or major issues found in the current version of the PR.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 1, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit 980e255 Aug 1, 2026
179 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 Aug 1, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Following up on the out-of-scope note in the validation gate above (row f): I ran the promised
per-file analysis of the 38 sibling shell tests that derive a query_id from $RANDOM. The
result is negative, so I am not planning a follow-up PR for them.

Two measurements changed the picture.

First, entropy. Most of those siblings use $RANDOM$RANDOM, not a single $RANDOM. Sampling
300,000 concatenated values on bash 5.2.21 gives 299,929 distinct strings, so 71 duplicates,
which implies an effective space of about 6.3e8 rather than 32,768. And bash never emits the
same $RANDOM twice in a row: 600,000 draws produced 0 adjacent repeats against 18.3 expected
under independence, and that holds even with clickhouse-client spawns between the two draws
(0 equal pairs in 200,000 runs of that shape).

Second, what that implies per file. Counting only pairs of distinct query_id assignments that
share a literal template and are not adjacent single draws, 35 of the 38 have no collideable
pair at all, so a within-run collision is structurally impossible rather than merely unlikely.
The remaining three all use $RANDOM$RANDOM: 1 in 1.8e8 for 03143_prewhere_profile_events,
1 in 3.6e8 for 02151_hash_table_sizes_stats_joins, 1 in 1.1e9 for 00177_memory_bound_merging.
For calibration the same model predicts 1 in 10,923 for the four single draws this PR fixed, and
400,000 simulated runs of that pattern measured 1 in 10,526, with distance-1 pairs contributing
exactly 0.

CI history agrees. Across all 38 tests over 90 days there are 707 FAIL or ERROR rows and 109
reference diffs, and none is collision shaped. Grouping every diff by hunk line count, the
shapes are either equal counts (a value change), fewer lines, or one of three line increases
that I read individually: two on 01666_merge_tree_max_query_limit, where the added lines are
result rows from queries that should have been throttled and whose $RANDOM id is not in that
lookup, and one on 03269_explain_unique_ids, where the whole EXPLAIN json=1 plan tree is
replaced under distributed plan, ParallelReplicas. All three are on tests where a within-run
collision is impossible anyway. The dominant real failure modes in that set are host memory
limits on amd_asan_ubsan, distributed plan, parallel and Fast test (arm_darwin) timeouts.

The second axis this PR closed, a repeat draw matching an earlier execution because the stress
runner reuses a fixed database, leaves five candidates whose id embeds neither the database nor
the pid. Those five have 0 Stress check and 0 Upgrade check failures over 90 days, against 1,334
Stress check failures for other tests in the last 7 days alone, so the absence is real rather
than a gap in the query.

So the property that made this test worth fixing, four 15-bit draws and 11 observed collision
failures, is absent from the siblings. Changing 38 test files with no measured occurrence did not
look like a good trade, so I am leaving them alone.

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