Skip to content

Add eval table function - #110132

Merged
alexey-milovidov merged 7 commits into
masterfrom
add-eval-table-function
Jul 13, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
add-eval-table-function

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #101293
Closes: #104396

A maximally simplified implementation of the eval table function, as requested in #104396 (comment):

  • The old analyzer is not supported: eval throws NOT_IMPLEMENTED unless enable_analyzer = 1.
  • eval is not allowed as an argument of another table function (e.g. remote('host', eval(...)) throws UNSUPPORTED_METHOD). The generated query can still be executed on a remote server through a query argument of view: remote('host', view(SELECT * FROM eval(...))).
  • There is no WITH-alias substitution machinery. The argument is resolved by the analyzer in the outer scope like any other table function argument (so WITH 'SELECT 1' AS q SELECT * FROM eval(q) works through common code), and the generated query is self-contained: it is resolved in its own scope and cannot reference names of the outer query.

The implementation reduces to a table function that evaluates its argument via evaluateConstantExpression, parses the result with ParserSelectWithUnionQuery (so any non-SELECT statement or output option is a syntax error), and wraps the generated query into StorageView — the same mechanism as the view table function. The eval(SELECT ...) form from the issue is kept as pure syntactic sugar: the parser wraps the bare query into a scalar subquery, so eval(SELECT ...) is equivalent to eval((SELECT ...)), and the single-row, single-column, and NULL checks come from the standard scalar subquery evaluation. The generated query cannot use eval again.

Compared to #104396, this PR does not touch ApplyWithSubqueryVisitor, QueryNormalizer, StorageView, StorageDistributed, SelectStreamFactory, or the ITableFunction interface. The only change outside the new table function, the parser layer, and the settings declarations is a three-line nesting ban in QueryAnalyzer::resolveTableFunction.

A known limitation shared with the view table function: a generated query with an unnamed scalar subquery column (e.g. eval('SELECT (SELECT 42)')) fails, because the auto-generated _subquery_N column name is not stable between schema inference and execution (the same happens with view(SELECT (SELECT 42)) on current master). Aliasing the column works: eval('SELECT (SELECT 42) AS x').

Changelog category (leave one):

  • Experimental Feature

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

Added an experimental table function eval, which evaluates a constant expression to a query string and executes the resulting single SELECT query. The feature is disabled by default and can be enabled with the setting allow_experimental_eval_table_function. Author: Yue Ni.

Version info

  • Merged into: 26.7.1.842 (included in 26.7 and later)

A maximally simplified implementation of the `eval` table function:
the argument is a constant expression evaluated to a query string, and
the generated `SELECT` query is wrapped into `StorageView`, same as the
`view` table function. `eval(SELECT ...)` is syntactic sugar for a scalar
subquery argument `eval((SELECT ...))`. The old analyzer is not supported,
`eval` cannot be used as an argument of another table function, and the
generated query must be self-contained.

Requested in #104396 (comment)
Closes #101293

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

mintlify Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 12, 2026, 2:47 AM

@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [064453c]

Summary: ✅


AI Review

Summary

PR #110132 adds an experimental eval table function that evaluates a constant expression into a SELECT string and executes it through StorageView. The follow-up fixes for persistence, query-result-cache safety, and analyzer-setting validation are in place, but the generated query still bypasses part of the normal executeQuery preflight, so I would not approve this version yet.

Findings

❌ Blockers

  • [src/TableFunctions/TableFunctionEval.cpp:136-165] The generated inner query never goes through checkASTSizeLimits, so max_ast_depth and max_ast_elements stop protecting eval. A short outer query can smuggle a very deep or huge inner SELECT past the normal entry gate, and recursive passes such as checkNoEval and analyzer resolution will process it even though executing the same SELECT directly would be rejected.
    Suggested fix: run the same AST-size check that executeQueryImpl applies, after applying the generated query's own SETTINGS to a temporary context.

⚠️ Majors

  • [src/TableFunctions/TableFunctionEval.cpp:152-162] [dismissed by author -- https://github.com/Add eval table function #110132#discussion_r3565451152] eval still does not preprocess the generated query the same way as a normal SELECT: ApplyWithGlobalVisitor is skipped, and the INTERSECT/EXCEPT/implicit-UNION visitors use the outer context settings instead of the generated query's own SETTINGS. That means eval('WITH 1 AS x SELECT x UNION ALL SELECT x') can diverge from a direct query when enable_global_with_statement = 1, and eval('SELECT 1 UNION SELECT 1 SETTINGS union_default_mode = ''DISTINCT''') still ignores the inner SETTINGS. I still consider this real because it changes the semantics of the query text that eval claims to execute.
    Suggested fix: preprocess the generated AST on a temporary context with InterpreterSetQuery::applySettingsFromQuery, ApplyWithGlobalVisitor, and the set-operation visitors before storing create.select.
Tests
  • ⚠️ Add a regression with low max_ast_depth or max_ast_elements and a deep or large generated query to prove the safety limits still trigger under eval.
  • ⚠️ Add a regression where the generated query carries SETTINGS union_default_mode = 'DISTINCT', plus one with WITH ... UNION ALL ..., to prove eval matches normal SELECT semantics.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: restore normal preflight parity for generated queries at least for AST-size enforcement, and add focused regressions for the remaining semantics-sensitive paths.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 12, 2026
The `eval` table function requires the analyzer and throws `NOT_IMPLEMENTED`
when `enable_analyzer = 0`. The `old analyzer` CI job forces
`enable_analyzer = 0` for the whole session, so every query in
`04512_eval_table_function` that exercises the analyzer path failed there
with `NOT_IMPLEMENTED` instead of the expected result.

Add the `no-old-analyzer` tag to skip the test under that job. The test
still runs in full under the regular (analyzer) jobs, where it also covers
the old-analyzer rejection explicitly via `SET enable_analyzer = 0` at the
end, so no coverage is lost.
…uery result cache

Two safety fixes for the experimental `eval` table function, following the
philosophy of keeping it maximally locked down:

* `CREATE TABLE ... AS eval(...)` is now rejected. The source expression would
  be re-evaluated on every `ATTACH`, so such a table could fail to attach after
  a restart (the experimental setting might be disabled) or silently change if
  the expression depends on parameters, settings, or time. There is no stable
  persisted representation, so `canBeUsedToCreateTable` returns `false`.

* The generated query is opaque to the query result cache, which only sees the
  outer `eval('...')` call. `SELECT * FROM eval('SELECT now()')` could be cached
  as if deterministic, and `eval('SELECT * FROM system.processes')` bypassed the
  system-table guard. `eval` is now treated as potentially non-deterministic and
  potentially reading a system table, so such queries are not cached by default.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 12, 2026
…by `eval`

The generated query did not go through `validateAnalyzerSettings`, so its
`SETTINGS` clause could flip `enable_analyzer` / `allow_experimental_analyzer`
even though `eval` is analyzer-only, while a usual query is rejected with
`INCORRECT_QUERY` when this setting is changed in a subquery. Expose
`validateAnalyzerSettings` from `executeQuery` and run it on the generated
query before storing it, so `eval('SELECT 1 SETTINGS enable_analyzer = 0')`
is rejected the same way as a plain query, and add regressions.

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

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110132&sha=978fd8028f27596a4f2e5cf37506a5425ba215d7&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 and provide a fix in a separate PR. It is unrelated to this PR: a LOGICAL_ERROR exception Reading from materialized CTE before its materialization completed under EXPLAIN ANALYZE with chained materialized CTEs and WITH TOTALS. I reduced it to a minimal reproducer and filed #110176 with the details.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated the unrelated AST fuzzer failure. Findings on the tracking issue: #110176 (comment)

Summary: this materialized-CTE DelayedPortsProcessor gate is missing error requires EXPLAIN ANALYZE, which was reverted from master in #110162 (2026-07-12 17:24 UTC), so it no longer reproduces on master. It is confined to the reverted EXPLAIN ANALYZE execution path and will return once the reintroduction PR #110164 lands (which fixes only the streaming 'clock' bug, not this gate). Asked there how you would like the gate fix sequenced relative to #110164.

Not caused by this PR.

settings[Setting::max_parser_depth],
settings[Setting::max_parser_backtracks]);

checkNoEval(query);

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.

eval parses the generated SELECT and then immediately walks/stores it, but unlike executeQueryImpl it never calls checkASTSizeLimits. That makes max_ast_depth / max_ast_elements ineffective for inner queries: a tiny outer SELECT * FROM eval('...') can smuggle a huge or very deep AST into checkNoEval and the analyzer even though executing the same inner SELECT directly would be rejected. Please apply the normal AST-size gate here, on a context with the generated query's own SETTINGS already applied.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@groeneai, send a follow-up PR.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Done: #110211 applies the AST size limits (max_ast_depth/max_ast_elements) to the generated query, reading them from a context with the inner query's own SETTINGS applied.

@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 142/143 (99.30%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 13, 2026
Merged via the queue into master with commit f3c5bea Jul 13, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the add-eval-table-function branch July 13, 2026 04:08
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The unrelated DelayedPortsProcessor gate is missing failure (STID 2467-2c2d) that hit this PR's AST fuzzer job is fixed in a separate PR: #110428. It is a distinct, non-EXPLAIN ANALYZE manifestation still live on master (a materialized CTE named like a base table it reads, with a set-operation body, self-references the unmaterialized CTE). Not caused by this PR.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 064453c0 Deployed Jul 13, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-experimental Experimental Feature 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.

Table function eval

3 participants