Repository navigation
Improve canceling queries in LimitByTransform and LimitBySortedStreamTransform - #106070
Conversation
|
@vdimir could you please assign |
|
Workflow [PR], commit [1683c9b] Summary: ❌
AI ReviewSummaryThis PR adds intra-chunk Findings
Final VerdictNeeds one more fix before merge: harden the new failpoint-based integration helpers so a cancellation regression fails promptly instead of hanging the shard. |
|
please fix the two comments by clickhouse-gh first. |
|
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. |
@tiandiwonder please advice about the tests. 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. 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 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
left a comment
There was a problem hiding this comment.
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()) | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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()) | |||
| cat2 | ||
| FORMAT Null | ||
| SETTINGS max_block_size = 100000000, max_threads = 1, max_rows_to_read=0 | ||
| " || exit 1 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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=0the 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)..
Thank you for the suggestion. I have updated the changelog.
Yes. Thank you for noticing it. I have updated the query as explained in other threads. |
|
@tiandiwonder do you have any questions/suggestions to this PR? It seems like all tests and checks were successfully passed. |
|
@rvasin please merge the current pr with latest master, thanks. |
|
@tiandiwonder I have resolved the merge conflicts. Could you restart the pipeline? I see Fast test and others were cancelled. |
|
@tiandiwonder I have resolved merge conflicts. One failed test is not related. |
|
@tiandiwonder do you have more suggestions for this PR? |
|
@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 |
|
@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. |
@tiandiwonder took care of this PR. Not needed my approval anymore
|
@tiandiwonder please take a look at the pool request again. |
| finally: | ||
| node1.query(f"SYSTEM DISABLE FAILPOINT {fault_name}") | ||
|
|
||
| query_thread.join() |
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 62/66 (93.94%) · Uncovered code |
18de9db
|
@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:
|
…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.
Improve canceling queries in LimitByTransform and LimitBySortedStreamTransform
Changelog category (leave one):
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
26.8.1.63(included in26.8and later)