Repository navigation
Add table function waitUntil - #94695
JasonLi-cn wants to merge 15 commits into
Conversation
|
Workflow [PR], commit [dc7e30f] AI ReviewSummaryThis PR adds the new Findings❌ Blockers
Final VerdictChanges requested: the current implementation mis-evaluates fractional numeric conditions. |
|
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. But I do not get what actually does 'work' as data is usually done after you get a block or pull block from storage. |
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. |
Thanks for the questions, they are very relevant.
|
I think your suggestion fits very well as a follow-up enhancement. Extending the signature to something like |
| auto interpreter = InterpreterSelectWithUnionQuery(wait_args.condition, local_context, SelectQueryOptions().subquery()); | ||
|
|
||
| BlockIO block_io = interpreter.execute(); |
There was a problem hiding this comment.
Are these runs of queries logged? If not, we should track, otherwise we can face silent failures that are difficult to debug and fix.
There was a problem hiding this comment.
Also, from the security point of view -- do we inherit all the permissions of the current user?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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
defaultuser 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?
There was a problem hiding this comment.
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
defaultuser 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.
There was a problem hiding this comment.
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.
|
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 This is why we chose an in-engine solution rather than external retries for this specific use case. |
e8527f1 to
7edb874
Compare
3a80d6e to
23fb57c
Compare
|
This feature looks doubtful for me. |
|
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. |
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]>
…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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 179/188 (95.21%) · Uncovered code |
…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]>
Preserve caller aggregation settings and check the outer query timeout around every polling attempt. CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=94695&sha=8bb8a399e4426da79fed54b4b6dfb18225aa1616&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 PR: ClickHouse#94695
|
🕵 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; |
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing Binary sizes
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
|
| 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
|
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. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
waitUntilfunction.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 function always returns exactly one row, making it suitable for use in SQL-level synchronization and test assertions.
Syntax
Arguments:
An expression or scalar subquery that evaluates to a single boolean value
Maximum number of condition evaluation attempts
Number of seconds to sleep between attempts (fractional values supported)
Return Value
The function returns a single-column table:
Exactly one row is returned.
Examples
The condition is never satisfied, and the function returns 0 after the specified number of attempts.
If the condition is satisfied during the first evaluation, the function returns immediately without additional waiting.
This can be used to wait for table state changes, asynchronous writes, or background tasks during testing.