Skip to content

Add table function waitUntil - #94695

Closed
JasonLi-cn wants to merge 15 commits into
ClickHouse:masterfrom
JasonLi-cn:feature/wait_util
Closed

JasonLi-cn wants to merge 15 commits into
ClickHouse:masterfrom
JasonLi-cn:feature/wait_util

Conversation

@JasonLi-cn

@JasonLi-cn JasonLi-cn commented Jan 21, 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):

  • Users can now block execution until a condition becomes true using the new waitUntil function.

Description

This PR introduces a new table function waitUntil, which provides a controlled way to repeatedly evaluate a boolean condition expression or scalar subquery until the condition is satisfied or a maximum number of attempts is reached.
Between evaluation attempts, the function blocks execution by sleeping for a configurable interval and returns a single-row result indicating whether the condition was satisfied within the allowed attempts.
The function is primarily intended for testing and control-flow scenarios, rather than production query workloads.

Function Overview

  • The waitUntil table function behaves as follows:
  • Accepts a condition that evaluates to a single boolean value
  • Repeatedly evaluates the condition up to a configurable maximum number of attempts
  • Sleeps between attempts to avoid busy-waiting
  • Returns immediately once the condition is satisfied
  • Returns a failure result if the condition is not satisfied within the allowed attempts
    The function always returns exactly one row, making it suitable for use in SQL-level synchronization and test assertions.

Syntax

waitUntil(condition[, max_tries[, sleep_seconds]])

Arguments:

  • condition
    An expression or scalar subquery that evaluates to a single boolean value
  • max_tries (optional, default: 10)
    Maximum number of condition evaluation attempts
  • sleep_seconds (optional, default: 1)
    Number of seconds to sleep between attempts (fractional values supported)
Return Value

The function returns a single-column table:

Name Type Description
result UInt8 1 if the condition is satisfied within max_tries, otherwise 0

Exactly one row is returned.

Examples

  1. Literal expression
SELECT *
FROM waitUntil(false, 3);

The condition is never satisfied, and the function returns 0 after the specified number of attempts.

  1. Expression evaluation
SELECT result
FROM waitUntil('2025-12-22 19:00:00' + interval 1 hour < now(), 3, 2);

If the condition is satisfied during the first evaluation, the function returns immediately without additional waiting.

  1. Scalar subquery
SELECT result
FROM waitUntil((SELECT count() > 10 FROM t), 10, 2.5);

This can be used to wait for table state changes, asynchronous writes, or background tasks during testing.

@Fgrtue Fgrtue self-assigned this Jan 21, 2026
@Fgrtue Fgrtue added the can be tested Allows running workflows for external contributors label Jan 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc7e30f]


AI Review

Summary

This PR adds the new waitUntil table function and addresses the earlier schema, permission, and timeout issues, but one correctness bug remains in the current condition-evaluation path. As written, some valid numeric conditions are interpreted differently from normal ClickHouse boolean semantics, so I cannot recommend merging it yet.

Findings

❌ Blockers

  • [src/TableFunctions/TableFunctionWaitUntil.cpp:128] waitUntil promises to evaluate a numeric condition, but it currently converts the result with getUInt(0) != 0. For floating-point results that changes the condition's meaning: 0.5 is a valid non-zero numeric value, yet ColumnVector<Float64>::getUInt truncates it to 0, so SELECT * FROM waitUntil(0.5, 1) returns 0 instead of succeeding immediately. Use boolean conversion semantics (getBool(0) or an equivalent helper) and add a focused stateless regression test for a fractional non-zero condition.
Final Verdict

Changes requested: the current implementation mis-evaluates fractional numeric conditions.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jan 21, 2026
@qoega

qoega commented Jan 21, 2026

Copy link
Copy Markdown
Member

why you made it a table function and not just function? It looks to not return tables and you just need true/false in result.
SELECT waitUntil((SELECT count() > 10 FROM t), 10, 2.5); looks to have the same result.

But I do not get what actually does 'work' as data is usually done after you get a block or pull block from storage.

@UnamedRus

Copy link
Copy Markdown
Contributor

The function is primarily intended for testing and control-flow scenarios, rather than production query workloads.

OK, but may be in follow up PRs, it could make sense to add support for running SQL statement after condition was satisfied and return it's result instead of 1/0.

waitUntil(condition[, max_tries[, sleep_seconds]], query)

@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

why you made it a table function and not just function? It looks to not return tables and you just need true/false in result. SELECT waitUntil((SELECT count() > 10 FROM t), 10, 2.5); looks to have the same result.

But I do not get what actually does 'work' as data is usually done after you get a block or pull block from storage.

Thanks for the questions, they are very relevant.

  1. Regarding why this is a table function and not a scalar function, the main reason is that waitUntil is designed to control query execution flow, not to compute a value. A scalar function like SELECT waitUntil((SELECT count() > 10 FROM t), 10, 2.5); would be evaluated as part of expression execution, but expression evaluation in ClickHouse is not guaranteed to be re-executed over time. Once the subquery is executed and the expression is folded, there is no well-defined place to re-run it periodically.

  2. You are right that data is normally produced only after blocks are pulled from storage. waitUntil intentionally produces "no meaningful data", but instead delays producing its (single) block until the condition becomes true. In other words, it behaves like a synchronization barrier in the pipeline rather than a data source.

@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

The function is primarily intended for testing and control-flow scenarios, rather than production query workloads.

OK, but may be in follow up PRs, it could make sense to add support for running SQL statement after condition was satisfied and return it's result instead of 1/0.

waitUntil(condition[, max_tries[, sleep_seconds]], query)

I think your suggestion fits very well as a follow-up enhancement. Extending the signature to something like waitUntil(condition[, max_tries[, sleep_seconds]], query) would allow waitUntil to act as a gating mechanism for deferred execution, which is a natural next step once the basic behavior is established.
I’ll note this as a follow-up idea and would be happy to work on it separately, once the base functionality is settled.

Comment on lines +73 to +75
auto interpreter = InterpreterSelectWithUnionQuery(wait_args.condition, local_context, SelectQueryOptions().subquery());

BlockIO block_io = interpreter.execute();

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.

Are these runs of queries logged? If not, we should track, otherwise we can face silent failures that are difficult to debug and fix.

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.

Also, from the security point of view -- do we inherit all the permissions of the current user?

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.

Also, from the security point of view -- do we inherit all the permissions of the current user?

From a security perspective, I think inheriting the permissions of the current user is the more appropriate default.

This keeps the behavior consistent with how ClickHouse normally executes queries and avoids introducing a separate or implicit privilege model that could be surprising to users. It also follows the principle of least surprise: the function can only do what the invoking user is already allowed to do.

Introducing an independent permission set would add complexity and increase the risk of misconfiguration. If stricter isolation is needed in the future, it could be considered as an explicit, opt-in mechanism rather than the default behavior.

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.

From a security perspective, I think inheriting the permissions of the current user is the more appropriate default.

But that does not answer a question. The problem can be that storage is using default user context after being created and it can be a security backdoor(almost rce).

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.

From a security perspective, I think inheriting the permissions of the current user is the more appropriate default.

But that does not answer a question. The problem can be that storage is using default user context after being created and it can be a security backdoor(almost rce).

Thank you for pointing this out. Could you please share your recommended approach for handling user context in this scenario?

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.

From a security perspective, I think inheriting the permissions of the current user is the more appropriate default.

But that does not answer a question. The problem can be that storage is using default user context after being created and it can be a security backdoor(almost rce).

I added a test tests/queries/0_stateless/03799_table_function_wait_until_permissions.sh to verify that the security concern does not apply here.

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.

Using the read call's ContextPtr as the parent and creating each poll attempt via Context::createCopy(context) is the safe model here; that preserves the invoking user, roles, and row policies, and it avoids stashing a global/default context on the storage.

On observability, those inner SELECTs still go through executeQuery(..., QueryFlags{.internal = true}), so with log_queries enabled they show up in system.query_log / system.processes as internal queries.

@Fgrtue

Fgrtue commented Jan 28, 2026

Copy link
Copy Markdown
Contributor

Hi @JasonLi-cn! Thank you for contribution. I have a question about the use case. You mentioned the usage of function is primarily intended for testing scenarios. I wonder, why wouldn't we handle the retries externally? For example using http client with retry logic? Are there any particular benefits from having this function as a ClickHouse table function?

@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

Hi @JasonLi-cn! Thank you for contribution. I have a question about the use case. You mentioned the usage of function is primarily intended for testing scenarios. I wonder, why wouldn't we handle the retries externally? For example using http client with retry logic? Are there any particular benefits from having this function as a ClickHouse table function?

Thank you @Fgrtue for the suggestion. I agree that handling retries externally (e.g. via an HTTP client) is generally a good approach.

However, our project is based on ClickHouse, and some tests involve asynchronous background writes. When validating results, the challenge is to reliably detect that these async tasks have completed. Using fixed sleep calls is brittle and often leads to flaky tests under varying load.

Our test framework is largely stateless and SQL-driven (similar to ClickHouse *. sql tests), which makes it difficult to implement retry or polling logic outside of SQL. Implementing waitUntil as a table function allows us to express “wait until a condition is met” directly in SQL, making the tests more deterministic and robust.

This is why we chose an in-engine solution rather than external retries for this specific use case.

@alexey-milovidov

Copy link
Copy Markdown
Member

This feature looks doubtful for me.

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @Fgrtue, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@JasonLi-cn
JasonLi-cn marked this pull request as draft June 3, 2026 03:37
alexey-milovidov and others added 2 commits July 13, 2026 19:56
Resolved conflicts in `registerTableFunctions.cpp` and `registerTableFunctions.h`:
kept master's `registerTableFunctionFilesystem` registration and added the
PR's `registerTableFunctionWaitUntil` next to it.

Co-Authored-By: Claude Fable 5 <[email protected]>
Master moved since the branch was written:
- `TableFunctionFactory::registerFunction` now takes `FunctionDocumentation`
  as a separate first argument instead of a `TableFunctionProperties` that
  contained it (`Case::Sensitive` is the default and needs no explicit argument).
- `ITableFunction::skipAnalysisForArguments` now returns
  `VectorWithMemoryTracking<size_t>` instead of `std::vector<size_t>`.
- `IStorage::getInMemoryMetadataPtr` now requires a context argument; use
  `storage_snapshot->metadata` inside `read` instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov alexey-milovidov removed the can be tested Allows running workflows for external contributors label Jul 13, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 13, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 13, 2026
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Jul 13, 2026
…ck and required grants

Three user-visible contract gaps reported by the AI review:

* `getActualTableStructure` returned an empty `ColumnsDescription`, so
  `DESCRIBE TABLE waitUntil(...)` and `CREATE TABLE ... AS waitUntil(...)`
  saw zero columns even though `StorageWait` and the documentation both
  promise a single `result UInt8` column. Both places now share
  `getResultStructure`, and the table function reports a static structure.

* The static AST heuristic `!has_array_join && (no_from ||
  aggregate_without_group_by)` did not actually establish "returns exactly
  one row": `SELECT count() FROM tab HAVING 0` passed it and was silently
  treated as `false`, while a valid `SELECT ready FROM tab ORDER BY id DESC
  LIMIT 1` was rejected. It was also inspecting an AST the user never wrote -
  with the analyzer enabled the argument is rebuilt from the query tree,
  which materializes an implicit `FROM system.one`, so even
  `waitUntil((SELECT 1))` was rejected.

  The heuristic is removed in favour of enforcing the scalar subquery
  contract on the executed result of every attempt: more than one row throws
  `INCORRECT_RESULT_OF_SCALAR_SUBQUERY` instead of silently using the first
  row, and no rows counts as "not satisfied yet", which is what lets
  `waitUntil((SELECT ready FROM tab LIMIT 1))` wait for the row to appear.

* The function was registered without `allow_readonly`, so
  `ITableFunction::execute` required the `CREATE TEMPORARY TABLE` grant and
  rejected `waitUntil` in readonly profiles even when the inner query itself
  was permitted. It creates nothing, so it is now registered with
  `{.allow_readonly = true}` and the permissions test grants only the
  privileges the inner query needs.

Adds `04656_table_function_wait_until_contract` covering `DESCRIBE` and
`CREATE TABLE ... AS`, the empty-result and `LIMIT 1` conditions, and the
rejection of multi-row and `UNION` conditions.
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 179/188 (95.21%) · Uncovered code

Full report · Diff report

alexey-milovidov and others added 2 commits August 6, 2026 14:05
…limit is reached

Previously `checkTimeLimit` returning `false` (`timeout_overflow_mode = 'break'`)
only exited the inner sleep loop, and the outer retry loop immediately started
the next poll attempt, so the query could keep running for roughly
`max_tries * sleep_seconds` past its execution-time budget. Now the `false`
result stops the polling loop entirely.

Adds `04819_table_function_wait_until_time_limit` covering both
`timeout_overflow_mode = 'break'` (stops after the first timed-out sleep) and
`'throw'` (`TIMEOUT_EXCEEDED`).

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed dc7e30f to address the active timeout review: preserve caller condition settings and enforce the parent timeout around condition attempts, with focused coverage. @alexey-milovidov, the remaining question is product direction: should this testing-only table function continue at all, or should the PR be closed? I cannot resolve that design decision mechanically.

ErrorCodes::INCORRECT_RESULT_OF_SCALAR_SUBQUERY, "`condition` of `waitUntil` returned more than one row");

const auto & column = chunk.getColumns()[0];
satisfied = !column->isNullAt(0) && column->getUInt(0) != 0;

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.

column->getUInt(0) != 0 is not the same truthiness rule ClickHouse uses for numeric conditions. ColumnVector<T>::getUInt does an integer cast first, so a valid non-zero float like 0.5 is truncated to 0 here and SELECT * FROM waitUntil(0.5, 1) returns 0 instead of succeeding immediately.

Please evaluate the row with boolean semantics (getBool(0) or the same numeric-to-bool helper used by logical functions) and add a focused stateless case for a fractional value.

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dc7e30fbb with master 0eb658995 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.32 MiB 689.34 MiB -2.98 MiB (-0.43%)

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.

Object file sizes ⚠️

3 object files changed (+313.81 KiB total), 1 added.

Object file Master PR Δ
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionWaitUntil.cpp.o new 313.71 KiB +313.71 KiB

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

44 translation units recompiled, 312 s compile time in total, 43 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/TableFunctions/TableFunctionWaitUntil.cpp: 8.5 s

Job report

@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Aug 14, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

I'd like to advocate against this function. It adds a kind of logic to SQL that should be outside of the SQL. It will make a lot of complications and make reasoning about queries harder.

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 hold Skip for auto-updating. manual approve Manual approve required to run CI pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants