Skip to content

Assert the stop itself instead of the clock in the distributed-plan early-stop tests - #117764

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-04891-05024-clock-free-oracle
Sep 20, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-04891-05024-clock-free-oracle

Conversation

@groeneai

@groeneai groeneai commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115360

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

04891_distributed_plan_limit_early_stop and 05024_distributed_plan_limit_early_stop_idle_sink
decided PASS/FAIL by elapsed time. A satisfied LIMIT must stop the upstream distributed-plan
stages, so a correct run finished in seconds while an unstopped run kept a sleepEachRow scan going
and tripped the query's own max_execution_time = 25. The cap therefore fired on any run that was
merely slow: every sighting overshot it by 0.3%-2.6% and was green on rerun.

Raising the cap is not the fix, because the correct-run tail is host contention and unbounded in
wall clock. So the tests now assert the propagation. Each exchange endpoint traces the action it
takes when the stop reaches it, and both halves are required for every stream between the LIMIT
and the sleeping scan: the sink closing its input, and the source sending NoMoreDataNeeded one hop
upstream. The expected stream set comes from EXPLAIN PLAN distributed = 1 and the pinned bucket
counts; max_execution_time becomes a 300 s backstop, as in 04335_distributed_plan_cancel.sh.

The oracle keys on the close, not on the packet's receipt, because the receipt log predates the
fixes these tests guard and would also be satisfied by the regressed code. It matches per stream,
not per exchange, because each bucket is an independently idle endpoint and
ScatterByPartitionTransform keeps the scan alive while any one output is unfinished. A stream that
runs out of data produces no source-side action, so normal completion cannot pass for an early stop.

src/ gains three LOG_TRACE lines inside branches that already ran, no new state.

Requested on #115360, where I said I would use PAUSEABLE_ONCE failpoints at these sites. Log lines
replace them: a name-keyed failpoint cannot tell the streams of one query apart, and per-stream
identity is what catches a single stuck bucket. It also adds no failpoints to the exchange sinks and
needs no no-parallel.

Validation matrix

Each row is a separate build; each server's buildId() was asserted against its binary's Build ID.

tree contains 04891 05024
this PR both fixes PASS 5.41 s PASS 3.29 s
649a4ebd10fc577^ 04891's fix, not 05024's PASS 8.48 s RED 101.6 s, 18 of 21 streams never stopped
dd3d060e23c4846^ neither fix RED 201.5 s, both arms RED 101.2 s, all 21 streams

649a4ebd10fc577^ is the primary control: the instrumentation applies cleanly there, so 04891
passing while 05024 fails separates the mechanism from the oracle. The three streams that did stop
are the gather directly below the LIMIT, the only endpoint still active because it delivered the
row, so a per-exchange or count-based oracle would have been satisfied by those three. At
dd3d060e23c4846^ no log line has a host branch to port onto, so src/ was left pristine there;
the receipt log fires for 3 streams while the close log cannot fire at all, which is why the oracle
keys on the close.

Clock independence: CPU load could not manufacture a slow run on a 384-core box, so the sleep was
moved to the join's build side, which a satisfied LIMIT cannot skip. That query is correct and
takes 36.1 s. At max_execution_time = 25 it gives Code: 159 ... elapsed 25000.147 ms ... While executing ReadFromDistributedPlanSource, the signature of every CI sighting; at 300 it
returns the right answer with every expected stream stopped.

Other runs: --test-runs 50 on both tests with randomization on, 100/100 green with zero variation
in the expected stream set; --test-runs 16 -j 8 self-concurrent, 32/32 green, which is why neither
needs no-parallel; regression sweep over distributed_plan* and distributed_shuffle*,
53 green. Corrupting one format-string literal turns them red, and only the arm whose transport it
belongs to, so a reworded message fails loudly rather than vacuously.


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

…an oracle on the stop itself

04891_distributed_plan_limit_early_stop and
05024_distributed_plan_limit_early_stop_idle_sink decided PASS/FAIL by elapsed
time: a satisfied LIMIT must stop the upstream distributed-plan stages, so a
correct run finished in seconds while an unstopped run kept a sleepEachRow scan
going and tripped the query's own max_execution_time = 25. The cap therefore
fired on any run that was merely slow, which is what CI produces under
parallel-suite load, and every recorded failure overshot the cap by 0.3% to 2.6%
and was green on rerun. A passing run has been measured at 40.2 s, so no
constant threshold separates the two cases.

The tests now assert the propagation instead. Each exchange endpoint traces the
action it takes when the stop reaches it, and both halves are required for every
stream between the LIMIT and the sleeping scan: the sink closing its input and
the source sending NoMoreDataNeeded one hop upstream. The expected set of streams
is derived from EXPLAIN PLAN distributed = 1 and the two pinned bucket counts,
and the receipt of the packet is deliberately not part of the oracle - it
predates the fixes these tests guard, so an oracle keyed on it would also be
satisfied by the regressed code. A stream that ends by running out of data
produces no source-side action, so a normal completion cannot pass for an early
stop. max_execution_time becomes a 300 s backstop against a hang.

Three LOG_TRACE lines are added inside branches that already ran, so that the
in-memory transport is as observable as the streaming one, which already logs
both halves. Both tests move from .sql to .sh because the assertion needs a
captured query_id and a two-step log join: worker tasks log under their own
query_id and are only reachable through initial_query_id, which system.text_log
does not have.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 2, 2026
@groeneai

groeneai commented Sep 2, 2026

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

Pre-publication review by an independent model (engine: codex; 0 findings), plus my own cold review
of the resulting tree, which raised 3 nits and no blocker or major.

# Sev Finding Verdict Evidence / action
1 💡 InMemoryExchange::getLog returns LoggerPtr by value, so every call copies a shared_ptr even when trace is off, because LOG_IMPL binds the logger before testing the level (DistributedPlanExecutor.cpp:281) AGREE, not blocking const LoggerPtr & would be free and would match the sibling accessor added beside it. Both call sites are once-per-stream stop paths, so there is nothing to measure.
2 💡 The assertion queries scan system.text_log for a whole day without pinning max_threads = 0, which 03096_text_log_format_string_args_not_empty.sh does pin, with the comment that a one-thread scan under TSan is too slow AGREE, not blocking 04512_distributed_limit_no_more_packets_race.sh runs the same full-day scan with only max_rows_to_read = 0 and is accepted in CI, so the cost is precedented rather than measured, against a 5.4 s healthy runtime. I will add the pin if you would rather have it.
3 💡 The oracle proves the stop propagates, not that it is prompt: max_execution_time = 300 sits above the un-stopped scan time, so a stop arriving only after the scan would still show every expected trace DISAGREE Both remedies are already closed. A tighter cap is the flakiness this PR removes, and no constant separates a correct slow run from an incorrect one. A row-count sentinel was ruled out on #115360 with a mechanism: producers legitimately run ahead behind 16 MiB of sink buffering, and local task counters do not roll up to the initiating query. For 05024 nothing flows after the first block, so a late stop degenerates into no stop and still reddens, which is what 649a4ebd10fc577^ measures with 18 of 21 streams missing.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding.

Also verified so a reviewer does not have to: both .sh files are mode 755, and no tracked file
outside tests/queries/0_stateless/ names either test, so the .sql to .sh rename breaks no CI
list.

Session id: cron:clickhouse-review-slot-10:20260902-183400

@clickhouse-gh clickhouse-gh Bot closed this Sep 2, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [da64f0b]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR replaces the wall-clock oracle in 04891 and 05024 with log-based assertions that the stop propagates through each expected exchange stream, and adds the three LOG_TRACE hooks needed to observe the local and streaming stop paths. I reviewed the current diff, the touched C++ files, the new shell tests, and all prior discussion/threads; the earlier stale-query_id issue is fixed in the current head, and I do not see any unresolved correctness, coverage, or PR-metadata problem.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit da64f0b.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 80.50% 80.50% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? The flake is a ~15 ppm host-timing event and is deliberately not chased. What reproduces on demand is the defect being fixed: one correct early-stopping query gives Code: 159 ... elapsed 25000.147 ms ... While executing ReadFromDistributedPlanSource under the old 25 s cap and returns the right answer in 36.1 s under the new backstop. The regression each test guards reproduces on that test's own pre-fix tree.
b Root cause explained? The oracle was the initiator's wall clock (checkCancelled() -> QueryStatus::checkTimeLimit()), and the correct-run tail is host contention, so it is unbounded. Passing runs have been measured at 40.2 s, 26.2 s and 36.1 s, all above the 25 s cap.
c Fix matches root cause? The clock stops being the oracle; the propagation becomes the oracle, and max_execution_time is demoted to a 300 s hang backstop. Deliberately not the band-aid of raising the cap, which no constant can fix.
d Test intent preserved / new tests added? Preserved and strengthened. Each test still reddens on its own pre-fix tree, and now also catches a single stuck bucket. Every pinned setting and comment survives except max_execution_time; no-fasttest and no-old-analyzer kept verbatim.
e Demonstrated in BOTH directions? Yes, on four builds with each server's buildId() asserted against its binary. 649a4ebd10fc577^: 05024 RED 101.6 s, 04891 still PASS. dd3d060e23c4846^: 04891 RED 201.5 s on both arms, 05024 RED. This PR: both PASS, re-run as a paired control on the same server-config recipe.
f General across CODE paths? All four propagation carriers covered: streaming sink and source, in-memory sink and source. 04891's local arm drives the in-memory pair, its remote arm and 05024 drive the streaming pair.
g Generalizes across INPUTS? Not a data-typed change. The relevant matrix is the exchange topology, and the expected set is derived from the pinned bucket counts rather than hardcoded to one shape: 12 streams over 2 exchanges for 04891, 21 over 3 for 05024. Verified across both transports, both arms, 180 runs, 3 trees.
h Backward compatible? No setting default changes, so no SettingsChangesHistory.cpp entry; no serialization, on-disk format or wire change. Log statements only.
i Invariants and contracts preserved? Each LOG_TRACE is the first statement inside an existing guard, before the action: no reordering, no new branch, no early return, no new state, no lock taken or released. The two accessors are const and read members never mutated after construction, which is why they need no lock.

Other runs: --test-runs 50 on both tests with randomization on, 100/100 green with zero variation in
the expected stream set; --test-runs 16 -j 8 self-concurrent, 32/32 green, which is why neither test
needs no-parallel; --test-runs 24 -j 24 under CPU load, 48/48 green; regression sweep over
distributed_plan* and distributed_shuffle*, 53 green. various_checks.sh and check_cpp.sh from
the repo root produce zero output bytes, and shellcheck is clean on both new .sh files.

Controls: corrupting one format-string literal turns both tests red, per arm, so a reworded message
fails loudly rather than vacuously. Correlating the worker rows on query_id instead of
initial_query_id returns 0 rows, and applying current_database = currentDatabase() to them also
returns 0, so the two-step join is required and the database predicate must not touch worker rows.
Streams that end by running out of data show a normal completion and neither stop action, so benign
end-of-stream is excluded by the per-stream conjunction rather than by new state.

Note on the design: #115360 named PAUSEABLE_ONCE failpoints at the two sink-side input.close()
sites. Those two sites are instrumented here, as LOG_TRACE rather than failpoints, and their
source-side counterparts complete the per-stream conjunction. A name-keyed one-shot boolean cannot
distinguish the several streams of one query, so the LIMIT-adjacent hop consumes it and the
assertion goes vacuous, and it would have keyed on the receipt of the packet rather than on the
propagation.

Not done, and flagged rather than claimed: the tests were verified on a debug build only, not on a
sanitizer build. The assertions are presence-based, so a level or build difference fails loudly.

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @davenger @KochetovNicolai, could you review this? 04891 and 05024 decided PASS/FAIL by elapsed time, so a merely slow host turned them red; they now assert the backward stop itself, requiring both halves on every exchange stream between the LIMIT and the sleeping scan (the sink closing its input, the source sending NoMoreDataNeeded), which needed three LOG_TRACE lines inside branches that already ran.

@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit da64f0b2f81501557a04aad7b49607aac983358a with master failed: RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes W….

See the job log for details.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c42c017

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Docs examples / Documentation examples trunk-side, and not reachable from this diff, which touches no documentation: 2105 of 2226 examples are ok and the one unexpected failure is Function/timeSeriesPrometheusValueToString#0, whose documented output box is one character wider than the box the server actually prints. First sighting is 2026-09-02 21:10:17Z, and over 30 days the signature is 68 rows across 62 distinct pull requests with 7 true-master trees, every one of them inside that window #117789 (external, open), which deletes src/Functions/TimeSeries/timeSeriesPrometheusValueToString.cpp and with it the mis-padded example

Session id: cron:our-pr-ci-monitor:20260903-040000

Both tests identify their own log rows by a query id built from
CLICKHOUSE_TEST_UNIQUE_NAME, which is only unique per database, and then scan
system.query_log and system.text_log from yesterday(). A run can be given a fixed
database for a whole pass over the suite (ci/jobs/scripts/stress/stress.py passes
--database=test_{i} for some of its workers), and a directly executed .sh defaults
to "test" (tests/queries/shell_config.sh:8), so the id repeats and an earlier run's
rows can answer for the current one.

That is a green-while-broken hazard rather than a cosmetic one. max_execution_time
is only a 300s backstop now, so a run whose stop never propagates still returns its
row, which leaves the log assertion as the only thing that can catch it. Measured on
a pinned database with the probe table cut to a single block, so that nothing needs
stopping: the oracle printed "stop propagated on every expected exchange stream" for
both arms and stdout was byte-identical to the reference, i.e. reported OK. The same
run in a fresh database printed MISMATCH on all 12 streams, and with a per-run id it
prints MISMATCH even with the earlier rows present.

Append random_str 8 to the id, as in
01710_projections_partial_optimize_aggregation_in_order.sh.
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0d96ede

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation flaky, and reproducing on master rather than on this branch: the recorded CANNOT_SCHEDULE_TASK is lost and the client gets Code: 1000 ... peer closed connection where 439 is expected. Failed 0 out of 3 reruns. Breadth 81 rows / 58 pull requests / 14 true-master runs in 30 days since a 2026-08-09 onset, and neither failing test file is in this branch's diff #118390 (mine, open) plus #118417 (external, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky, same run and same class as the row above: reenqueue fault handled: 0 instead of 1, i.e. the injected recordFailure log line is absent. Failed 0 out of 3 reruns. Breadth 73 rows / 50 pull requests / 9 true-master runs in 30 days #118417 (external, open), which covers both halves of this defect; #105942 (external, open) is the runner-level class fix on top

Session id: cron:our-pr-ci-monitor:20260908-120121

Both conflicts are modify/delete on the two tests this branch converts from
`.sql` to `.sh`: master dropped their `no-old-analyzer` tag when it removed the
old-analyzer test mode, while this branch deletes the `.sql` files. Resolved by
keeping the deletion and carrying master's tag change into the `.sh`
replacements, so neither test names a tag that no longer exists.

The two source hunks auto-merged. Their anchors survived master's exchange
rework: the `no_more_data_needed` early return in `StreamingExchangeSink` and
the `isReaderDetached` / `detachReader` sites of the in-memory exchange source
are all still there, and master added no trace of its own at any of them, so the
oracle still has to rely on the lines this branch adds.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - da64f0b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: 176 checks, 153 pass, 20 skipped, 2 failed,
aggregator complete, and nothing left running except CH Inc sync. The last real check completed at
17:37:18Z, well past the 20 minute buffer the CI database needs.

Check / test Reason Owner / fixing PR
Build profile diff infra, nothing tested: has_pr_data raised RuntimeError: CI logs cluster query failed on the binary_sizes read and aborted the job before any comparison ran #120121 (mine, open), which turns a transient cluster read failure into a skipped comparison instead of a failed one
CH Inc sync still pending: the private mirror sync does not complete on a fork CH Inc sync (private, not actionable by me)

PR aggregate the rows above rather than adding a failure of their own.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117764&sha=da64f0b2f81501557a04aad7b49607aac983358a&name_0=PR

Session id: cron:our-pr-ci-monitor:20260915-190256

Merged via the queue into ClickHouse:master with commit 2f7c7d1 Sep 20, 2026
175 of 177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot added comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... and removed comp-testing Test content only (no production code). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

4 participants