Skip to content

Reimplement the KQL (Kusto) dialect on a lexer, an AST and AST translation - #112932

Merged
alexey-milovidov merged 89 commits into
masterfrom
kql-rewrite
Aug 29, 2026
Merged

alexey-milovidov merged 89 commits into
masterfrom
kql-rewrite

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Experimental Feature

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, substring with 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.mdx


Why

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::format sites, 41 places that re-lexed generated text, and no AST anywhere in the function layer. Everything below follows from that:

before after
T | where s contains "x') OR 1 = 1 OR ilike(s, 'y" injected the expression needle is an ASTLiteral; no injection is representable
'50x' contains '50%' true — needle was pasted into a LIKE pattern false
substring('abcdefg', -3, 2) 'ab' 'ef'
7 / 2 3.5 3
format_timespan(col, 'hh:mm') stoi: no conversion — std::stoi on generated SQL rejected by name
series_fir(...) Function series_fir does not exist (one of 28 stubs) rejected by name
search 'x' Unknown table expression identifier 'search' 'search' is not a supported KQL operator
let bindings static thread_local, leaked between queries scoped to one parse

What is here

Two commits: the removal, then the reimplementation.

src/Parsers/Kusto/
  KQLLexer      KQL's own tokens: !in, =~, .., timespans (2.5h), verbatim @'...',
                datetime(...). A bad literal is an Error token carrying a reason,
                so nothing downstream asks isValidKQLPos() — the core of #61742.
  KQLAST        the tabular level only. Scalar expressions are ClickHouse AST
                directly; a parallel expression hierarchy would add only conversions.
  KQLParser     recursive descent. `let` bindings are an ordinary member.
  KQLTranslator 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 — the choice depends on operand
  kqlBin        types, so it is made by an IFunctionOverloadResolver during analysis
                rather than guessed from how the argument was spelled.

KQL now has its own entry point (parseKQLQuery) and never touches the SQL tokenizer. Because ClientBase already catches, the parser can simply throw — so there is no tryParseKQLQuery, and no catch anywhere in the new code. src/Parsers/Kusto no longer needs its carve-out from check 19 ("do not catch exceptions in src/Parsers"), and this PR deletes it.

src/Parsers/Kusto goes 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-series and friends; the series_*, bag_*/pack_* and ipv4_* families; parse_url, parse_csv, parse_json, toscalar, format_timespan; and dynamic objects (arrays map onto ClickHouse Array).

Three known divergences are documented rather than papered over: subtracting two datetimes yields seconds instead of a timespan, project-rename moves the renamed column to the end, and union needs compatible schemas.

Testing

04670–04673 cover 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]

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.
@alexey-milovidov
alexey-milovidov requested a review from a team as a code owner August 1, 2026 16:56
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5c1cc13]

Summary: ✅


AI Review

Summary

This 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
  • ❌ [src/Parsers/Kusto/KQLParser.cpp:679] Nested function-body classification drops the nested function's scalar parameters, so a scalar inner UDF like let F = (x:long) { x } is misclassified as tabular. That propagates outward and makes valid scalar calls such as let Outer = () { let F = (x:long) { x }; F(1) }; print Outer(); fail with the tabular-function guard. The nested-function path in bodyLooksTabular needs to seed the inner parameter names the same way parseFunctionDefinition does, or reuse the same classification logic.
  • ❌ [src/Functions/Kusto/FunctionKQLMultiply.cpp:72] kqlMultiply preserves the original interval kind and scales its raw unit count directly, which silently breaks fractional scaling for ClickHouse interval functions that KQL now allows through. print 1.5 * toIntervalHour(1) is lowered to kqlMultiply(1.5, toIntervalHour(1)), multiplies the raw hour tick 1 by 1.5, truncates it to 1, and returns IntervalHour(1) instead of a 90-minute duration. This path needs to normalize fixed-length interval kinds to nanoseconds before scaling, or reject non-KQL interval kinds explicitly.
Tests
  • ⚠️ Add a focused regression where a scalar UDF declares an inner scalar UDF with parameters and then calls it from scalar context, e.g. let Outer = () { let F = (x:long) { x }; F(1) }; print Outer();.
  • ⚠️ Add a regression for fractional scaling of a non-IntervalNanosecond ClickHouse interval reached from KQL, e.g. print 1.5 * toIntervalHour(1).
Final Verdict

Status: ❌ Block
Minimum required actions: fix the nested-UDF tabular/scalar misclassification, make kqlMultiply preserve actual duration semantics for non-IntervalNanosecond intervals, and add the focused regressions above.

LLVM Coverage Report

Measured on commit 5c1cc13.

Metric Baseline Current Δ
Lines 88.40% 88.50% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 3899/4372 (89.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 1, 2026
@mintlify

mintlify Bot commented Aug 1, 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 Aug 1, 2026, 5:23 PM

…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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 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] in ClickHouse.

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: 02366_kql_func_iif, 02366_kql_tabular, 04123_kql_operators, 02366_kql_native_interval_format.

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 make-series suites (neither family is supported), the kql() table-function OOM regression (that parser no longer exists), and the assertion that array_sort is gone.

Running the restored tests found fourteen real defects, all fixed in the same commit — among them trim_start/trim_end taking a regex in Kusto but being mapped onto ClickHouse's one-argument trimLeft/trimRight; extend x = * Price raising LOGICAL_ERROR; a[-1] indexing from the front; decimal(1.23) printing as 1.23000000000000000002; and format_datetime returning its format string unchanged because Kusto's yyyy-MM-dd specifiers are not ClickHouse's (now rejected rather than approximated).

Also added: the typed literals bool(), int(), long(), real(), decimal(), time(), timespan(), typeof(), the endof* family, and set_intersect / set_difference / pack_array.

Known gaps, deliberately left

  • format_datetime and extract_all are rejected until they can be translated faithfully.
  • Datetimes print as 2017-01-01 00:00:00, not Kusto's 2017-01-01T00:00:00.0000000; they are real DateTime64 values now, which the old string-formatted output was not.
  • Timespans need interval_output_format = 'kusto' to render as 1.00:00:00. Making the dialect imply that setting would be an improvement.
  • ClickHouse's parametric aggregates (quantileExact(0.5)(x)) have no KQL spelling.

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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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.

Kusto documents supported here
Tabular operators 52 20
Scalar + aggregate functions 307 123

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 (cos, pi, not, any) or fails cleanly on case (extractAll, toTime, isASCII).

Two defects this found, fixed in 7a1340f

summarize AvgCpu = avg(v) by Computer, bin(TimeGenerated, 1h) did not work. Kusto names a computed group key after its source column, so the key is TimeGenerated — and emitting kqlBin(TimeGenerated, …) AS TimeGenerated … GROUP BY kqlBin(TimeGenerated, …) either fails with 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. This is the canonical KQL query shape, so it mattered.

repeat, replace and translate were reaching ClickHouse through the escape hatch and running with ClickHouse's meaning. Kusto's repeat(value, n) builds an array where ClickHouse's repeats a string; Kusto's replace(regex, rewrite, text) orders its arguments differently. Both returned a plausible wrong answer. They're on the guard list now.

The main gaps, in rough order of how much I'd expect users to hit them

  1. User-defined functions — let f = (x: long) { x * 2 }. let binds a scalar or a tabular expression but not a lambda. This is the biggest single gap: UDFs are how non-trivial KQL is organised.
  2. parse / parse-where — extracting fields from unstructured text is a large part of what KQL is used for in Sentinel and Log Analytics.
  3. make-series plus the series_* family (51 functions) — the whole time-series analysis half of the language.
  4. mv-apply, evaluate and its plugins (bag_unpack, pivot, narrow, …), search, find, lookup, top-nested, scan, partition, fork, facet.
  5. dynamic objects — property bags, bag_*/pack_*, x.y member access. Only arrays are mapped.
  6. Operator options — mv-expand … to typeof(T) / limit N, summarize hint.*, union kind= / withsource= / isfuzzy=, join hint.*. These currently parse as far as the option and then fail confusingly rather than saying the option is unsupported.
  7. Function families: IPv4/IPv6 (18), geospatial (52), binary (7), hash beyond md5/sha256, datetime_add/datetime_part, the window functions next/prev/row_number/row_cumsum (which need serialize), gettype, bin_auto, toscalar, materialize.
  8. Smaller syntax: project-reorder, project-by-names, obfuscated (h"…") and multi-line (triple-backtick) string literals, application statements (alias database, declare query_parameters, restrict access to).

Two conformance details worth recording

Both already match, but they're the ones implementations most often get wrong, so they're worth stating: join defaults to innerunique, not inner; and sort by defaults to desc with null placement flipping with direction. The docs also confirm bin() and floor() are the same function and that a negative bin size yields null.

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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

User-defined functions are implemented in 53fc90b — the largest gap the doc comparison turned up.

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

How

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 lets already go through, and it is why a 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 one 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 (f(c = 7, a = 12) — both of Microsoft's own examples reproduce exactly); a body of zero or more lets and one expression, which sees the bindings that enclose it and whose parameters shadow them; a parameterless function called with or without parentheses; and view (), accepted and meaning () here since nothing resolves union * wildcards.

Rejected, each by name

Recursion (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 Maximum parse depth (1000) exceeded, not a crash.

Worth knowing

A let binds only for the statement that follows it, because 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 lets just as much:

let n = 5; print n; print n     -- the second `print` does not see `n`
let n = 5; print a = n, b = n   -- fine

Kusto 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; various_checks.sh and check 19 are clean.

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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

I went through item 7 family by family, checking each against its Microsoft reference page rather than mapping by name. Pushed as 59177f5: 123 of the 307 documented function names becomes 162.

Mapped, and verified against Microsoft's own printed examples

Family Done Notes
Binary 7 / 7 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(_mask), ipv4_compare, ipv4_is_match, ipv4_is_in_range, ipv4_is_in_any_range, ipv4_is_private, ipv4_netmask_suffix, plus four IPv6 counterparts.
Geospatial (point half) 9 geo_distance_2points, geo_point_in_circle, geo_point_to_geohash, geo_point_to_h3cell, geo_h3cell_level / _parent / _children / _neighbors.
Maths & strings 20 trig, gamma, loggamma, erf, erfc, cot, pi, 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, µs/ns unixtime_*.

Traps a name-to-name mapping would have walked into

  • ClickHouse's geoToH3 takes latitude first, while every Kusto geo_* takes longitude first. Mapping positionally gives a valid-looking H3 cell for the wrong place on Earth.
  • greatCircleDistance is a fast approximation on a different radius — about 600 m out over 1500 km. Kusto uses a sphere of radius exactly 6,371,010 m, which I recovered by solving its documented example. The haversine is written out so geo_distance_2points(-122.407628, 47.578557, -118.275287, 34.019056) returns 1546754.351973809 against the doc's 1546754.35197381.
  • A CIDR suffix inside an IP string masks the low bits rather than being ignored: parse_ipv4('192.168.1.1/24') is 3232235776, not …777.
  • IP comparison uses the narrowest prefix of both operands and any explicit one, so ipv4_compare('192.168.1.1/30', '192.168.1.255/24') is 0.
  • ipv4_is_private is RFC 1918 only — loopback is not private, which Microsoft calls out explicitly.
  • datetime_part's sub-second parts are cumulative, not disjoint: .7654321 gives 765, 765432, 765432100.

Two defects found by reading the reference

  • dayofweek() returned a number. Kusto returns the timespan since the preceding Sunday, so a Monday is 1.00:00:00. This changed two conformance references — for the better.
  • tohex() upper-cased and zero-padded to whole bytes.

Still rejected, now for a stated reason

  • Every geospatial function that takes or returns GeoJSON — all the *_to_central_point ones and the whole polygon/line half. These need the dynamic object mapping the dialect doesn't have, which is the real blocker behind this half of item 7.
  • geo_point_to_s2cell — ClickHouse's geoToS2 returns a UInt64 and there is no S2 token-string form, so the result would not be a Kusto S2 token.
  • has_ipv4 / has_ipv4_prefix / has_any_ipv4* — these are term-delimited text searches with a trailing-dot rule for prefixes, not substring matches.

The rest of item 7, assessed but not done

  • gettype wants a runtime type name mapped to Kusto's vocabulary (long, real, dictionary, array, …). Needs a small IFunction, like kqlDivide — straightforward, just not done here.
  • toscalar maps cleanly onto a scalar subquery, but its argument is a tabular expression, so it needs parser handling like typeof rather than a registry entry.
  • The next/prev/row_number window functions need serialize and a defined row order first; ClickHouse has the window functions, so this is gated on the operator rather than the functions.
  • bin_auto reads query_bin_auto_size / query_bin_auto_at set by a set statement, so it needs those plumbed through as settings.

All 25 test files pass; 04676 checks every new mapping against its documented value. various_checks.sh and check 19 are clean.

`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Switched geo_distance_2points / geo_point_in_circle to ClickHouse's fast greatCircleDistance (6fb578d), per the steer that 100% Kusto compatibility is not the goal here. The written-out exact haversine on Kusto's 6371010 m sphere is gone.

The distance is now about 600 m out over 1500 km — Seattle to Los Angeles gives 1547353.4142994815 where Kusto prints 1546754.35197381. These functions are normally used to filter rather than to report, and Kusto's own documentation recommends the sphere over the spheroid for performance.

Two things fell out of the switch:

  • use_spheroid is a real fifth Kusto parameter that the haversine version accepted and silently ignored. It now selects geoDistance, the ellipsoid formula.
  • greatCircleDistance and geoDistance reject non-float arguments, so coordinates are widened with toFloat64 exactly as the neighbouring geo_* mappings already do. geo_distance_2points(1, 1, 2, 2) used to fail on the argument type and now works.

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; 04676_kql_function_families gained the spheroid case and its reference was regenerated.

`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.
Comment thread src/Parsers/Kusto/KQLTranslator.cpp Resolved
Comment thread src/Parsers/Kusto/KQLTranslator.cpp Resolved
Comment thread src/Parsers/Kusto/KQLParser.cpp Resolved
Comment thread src/Parsers/Kusto/KQLParser.cpp Resolved
Comment thread src/Parsers/Kusto/KQLFunctions.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5c1cc13e5 with master f1840f9f3 (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 712.38 MiB 709.10 MiB -3.28 MiB (-0.46%)

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 ⚠️

8 object files changed (+3.88 MiB total), 11 added.

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

Job report

alexey-milovidov and others added 3 commits August 4, 2026 04:06
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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed be2164446db1: merged master (the branch was behind since 2026-08-12; the only conflict was src/Parsers/Kusto/ParserKQLOperators.cpp, which this PR deletes and which master had touched in #115066's !~ operator work — the new KQLLexer handles !~ itself, so the file stays deleted), fixed the one CI red, and addressed all five AI-review findings (four blockers and the major).

  • The Stateless tests red, 02366_kql_func_string (773d46408bfe), was this PR's own stale reference: extract lowers to arrayElementOrNull over extractGroups, so a capture group the pattern does not have is NULL — which is exactly what 04927_kql_review_regressions pins for a pattern that does not match — while the reference still expected the empty string for extract('(\\b[A-Z]+\\b).+(\\b\\d+)', 3, ...).
  • Exact timespan scaling and range counting (f2b11a4fd7c7): kqlMultiply, kqlToTimespan and kqlRangeCount no longer read their numeric argument through Float64. New KQLExact helpers read an integer of any width, or a decimal's unscaled digits, into Int256; 1d * decimal(0.57) and totimespan(decimal(0.57)) are 49248000000000 again, and kqlRangeCount(toUInt128(9007199254740993), toUInt128(9007199254740995), toUInt128(1)) is 3. Only a float keeps the long double path, and an out-of-carrier result is still BAD_ARGUMENTS.
  • The tabular-parameter schema is honored (be2164446db1): the declared column names are remembered and binding a tabular argument projects it onto them, so let F = (T:(a:long)) { T | project b } cannot reach b from the call site. T:(*) passes the argument through; T:() and a duplicate column are syntax errors.
  • A tabular-bodied function is no longer a value (be2164446db1): a scalar site rejects it instead of re-parsing its body as an identifier, so datatable (Source:long) [7] | extend y = F no longer silently returns the row's Source column.

New test 05044_kql_exact_scaling_and_tabular_contract; the guide documents both function rules. All 47 KQL stateless tests pass locally against a server via tests/clickhouse-test, and check_cpp.sh and various_checks.sh are clean.

Comment thread src/Parsers/Kusto/KQLParser.h Resolved
Comment thread src/Functions/Kusto/FunctionKQLBin.cpp Resolved
…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);

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.

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;

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.

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.

@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 Aug 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into master with commit 5cd66ef Aug 29, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the kql-rewrite branch August 29, 2026 20:49
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
alexey-milovidov added a commit that referenced this pull request Aug 30, 2026
`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
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 31, 2026
…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]>
alexey-milovidov added a commit to Onyx2406/ClickHouse that referenced this pull request Sep 8, 2026
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.
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks

This branch was successfully deployed

1 active deployment
staging - docs — 5c1cc13e Deployed Aug 28, 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.

3 participants