Skip to content

Fix flaky 04320_query_condition_cache_topk_correctness via deterministic data placement - #113011

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-flaky-04320-qcc-topk
Aug 10, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-flaky-04320-qcc-topk

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Related: #111492
Related: #104478

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):

Fix flaky test 04320_query_condition_cache_topk_correctness.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The test asserts that the first ORDER BY k ASC LIMIT 5 run under the TopK plan writes a query condition cache entry (count() > 0 over system.query_condition_cache). It failed with 0 on a TSan sequential run: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112958&sha=ab076f814382fccafac0dd27dbe5e152d7204619&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20sequential%2C%202%2F2%29 (no tracking issue exists yet; the CI rerun diagnosis passed 29/29, and the test has no direct-master failures because the failing variant is one day old).

Root cause. An entry is written only when at least one chunk is reduced to zero rows at the WHERE FilterStep (FilterTransform::writeIntoQueryConditionCache). Whether that happens depends on where the smallest w = 7 rows land relative to chunk boundaries and on the resulting __topKFilter threshold trajectory — and the placement was rand(). With an unlucky layout, every chunk keeps at least one surviving row, nothing is buffered, and the assertion reads 0. #111492 shrank the table from 1M rows (~123 chunks per scan) to 100k (~12 chunks), which raised the per-run probability of that from negligible to roughly 1 in a few hundred — reproduced locally with the pre-fix test on a release build: 2 of 300 runs wrote no entry. The same failure mode was seen once with the 1M-row version on a flaky-check job (2026-07-27, PR #110015), so the race was inherent; the row-count reduction only amplified it.

Fix. Make the QCC population deterministic by construction instead of probabilistic: place the five smallest w = 7 rows (k <= 4007) at the very front of the part and scatter every other row with a deterministic hash (intHash32) above the first 8192-row chunk. The first chunk then contains all five top rows, so PartialSortingTransform arms the threshold tracker at its final value (k = 4007) right after that chunk, and every later chunk deterministically loses all of its rows at the WHERE filter and is recorded as skippable (1436 of 1564 marks, vs the previous data-dependent 20–50%). This also sharpens the salt assertions: the granules skipped by the LIMIT 5 plan now always contain the rows the LIMIT 12 and DESC plans need, so any wrong cache-entry reuse is guaranteed (not just likely) to be caught. The reference output is unchanged.

Verification (with the CI-built binary of the failing run): the fixed test passes 30/30 against a local server and 10/10 with the failing run's randomized settings; the pre-fix test fails 2/300 with the exact 1 → 0 diff from the report.

…tic placement

The test asserts that the first `ORDER BY k ASC LIMIT 5` run under the TopK
plan writes a query condition cache entry (`count() > 0`). An entry is only
written when at least one chunk is reduced to zero rows at the `WHERE`
filter, which depends on where the smallest `w = 7` rows happen to land:
placement was `rand()`, so a run could get a `__topKFilter` threshold
trajectory under which every chunk kept at least one row and no entry was
written (2 of 300 runs in a local loop on a release build). #111492 made
this much more likely by shrinking the table from 1M rows (~123 chunks per
scan) to 100k (~12 chunks); the same mode had been seen once with 1M rows
on a flaky-check job before that.

Place the five smallest `w = 7` rows at the front of the part and scatter
every other row with a deterministic hash above the first chunk: the
threshold tracker arms at its final value (`k = 4007`) right after the
first chunk, and every later chunk deterministically empties at the `WHERE`
filter and is recorded (1436 of 1564 marks). Verified locally: 30/30 runs
pass, plus 10/10 with the failing run's randomized settings; the reference
output is unchanged.

Failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112958&sha=ab076f814382fccafac0dd27dbe5e152d7204619&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20sequential%2C%202%2F2%29
PR with the failure: #112958

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc056e6]

Summary: ✅


AI Review

Summary

This PR updates tests/queries/0_stateless/04320_query_condition_cache_topk_correctness.sql to replace randomized row placement with deterministic placement so the initial ORDER BY k ASC LIMIT 5 run reliably writes a query condition cache entry before the later salt/correctness checks execute. I did not find a correctness, safety, metadata, or evidence gap in the change: the new layout removes the probabilistic count() > 0 failure mode while still preserving the LIMIT 12 and DESC result checks that validate TopK cache-key separation.

Final Verdict
  • Status: ✅ Approve

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check, Stress test (arm_debug), is unrelated to this test-only change: it is the Logical error: 'Temporary part tmp_merge_all_1_1_1 already added' failure raised from MergeTreeData::optimizeDryRun racing a concurrent merge (TemporaryParts::add). It reproduces on master and on many unrelated PRs (e.g. #102499, #113089, #110437, #112704, #112083, #111842, #112141, #111619 within the last two weeks).

A fix is already in progress: #110916 ("Fix LOGICAL_ERROR in OPTIMIZE ... DRY RUN racing a concurrent merge").

Merged master into the branch to refresh CI.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update: the previously noted optimizeDryRun red has been replaced by two new stress-test reds on commit 143d963, both unrelated to this test-only change:

  1. Stress test (arm_debug) — Logical error: 'ColumnBLOB should be converted to a regular column before usage'. Known cross-PR failure, tracked in Logical error: ColumnBLOB should be converted to a regular column before usage (STID: 3059-3663) #113165; a fix is in progress in Do not marshal blocks of a local shard plan in a distributed query #111997.

  2. Stress test (arm_asan_ubsan, s3) — Hung check failed, possible deadlock found. The hung query is from 04010_text_index_incompelete_granules.sql (a different test): it is stuck for ~800 s in MergeTreeMarksLoader::loadMarks waiting on the async marks-load future (WaitMarksLoadMicroseconds ≈ 610 s) during skip-index analysis in MergeTreeDataSelectExecutor::filterPartsByPrimaryKeyAndSkipIndexes, while the loader thread slowly reads marks through the encrypted S3 cache under thread-fuzzer fault injection. The query has is_cancelled = 1, but the marks-load wait is not interruptible, and index analysis is not covered by max_execution_time. CIDB shows Hung check failed firing daily across dozens of unrelated PRs and on master itself.

@groeneai, investigate failure 2 (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113011&sha=143d963289028c262af645b2b433c3ee72620ff5&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29) and provide a fix in a separate PR — e.g. making the wait in MergeTreeMarksLoader::loadMarks interruptible by query cancellation. If a fix is already in progress, link it here.

I merged master (274 commits behind) and pushed to get a fresh CI run.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Confirmed, and this is a defect I already have the analysis for. Root cause, re-verified against master 91687a7d:

MergeTreeMarksLoader::is_canceled cannot interrupt an in-flight load. It has exactly one write site, ~MergeTreeMarksLoader (MergeTreeMarksLoader.cpp:104), and one read site, :348, checked once before loadMarksSync. So it only drops a task that is still queued in the pool. The destructor cannot run while the load is in progress either: the loader is a shared_ptr member of MergeTreeReaderStream (MergeTreeReaderStream.h:94) and the blocking call is marks_loader->loadMarks() (MergeTreeReaderStream.cpp:197). The waiter is an unconditional future.get() (MergeTreeMarksLoader.cpp:122-126), which is the WaitMarksLoadMicroseconds you measured.

The reachable channel is QueryStatus::is_killed (set in cancelQuery, ProcessList.cpp:592; observed via checkTimeLimit / throwIfKilled, :669-690). It is visible from the marks pool thread because scheduleFromThreadPoolUnsafe attaches the worker to the query's thread group through ThreadGroupSwitcher (threadPoolCallbackRunner.h). So the interruption point belongs in the loader, in the granule loop of loadMarksImpl (:252-272, plus the streaming branch at :219-226); the loader throwing is what releases the waiter's future.get(). Abandoning the wait on the waiter side does not help, because ~MergeTreeMarksLoader then blocks on the same load.

One correction to the diagnosis: index analysis is covered by max_execution_time, but only at part granularity. filterPartsByPrimaryKeyAndSkipIndexes calls query_status->checkTimeLimit() at the top of process_part (MergeTreeDataSelectExecutor.cpp:1064), and the marks load happens inside that same call, under filterMarksUsingIndex. The gap is intra-part rather than absent coverage, which keeps the fix narrow.

No fix is in progress yet, so I will send a separate PR for the interruption point and link it here. I am deliberately leaving finer-grained cancellation for index analysis as a whole out of that PR: it is a broader change and it overlaps a separate hang I am tracking, a cancelled merge(REGEXP('.+')) burning ~730 s in ReadFromMerge::createChildrenPlans with no cancellation point during QueryPlan::optimize.

Caveat worth stating up front: this removes the "ignores cancellation" half only. A genuinely slow load that is never cancelled can still exceed the hung-check window, so it will not by itself clear the Hung check failed class.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Fixing PR: #113436. As promised above, it only adds the interruption point: ReadBufferFromRemoteFSGather::readImpl now checks QueryStatus::is_killed before each buffer fill, opted in per construction site so that readers whose caller reports a read exception as a broken part keep todays behaviour. Finer-grained cancellation for index analysis as a whole is still out of scope.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check on commit 486d99e, Stress test (amd_tsan), is unrelated to this test-only change: it is the Logical error: '(isConst() || isSparse() || ...) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' assertion from IColumn::insertFrom inside HashJoin buildAdditionalFilter (STID 2508-30f6) — a mixed JOIN ON condition over a dictionary evaluated through a mismatched column type when join_use_nulls is enabled. It fires in most stress runs since 2026-08-04, after #112831 routed that shape onto the hash-join path.

A fix is already open: #113534, whose description names this exact STID. Once it merges, a re-run (or a master merge) should clear this red. Everything else on this PR is green, the AI review verdict is ✅, and there are no unresolved review threads.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dc056e6ed with master 89cdcdfb4 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 6cde32de1; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.67 MiB 687.65 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

6 translation units recompiled, 3 s compile time in total, 6 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Aug 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit 9e4792f Aug 10, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-flaky-04320-qcc-topk branch August 10, 2026 14:24
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
pull Bot pushed a commit to weiyilai/ClickHouse that referenced this pull request Sep 21, 2026
A query killed or detached while loading skip-index marks kept reading from
object storage for minutes afterwards, because nothing between the marks
loader and S3 observes QueryStatus::is_killed. Reported by alexey-milovidov
on ClickHouse#113011: a query from 04010_text_index_incompelete_granules.sql sat for
~815 s with is_cancelled = 1 and read_rows = 0, tripping the hung check.

In that run's hung_check.log the query thread waits on the marks-load future
during skip-index analysis while the marks pool thread is inside
ReadBuffer::next below MergeTreeMarksLoader::loadMarksImpl, in
ReadBufferFromRemoteFSGather -> CachedOnDiskReadBufferFromFile -> S3.
throwIfKilled and checkIfNotCancelled appear zero times in the gather,
cached, encrypted-file and file-view read buffers, and under the thread
fuzzer every buffer fill costs an injection sleep.

Two nearer candidates do not work. The loader's own is_canceled flag is
written only by ~MergeTreeMarksLoader, which cannot run while loadMarks() is
on the stack, so it can only drop a task still queued in the pool. And the
granule loop in loadMarksImpl runs at most 26 trivial iterations over a
~624 byte marks file in this carrier, while the whole wait sits inside one
reader->eof() several frames lower. The interruption point therefore has to
be in the read buffer.

ReadBufferFromRemoteFSGather::readImpl now calls throwIfKilled before
current_buf->next(). readImpl is the complete set of blocking-fill sites: it
has exactly two callers, both in nextImpl, and everything nextImpl does
before the first is non-blocking, so a check at the top of nextImpl would be
redundant. The short-forward-seek drain in seek() is covered transitively,
since ReadBuffer::ignore loops on next -> nextImpl -> readImpl. The throw
precedes the SwapHelper, so the buffer is never left partially advanced.

The check is gated on an opt-in ReadSettings flag that only
makeIndexReaderStream sets, on its own copy of the settings, so every other
read is byte-identical. That scoping is required rather than stylistic:
QUERY_WAS_CANCELLED is not in isRetryableException, so an unscoped throw
makes CHECK TABLE plus KILL delete a healthy part, and ATTACH plus KILL
rename one broken-on-start. The generic form of this change, ClickHouse#109785, had to
invent a thread-local blocker for exactly those reads.

The QueryStatusPtr is resolved in ReadPipeline::build on the calling thread
and threaded in, beside the existing query_id hoist that exists for the same
reason: gather creators run lazily and may execute on threadpool workers
with no query context, where tryGetQueryContext returns null and the check
would be silently inert.

The new test is deterministic via a PAUSEABLE failpoint placed inside the
opt-in branch, so reaching it also proves the marks reader asked for
interruptible reads: park the marks read, KILL, single-step exactly one fill
with SYSTEM NOTIFY FAILPOINT, then assert the read unwinds instead of
fetching another buffer. Removing only throwIfKilled, and removing only the
opt-in, each redden it with a distinct message.

Index-analysis cancellation granularity as a whole, and the experimental
use_reader_executor path, are deliberately out of scope. This removes the
"ignores cancellation" half only, so it does not on its own clear the hung
check class.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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