Skip to content

Build the SQL parser standalone: cut abseil, cctz, re2, boost, locale and the settings schema - #111986

Closed
alexey-milovidov wants to merge 22 commits into
masterfrom
parser-standalone-v2
Closed

alexey-milovidov wants to merge 22 commits into
masterfrom
parser-standalone-v2

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Supersedes #111971 and
#111952 — both are contained here and can be closed.

How small does src/Parsers get when built on its own? utils/wasm-parser answers it: a build
script, a five-function C entry point and a test, producing a 1.6 MB WebAssembly module (463 KB
gzipped)
that parses, pretty-prints and reports syntax errors with positions. It runs on any
engine — no flags, no exception-handling proposal. The motivating use case is
programs/server/play.html, which today ships only the lexer.

Most of the value is in what had to be cut to get there, and almost none of it is parser code.
Everything below stands on its own.

Dependencies the parser did not need

abseil, cctz, re2, boost::algorithm::string and Core/Settings.h are all gone from the parser's
transitive closure.

  • cctz and the timezone database entered through one line: SYSTEM ... SET FAKE TIME was parsed
    and formatted through DateLUT. Which timezone applies belongs to the server, not to the query
    text, so the AST keeps the literal and the interpreter resolves it.
  • re2 was reachable from three places. Two were regular expressions doing what a string scan does
    (maskURIPassword, Azure connection strings). The third compiled COLUMNS('regexp') patterns
    inside IASTColumnsTransformer::transform — applying a transformer needs the expanded column
    list, so it is name resolution, and it moves to Interpreters/applyColumnsTransformer.cpp.
    Validating a GRANT ... ON S3('...') pattern moves to InterpreterGrantQuery.
  • abseil went with re2, plus IParser.h wanting a short non-allocating list and
    LiteralTokenMap wanting a flat map. The latter gets a purpose-built open-addressing table
    which is faster than abseil's at every size, because nothing erases and the first entries live
    inside the object.
  • ParserSetQuery consulted the settings schema for one thing — whether a bare SET x names a
    Bool setting. It records that the value was omitted and BaseSettings::applyChange checks the
    type, which is where the schema is known.

Exceptions

The parser used throw/catch to choose between alternatives, which is the wrong mechanism — the
failure is an ordinary parse outcome, and one of the four sites fired on any malformed string
literal. All four are gone, src/Parsers contains no catch, and a style check keeps it that
way. That lets the standalone build use -fignore-exceptions, which dropped 262 KB and the need
for an engine implementing the exception-handling proposal.

Locale

Nothing wants a locale — keywords, identifiers and access-type names are ASCII — but twelve
objects were pulling <locale> in. boost::to_lower and friends are locale-based, and
AccessType.h reached <ostream> through boost/algorithm/string/split.hpp. Poco's
Bugcheck::what built one message with an ostringstream, and since Bugcheck.h comes in via
Poco/Foundation.h, that single include cost 181 KB. A second style check forbids
boost::to_lower/to_upper where the locale must not be linked.

Costs that were not the parser

abi::__cxa_demangle was 132 KB, reached only to put a type name in an exception message.
ErrorCodes::values was 150 KB of data — the per-code error statistics behind system.errors,
which a parser has no use for. Two Access tables were built at startup by expanding a macro list
at each of 258 call sites; they are constexpr-driven now.

Latent bugs found on the way

  • ASTSQLSecurity::formatImpl was defined identically in two translation units. Static-library
    linking never pulls both objects in, so the ODR violation stayed invisible.
  • Several includes were entirely unused, the widest being Poco/Util/Application.h in
    DumpASTNode.h, which reaches Poco::ThreadPool and is pulled in by InDepthNodeVisitor.h —
    over sixty translation units were paying for it.
  • 32-bit correctness, all latent: a uz literal that does not fit a 32-bit size_t, a
    ProfileEvents counter/increment size mismatch, a Boost stored_size constraint in ASTs, and
    itoa/iota guarding their long overloads on OS_DARWIN when the real condition is that
    long is a distinct type.

For every build, not just the standalone one

The SQL keyword table was built at startup by 645 inlined resize/string-assign/emplace
sequences, compiling to a 57 KB constructor — the largest function in the parser — and costing 645
string allocations per process. It is a constexpr std::array now, and the two consistency checks
the constructor performed became static_asserts, so they also run in release builds. Every
throw() exception specification in base/poco is now noexcept.

Testing

No behaviour change is intended except where listed, so coverage is existing tests plus two unit
tests where hand-written code replaced a library:

  • gtest_mask_uri_password.cpp checks the string scan against the regular expression it replaces;
    they also agree on 200000 random strings over ab:@/. and newline. This is masking of secrets,
    so "close enough" is not good enough.
  • gtest_literal_token_map.cpp covers overwriting, growth past the inline storage, and agreement
    with std::unordered_map over 500 randomised rounds.

User-visible changes, all deliberate:

  • SET max_threads reports TYPE_MISMATCH from the server rather than a syntax error from the
    client (03623 updated). It does not silently become max_threads = 1, which is what
    deferring the check without a marker would have done.
  • An invalid GRANT ... ON S3('[') pattern reports CANNOT_COMPILE_REGEXP instead of a syntax
    error. It cannot simply be dropped: the pattern is matched with RE2::FullMatch, so one that
    does not compile would grant nothing, silently.
  • SYSTEM ... SET FAKE TIME echoes its literal instead of renormalising it when formatted.
  • A malformed URI in a setting value is now masked rather than printed; user@host with no
    password is no longer rewritten to user:[HIDDEN]@host, since there is nothing to hide.
  • Case-insensitive comparison of keywords and access-type names is ASCII rather than
    locale-driven.

Verified with a full dbms build, the whole of check_cpp.sh, and the standalone build's test
suite at every step.

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Reduced the dependencies and the code size of the SQL parser, which can now be built on its own — see utils/wasm-parser for a standalone WebAssembly build of it. The table of SQL keywords and the access-type tables are now built at compile time instead of on every server start.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

alexey-milovidov and others added 10 commits July 26, 2026 20:40
…ncies

Groundwork for building `src/Parsers` on its own (the WebAssembly experiment in
`utils/wasm-parser` that follows). Everything here stands on its own as a fix or a
build-time improvement; nothing is WebAssembly-specific except the platform guards.

Dependencies the parser did not need:

* `DumpASTNode.h` included `Poco/Util/Application.h` and never used it. That header
  reaches `Poco::ThreadPool` and `Poco::SignalHandler`, and `DumpASTNode.h` is pulled in
  by `InDepthNodeVisitor.h`, so over 60 translation units paid for it.
* `ExpressionListParsers.cpp` included `AggregateFunctions/AggregateFunctionFactory.h`
  and never used it either, dragging `IAggregateFunction` and all of `Columns` into one
  of the heaviest translation units in the tree.
* `ParserSystemQuery.cpp` included the whole Keeper client for three path-string
  helpers. Those move to a new `Common/ZooKeeper/ZooKeeperPathUtils.h`; `ZooKeeper.h`
  includes it, so every existing user is unaffected.

`ASTSQLSecurity::formatImpl` was defined identically in both `ASTSQLSecurity.cpp` and
`ASTCreateQuery.cpp`. Static-library linking never pulls both objects in, so the ODR
violation stayed latent; it becomes a duplicate-symbol error as soon as the objects are
linked directly. Removed the copy in `ASTCreateQuery.cpp`.

`CommonParsers.cpp` built the keyword table at startup: 645 inlined
`resize`/`std::string` assign/`unordered_set::emplace` sequences, which compiled to a
57 KB constructor - the single largest function in the parser - plus 645 string
allocations and a hash-set build in every process. It is a `constexpr
std::array<std::string_view, N>` now, indexed directly by `Keyword`; the two consistency
checks the constructor performed became `static_assert`s, so they now also run in release
builds. `getAllKeyWords` and `getKeyWordSet` only feed system tables and query
obfuscation, so they materialize on first use.

32-bit correctness, all of which were latent:

* `ASTs` asked Boost for a `uint32_t` stored size, which Boost rejects unless the type is
  strictly smaller than `size_t`. Pick `size_t` when there is nothing to shrink.
* `DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS` was a `uz` literal that does not fit in a 32-bit
  `size_t`, and is compared against a `UInt64` read off the wire.
* `ProfileEvents::Count` was `size_t` while `Increment` was `Int64`, tripping the
  `static_assert` that the two match.
* `itoa` and `iota` guarded their `long`/`size_t` overloads on `OS_DARWIN`. The real
  condition is that `long` is a type of its own, which is also true on any 32-bit
  platform, so the guard is now `!defined(__LP64__)` as well.
* `CLOCK_MONOTONIC_COARSE` is a Linux extension; `base/time.h` listed the platforms that
  need a substitute one by one and now falls back generically.

`base/defines.h` and Poco's `Platform.h` learn about `__wasm__` so that headers naming
the platform stop erroring out.

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

Three visitors in `src/Databases` were relying on `DumpASTNode.h` to give them
`Poco/Util/AbstractConfiguration.h` transitively; they include it themselves now.
An experiment in how small `src/Parsers` gets on its own. The Web UI currently ships only
the lexer (`Lexer.cpp` builds to a 6 KB `.wasm` with no dependencies); a real parser would
give exact syntax errors with positions and query pretty-printing in the browser.

`utils/wasm-parser/build.sh` compiles 500 translation units with wasi-sdk and links a
2.7 MB module (789 KB gzipped) exporting a five-function C interface. `test.mjs` drives it
through `SELECT`, `CREATE TABLE`, window functions, recursive CTEs, `ALTER`, `INSERT`,
`SYSTEM`, `CREATE USER`, `GRANT`, and two deliberate syntax errors.

`-fwasm-exceptions` is required rather than optional: the parser reports errors by
throwing, and the wasi-sdk headers refuse `setjmp.h` without it.

`wasm_runtime.cpp` substitutes no-ops for the pieces a browser has no use for, each of
which would otherwise dominate the bundle. Stack traces are the sharpest case:
`Common/Exception.cpp` cannot compile against stock libc++ at all, because it
`static_assert`s on `STD_EXCEPTION_HAS_STACK_TRACE` from ClickHouse's patched libc++.
`Core/Settings.cpp` is left out because `ParserSetQuery` calls `Settings::castValueUtil`
once - only to ask whether a bare `SET x` names a `Bool` setting - and that single call
pulls in every `SettingField*Traits` specialization, more code than the parser itself.
The timezone database that `contrib/cctz-cmake` generates into the binary is left out
too, as is query masking.

`shim/` holds the POSIX headers wasi-libc omits (`netdb.h`, `ucontext.h`, `sched.h`,
`pwd.h`, `fenv.h` rounding modes, `sun_path`, `__u6_addr`). Nothing calls into them; they
exist so headers that name those types in signatures still compile.

The README records where the size goes. The largest remaining cut is access-entity DDL:
`CREATE USER`/`ROLE`/`QUOTA`/`ROW POLICY` and `GRANT` account for 334 KB of parser and
`Access` code, roughly a third of the bundle once the re2 and abseil they share with
`COLUMNS('regexp')` matchers is counted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…confine re2

Continues cutting what `src/Parsers` drags in. Measured on the standalone WebAssembly build
(`utils/wasm-parser`), which links only the parser's transitive closure.

abseil is gone. `IParser.h` used `absl::InlinedVector` for the list of expected tokens, which
is a short append-only list that must not allocate - `Parsers/InlineVector.h` does that in
80 lines. `LiteralTokenMap` used `absl::flat_hash_map`; it is only populated when a caller asks
for literal positions, so `std::unordered_map` is enough.

cctz and the timezone database are gone. They entered through one line: `SYSTEM ... SET FAKE
TIME '...'` was parsed into a timestamp with `readDateTimeText` and formatted back with
`LocalDateTime`, both of which resolve against the server timezone via `DateLUT`. Which
timezone applies is a property of the running server, not of the query text, so the AST now
keeps the literal and `InterpreterSystemQuery` resolves it. As a side effect the formatter
echoes the literal instead of renormalizing it.

re2 was reachable from three places, and is now needed only by access-entity DDL:

* `maskURIPassword` and the Azure connection-string masking in `AzureQueue_fwd.h` were regular
  expressions doing what a string scan does. `Common/maskURIPassword.h` scans instead. This is
  masking of secrets, so `gtest_mask_uri_password.cpp` checks the new code against the regular
  expression it replaces - the two also agree on 200000 random strings over `ab:@/.` plus
  newline, which is how the edge cases around leftmost-match were settled.
* `IASTColumnsTransformer::transform` compiled `EXCEPT('regexp')` patterns. Applying a
  transformer needs the expanded column list, so it is name resolution rather than parsing;
  it moves to `Interpreters/applyColumnsTransformer.cpp`, and the AST nodes go back to being
  syntax. Every caller was already in `Interpreters` or `Analyzer`.
* `parseAccessRightsElements.cpp` validates a `GRANT ... ON ...(regexp)` pattern while parsing.
  Left alone: dropping the check would silently accept a grant that can never match. re2 and
  abseil are therefore now exactly the cost of access-entity DDL.

`Core/Settings.h` is gone from the parser. `ParserSetQuery` consulted the settings schema for
one thing: whether a bare `SET x` names a Bool setting, since the shorthand means `= true`. The
parser now records that the value was omitted and `BaseSettings::applyChange` checks the type,
which is where the schema is known. `SET max_threads` reports TYPE_MISMATCH instead of a syntax
error - 03623 is updated - and, importantly, does not silently become `max_threads = 1`, which
is what deferring without the marker would have done. The two `Settings`-taking overloads of
`parseIdentifiersOrStringLiterals` had no caller inside the parser and move to `Interpreters`.

Two more dead includes: `Core/ServerSettings.h` in `ASTAlterQuery.cpp`, and the `<ranges>` and
`Poco/Util/AbstractConfiguration.h` that other files had been getting transitively through the
includes removed here.

Parser bundle: 2759909 -> 2589773 bytes; cctz 30 KB -> 0, abseil and re2 now attributable
entirely to `GRANT`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`parseAccessRightsElements` compiled the pattern of `GRANT READ ON S3('...')` with re2 while
parsing, purely to reject one that does not compile. That is semantics, and it was the last
thing keeping a regex engine in `src/Parsers`.

The check moves to `InterpreterGrantQuery::execute`, next to the existing validation of TABLE
ENGINE parameter names. It cannot simply be dropped: the pattern is matched with
`RE2::FullMatch` when access is checked, and a pattern that does not compile never matches, so
the grant would be accepted and then silently grant nothing.

An invalid pattern now reports CANNOT_COMPILE_REGEXP from the server instead of a syntax error
from the client.

With this, re2 and abseil leave the parser entirely, and `utils/wasm-parser` stops building
them: 500 translation units down to 320, and 2759909 -> 2292544 bytes (788548 -> 622764
gzipped) since this series started.

Also records in `LiteralTokenInfo.h` why that map is no longer an `absl::flat_hash_map`, and
what to do instead if it ever matters: the flat map really is about twice as fast for the
create/insert/destroy pattern used there, so the note should not be lost.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`LiteralTokenMap` was an `absl::flat_hash_map`, and it was that for a reason: it is built from
scratch for every column expression the `Values` format has to parse and for every query the
client highlights, so construction and destruction dominate, and the flat map was measurably
faster than `std::unordered_map` there. Swapping it for `std::unordered_map` to shed abseil
was a regression.

Rather than take abseil back for one map, this is a table that serves only what the parser asks
of it. Nothing erases, so there are no tombstones and probing stops at the first empty slot;
nothing iterates; keys are `ASTLiteral` addresses and never null, so a null key marks an empty
slot. The first eight entries live inside the object, which is what actually matters here - the
common case stops allocating entirely.

It is faster than what it replaces at every size, on the construct/insert/look-up/destroy
pattern the parser uses (nanoseconds per cycle, aarch64):

    entries   unordered_map   flat_hash_map   LiteralTokenMap
          1          29              12                 5
          3         121              54                10
          8         322             150                57
         64        3673            1124               497
        512       32404            7015              3516

`find` returns a pointer rather than an iterator, which is what the three call sites wanted
anyway. `gtest_literal_token_map.cpp` covers overwriting, growth past the inline storage, and
agreement with `std::unordered_map` over 500 randomised rounds including absent keys.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two related cleanups.

`boost::algorithm::string` is gone from `src/Parsers`. What it was used for was case-insensitive
comparison, ASCII case conversion, splitting, joining and trimming, so `Common/StringUtils.h`
grows a string overload of `equalsCaseInsensitive` and ASCII `toLowerASCII`/`toUpperASCII` beside
the per-character helpers it already had, and the rest became a few lines at the call site. The
comparisons are ASCII now rather than locale-driven, which is what SQL keywords, identifiers and
function names want anyway. Four of the includes turned out to be unused.

The parser also used exceptions to decide between alternatives, which is the wrong mechanism for
it - the "failure" is an ordinary parse outcome, and it forces the whole exception machinery into
a component that otherwise would not need it. All four sites are gone:

* a malformed string literal went through `readQuotedStringWithSQLStyle` and was caught to report
  a syntax error. `tryReadQuotedStringWithSQLStyle` already existed.
* `tryGetLiteralBool` let `FieldVisitorConvertToNumber` throw for anything that is not a number.
  It now asks the field what it holds.
* checking whether a word names an access type constructed `AccessFlags` and caught the failure.
  `AccessFlags::tryFromKeyword` reports it instead; the throwing constructor is unchanged and now
  shares the lookup.
* `ASTSetQuery` ran the value of `format_avro_schema_registry_url` through `Poco::URI` to find
  embedded credentials, catching `Poco::SyntaxException`. Locating credentials in a URI is not
  the parser's job and `Common/maskURIPassword.h` already does exactly this, so it just calls
  that. A URI that `Poco::URI` would have rejected is now masked rather than printed, which is
  the safer direction; a `user@host` with no password is no longer rewritten to
  `user:[HIDDEN]@host`, since there is nothing there to hide.

`src/Parsers` now contains no `catch` at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Now that `src/Parsers` has no `catch`, keep it that way: an alternative that does not match is an
ordinary parse outcome and a parser says so by returning false, and routing that through
throw/catch also drags the exception machinery into a component that otherwise does not need it.

The check exempts the harnesses under `tests/`, `examples/` and `fuzzers/`, which are expected to
catch, and `Kusto/`, which is the one part of the parser still using exceptions this way - it
falls back between a number and a timespan, and turns a failed cast into NULL. The exemption is
named in the comment rather than left implicit so it reads as remaining work.

Verified both directions: the check is silent on the tree as it stands, and fires when a `catch`
is put back into `parseQuery.cpp`. The word "catch" in the `obfuscateQueries` word list is not a
false positive, since the pattern requires the opening parenthesis.

Also fixes what running the whole of `check_cpp.sh` turned up in the preceding commits: two error
codes left declared but unused once their throws moved out (`ZooKeeper.cpp`,
`parseIdentifierOrStringLiteral.cpp`), and blank lines left behind by a removed try/catch. The
headers under `utils/wasm-parser/shim/` are exempted from the source heuristics - they deliberately
imitate wasi-libc's own headers, down to the include guards, so `#pragma once` and the indentation
rules do not apply to them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`src/Parsers` has no `catch`, and a syntax error is reported by `tryParseQuery` returning null,
not by throwing. So in a standalone build an exception can only mean a bug or a resource limit,
and there is nothing to unwind to - the exception machinery is pure overhead.

The build now passes `-fignore-exceptions`, which compiles `throw`, `try` and `catch` but emits no
landing pads and no unwind tables. This needs no source changes at all - in particular no macro
over the `throw` keyword, which would have been undefined behaviour and would have mangled the
`throw()` exception specifications in Poco. What is left is a call to `__cxa_throw`, and defining
that in the WebAssembly runtime keeps libc++abi out of the bundle entirely: the exception object
is constructed, its message printed, and the module stops.

`CLICKHOUSE_PARSER_MINIMAL_BUILD` now has a job: `Common/StackTrace.h` is included by
`Common/Exception.h` and so by most of the tree, and it needs `<csetjmp>`, `<csignal>` and
`<ucontext.h>`, none of which exist without exception handling on WebAssembly. The parts that
need them are guarded out rather than making the header unavailable. Poco's `SignalHandler` is
guarded the same way, and `Thread_POSIX` stops referring to it.

Measured, `-Os`, stripped:

    2278794 -> 2016304 bytes,  618187 -> 569362 gzipped

and the module no longer needs an engine implementing the exception-handling proposal - it now
loads on stock Node 20 with no flags, where before it required `--experimental-wasm-exnref`.

Separately, and because they are an obsolete C++ feature in a library we own: every `throw()`
exception specification in `base/poco` is now `noexcept`. There were nineteen, plus two written
`throw ()`. None of them were dynamic specifications, so this is a straight rename.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three findings from breaking down where the 2.0 MB bundle actually goes. None of them is parser
code; together they are 203 KB, about 10%.

`abi::__cxa_demangle` was 132 KB - a complete C++ name parser, more than `src/IO` and `src/Core`
put together. The only thing reaching it is a type name inside an exception message, from
`FieldVisitorConvertToNumber`, `typeid_cast` and `makeASTForLogicalFunction`. In a build with no
exception handling that message is never displayed, so `demangle` returns the mangled name, which
is what it already does when demangling fails.

`ErrorCodes::values` was 150 KB of data - 86% of the whole DATA section. It is one
`ErrorPairHolder` per error code, each holding the last message, format string, query id and
captured stack trace, twice over for local and remote, plus a mutex. That is what backs
`system.errors`; a parser needs the code-to-name table above it and nothing else.

Two tables in `Access` were built at startup by expanding a macro list at every call site, the
same pattern already fixed for the SQL keywords: `makeNodes` compiled to 35 KB and the access-type
name converter to 11 KB, because each of the 258 entries materialized its own string views and
call. Both are driven from a `constexpr` table now. `makeNodes` still builds its tree at runtime -
it resolves parent groups by name - but from a loop rather than 258 inlined calls.

    2016304 -> 1813657 bytes,  569362 -> 512278 gzipped

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…se conversion

libc++'s locale.cpp is over 150 KB and nothing in the parser wants a locale: keywords,
identifiers, access-type names and connection strings are all ASCII, and converting them
according to the C++ locale is wrong as well as expensive. Twelve objects were dragging it in,
none of them deliberately.

`boost::to_lower` and friends are locale-based, so `Access/Common` reached `std::locale` through
them - and `AccessType.h` reached it through `boost::algorithm::string/split.hpp`, which includes
`<ostream>`, so every translation unit that touched an access type paid for it. Those use the
ASCII helpers now, and `Common/StringUtils.h` gains `replaceAll` for the multi-character
replacements that `std::replace` cannot do.

The rest:

* fmt is built with `FMT_USE_LOCALE=0`; it only wanted a locale for thousands separators.
* Poco's `Bugcheck::what` built its message with an `ostringstream`. `Bugcheck.h` is reached from
  `Poco/Foundation.h`, so that single `<sstream>` put the locale tables in front of nearly every
  Poco translation unit - by itself it accounted for 181 KB of the bundle.
* `Poco/Net/IPAddress.h` included `<ostream>` for one `operator<<` declaration; `<iosfwd>` is
  enough for a declaration.

    1813657 -> 1603384 bytes,  512278 -> 462982 gzipped

Three referrers are left and locale.cpp stays linked until all of them go: Poco's `Format` and
`DigestStream`, which are stream-based by nature, and `double-conversion`, whose `ToLower` uses
`std::use_facet<std::ctype<char>>` to parse "infinity" and "nan" - that one is in the submodule
and needs a bump of the ClickHouse fork.

Check 20 forbids `boost::to_lower`/`to_upper` where the locale must not be linked. It covers
`src/Parsers`, `src/Access` and `base/poco`, which are now free of it; the rest of the tree still
has around ninety call sites, and the paths widen as those are converted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts:
#	src/Common/ErrorCodes.cpp
#	src/Common/QueryFuzzer.cpp
#	src/Interpreters/InterpreterSystemQuery.cpp
#	src/Parsers/ASTAlterQuery.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
`programs/keeper-bench/Generator.cpp` uses `std::views::keys` while relying on `<ranges>`
arriving transitively. The build defines `_LIBCPP_REMOVE_TRANSITIVE_INCLUDES`, so trimming
includes elsewhere is enough to break it, which merging master into this branch did.
The README described the module as it was in the first commit of this series: 2.7 MB with
abseil, re2 and cctz in it, requiring an engine that implements the WebAssembly
exception-handling proposal, and shimming `Settings::castValueUtil` to keep the settings schema
out. None of that is true any more - it is 1.6 MB, needs no flags, and the settings schema left
the parser's closure for good rather than being shimmed away.

Also:

* `build.sh` no longer swallows compilation failures. It piped the compilers' output through
  `grep error: | head -20 || true`, so a translation unit that failed to compile was printed and
  then ignored, and the link picked up whichever objects a previous run had left in place. Each
  object is now removed before its compiler runs, and a failure stops the build.
* `wasm_runtime.cpp` no longer defines `Settings::castValueUtil`. Nothing references it since
  `ParserSetQuery` stopped consulting the settings schema.
Deferring the "is this a Bool setting?" question from the parser to `BaseSettings::applyChange`
left the check unreachable for a query's own settings: `Context` applies them through
`Context::setSetting`, which takes a name and a value and never sees `SettingChange::shorthand`.
So `SET max_threads` silently became `max_threads = 1` - exactly the outcome the marker exists to
prevent - and `03623_setting_boolean_shorthand_err_test` failed on three of its four cases.

The check now runs wherever a whole `SettingChange` is available: `BaseSettings::applyChange` as
before, plus `Context::applySettingChange` and `Context::checkSettingsConstraints`. The constraint
check has to be covered too, because it converts the value to the setting's type first and would
otherwise report the type error as `BAD_GET` from a layer that cannot explain it - which is what
`SET default_database_engine` did.

The test gains the two cases that only the wrong-layer report would have hidden: that a rejected
shorthand leaves the setting at its previous value rather than at 1, and that `SETTINGS` in a
query is checked the same way. The latter uses `{ error ... }` rather than `{ serverError ... }`
because the client applies a query's `SETTINGS` to its own context and rejects it before sending.
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [15c8d2b]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
CI Tests DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

AI Review

Summary

This PR substantially reduces the parser's dependency footprint and adds the standalone utils/wasm-parser build, but the new valueless-setting machinery still has two correctness gaps in ASTSetQuery. Both are user-visible: one breaks the promised parseQueryToJSON / clickhouse_json round trip, and the other turns a specific invalid shorthand into the wrong exception before setting validation runs.

Findings

⚠️ Majors

  • [src/Parsers/ASTSetQuery.cpp:82] SettingChange::shorthand now changes parsing, formatting, hashing, and validation, but ASTSetQuery::writeJSON / readJSON do not serialize it. parseQueryToJSON('SET max_threads') therefore round-trips through clickhouse_json as an explicit Bool(true) change, so the JSON dialect accepts and applies a query that plain SQL is supposed to reject. Serialize and restore shorthand for every entry in changes.
  • [src/Parsers/ASTSetQuery.cpp:356] ASTSetQuery::hasSecretParts now assumes format_avro_schema_registry_url always carries a String, but the parser stores valueless settings as Bool(true) until checkShorthandChange runs. Because query logging calls hasSecretParts before InterpreterSetQuery validates the setting, SET format_avro_schema_registry_url currently fails with BAD_GET from secret detection instead of the intended TYPE_MISMATCH. Skip shorthand entries here, the same way formatImpl already does.
Tests
  • ⚠️ Add an AST JSON round-trip regression for a valueless setting, e.g. SET max_threads or SELECT 1 SETTINGS max_threads, and assert that parseQueryToJSON followed by clickhouse_json still rejects it instead of applying true / 1.
  • ⚠️ Add a focused test for SET format_avro_schema_registry_url (and the query-local SETTINGS form) to prove the error still comes from shorthand validation (TYPE_MISMATCH) rather than from ASTSetQuery::hasSecretParts.
Final Verdict

⚠️ Changes required before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Jul 27, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

This supersedes #111971, but three fixes made there after its AI review are not, as far as I can see, in this branch — worth carrying over before #111971 is closed (commits on parser-standalone-build):

  1. The standalone module aborts on a query the parser rejects by throwing. -fignore-exceptions leaves nothing to catch, so SELECT sum(x) OVER (ROWS BETWEEN UNBOUNDED FOLLOWING AND CURRENT ROW) reaches __cxa_throw and kills the instance instead of returning an error. Fixed in ebca1217404 by arming a setjmp boundary in ch_format and jumping back to it from __cxa_throw: 570 bytes and -lsetjmp (plus -mllvm -wasm-enable-sjlj), against the 262 KB and the exception-handling proposal that -fwasm-exceptions costs. Verified against a real wasi-sdk-33 build here — the module returns the message and stays usable for the next query, which test.mjs now checks.

  2. The value-less SETTINGS name check is also bypassed by the CREATE ... SETTINGS split. InterpreterSetQuery::applySettingsFromQuery moves a query setting out of the engine-settings list with setSetting(name, it->value), so CREATE TABLE t (a UInt8) ENGINE = Memory SETTINGS max_threads was accepted silently and SETTINGS default_database_engine reported BAD_GET. Fixed in 6a0d6942ab3, with 04662_setting_boolean_shorthand_in_create_settings covering both halves of the split.

  3. GRANT ... ON S3('...') patterns are validated on only one of four paths. Moving the check out of the parser into InterpreterGrantQuery::execute left CHECK GRANT, grants in users.xml and the ATTACH USER/ATTACH ROLE replay in AccessEntityIO accepting a pattern that cannot compile — and one that cannot compile grants nothing, because it is matched with RE2::FullMatch. Same commit moves it to AccessRightsElement::throwIfFilterIsNotCompilable, called from all four; test 04661_grant_source_filter_pattern_validation.

Also in bb2422f8b34: maskConnectionStringKey (the Azure account key / shared-access signature masking that replaced AccountKey=.*?(;|$)) had no test, and the randomised agreement check for maskURIPassword was described in the description but not written. Both are there now, 200000 random strings each. The connection-string scan is deliberately not equivalent: .*? cannot cross a newline, so the expression used to leave a value containing one exposed.

Comment thread utils/wasm-parser/wasm_parser.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Superseded by #111994 (branch parser-standalone-v3).

parser-standalone-v3 is this branch's series redone from the same base, plus two extra commits (LTO with -fvirtual-function-elimination, and -Oz), so it is smaller: 1.17 MB / 362 KB gzipped / 273 KB brotli versus 1.6 MB / 463 KB here. Every file touched by this branch is also touched by v3 (131 files here, 140 there, no file unique to this branch), and the three fixes made on this branch after the merge with master — the BaseSettings::checkShorthandChange call from Context::applySettingChange and every Context::checkSettingsConstraints overload carrying changes, the explicit #include <ranges> in programs/keeper-bench/Generator.cpp, and the utils/wasm-parser build.sh / README / dead Settings::castValueUtil cleanups — were all re-ported there.

The two open review findings here (the missing exception boundary around ch_format, and source-filter validation living only in InterpreterGrantQuery::execute) are also open on #111994, so nothing is lost by closing this one. Not closing it myself — pick whichever of the two to keep.

@alexey-milovidov

alexey-milovidov commented Jul 30, 2026 •

Copy link
Copy Markdown
Member Author

Update to the note above: the successor chain has moved on once more, so the branch that carries this work is now #112067 (parser-standalone-v4), which supersedes #111994, this PR, #111971 and #111952.

Re-verified today against the current heads (0906d69aad2 here, 37a51fa000d on v4): the PR-only file set of this branch against its merge base is 131 files, v4's is 158, and the only file comm -23 reports as unique here is src/Parsers/FunctionSecretArgumentsFinder.h — an artifact of master having moved that code into a new src/Parsers/FunctionSecretArgumentsFinder.cpp. All three of this branch's edits to it are present on v4 in the .cpp: equalsCaseInsensitive replaces boost::iequals for HMAC and for both NOSIGN checks (the two NOSIGN sites are folded into one is_nosign lambda there), maskConnectionStringKey replaces the AccountKey= / SharedAccessSignature= re2::RE2 patterns, and neither Common/re2.h nor boost::iequals is left in the file. So nothing here is lost by dropping this branch.

The two unresolved clickhouse-gh findings on this PR are not both carried over yet, so correcting the note above:

  • The access source-filter validation living only in InterpreterGrantQuery::execute (bypassed by UsersConfigParser, the ATTACH USER / ATTACH ROLE replay in AccessEntityIO, and InterpreterCheckGrantQuery) is fixed on v4, by AccessRightsElement::throwIfFilterIsNotCompilable called from all four paths, with test 04661.
  • The missing exception boundary under -fignore-exceptions is not fixed on v4. It is fixed only on Build the SQL parser standalone: cut abseil, cctz, re2, boost and the settings schema #111971 (ebca1217404 on parser-standalone-build, later refined by 905c264506e to gate recovery on the thrown type): a setjmp boundary armed by ch_format that __cxa_throw jumps back to, for 570 bytes and -lsetjmp. On parser-standalone-v4 today, utils/wasm-parser/wasm_parser.cpp has no boundary at all and wasm_runtime.cpp:307 still ends in std::fprintf + std::abort, on the stated reasoning that a throw can only mean a bug or a resource limit. That reasoning does not hold: src/Parsers/ExpressionElementParsers.cpp:760 throws Frame start cannot be UNBOUNDED FOLLOWING on plain user input, and :804, :1888 and :1892 are reachable the same way, so an ordinary mistyped query still kills the module instance. Worth porting to v4 before Build the SQL parser standalone: cut abseil, cctz, re2, boost and the settings schema #111971 is closed. Flagged there rather than fixed here, since the wasm build cannot be verified in this environment (no network for the wasi-sdk).

Leaving this open; which branch to keep and when to close the others is a human call. No rework or push done on parser-standalone-v2.

alexey-milovidov and others added 7 commits July 31, 2026 07:30
# Conflicts:
#	src/Parsers/ASTColumnsTransformers.cpp
#	src/Parsers/ASTCreateQuery.cpp
#	src/Parsers/ASTSetQuery.cpp
#	src/Parsers/FunctionSecretArgumentsFinder.h
`cert-msc32-c`/`cert-msc51-cpp` on the deliberately deterministic seed, and
`cppcoreguidelines-init-variables` on a pointer assigned on both branches below.
Same fix as on the superseding branch, where `Build (arm_tidy)` verified it.

Co-Authored-By: Claude Fable 5 <[email protected]>
…d out of a subquery

`QueryTreeBuilder::buildSelectExpression` reads `limit` and `offset` out of a
nested `SETTINGS` clause with `safeGet<UInt64>`, and `Field(true)` is stored as
`UInt64`, so `SELECT * FROM (SELECT number FROM numbers(10) SETTINGS limit)`
silently returned one row instead of rejecting the shorthand. Validate the
changes against the settings schema first, as on the superseding branch.

Co-Authored-By: Claude Fable 5 <[email protected]>
…orthand

The storage `SETTINGS` clause is parsed with the shorthand enabled, and
`Field(true)` is stored as `UInt64`, so `ENGINE = Join(...) SETTINGS
max_rows_in_join` silently became `1` in `registerStorageJoin`, and the raw
`String` readers (`getDiskName` of the Log family, `keeper_path` of the queue
storages) gave `BAD_GET` instead of pointing at the shorthand. Reject the
shorthand where the reader has no settings schema at hand, make `shorthand`
part of a change's identity, and apply `SET` through `applySettingChange` so
the flag survives the context-move path. Same change as on the superseding
branch, with tests `04663` and `04664`.

Co-Authored-By: Claude Fable 5 <[email protected]>
…access rights

The filter is matched with `RE2::FullMatch` when access is checked, so a
pattern that does not compile would grant nothing, silently. Validating it
only in `InterpreterGrantQuery::execute` left `users.xml` grants, the
`ATTACH USER`/`ATTACH ROLE` replay of `AccessEntityIO`, and `CHECK GRANT`
unchecked. Move the check to `AccessRightsElement::throwIfFilterIsNotCompilable`
and call it from all four paths, as on the superseding branch. Test `04661`;
`03595` now expects `CANNOT_COMPILE_REGEXP` instead of a syntax error, which is
this branch's deliberate behavior change.

Addresses the unresolved review thread on the PR.

Co-Authored-By: Claude Fable 5 <[email protected]>
…orting

A few checks in the parser still report an invalid query by throwing -
`Frame start cannot be UNBOUNDED FOLLOWING`, for one - so with
`-fignore-exceptions` a mistyped query killed the module instance. `ch_format`
now arms a `setjmp` boundary and `__cxa_throw` returns to it with the message,
as a parse failure; recovery is gated on the thrown type being exactly
`DB::Exception`, anything else still stops the module. Ported from the
`parser-standalone-build` branch, where it costs 570 bytes.

Addresses the unresolved review thread on the PR.

Co-Authored-By: Claude Fable 5 <[email protected]>
On this branch `SYSTEM ... SET FAKE TIME` keeps its literal as text - which
timezone applies belongs to the server, not to the query - so the JSON
(de)serialization added on master has to write it as a string, not an integer.
Semantic follow-up to the master merge.

Co-Authored-By: Claude Fable 5 <[email protected]>
Master added AST JSON (de)serialization to `src/Parsers`, and the `writeJSON` /
`readJSON` virtuals are referenced from every AST vtable even though nothing in
the standalone module calls them, so the link needs the symbols. (The
superseding branch strips them instead with full LTO and
`-fvirtual-function-elimination`, which this branch does not use.)

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

Copy link
Copy Markdown
Member Author

Brought the branch up to date with master (2249 commits, resolved the FunctionSecretArgumentsFinder split and the AST JSON (de)serialization conflicts — fake_time_for_view stays a string, ASTSQLSecurity::formatImpl keeps its single definition, and style check 19 exempts the JSON boundary files) and addressed both review findings:

  • the WebAssembly module now recovers from parser-thrown syntax errors through a setjmp boundary instead of aborting (185caea);
  • the GRANT ... ON S3('...') filter is validated on every path that builds access rights, including users.xml, the ATTACH USER/ATTACH ROLE replay and CHECK GRANT (a4af6ef), with test 04661.

Also carried over from the superseding branch, since the defects are in this branch's changes too: the schema check for the valueless SETTINGS shorthand before limit/offset are peeled out of a subquery (SETTINGS limit silently returned one row), the guards for raw engine-settings readers (ENGINE = Join(...) SETTINGS max_rows_in_join silently became 1), the clang-tidy fixes that made Build (arm_tidy) red, and the 03595 expectation update for the deliberate CANNOT_COMPILE_REGEXP behavior change.

Verified locally: ninja clickhouse + unit_tests_dbms green (249 relevant tests pass; the 2 ParserPRQL failures are Rust being disabled locally), full check_cpp.sh clean, all 40 ast_json tests plus 03623/04655/04663/04664 byte-identical under clickhouse local, and the grant validation spot-checked on GRANT/CHECK GRANT. The wasm build is not verifiable in this environment (no network for wasi-sdk). This branch remains superseded by #112067 — which of the two to keep is still the human's call.

Related: #112067

{
hash_state.update(change.name.size());
hash_state.update(change.name);
hash_state.update(change.shorthand);

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.

shorthand is now part of ASTSetQuery semantics (updateTreeHashImpl, the formatter, and the setting-validation paths all consult it), but writeJSON / readJSON still drop it. That breaks the parseQueryToJSON / clickhouse_json round trip for valueless settings: SET max_threads serializes as a plain Bool(true) change, deserializes with shorthand = false, and is then applied as an explicit true/1 instead of being rejected as the valueless form. The new bit needs to be serialized and restored with each change.

const auto maybe_uri = tryParseURI(change.value.safeGet<String>());
if (maybe_uri && !maybe_uri->getUserInfo().empty())
/// Secret only if there is actually a password embedded in it.
String uri_string = change.value.safeGet<String>();

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 runs before shorthand validation on the logging / query-normalization path (executeQuery.cpp calls hasSecretParts() on the parsed AST before InterpreterSetQuery ever checks the setting). For SET format_avro_schema_registry_url or SELECT 1 SETTINGS format_avro_schema_registry_url, change.value is the parser's placeholder Bool(true), so safeGet<String>() throws BAD_GET here and the user sees the wrong error from the secret-detection path instead of the intended TYPE_MISMATCH. hasSecretParts() needs the same if (change.shorthand) continue; guard that formatImpl() already has.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-build Pull request with build/testing/packaging improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant