Repository navigation
Reimplement the KQL (Kusto) dialect on a lexer, an AST and AST translation - #112932
Conversation
The dialect was contributed in 2022 and abandoned by its authors; the rewrite they promised in #62668 was closed unmerged. Since then it has been emergency-disabled once (#59305) and gated behind `allow_experimental_kusto_dialect` (#74224), and issue #61742 ("Remove KQL support if this code will not be fixed") has stayed open. The implementation translated a KQL token stream directly into ClickHouse SQL *text* and re-parsed it. Everything below follows from that: - KQL string literals were spliced into generated SQL unescaped, so `T | where s contains "x') OR 1 = 1 OR ilike(s, 'y"` injected arbitrary expressions -- and `contains '50%'` matched `'50x'` because LIKE metacharacters passed through. - No types were available while translating, so 14 sites emitted runtime `toTypeName()` dispatch and datetimes were modelled as strings truncated to 27 characters. - Arguments were SQL text, so a dozen sites called `std::stoi` on it; `format_timespan(col, 'hh:mm')` failed with "stoi: no conversion". - 28 of the 237 registered functions were stubs that returned the raw KQL name into the generated SQL, including every `series_*`. - `let` bindings lived in a `static thread_local` map that, by its own comment, leaked between unrelated queries. This commit removes the implementation and every trace of it: the parser, the `kusto` dialect and its experimental setting, the `kusto` value of `interval_output_format` and the interval serialization it drove, the client/server call sites, the fuzzer and style-check carve-outs, and the tests. A correct implementation is added next. Two notes on what was deliberately kept. `ASTSelectQuery::normalize ChildrenOrder` stays -- several other parsers use it -- with its comment generalized. `04305_parser_error_message_oob_101143.sh` stays as a regression test for the error-formatter buffer overflow; its rationale is rewritten, since the parser it originally exercised is now gone. Release history in CHANGELOG.md, docs/changelogs/ and SettingsChangesHistory.cpp is left untouched.
The dialect now has a front end of its own instead of reinterpreting the
SQL tokenizer's errors and emitting SQL text.
src/Parsers/Kusto/
KQLLexer KQL's own tokens: `!in`, `=~`, `..`, timespans like
`2.5h`, verbatim `@'...'`, `datetime(...)`. A bad
literal is an Error token carrying a reason, so nothing
downstream has to ask `isValidKQLPos()` (issue #61742).
KQLAST the tabular level -- sources and the operator pipeline.
Scalar expressions are ClickHouse AST directly; a
parallel expression hierarchy would only add conversions.
KQLParser recursive descent. `let` bindings are a member, so they
are scoped to one parse instead of a `thread_local` map
that leaked between queries.
KQLTranslator lowers the pipeline: each operator fills a still-empty
clause of the select being built, or wraps what exists
so far in a subquery and starts a new one.
KQLFunctions name -> builder returning an ASTPtr.
src/Functions/Kusto/
kqlDivide `7 / 2` is 3 in KQL and 3.5 in SQL. Which applies
depends on the operand types, so it is decided at
analysis time rather than guessed from spelling.
kqlBin `bin()` over a number or a datetime, likewise.
What this buys, with the old behaviour first:
contains '50%' matched '50x' now false
a needle could close the generated literal now impossible: a KQL
and inject an expression string is an ASTLiteral
substring('abcdefg', -3, 2) = 'ab' now 'ef'
7 / 2 = 3.5 now 3
isnull(parse_json('null')) = false parse_json is rejected
28 functions silently returned their own name unknown names are rejected
search 'x' -> "Unknown table expression" -> "'search' is not a
supported KQL operator"
The subset is deliberately smaller than before and documented in
docs/guides/clickhouse/kusto-query-language.mdx: a construct is either
translated with the semantics Kusto documents, or rejected by name.
src/Parsers/Kusto goes from 13017 lines to 3967, plus 310 lines of
runtime functions. `src/Parsers/Kusto` no longer needs the
carve-out from check 19 ("do not catch exceptions in src/Parsers"),
which is removed.
Tests 04670-04673 cover the pipeline, the string operators (including the
injection cases), the scalar semantics that used to be wrong, and 39
constructs that must be rejected.
|
Workflow [PR], commit [5c1cc13] Summary: ✅
AI ReviewSummaryThis PR replaces the old KQL text-to-text translator with a real lexer/parser/AST pipeline and closes a long list of semantic gaps. The rewrite is substantially better than the previous implementation, but I still found two correctness issues in the new user-defined-function and timespan-arithmetic paths that can either reject valid scalar KQL or return the wrong duration silently. Findings
Tests
Final VerdictStatus: ❌ Block LLVM Coverage ReportMeasured on commit 5c1cc13.
Changed lines: Changed C/C++ lines covered: 3899/4372 (89.18%) · Uncovered code |
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
…ctions
Two things, because the first found the work for the second.
**ClickHouse functions are reachable from KQL.** A name the KQL registry does
not know is now passed through under the spelling the user wrote, so a query
can use anything the server offers:
StormEvents
| extend Bucket = toStartOfHour(StartTime), Fingerprint = cityHash64(EventType)
| summarize Events = count() by Bucket
The exception is names Kusto itself defines but this dialect does not
implement: those stay rejected, so a Kusto name can never quietly mean
something else. `range` is the clearest case -- `range(1, 3, 1)` is
`[1, 2, 3]` in Kusto and `[1, 2]` here.
**The tests deleted with the old implementation are back**, trimmed to what the
dialect supports and with their references regenerated. 18 files, including
the three conformance suites adapted from baby-kusto-csharp, kusto-loco and
pql. 236 statements are commented out with the reason in place, so the gaps
are visible rather than quietly missing. `02366_kql_func_iif`,
`02366_kql_tabular`, `04123_kql_operators` and
`02366_kql_native_interval_format` reproduce their pre-rewrite references
byte for byte. Dropped entirely: the IP-function and make-series suites
(neither operator family is supported), the `kql()` table-function OOM
regression (that parser no longer exists) and the array_sort removal
assertion.
Running them found fourteen real defects, all fixed here:
- `trim_start`/`trim_end` take a regex and the text in Kusto; they were
mapped onto ClickHouse's one-argument `trimLeft`/`trimRight`, which strip
whitespace and ignore the pattern.
- `extend x = * Price` raised LOGICAL_ERROR ("Can't set alias of *") because
`*` was parsed as a scalar. A wildcard is now only itself.
- `a[-1]` indexed from the front; a negative KQL index counts from the end.
- `array_slice` ignored negative bounds.
- `decimal(1.23)` printed as 1.23000000000000000002, having gone through a
double.
- `split(s, '')` exploded into characters instead of returning `[s]`.
- `tolong('0xA0')` returned null; Kusto reads the `0x` prefix.
- `floor(x, roundTo)` is Kusto's alias for `bin`, not ClickHouse's
round-to-N-decimals.
- `extract` lacked its `typeof(T)` argument, `countof` its `kind`, `indexof`
its start offset, `now`/`startof*` their offsets.
- `isnan` and friends printed 0/1 rather than false/true.
- Missing: the typed literals `bool()`, `int()`, `long()`, `real()`,
`decimal()`, `time()`, `timespan()`, `totimespan()`, `typeof()`; the
`endof*` family; `set_intersect`, `set_difference`, `pack_array`,
`toboolean`.
- `\w` in a plain string was a lexical error; the backslash is now kept, as
a regex needs.
- `format_datetime` returned its format string unchanged, because Kusto's
`yyyy-MM-dd` specifiers are not ClickHouse's. It is rejected now, as is
`extract_all`, whose Kusto result is one array per capture group.
All 24 test files pass against their references.
|
Two follow-ups pushed since the PR was opened. KQL can now call ClickHouse functions. A name the KQL registry does not know is passed through under the spelling you wrote, so a KQL query can reach anything the server offers: SET dialect = 'kusto';
StormEvents
| extend Bucket = toStartOfHour(StartTime), Fingerprint = cityHash64(EventType)
| summarize Events = count() by BucketThe exception is names Kusto itself defines but this dialect does not implement — those stay rejected, so a Kusto name can never quietly mean something else. The functional tests are back. 18 restored files, trimmed to the supported subset with their references regenerated, on top of the 6 written for the rewrite — 24 in total, all passing. Four reproduce their pre-rewrite references byte for byte: 236 statements are commented out with the reason left in place, so a gap is visible in the file rather than silently missing. Four suites were dropped outright: the IP-function and Running the restored tests found fourteen real defects, all fixed in the same commit — among them Also added: the typed literals Known gaps, deliberately left
|
Found by reading Microsoft's KQL reference and diffing it against what this dialect accepts. **`summarize AvgCpu = avg(v) by Computer, bin(TimeGenerated, 1h)` did not work.** Kusto names a computed group key after the column it derives from, so the key is called `TimeGenerated` -- and emitting `kqlBin(TimeGenerated, ...) AS TimeGenerated ... GROUP BY kqlBin(TimeGenerated, ...)` either fails to resolve (NOT_AN_AGGREGATE) or, under `prefer_column_name_to_alias`, silently groups by the raw column instead of the binned value. Computed keys are now evaluated one level down under an internal name and grouped by that, which is right under both settings. This is the canonical KQL query shape, so it mattered. **`repeat`, `replace` and `translate` reached ClickHouse** through the unknown-name escape hatch and ran with ClickHouse's meaning: Kusto's `repeat(value, n)` builds an array where ClickHouse's repeats a string, and Kusto's `replace(regex, rewrite, text)` orders its arguments differently. Both returned a plausible wrong answer rather than an error. They join the guard list, which is what keeps the rule that a Kusto name never quietly means something else. The guard list is now audited rather than assembled from memory: of the 307 function names Microsoft documents, 123 are implemented, 79 are rejected by name, and of the 105 that reach ClickHouse only 19 share a name with a ClickHouse function -- all of them either agreeing (`cos`, `pi`, `not`, `any`) or failing cleanly on case (`extractAll`, `toTime`, `isASCII`). The guide now carries the measured coverage (20 of 52 tabular operators, 123 of 307 functions) and names what is missing, including user-defined functions, operator options such as `mv-expand ... to typeof(T)`, and the whole `evaluate` plugin mechanism.
|
I read Microsoft's KQL reference end to end and diffed it against this branch. Numbers below are measured, not estimated — the operator list comes from the docs TOC, the function lists from the scalar and aggregation indexes.
Of the 307 function names: 123 implemented, 79 rejected by name, 105 reach ClickHouse. Of those 105, only 19 share a name with a ClickHouse function, and every one of those either agrees ( Two defects this found, fixed in 7a1340f
The main gaps, in rough order of how much I'd expect users to hit them
Two conformance details worth recordingBoth already match, but they're the ones implementations most often get wrong, so they're worth stating: The guide now carries the measured coverage table and names each gap, so the boundary is documented rather than discovered. |
let MultiplyByN = (val: long, n: long = 2) { val * n };
let RecentErrors = (since: timespan) { Logs | where Timestamp > ago(since) };
RecentErrors(1h) | summarize Count = count() by Component
The largest gap against the Kusto reference: `let` bound a scalar or a whole
tabular expression, but not a lambda, and user-defined functions are how any
non-trivial KQL is organised.
A KQL function is a *calculation*, not a value -- Microsoft's own wording -- so
the body is kept as a token range and re-parsed at each call under a scope where
the parameter names are bound to that call's arguments. That reuses the
substitution plain scalar `let`s already go through, and it is why a function
call needs no new machinery in the translator: by the time the pipeline is
lowered, the call has already become ordinary AST.
Whether the body reads as a scalar or as a pipeline is decided by where the name
appears. `parsePrimary` evaluates it as an expression, `parseSource` as a
tabular expression, so the same definition serves both:
let Above = (n: long) { datatable (a:long) [1,2,3] | where a > n };
Above(1) | count
Supported: scalar parameters with literal defaults; tabular parameters declared
`T: (*)` or `T: (col: type, ...)`, which Kusto requires to come first; arguments
passed by name in any order; a body of zero or more `let`s and one expression,
which can see the bindings that enclose it and whose parameters shadow them; a
parameterless function called with or without parentheses; and `view ()`, which
is accepted and means `()` here because nothing resolves `union *` wildcards.
Rejected, each by name: recursion, direct or mutual (Kusto has none either); a
missing argument; too many arguments; an unknown parameter name; a duplicate
parameter; a required parameter after a defaulted one; a scalar parameter before
a tabular one; an unknown parameter type; an empty body; and text left over at
the end of a body. A chain deep enough to matter meets the existing parse-depth
guard rather than the stack.
Tests: 04675 covers the shape of every supported form, and 04673 gains the
eleven rejections. A 1500-query fuzz over the new syntax found nothing.
One behaviour is worth stating because the tests show it: a `let` binds only for
the statement that follows it, since one KQL statement is one ClickHouse query.
That is also what keeps a binding from leaking into a concurrent query, and it
applies to plain scalar `let`s just as much. It is now in the guide.
|
User-defined functions are implemented in let MultiplyByN = (val: long, n: long = 2) { val * n };
let RecentErrors = (since: timespan) { Logs | where Timestamp > ago(since) };
RecentErrors(1h) | summarize Count = count() by ComponentHowA KQL function is a calculation, not a value — Microsoft's own wording — so the body is kept as a token range and re-parsed at each call under a scope where the parameter names are bound to that call's arguments. That reuses the substitution plain scalar Whether the body reads as a scalar or as a pipeline is decided by where the name appears — let Above = (n: long) { datatable (a:long) [1,2,3] | where a > n };
Above(1) | countSupportedScalar parameters with literal defaults; tabular parameters declared Rejected, each by nameRecursion (direct and mutual — Kusto has none either), a missing argument, too many arguments, an unknown parameter name, a duplicate parameter, a required parameter after a defaulted one, a scalar parameter before a tabular one, an unknown parameter type, an empty body, and text left over at the end of a body. A chain deep enough to matter meets the existing parse-depth guard rather than the stack — 3000 chained functions gives Worth knowingA let n = 5; print n; print n -- the second `print` does not see `n`
let n = 5; print a = n, b = n -- fineKusto would scope the binding across every statement in the query. Matching that would mean one KQL query producing several result sets, which does not map onto a ClickHouse query; this is documented in the guide rather than papered over. 24 test files pass. A 1500-query fuzz over the new syntax found nothing; |
Working through the families the doc comparison flagged, and taking each one
only as far as it can go faithfully. 123 of the 307 documented function names
become 162.
**Binary (7/7).** Straight onto `bitAnd` and friends. Kusto shifts by
`n % 64` and answers null for a negative shift, where ClickHouse raises.
**IPv4 / IPv6 (13).** `parse_ipv4`, `parse_ipv4_mask`, `format_ipv4`,
`format_ipv4_mask`, `ipv4_compare`, `ipv4_is_match`, `ipv4_is_in_range`,
`ipv4_is_in_any_range`, `ipv4_is_private`, `ipv4_netmask_suffix`, and the four
IPv6 counterparts. Three details that a name-to-name mapping would have got
wrong: a CIDR suffix inside the string *masks* the low bits rather than being
ignored; a comparison uses the narrowest of both operands' prefixes and any
explicit one; and `ipv4_is_private` is RFC 1918 only, so loopback is not
private. `isIPAddressInRange` also insists on a `/prefix` where Kusto accepts
a bare address.
**Geospatial, the point-based half (9).** `geo_distance_2points`,
`geo_point_in_circle`, `geo_point_to_geohash`, `geo_point_to_h3cell`,
`geo_h3cell_level` / `_parent` / `_children` / `_neighbors`. Two traps here:
ClickHouse's `geoToH3` takes *latitude* first while every Kusto `geo_*` takes
longitude first, and `greatCircleDistance` is a fast approximation on a
different radius that lands ~600 m out over 1500 km. The distance is therefore
written out as a haversine on a sphere of radius 6371010 m, which reproduces
Microsoft's own documented figure to the last digit.
**More mathematics and strings (20).** The trigonometric functions, `gamma`,
`loggamma`, `erf`, `erfc`, `cot`, `pi`, plus `tohex`, `strcmp`, `isascii`,
`isutf8`, `url_encode`, `new_guid`, `hash_sha1`.
**Datetime (8).** `datetime_add`, `datetime_part`, `datetime_utc_to_local`,
`datetime_local_to_utc`, `make_timespan`, `week_of_year`, and the microsecond
and nanosecond `unixtime_*` converters. `datetime_add` and `datetime_part`
name their unit with a string literal, so the right function is picked while
parsing rather than dispatched on at runtime.
Two defects fixed on the way, both found by reading the reference rather than
by a test:
- `dayofweek()` returned a number. Kusto returns the *timespan* since the
preceding Sunday, so a Monday is `1.00:00:00`.
- `tohex()` upper-cased and zero-padded to whole bytes.
Still rejected, and now for a stated reason rather than for want of a mapping:
every geospatial function that takes or returns GeoJSON, since that needs the
`dynamic` object mapping this dialect does not have; `geo_point_to_s2cell`,
because ClickHouse has no S2 token form; and `has_ipv4` and friends, whose
term-delimiter rules are not a substring search.
04676 checks every one of these against the value printed on its own Microsoft
reference page.
|
I went through item 7 family by family, checking each against its Microsoft reference page rather than mapping by name. Pushed as Mapped, and verified against Microsoft's own printed examples
Traps a name-to-name mapping would have walked into
Two defects found by reading the reference
Still rejected, now for a stated reason
The rest of item 7, assessed but not done
All 25 test files pass; |
`geo_distance_2points` and `geo_point_in_circle` computed an exact haversine on a sphere of radius 6371010 m, written out as an AST, so that they reproduced Kusto's documented figures to the last digit. Exact agreement is not worth that: these functions usually filter rather than report, and Kusto itself recommends the sphere over the spheroid on the grounds of speed. Both now call `greatCircleDistance`, which is a fast approximation and lands about 600 m out over 1500 km, and `use_spheroid = true` -- a real Kusto parameter that the previous code accepted and ignored -- selects `geoDistance`. Coordinates are widened with `toFloat64`, as the neighbouring `geo_*` functions already do, so integer arguments work rather than failing on the argument type. Neither ClickHouse function range-checks its arguments, so an out-of-range coordinate gives a meaningless number where Kusto gives null. Documented rather than guarded, for the same reason. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Switched The distance is now about 600 m out over 1500 km — Seattle to Los Angeles gives Two things fell out of the switch:
One divergence is documented rather than fixed: neither ClickHouse function range-checks its arguments, so a coordinate outside [-180, 180] or [-90, 90] yields a meaningless number where Kusto yields null. Guarding it would cost eight comparisons on every row, which runs against the same speed-over-fidelity trade. All 26 KQL test files pass; |
`lowerUTF8` is only registered when ClickHouse is built with ICU, so the case-insensitive string operators failed with `Function with name lowerUTF8 does not exist` in the fast test. Kusto compares ordinally, which is what the `*CaseInsensitiveUTF8` search functions already do, so `contains`, `startswith`, `endswith`, `=~`, `!~` and `in~` are built from those instead. `toint` and `tolong` test the ASCII `0x` prefix with `lower`. `tolower` and `toupper` still need Unicode case mapping, so the two conformance tests that use them are tagged `no-fasttest`, and the H3 cell cases move to `04693_kql_geo_h3`, tagged the same way because the fast test has no H3 library. Also fixes the style check (double spaces after a comma) and two clang-tidy findings, and drops a link to a not-yet-generated anchor from the guide.
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/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLFunctions.cpp.o |
new | 741.46 KiB | +741.46 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLBinAt.cpp.o |
new | 528.11 KiB | +528.11 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLParser.cpp.o |
new | 479.86 KiB | +479.86 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLBin.cpp.o |
new | 449.58 KiB | +449.58 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLParameterCast.cpp.o |
new | 435.89 KiB | +435.89 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLDivide.cpp.o |
new | 376.06 KiB | +376.06 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLRangeCount.cpp.o |
new | 263.43 KiB | +263.43 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLToTimespan.cpp.o |
new | 246.68 KiB | +246.68 KiB |
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/Kusto/FunctionKQLMultiply.cpp.o |
new | 235.82 KiB | +235.82 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLTranslator.cpp.o |
new | 204.36 KiB | +204.36 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/KQLLexer.cpp.o |
new | 54.46 KiB | +54.46 KiB |
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Kusto/parseKQLQuery.cpp.o |
111.50 KiB | 59.20 KiB | -52.30 KiB (-46.91%) |
771 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
51 translation units recompiled, 218 s compile time in total, 40 of them have a recent master baseline.
Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +7.9 s (+5%) in total before that adjustment.
Translation units without a recent master baseline:
src/Functions/Kusto/FunctionKQLBinAt.cpp: 5.4 s
The function-property fuzzer found `kqlBin(Nullable(UInt128), UInt8)` answering with a logical error: the delegated `intDiv`/`multiply` were built over the original `Nullable` types, but the executable's default null implementation stripped the columns before they reached them. The resolver and the executable now keep nulls out of the default handling (as `kqlDivide` already did), so the delegated functions always see the types they were built for. A NULL literal argument now short-circuits through `divide` instead of failing the type checks. `bin_at` was registered as supported but translated to `kqlBinAt`, which did not exist, so it failed at analysis with an unknown-function error. Implement it: a datetime is `toStartOfInterval(value, binSize, fixedPoint)`, numbers compute `fixedPoint + bin(value - fixedPoint, binSize)`. Failure report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112932&sha=b19aa993b30bead701175fd15000b69a39b0f307&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29 PR: #112932 Co-Authored-By: Claude Fable 5 <[email protected]>
…left` lexing - The string form of `timespan(...)` did unchecked signed arithmetic on up-to-18-digit fields of untrusted text; an oversized literal overflowed instead of failing. Every step now goes through `common::mulOverflow`/`common::addOverflow`, including the final ticks-to-nanoseconds conversion. - `let` recognized an identifier-led tabular expression only when the next token was `|`, so `let U = T;` rebinding a tabular result and `let Q = Tail(2);` binding a tabular function call both went down the scalar path and broke. Function definitions now record whether their body reads as a pipeline, and `let` uses that plus the tabular bindings in scope. - The lexer had no rule for `$`, so the `$left.a == $right.b` join condition the parser supports could never be reached. PR: #112932 Co-Authored-By: Claude Fable 5 <[email protected]>
# Conflicts: # src/Parsers/Kusto/ParserKQLOperators.cpp
`extract` lowers to `arrayElementOrNull` over `extractGroups`, so a capture
group the pattern does not have is `NULL`, which is what
`04927_kql_review_regressions` pins for a pattern that does not match. The
reference of `02366_kql_func_string` still expected the empty string for
`extract('(\b[A-Z]+\b).+(\b\d+)', 3, ...)`, and failed in every
`Stateless tests` job.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112932&sha=42c6e49265a74d15daf5611de8f24a202b31f24e&name_0=PR&name_1=Stateless%20tests%20(amd_debug,%20parallel)
PR: #112932
Address review: `kqlMultiply`, `kqlToTimespan` and `kqlRangeCount` read their
numeric argument with `getFloat64`, which cannot spell every `Decimal` or any
integer above 2^53, so an exact duration came out a tick short and a wide
integer range came out with the wrong number of rows:
- `kqlMultiply(toIntervalNanosecond(86400000000000), toDecimal64('0.57', 2))`
gave `49247999999999` instead of `49248000000000`, so `1d * decimal(0.57)`
did not equal the literal `13.68h` and was not even a whole Kusto tick.
- `kqlToTimespan(toDecimal64('0.57', 2))` was one nanosecond short the same way.
- `kqlRangeCount(toUInt128(9007199254740993), toUInt128(9007199254740995),
toUInt128(1))` counted 5 rows instead of 3.
The new `KQLExact` helpers read an integer of any width, or a decimal's
unscaled digits, into `Int256` and do the scaling there; the quotient still
truncates toward zero as `trunc` did, and a result outside the `Int64` tick
carrier is still `BAD_ARGUMENTS`. Only a float argument keeps the `long double`
path. `kqlRangeCount`'s separate integral and decimal domains collapse into one
exact domain, since an integer is a decimal of scale zero.
…a value
Address review: two user-defined-function paths did not keep to the KQL
function contract.
A tabular parameter's declared schema was parsed and thrown away, so
`T:(*)` and `T:(a:long)` behaved the same and the body could read a column
the parameter never declared, leaking it from the call site:
let F = (T:(a:long)) { T | project b };
F(datatable (a:long, b:long) [1, 2])
The declared column names are now remembered, and binding the argument
projects it onto them, so the body sees exactly the declared columns and
nothing else. `T:(*)` declares none and passes the argument through. An empty
declaration `T:()` and a column declared twice are now syntax errors.
`parsePrimary` also routed every user-defined name through
`callScalarFunction`, so a function whose body is a pipeline could run in a
scalar position, where re-parsing its body silently read its leading name as a
column of the current row:
let Source = datatable (x:long) [1];
let F = () { Source };
datatable (Source:long) [7] | extend y = F
A scalar site now rejects a tabular-bodied function outright.
New test `05044_kql_exact_scaling_and_tabular_contract`, which also covers the
exact timespan scaling and range counting of the preceding commit. The guide
documents both rules.
|
🕵 Pushed
New test |
…ime64` and literal outputs The datetime examples called the functions with `toDateTime`, which the implementation deliberately rejects (a KQL datetime is a `DateTime64`; `DateTime` cannot represent a bin before the Unix epoch), and the timespan example documented a prose description instead of the literal output. The `Docs examples` CI job executes these examples and failed on all three. The examples now use `toDateTime64(..., 7, 'UTC')` and the exact outputs, and the descriptions spell out that the narrower `DateTime`/`Date` carriers are rejected. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112932&sha=be2164446db1cb25a9a41aec0d7c76a69b98ea90&name_0=PR #112932
The `:type` annotations in KQL function signatures were parsed and then dropped:
`FunctionParameter` remembered only the names, so `let F = (a:long) { a }; print F('x')`
succeeded with a `String` argument, and the declared column types of tabular parameters
were likewise ignored.
The parser cannot check the types itself - it lowers to SQL without ever seeing a schema -
so the check is deferred to analysis time: `FunctionParameter` now keeps the declared KQL
type of a scalar parameter and of every declared tabular column, and `bindArguments`/
`restrictToDeclaredColumns` wrap each argument in the new `kqlParameterCast` function.
Its resolver rejects an argument whose type does not belong to the declared KQL type with
`ILLEGAL_TYPE_OF_ARGUMENT`, then delegates to `accurateCast`, which widens losslessly
(`long` to `real`) and makes a value that does not fit the declared type (an `int`
overflow) a per-row error rather than a silent truncation. A `NULL` literal stays a typed
null of the declared type, and a fixed-length `Interval` of another kind converts to
nanosecond ticks by integer arithmetic.
Addresses the review thread on `KQLParser.h` about the typed-parameter contract.
#112932
| { | ||
| is_function_definition = true; | ||
| bound_tabular = tokens[let_end - 1].type == KQLTokenType::ClosingCurlyBrace | ||
| && bodyLooksTabular(body + 1, let_end - 1, tabular_names, scalar_names); |
There was a problem hiding this comment.
This recursive classifier drops the nested function's own scalar parameters. A concrete repro is:
let Outer = () { let F = (x:long) { x }; F(1) };
print Outer();When bodyLooksTabular() classifies F, the recursive call sees the inner body as the lone bare name x, but x is not in scalar_names here. expressionLooksTabular() therefore falls through to unknown_name_is_table = true, marks F as tabular, and then propagates that misclassification to Outer. The scalar call Outer() is rejected as "a tabular function" even though both bodies are scalar. parseFunctionDefinition() already seeds scalar parameter names before classifying a body; this nested-function path needs the same treatment (or it should reuse the full definition parser) so nested scalar UDFs stay callable in scalar context.
| getName(), | ||
| left->getName(), | ||
| right->getName()); | ||
| return left->isNullable() || right->isNullable() ? makeNullable(interval) : interval; |
There was a problem hiding this comment.
Because the dialect now lets arbitrary ClickHouse functions through, this path is reachable with non-IntervalNanosecond carriers such as toIntervalHour(1). Returning the original interval kind breaks the * contract on fractional scales:
print 1.5 * toIntervalHour(1)is lowered to kqlMultiply(1.5, toIntervalHour(1)), executeImpl() multiplies the raw hour tick 1 by 1.5, truncates it back to 1, and hands back IntervalHour(1) instead of a 90-minute duration. kqlDivide() and kqlRangeCount() already normalize arbitrary fixed-length interval kinds to nanoseconds; kqlMultiply() needs the same normalization (or it needs to reject coarse interval kinds) to avoid silent wrong answers as soon as a KQL query combines * with a ClickHouse interval function.
`LocalConnection::sendQuery` applies the settings sent with the query, so that the sandbox of the read-only tool of the agent takes effect in `clickhouse-local` as it does against a server. The client also puts the `SETTINGS` clause of the query itself into those settings (`InterpreterSetQuery::applySettingsFromQuery`), and the receiving side parses the very same text with them - so an `INSERT` written in ClickHouse SQL with `SETTINGS dialect = 'kusto'` was parsed as KQL and rejected by the `allow_experimental_kusto_dialect` gate. `pinOutboundDialectForJSONDialect` already pinned the outbound `dialect` to the form of the text being sent for the `clickhouse_json` dialect. Generalize it to `pinOutboundDialect`: the transport `dialect` is now the one the client actually parsed the query with, for every query. A `SET dialect = ...` is a statement of its own and still reaches the session, so switching the dialect keeps working. This surfaced as `04349_ast_json_local_input_dialect_boundary` once the `kusto` case of that test arrived on master with #112932: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114043&sha=ab926893ca906581840d77e9f0a0a8b121c2de0d&name_0=PR&name_1=Fast%20test
…rgument `kqlParameterCast(value, 'timespan', parameter)` converts a fixed-length `Interval` argument of a kind other than `Nanosecond` by integer tick arithmetic: it retypes the argument slot to `Int64`, multiplies by the kind's nanoseconds per tick, and wraps the product with `toIntervalNanosecond`. `convertIntervalToNanoseconds` decided that slot's nullability from `arguments[0].type->isNullable()` on the unstripped type, and `DataTypeLowCardinality::isNullable` returns `false` because the wrapper is not itself nullable, its dictionary is. So an argument of type `LowCardinality(Nullable(Interval*))` declared the slot plain `Int64`, while the framework hands the plan that column with only the `LowCardinality` wrapper removed and its null map intact. `multiply` then received a `ColumnNullable` labelled `Int64`; declared `Int64` times `Int64` is a legal pair, so the numeric branch was chosen, `executeNumeric` could not match `ColumnNullable` to `ColumnVector<Int64>`, and `FunctionBinaryArithmetic` threw the logical error whose own comment states the violated invariant. The sibling helper `castTo` in the same file already strips the wrapper before asking; this one did not. That is also why `Nanosecond` never failed - `delegate` short-circuits that kind to `castTo`. Found by the fuzzer under `Stress test` on two unrelated pull requests 1.6 hours apart, on different architectures and build types (STID 2735-4fde `arm_release`, STID 2735-5108 `amd_debug`). Introduced by ClickHouse#112932, which is on no release branch and 26.9 is unreleased, so nothing has shipped and no backport is needed. The three sibling `kql*` resolvers that build a plan the same way misroute a `LowCardinality` argument at a different predicate, their type-family gate. That changes accepted input and result types, so it is deliberately not part of this change. Co-Authored-By: Claude Opus 5 <[email protected]>
Three unrelated reds on the previous head, plus the last unresolved review finding: 1. `Style check` and `Build (arm_tidy)` both flagged the same empty `catch (...)` in `ClientBase::queryNeedsContinuation` (`catch_all` and `bugprone-empty-catch`). Give the handler a body: the "is the KQL failure at the end of input" decision is now recorded in a local flag instead of returning from inside the handler. 2. `Fast test` timed out on `04510_kusto_continuation_no_side_effects`, `04511_set_dialect_continuation`, `04647_set_dialect_param_continuation` and `04692_kusto_throwing_operator_continuation`. The continuation behaviour is correct in all four -- the buffer folds and the completed query runs -- but the assertions went stale after the KQL rewrite (ClickHouse#112932): `print` now emits a `Column1` result column, so `PrettyCompact` pads the value (`| 1 |`, not `| 1 |`), and `numbers(3)` is no longer a KQL table expression. The assertions now tolerate the padding, and `04692` probes `system.numbers | take 3 | where number !between (`, which still reaches the throwing KQL operator parser at end of input. 3. Addressed the AI review finding on the `clickhouse_json` fast path: a JSON AST statement can be an `ASTSetQuery` (it is what `parseQueryToJSON('SET dialect = ...')` produces), and the executor applies its changes before parsing the next statement. The probe skipped past the balanced object without applying anything, so a JSON `SET dialect = 'clickhouse'` followed by an incomplete `SELECT` was still probed as JSON, judged complete, and committed -- running the `SET` while the last statement was still being typed. The object is now deserialized (only when a `;` shows that more statements follow) and a `SetQuery` is mirrored through the same path as a SQL `SET`, which is factored out into `mirror_set_query`. New test `05137_json_dialect_set_continuation.expect`; it fails against a build with the mirroring removed and passes with it. All 11 continuation `.expect` tests pass locally against a freshly built binary.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reimplemented the experimental KQL (Kusto) dialect. It now has its own lexer and parser and builds an AST directly, instead of translating a token stream into SQL text and reparsing it. This fixes an expression-injection hole in the string operators (
contains,has, ...), several results that silently disagreed with Kusto (7 / 2,substringwith a negative start,bin), and 28 functions that were registered but did nothing. The supported subset is smaller and documented; anything outside it is now rejected by name instead of being mistranslated.Documentation entry for user-facing changes
docs/guides/clickhouse/kusto-query-language.mdxWhy
The dialect was contributed in 2022 and abandoned by its authors; the rewrite they promised in #62668 was closed unmerged. Since then it has been emergency-disabled once (#59305) and gated behind
allow_experimental_kusto_dialect(#74224), and #61742 ("Remove KQL support if this code will not be fixed") has stayed open.The implementation translated a KQL token stream directly into ClickHouse SQL text and reparsed it — 298
fmt::formatsites, 41 places that re-lexed generated text, and no AST anywhere in the function layer. Everything below follows from that:T | where s contains "x') OR 1 = 1 OR ilike(s, 'y"ASTLiteral; no injection is representable'50x' contains '50%'true— needle was pasted into a LIKE patternfalsesubstring('abcdefg', -3, 2)'ab''ef'7 / 23.53format_timespan(col, 'hh:mm')stoi: no conversion—std::stoion generated SQLseries_fir(...)Function series_fir does not exist(one of 28 stubs)search 'x'Unknown table expression identifier 'search''search' is not a supported KQL operatorletbindingsstatic thread_local, leaked between queriesWhat is here
Two commits: the removal, then the reimplementation.
KQL now has its own entry point (
parseKQLQuery) and never touches the SQL tokenizer. BecauseClientBasealready catches, the parser can simply throw — so there is notryParseKQLQuery, and nocatchanywhere in the new code.src/Parsers/Kustono longer needs its carve-out from check 19 ("do not catch exceptions in src/Parsers"), and this PR deletes it.src/Parsers/Kustogoes from 13017 lines to 3967, plus 337 lines of runtime functions.Scope
Deliberately smaller than before, and written down in the guide. A construct is either translated with the semantics Kusto documents, or rejected by name. Rejected in this PR:
search,parse,mv-apply,lookup,evaluate,invoke,facet,top-nested,make-seriesand friends; theseries_*,bag_*/pack_*andipv4_*families;parse_url,parse_csv,parse_json,toscalar,format_timespan; anddynamicobjects (arrays map onto ClickHouseArray).Three known divergences are documented rather than papered over: subtracting two datetimes yields seconds instead of a timespan,
project-renamemoves the renamed column to the end, andunionneeds compatible schemas.Testing
04670–04673cover the pipeline, the string operators (including the injection cases), the scalar semantics that used to be wrong, and 47 constructs that must be rejected. A 2500-query random fuzz found no crashes or logical errors.The 302 conformance cases that were deleted with the old implementation are being reintroduced separately, on top of this branch.
Workflow [PR]
Sync PR [sync-upstream/pr/112932]