Skip to content

Improve canceling queries in LimitByTransform and LimitBySortedStreamTransform - #106070

Merged
tiandiwonder merged 29 commits into
ClickHouse:masterfrom
arenadata:ADQM-4537
Jul 24, 2026
Merged

tiandiwonder merged 29 commits into
ClickHouse:masterfrom
arenadata:ADQM-4537

Conversation

@rvasin

@rvasin rvasin commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

Reduced cancellation latency for the positive forms of LIMIT BY (LimitByTransform, LimitBySortedStreamTransform): KILL QUERY and Ctrl+C now interrupt processing within a single chunk instead of waiting for the entire step to complete.

Version info

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

@rvasin

rvasin commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

@vdimir could you please assign can be tested label?

@tiandiwonder tiandiwonder self-assigned this May 28, 2026
@tiandiwonder tiandiwonder added the can be tested Allows running workflows for external contributors label May 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1683c9b]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue
Integration tests (amd_tsan, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue
BuzzHouse (amd_msan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue

AI Review

Summary

This PR adds intra-chunk isCancelled checks to LimitByTransform / LimitBySortedStreamTransform and replaces the old timing-based coverage with failpoint-driven integration tests for the positive LIMIT BY paths. The processor changes themselves look consistent and the earlier inline concerns appear addressed, but the new test helpers still have one reliability hole that can turn the intended regression into an integration-shard hang.

Findings

⚠️ Majors

  • [tests/integration/test_limit_by_transform_kill_query/test.py:86] Both failpoint helpers use async KILL QUERY, but the worker query and query_thread.join() are unbounded. If cancellation stops reaching the transform, the test does not fail within the helper's 60 s synchronization window; it can sit until the whole integration job times out, and exceptional paths can leave a stray query running on the module-scoped server. Add bounded timeouts for the worker query / join and do best-effort cleanup KILL QUERY on failure paths.
Final Verdict

Needs one more fix before merge: harden the new failpoint-based integration helpers so a cancellation regression fails promptly instead of hanging the shard.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 28, 2026
@tiandiwonder

Copy link
Copy Markdown
Contributor

please fix the two comments by clickhouse-gh first.

@tiandiwonder

Copy link
Copy Markdown
Contributor

It's a real problem having array join with limit, but the current fix only applies to limit. what I am thinking is a more complete fix for array join, including limit, filter, etc.

@rvasin

rvasin commented May 29, 2026

Copy link
Copy Markdown
Contributor Author

please fix the two comments by clickhouse-gh first.

@tiandiwonder please advice about the tests.
For both paths transformCommon and transformInOrder I have carefully selected the queries in such way what LimitByTransform is executed long time and other processors like ExpressionTranform are short. So when KILL QUERY works it always make existing in LimitByTransform transformCommon/transformInOrder, But I agree with clickhouse-gh that it;s not evident.
I have been trying to improve functional tests framework by adding function similar to wait_for_log_line which we already have in integration tests. But I think it's overkill for function tests.
In fact I have improved cancellation in PostgreSQLSource and other sources the approach is the following src/Processors/Sources/PostgreSQLSource.cpp

template<typename T>
Chunk PostgreSQLSource<T>::generate()
{
    LOG_TEST(getLogger("PostgreSQLSource"), "Generate a chunk from stream");

    /// Check if source was cancelled or completed
    if (is_completed.load() || isCancelled())
        return {};

Then in my integration test tests/integration/test_postgresql_kill_query/test.py

    node1.wait_for_log_line("Generate a chunk from stream")
    time.sleep(1)

    node1.query(f"KILL QUERY WHERE query_id='{query_id}' SYNC")

I am planning to remove the functional test for LimitByTransform and add new integration test.
In src/Processors/Transforms/LimitByTransform.cpp

void LimitByTransform::transformInOrder(Chunk & chunk)
{
    LOG_TEST(getLogger("LimitByTransform"), "exec transformInOrder");
    

Then in the integration test:

    node1.wait_for_log_line("exec transformInOrder")
    time.sleep(1)

    node1.query(f"KILL QUERY WHERE query_id='{query_id}' SYNC")

I think this the only way to make the tests 100% correct: when LimitByTransform start we send KILL QUERY.
Are you agree with this approach? I may quickly implement it.

If needed it's possible also track the exit message like:

    for (UInt64 row = 0; row < num_rows; ++row)
    {
        if (isCancelled())
        {
             LOG_TEST(getLogger("LimitByTransform"), "transformInOrder exit loop");
            stopReading();
            return;
        }

then in test:

node1.wait_for_log_line("transformInOrder exit loop")

But may be it's overkill too. Let me to know your opinion.

Ergus
Ergus previously requested changes May 29, 2026

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changelog describes the mechanism rather than the user-visible impact.

Maybe better something like:

Reduced cancellation latency for queries using LIMIT BY: KILL QUERY and Ctrl+C now interrupt processing within a single chunk instead of waiting for the entire LIMIT BY step to complete.

Both test cases end up calling transformCommon. The isCancelled() check added to transformInOrder is dead code from the test's perspective

@@ -74,11 +83,23 @@ void LimitByTransform::transformInOrder(Chunk & chunk)
UInt64 num_rows = chunk.getNumRows();
auto columns = chunk.detachColumns();

if (isCancelled())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check should probably be moved before the detachColumns because detachColumns() moves the entire column data out of chunk and into the local columns vector.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Ergus I think placing if (isCancelled()) after detachColumns() is correct. Because in case of cancellation we return empty chunk. This leads to has_output = false in ISimpleTransform::work(). And the taken chunk is freed when the local auto columns goes out of scope.

@@ -45,11 +42,23 @@ void LimitByTransform::transformCommon(Chunk & chunk)
UInt64 num_rows = chunk.getNumRows();
auto columns = chunk.detachColumns();

if (isCancelled())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Look at the last comment

cat2
FORMAT Null
SETTINGS max_block_size = 100000000, max_threads = 1, max_rows_to_read=0
" || exit 1

@Ergus Ergus May 29, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC in order requires an ORDER BY

You need an explicit ORDER BY whose columns are a prefix of the LIMIT BY columns like (untested):

SELECT number AS key
  FROM numbers(100000000)
  ORDER BY key          -- SortingStep → SortScope::Global, desc = {key}
  LIMIT 1 BY key        -- applyOrder called: hasPrefix({"key"}) = true-> in_order = true
  FORMAT Null
  SETTINGS max_block_size = 100000000, max_threads = 1

Even with ORDER BY key, there's a new problem: the SortingStep itself is a heavy operation on 100M rows and it also respects isCancelled(). The KILL QUERY issued immediately after wait_for_query_to_start is just as likely probably more likely to cancel inside the merge-sort merge phase than inside transformInOrder.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have replaced function test with integration test where I use ORDER BY now. and I issue KILL QUERY in the integration test right after entering into LimitByTransform::transformInOrder

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the integration test I have replaced it with:

SELECT
    number AS key1,
    number + 1 AS key2,
    number AS value
FROM numbers(100000000)
ORDER BY key1 ASC, key2 ASC
LIMIT 1 BY key1, key2
FORMAT Null
SETTINGS max_block_size=100000000, max_threads=1, max_rows_to_read=0

the LimitByTransform::transformInOrder runs for 4 seconds for this query on my 48 machine. So it's hard to increase LimitByTransform::transformInOrder run time for example to 30 seconds without increasing RAM consumption. In integration tests there is the RAM limit for 10 GB. I will see how it will run on GitHub CI (on my local runs it is running fine)..

@rvasin

rvasin commented May 29, 2026

Copy link
Copy Markdown
Contributor Author

The changelog describes the mechanism rather than the user-visible impact.

Maybe better something like:

Reduced cancellation latency for queries using LIMIT BY: KILL QUERY and Ctrl+C now interrupt processing within a single chunk instead of waiting for the entire LIMIT BY step to complete.

Thank you for the suggestion. I have updated the changelog.

Both test cases end up calling transformCommon. The isCancelled() check added to transformInOrder is dead code from the test's perspective

Yes. Thank you for noticing it. I have updated the query as explained in other threads.

@rvasin

rvasin commented Jun 5, 2026

Copy link
Copy Markdown
Contributor Author

@tiandiwonder do you have any questions/suggestions to this PR? It seems like all tests and checks were successfully passed.

@tiandiwonder

Copy link
Copy Markdown
Contributor

@rvasin please merge the current pr with latest master, thanks.

@rvasin

rvasin commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

@tiandiwonder I have resolved the merge conflicts. Could you restart the pipeline? I see Fast test and others were cancelled.

@rvasin rvasin changed the title Improve canceling queries in LimitByTransform Improve canceling queries in LimitByTransform and LimitBySortedStreamTransform Jun 17, 2026
@rvasin

rvasin commented Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

@tiandiwonder I have resolved merge conflicts. One failed test is not related.

@rvasin

rvasin commented Jul 2, 2026

Copy link
Copy Markdown
Contributor Author

@tiandiwonder do you have more suggestions for this PR?

@Ergus

Ergus commented Jul 2, 2026

Copy link
Copy Markdown
Member

@tiandiwonder I requested some changes a while ago, but the PR is assigned to you, so if you approve it it can go on without a new review/aprovel from me

@rvasin

rvasin commented Jul 2, 2026

Copy link
Copy Markdown
Contributor Author

@Ergus could you please confirm that all changes you requested where implemented? If not let me to know what is not yet implemented. I will try to implement it.

@rvasin
rvasin requested a review from Ergus July 2, 2026 17:51
@Ergus
Ergus dismissed their stale review July 13, 2026 09:51

@tiandiwonder took care of this PR. Not needed my approval anymore

@rvasin

rvasin commented Jul 20, 2026

Copy link
Copy Markdown
Contributor Author

@tiandiwonder please take a look at the pool request again.

finally:
node1.query(f"SYSTEM DISABLE FAILPOINT {fault_name}")

query_thread.join()

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.

Because this helper intentionally uses async KILL QUERY, a cancellation regression here will not be bounded by the 60 s SYSTEM WAIT FAILPOINT timeout: the worker query has no client timeout, and query_thread.join() can sit forever until the whole integration shard times out. The same pattern is duplicated in run_kill_query_failpoint_after_loop_test.

Please give the worker query and the join a bounded timeout (and assert the thread actually exited), and do a best-effort cleanup KILL QUERY on exceptional paths so a broken cancel path cannot turn this regression test into a shard hang.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 62/66 (93.94%) · Uncovered code

Full report · Diff report

@tiandiwonder
tiandiwonder added this pull request to the merge queue Jul 24, 2026
Merged via the queue into ClickHouse:master with commit 18de9db Jul 24, 2026
173 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 Jul 24, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@rvasin are there any other transforms that could also improve query cancellation?

@rvasin

rvasin commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor Author

@rvasin are there any other transforms that could also improve query cancellation?

@PedroTadim In my company I am assigned to make analysis (and improvements) of ClickHouse codebase for query cancellation because it's critical for our clients. I have done several pull requests for most of Sources which were critical (we had to restart ClickHouse to cancel query), some pull requests for transforms (not too critical used in most queries like ExpressionTranform) and output formats.

Here is my analysis related to Transforms only:

  1. High Impact (long-running, common queries, ClickHouse is blocked for minutes)
  • AggregatingTransform
  • SortingTransform / MergeSortingTransform
  • MergeJoinTransform
  • JoiningTransform / (due to HashJoin/GraceHashJoin)
  1. Medium Impact (ClickHouse is blocked for seconds)
  1. Lower Impact (shorter loops or less common)
  • TotalsHavingTransform
  • TTLTransform / TTLCalcTransform
  • TTLDeleteFilterTransform
  • TTLColumnAlgorithm / TTLDeleteAlgorithm / TTLUpdateInfoAlgorithm
  • PartialSortingTransform
  • CheckConstraintsTransform
  • LazyMaterializingTransform
  • FilterSortedStreamByRange
  • ReverseTransform
  • TotalsHavingTransform

Shelestov7 pushed a commit to Shelestov7/ClickHouse that referenced this pull request Aug 30, 2026
…istic

test_kill_query_during_output waited up to 30 s for a "Consume a chunk" log
line, slept a second and then killed the query. Its fixture read 20 M rows with
max_block_size = 20000000, which clamps numbers to a single stream, so the whole
2.51 GiB result was materialised as one chunk on one thread before the output
format was entered and that line was logged. Locally that takes 0.46-0.99 s; in
the failing job it took over 31 s under ThreadSanitizer and the test died before
it ever issued the KILL. 3 hits across 3 unrelated PRs in 30 days, 0 on master
in 90 days.

The wait also looks 10000 lines behind, so from the second run in a module it
matched the previous run's line and returned at once, leaving the KILL to land
while the next query was still building its block. 1 of 20 local runs never
entered MySQLOutputFormat::consume and passed anyway.

Replace the wall-clock window with a PAUSEABLE_ONCE failpoint in each output
format's row loop, the mechanism introduced in ClickHouse#106070 for this defect class, so
the fixture no longer has to be large and drops to 1000 rows. The pause sits
immediately after the per-row cancellation check, so an enabled failpoint cannot
hide a cancellation that is already visible, and the check on the next iteration
is what observes a KILL that arrived while the loop was parked.

Reporting QUERY_WAS_CANCELLED is not a sufficient oracle, because the
pipeline-level check in QueryStatus reports it too once the whole chunk has been
written: with the per-row check deleted the client still receives the same
error, only after all 1000 rows arrive. The tests therefore also assert that the
killed query stopped streaming. The MySQL test counts the rows an unbuffered
cursor received; the PostgreSQL test reads NetworkSendBytes instead, because
psycopg2 buffers a whole result set and PostgreSQLHandler::processQuery lets an
exception raised after the first DataRow escape without an ErrorResponse, so the
rows that arrived are not observable client-side there.

Validated with five mutant arms, each checked for build integrity by comparing
the recompiled object rather than the Build ID. Deleting the per-row
isCancelled() check fails both tests (1000 rows delivered instead of 6, and
117967 wire bytes instead of 0); deleting the pauseFailPoint call fails both on
the 60 s liveness guard. 100/100 runs pass at about 1.1 s each. The added
per-row compare costs 22.710 s against 22.743 s of user CPU over 20 M rows,
inside the run-to-run spread.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Improve canceling queries in LimitByTransform and LimitBySortedStreamTransform
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-improvement Pull request with some product improvements 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.

5 participants