Skip to content

Enable dynamic evaluation of whether a short-circuit function's argument should be lazily executed - #73776

Closed
lgbo-ustc wants to merge 28 commits into
ClickHouse:masterfrom
bigo-sg:auto_lazy_execute
Closed

lgbo-ustc wants to merge 28 commits into
ClickHouse:masterfrom
bigo-sg:auto_lazy_execute

Conversation

@lgbo-ustc

@lgbo-ustc lgbo-ustc commented Dec 24, 2024 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Lazy execution in short-circuit evaluation is not entirely cost-free. The maskedExecute method incurs additional overhead for filtering and expanding columns. In certain scenarios, this overhead can exceed the cost of fully evaluating the expression.

In this PR, we have added runtime performance profiling for functions. Based on the collected runtime performance data, we can evaluate the cost of using lazy evaluation versus direct full computation for a function, and dynamically select the execution strategy with the lower cost.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

CI Settings (Only check the boxes if you know what you are doing):

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64, release, debug

  • Run only fuzzers related jobs (libFuzzer fuzzers, AST fuzzers, etc.)
  • Exclude: AST fuzzers

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

@lgbo-ustc
lgbo-ustc force-pushed the auto_lazy_execute branch 3 times, most recently from 2a7cd69 to 04e6b79 Compare December 24, 2024 07:20
@lgbo-ustc

Copy link
Copy Markdown
Contributor Author

Performance test

Use AdaptiveExpressionActions

SELECT (a > 1) AND ((a + b) > 1) AND ((a + (2 * b)) < 4000)
FROM
(
    SELECT
        moduloOrZero(rand(), 1000) AS a,
        moduloOrZero(rand(), 1000) AS b
    FROM numbers(10000000)
)
FORMAT `null`
SETTINGS max_threads = 8

Query id: a0ad64fa-a6cf-4752-8f8b-3039b5da5f0f

Ok.

0 rows in set. Elapsed: 0.054 sec. Processed 10.00 million rows, 80.00 MB (186.11 million rows/s., 1.49 GB/s.)
Peak memory usage: 4.02 MiB.
SELECT (a > 1) AND ((a + b) > 1) AND ((a + (2 * b)) < 4000)
FROM
(
    SELECT
        moduloOrZero(rand(), 1000) AS a,
        moduloOrZero(rand(), 1000) AS b
    FROM numbers(10000000)
)
FORMAT `null`
SETTINGS max_threads = 8, short_circuit_function_evaluation = 'force_enable'

Query id: 19fb7cf7-a8e3-4ef4-ad8b-1bca855e8901

Connecting to localhost:9000 as user default.
Connected to ClickHouse server version 25.1.1.

Ok.

0 rows in set. Elapsed: 0.052 sec. Processed 10.00 million rows, 80.00 MB (193.11 million rows/s., 1.54 GB/s.)
Peak memory usage: 4.01 MiB.

Use ExpressionActions

SELECT (a > 1) AND ((a + b) > 1) AND ((a + (2 * b)) < 4000)
FROM
(
    SELECT
        moduloOrZero(rand(), 1000) AS a,
        moduloOrZero(rand(), 1000) AS b
    FROM numbers(10000000)
)
FORMAT `null`
SETTINGS max_threads = 8, short_circuit_function_evaluation = 'enable'

Query id: 5d37dccd-31ce-485d-ae13-29f7d69a9856

Connecting to localhost:9000 as user default.
Connected to ClickHouse server version 25.1.1.

Ok.

0 rows in set. Elapsed: 0.053 sec. Processed 10.00 million rows, 80.00 MB (190.23 million rows/s., 1.52 GB/s.)
Peak memory usage: 4.01 MiB.
SELECT (a > 1) AND ((a + b) > 1) AND ((a + (2 * b)) < 4000)
FROM
(
    SELECT
        moduloOrZero(rand(), 1000) AS a,
        moduloOrZero(rand(), 1000) AS b
    FROM numbers(10000000)
)
FORMAT `null`
SETTINGS max_threads = 8, short_circuit_function_evaluation = 'force_enable'

Query id: 88c8f29f-34c5-4890-9702-64a0d0e69b1e

Ok.

0 rows in set. Elapsed: 0.128 sec. Processed 10.00 million rows, 80.00 MB (78.40 million rows/s., 627.22 MB/s.)
Peak memory usage: 4.01 MiB.

@lgbo-ustc lgbo-ustc changed the title Disable lazy executed expression action based on execution cost adaptivly Disable lazy execution of expression actions in short circuit execution adaptively Dec 24, 2024
@alexey-milovidov

Copy link
Copy Markdown
Member

Please fix the conflicts.

@lgbo-ustc
lgbo-ustc force-pushed the auto_lazy_execute branch 2 times, most recently from 0021b5b to 9e439b1 Compare December 31, 2024 03:12
@lgbo-ustc

Copy link
Copy Markdown
Contributor Author

Please fix the conflicts.

Done

@lgbo-ustc
lgbo-ustc force-pushed the auto_lazy_execute branch 2 times, most recently from 78d4c14 to 1f4c842 Compare February 17, 2025 07:53
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Feb 17, 2025
@clickhouse-gh

clickhouse-gh Bot commented Feb 17, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a69fbca]

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Feb 17, 2025
@lgbo-ustc
lgbo-ustc force-pushed the auto_lazy_execute branch 6 times, most recently from 39fefaa to b7a3fc8 Compare March 5, 2025 06:50
@lgbo-ustc lgbo-ustc changed the title Disable lazy execution of expression actions in short circuit execution adaptively Enable dynamic evaluation of whether a short-circuit function's argument should be lazily executed Mar 5, 2025
@lgbo-ustc

lgbo-ustc commented Mar 5, 2025 •

Copy link
Copy Markdown
Contributor Author

The scalar2 performance test runs slower because of the large actions DAG and the significant time spent on ActionsDAG::clone for each processor.
image

ActionsDAGPtr is removed in #65414

@lgbo-ustc
lgbo-ustc force-pushed the auto_lazy_execute branch 2 times, most recently from b8848ae to 98b2359 Compare March 6, 2025 01:02
@lgbo-ustc

Copy link
Copy Markdown
Contributor Author

The result is promising
image
image

@lgbo-ustc
lgbo-ustc force-pushed the auto_lazy_execute branch from ecc8e6c to af54d6e Compare March 6, 2025 07:07
@lgbo-ustc

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov I think this PR is almost ready, could anyone review it?

@rschu1ze

Copy link
Copy Markdown
Member

@lgbo-ustc This PR adds a lot of complex logic in central places. Before reviewing it, can you please explain the background and implementation in more detail?

@lgbo-ustc

Copy link
Copy Markdown
Contributor Author

The short-circuit evaluation function can perform lazy evaluation on parameter expressions. While the original intention might have been to avoid exceptions caused by computing invalid data, lazy evaluation can also be used to improve computational performance. For example, in the expression and(e1, e2), if e1 can filter out the majority of the data, applying lazy evaluation to e2 means that e2 only needs to compute a small portion of the data. However, lazy evaluation does not always lead to an overall performance improvement. Lazy evaluation incurs additional performance overhead, including identifying which rows need to be computed and then expanding the data back to the original number of rows. Lazy evaluation is only beneficial when the following condition is met:

$$ Cost_{additional} + Cost_{remainingRows} < Cost_{totalRows} $$

Where $Cost_{additional}$ is the additional cost with lazy evaluation, $Cost_{remainingRows}$ is the cost on the remaing data after filter out the unnecessary rows, $Cost_{totalRows}$ is the cost with all input rows computed.

Therefore, we generally do not enable short-circuit evaluation for performance improvement. This PR aims to enhance short-circuit evaluation so that it can automatically determine whether an expression is worth evaluating lazily. To achieve this, we have made the following modifications.

During runtime, we collect statistics for each necessary function, including its execution time(denoted as $elapsed_{total}$), the number of rows processed(denoted as $rows_{executed}$), and the additional overhead required for lazy evaluation(denoted as $elapsed_{additional}$). An optional profile argument is added in Function::execute

ColumnPtr execute(const ColumnsWithTypeAndName & arguments, 
    const DataTypePtr & result_type,
    size_t input_rows_count,
    bool dry_run,
    FunctionExecutionProfile * profile = nullptr) const;

Three shor-circuit functions(and/or/multiIf) that require additional special handling. In these functions, we need to monitor the additional overhead introduced by lazy evaluation. So far, the overhead introduced by this statistical collection has not caused noticeable performance degradation.

Based on the above statistics, we use the following method to determine whether to apply lazy evaluation to an expression.

$$ (elapsed_{total} - elapsed_{additional}) / rows_{executed} * rows_{input} < elapsed_{total} $$

If the above condition is false, it is deemed not worthwhile to apply lazy evaluation to the expression. Otherwise, lazy evaluation should be applied. This is done in AdaptiveExpressionActions::identifyNonBeneficialLazyActions. AdaptiveExpressionActions::identifyNonBeneficialLazyActions will be executed periodically, updating the scheduling of lazy expressions based on the latest statistical data.

@SmitaRKulkarni SmitaRKulkarni self-assigned this Apr 18, 2025
@clickhouse-gh

clickhouse-gh Bot commented May 20, 2025

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2025

Copy link
Copy Markdown
Contributor

Dear @SmitaRKulkarni, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@SmitaRKulkarni

Copy link
Copy Markdown
Member

@lgbo-ustc : Sorry for the delay. I will review this PR. Looks like we have lot of conflicts, could you please resolve them ?

@alexey-milovidov

Copy link
Copy Markdown
Member

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @SmitaRKulkarni @lgbo-ustc — I rebased this branch onto the current master and reworked it where the interfaces have changed, so the conflicts are resolved: #114734

The branch was ~17 months behind and 27 files conflicted, so it is more than a mechanical merge. The author's commits are preserved; the notable changes on top of them:

  • enable_adaptive_short_circuit_lazy_execution no longer travels through the ExpressionStep/FilterStep constructors, their serialization, the planner and the QueryPlan/Optimizations suite. It is a field of ExpressionActionsSettings, next to enable_lazy_columns_replication, which is where transformPipeline already reads its settings from. That removes ~20 files from the change (27 changed files instead of 42) and all the signature ripple that was causing most of the conflicts.
  • ExpressionActions::execute and executeOnColumns stay const. The free executeAction became a member with three virtual hooks (shouldExecuteLazily, executeFunction, finalizeBlockExecution) which AdaptiveExpressionActions overrides.
  • The FunctionExecutionProfile plumbing follows the current IExecutableFunction chain, including executeWithoutReplicatedColumns and the dry_run argument of ColumnFunction::reduce, neither of which existed when the branch was written.
  • is_no_except is computed only when the setting is enabled, so nothing changes for the default path.

Verified locally: 04893_adaptive_short_circuit_execution matches the author's reference output, the adaptive decisions do fire, the lazy execution of arguments which can throw (intDiv) is preserved, and the first query of the new performance test goes 0.113 s -> 0.063 s.

This PR is left open — please decide whether to continue here (the branch is in a fork with maintainer edits disabled, so I could not push the resolution to it) or to review the rebased one.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #114734, which rebases and reworks this change on the current master. The original fork has maintainer edits disabled, so its conflicts cannot be resolved and pushed here. Thanks @lgbo-ustc for the original implementation.

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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants