Repository navigation
Conversation
`ParserExpressionImpl::tryParseOperand` tries `ParserCastOperator` on every opening bracket. For a collection, `parseLiteralAsText` walked the whole collection appending each token to a string, and only then looked for `::`. For an `IN` list there is none, so the text was discarded and the list was parsed again by the literal parsers. The cast parser now scans the collection on `pos` with text building off, looks for `::` at the same position, and rescans a copy of the begin position with text only when `::` follows. Scanning `pos` itself (rather than a copy) keeps the parser backtrack count unchanged: a failed scan or a missing `::` still costs exactly one backtrack (the `IParserBase` restore), so `max_parser_backtracks` sees the same count. `Expected` is not touched by the scan, and the `::` lookup happens at the same position, so error messages are unchanged. The scan also reads each token once per step instead of through `pos->` about ten times. Analysis and the original patch: issue ClickHouse#132157. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…probes `ParserCollectionOfLiterals` parsed every element with `ParserLiteral`, which tries `ParserNull` before `ParserNumber`, and for a string also `ParserNumber` and `ParserBool` (two keyword parsers) before `ParserStringLiteral`: three extra `IParserBase::parse` calls per number and seven per string, each an `Expected::add`, a depth bump and a position save/restore. `Number`, `Minus` and `Plus` tokens now go to `ParserNumber` directly and string literals to `ParserStringLiteral`. For these token types every parser `ParserLiteral` tries before them needs a bare word, so the first parser that can succeed is the one called now, and the AST is the same. An element they reject, or any other token, still goes through `ParserLiteral`. Analysis and the original patch: issue ClickHouse#132157. Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a release build each query took ~75 ms on the PR side; 100 calls instead of 30 put both above the perf guide's 0.2 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings in round 1, none in round 2), plus my own review (nits only, no code change).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261117-073100 |
|
cc @evillique, could you review this? It speeds up parsing of long literal lists such as x IN ('a', 'b', ...): the cast parser now checks for a following :: before building the list's text, and list elements that are numbers or strings go straight to ParserNumber / ParserStringLiteral instead of trying the NULL and boolean keywords first. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261117-060200 |
|
Workflow [PR], commit [d64f1ed] Summary: ✅
AI ReviewSummaryReviewed PR #132285 at Missing context / blind spots
Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Commit See the job log for details. |
|
Part 1 of this PR overlaps #133041, which also checks for Measured on master 5720d28 (Release build, 4-vCPU x86-64, the 10000-key lookups from #132157). Each cell is the median query-time ratio of 60 paired runs over both port assignments, with 95% CI; below 1 is faster.
¹ #132247 is applied to both builds. So if #133041 is merged, part 1 can be dropped: #133041 + part 2 is as fast as this PR or faster. Part 2 alone still saves 2–4% (0.5–0.7 ms per 10000 values) over #133041 on three of the four lookups. A 10-value |
This reverts bf6b05d, which made `ParserCastOperator` scan a literal collection without building its text and build it only when `::` follows. ClickHouse#133041 rewrites the same scan: it checks for `::` before building the text and also remembers the brackets where a reading failed. Both changes edit `scanCollectionOfLiteralsAsText` and `ParserCastOperator::parseImpl`, so they conflict, and ClickHouse#133041 covers this part. What stays is the independent change to `ParserCollectionOfLiterals`: numbers and strings go straight to `ParserNumber` and `ParserStringLiteral`. It merges with ClickHouse#133041 without conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: No query in clickbench or tpch_adapted_1_official showed a change that can be attributed to this PR. The tested merge changes only how the parser reads number, string and array/tuple literals (src/Parsers/ExpressionElementParsers.cpp) and adds a parser perf test. None of the benchmark queries contain literal lists, and parsing costs microseconds, far too little to affect queries that take hundreds of milliseconds. The three flagged clickbench rows (Q28 +5.9%, Q30 +21.9%, Q31 +17.8%) all fall inside master's normal run-to-run range and are correctly not counted as regressions. Q30 and Q31 both have noisy histories, and Q28's source measurements were noisy. clickbenchFlagged queries (3 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
Reading the numbers and strings of a literal list straight into the collection, without building and freeing an
Master 5720d28 + bd57a55 against the same plus the patch below; Release build, 4-vCPU x86-64. Each cell is the geometric mean ratio of the server query time ( The bodies of Patch on top of bd57a55diff --git a/src/Parsers/ExpressionElementParsers.cpp b/src/Parsers/ExpressionElementParsers.cpp
index 9379d2b..f0c6b03 100644
--- a/src/Parsers/ExpressionElementParsers.cpp
+++ b/src/Parsers/ExpressionElementParsers.cpp
@@ -1528,9 +1528,10 @@ static bool parseNumber(char * buffer, size_t size, bool negative, int base, Fie
return false;
}
-bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
+/// Reads a number literal (with an optional sign, or `inf` / `nan`) at `pos` into `res` and moves `pos` past it.
+/// `pos` is left as is on failure.
+static bool readNumberLiteral(IParser::Pos & pos, Field & res, Expected & expected)
{
- Pos literal_begin = pos;
bool negative = false;
if (pos->type == TokenType::Minus)
@@ -1541,8 +1542,6 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
else if (pos->type == TokenType::Plus) /// Leading plus is simply ignored.
++pos;
- Field res;
-
if (!pos.isValid())
return false;
@@ -1572,10 +1571,7 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
res = float_value;
- auto literal = make_intrusive<ASTLiteral>(res);
++pos;
- recordLiteralTokens(literal.get(), literal_begin, pos, expected);
- node = literal;
return true;
}
@@ -1634,10 +1630,7 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
--size;
if (parseNumber(start_pos, size, negative, 2, res))
{
- auto literal = make_intrusive<ASTLiteral>(res);
++pos;
- recordLiteralTokens(literal.get(), literal_begin, pos, expected);
- node = literal;
return true;
}
@@ -1651,10 +1644,7 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
--size;
if (parseNumber(start_pos, size, negative, 16, res))
{
- auto literal = make_intrusive<ASTLiteral>(res);
++pos;
- recordLiteralTokens(literal.get(), literal_begin, pos, expected);
- node = literal;
return true;
}
@@ -1669,10 +1659,7 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
}
if (parseNumber(start_pos, size, negative, 10, res))
{
- auto literal = make_intrusive<ASTLiteral>(res);
++pos;
- recordLiteralTokens(literal.get(), literal_begin, pos, expected);
- node = literal;
return true;
}
@@ -1680,10 +1667,7 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
}
else if (parseNumber(start_pos, size, negative, 10, res))
{
- auto literal = make_intrusive<ASTLiteral>(res);
++pos;
- recordLiteralTokens(literal.get(), literal_begin, pos, expected);
- node = literal;
return true;
}
@@ -1691,6 +1675,19 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
return try_read_float(buf, buf + buf_size);
}
+bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
+{
+ Pos literal_begin = pos;
+ Field res;
+ if (!readNumberLiteral(pos, res, expected))
+ return false;
+
+ auto literal = make_intrusive<ASTLiteral>(std::move(res));
+ recordLiteralTokens(literal.get(), literal_begin, pos, expected);
+ node = literal;
+ return true;
+}
+
bool ParserUnsignedInteger::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
{
@@ -1716,22 +1713,12 @@ bool ParserUnsignedInteger::parseImpl(Pos & pos, ASTPtr & node, Expected & expec
return true;
}
-inline static bool makeStringLiteral(IParser::Pos & pos, ASTPtr & node, String str, Expected & expected)
-{
- auto literal_begin = pos;
- auto literal = make_intrusive<ASTLiteral>(str);
- ++pos;
- recordLiteralTokens(literal.get(), literal_begin, pos, expected);
- node = literal;
- return true;
-}
-
-inline static bool makeHexOrBinStringLiteral(IParser::Pos & pos, ASTPtr & node, bool hex, size_t word_size, Expected & expected)
+static String decodeHexOrBinStringLiteral(IParser::Pos & pos, bool hex, size_t word_size)
{
const char * str_begin = pos->begin + 2;
const char * str_end = pos->end - 1;
if (str_begin == str_end)
- return makeStringLiteral(pos, node, "", expected);
+ return {};
PODArray<UInt8> res;
res.resize((str_end - str_begin + word_size - 1) / word_size);
@@ -1749,16 +1736,15 @@ inline static bool makeHexOrBinStringLiteral(IParser::Pos & pos, ASTPtr & node,
/// The buffer is sized for the worst case; a binary literal whose length is not a multiple of
/// eight can write fewer bytes than that, and the unwritten tail is uninitialized memory.
- return makeStringLiteral(pos, node, String(res_begin, res_pos - res_begin), expected);
+ return String(res_begin, res_pos - res_begin);
}
-bool ParserStringLiteral::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
+/// Reads a string literal at `pos` into `res` and moves `pos` past it. `pos` is left as is on failure.
+static bool readStringLiteral(IParser::Pos & pos, String & res, Expected & expected)
{
if (pos->type != TokenType::StringLiteral && pos->type != TokenType::HereDoc)
return false;
- String s;
-
if (pos->type == TokenType::StringLiteral)
{
char first_char = *pos->begin;
@@ -1766,24 +1752,30 @@ bool ParserStringLiteral::parseImpl(Pos & pos, ASTPtr & node, Expected & expecte
if (first_char == 'x' || first_char == 'X')
{
constexpr size_t word_size = 2;
- return makeHexOrBinStringLiteral(pos, node, true, word_size, expected);
+ res = decodeHexOrBinStringLiteral(pos, true, word_size);
+ ++pos;
+ return true;
}
if (first_char == 'b' || first_char == 'B')
{
constexpr size_t word_size = 8;
- return makeHexOrBinStringLiteral(pos, node, false, word_size, expected);
+ res = decodeHexOrBinStringLiteral(pos, false, word_size);
+ ++pos;
+ return true;
}
/// The case of Unicode quotes. No escaping is supported. Assuming UTF-8.
if (first_char == '\xE2' && pos->size() >= 6)
{
- return makeStringLiteral(pos, node, String(pos->begin + 3, pos->end - 3), expected);
+ res = String(pos->begin + 3, pos->end - 3);
+ ++pos;
+ return true;
}
ReadBufferFromMemory in(pos->begin, pos->size());
- if (!tryReadQuotedStringWithSQLStyle(s, in))
+ if (!tryReadQuotedStringWithSQLStyle(res, in))
{
expected.add(pos, "string literal");
return false;
@@ -1800,10 +1792,24 @@ bool ParserStringLiteral::parseImpl(Pos & pos, ASTPtr & node, Expected & expecte
std::string_view here_doc(pos->begin, pos->size());
size_t heredoc_size = here_doc.find('$', 1) + 1;
chassert(heredoc_size != std::string_view::npos);
- s = String(pos->begin + heredoc_size, pos->size() - heredoc_size * 2);
+ res = String(pos->begin + heredoc_size, pos->size() - heredoc_size * 2);
}
- return makeStringLiteral(pos, node, s, expected);
+ ++pos;
+ return true;
+}
+
+bool ParserStringLiteral::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
+{
+ auto literal_begin = pos;
+ String s;
+ if (!readStringLiteral(pos, s, expected))
+ return false;
+
+ auto literal = make_intrusive<ASTLiteral>(std::move(s));
+ recordLiteralTokens(literal.get(), literal_begin, pos, expected);
+ node = literal;
+ return true;
}
template <typename Collection>
@@ -1832,6 +1838,30 @@ bool ParserCollectionOfLiterals<Collection>::parseImpl(Pos & pos, ASTPtr & node,
ParserNumber number_p;
ParserStringLiteral string_p;
+ /// Reads a number or a string straight into the collection, without making a literal for it. Otherwise does what
+ /// `parser.parse` would do: notes the expected token, counts the depth and highlights the value.
+ auto read_value_in_place = [&](const IParser & parser, auto && read)
+ {
+ expected.add(pos, parser.getName());
+ Pos value_begin = pos;
+ pos.increaseDepth();
+ Field value;
+ if (!read(value))
+ {
+ pos = value_begin;
+ return false;
+ }
+ pos.decreaseDepth();
+ if (expected.enable_highlighting)
+ {
+ Pos last_token = pos;
+ --last_token;
+ expected.highlight({value_begin->begin, last_token->end, parser.highlight()});
+ }
+ layers.back().arr.push_back(std::move(value));
+ return true;
+ };
+
while (pos.isValid())
{
if (!layers.back().arr.empty())
@@ -1879,16 +1909,27 @@ bool ParserCollectionOfLiterals<Collection>::parseImpl(Pos & pos, ASTPtr & node,
}
/// `ParserLiteral` tries the `NULL` and boolean keywords before these, which need a bare word.
- ASTPtr literal_node;
bool parsed = false;
if (isOneOf<TokenType::Number, TokenType::Minus, TokenType::Plus>(pos->type))
- parsed = number_p.parse(pos, literal_node, expected);
+ parsed = read_value_in_place(number_p, [&](Field & value) { return readNumberLiteral(pos, value, expected); });
else if (pos->type == TokenType::StringLiteral)
- parsed = string_p.parse(pos, literal_node, expected);
+ parsed = read_value_in_place(string_p, [&](Field & value)
+ {
+ String str;
+ if (!readStringLiteral(pos, str, expected))
+ return false;
+ value = std::move(str);
+ return true;
+ });
+
+ ASTPtr literal_node;
+ if (parsed)
+ continue;
- if (parsed || literal_p.parse(pos, literal_node, expected))
+ if (literal_p.parse(pos, literal_node, expected))
{
- layers.back().arr.push_back(literal_node->as<ASTLiteral &>().value);
+ /// `literal_node` is discarded right after, so its value can be moved out.
+ layers.back().arr.push_back(std::move(literal_node->as<ASTLiteral &>().value));
}
else if (pos->type == opening_bracket)
{ |
…l each `ParserCollectionOfLiterals` parsed every number and string element through `ParserNumber` / `ParserStringLiteral`, so each element allocated an `ASTLiteral`, recorded its tokens, and was freed right after its value was copied into the collection. The bodies of `ParserNumber::parseImpl` and `ParserStringLiteral::parseImpl` move unchanged into `readNumberLiteral` and `readStringLiteral`, which the two parsers now wrap. The collection loop reads these elements straight into the `Field` and keeps what `IParserBase::parse` did for them: the `Expected` entry, the depth count, the restore on failure and the highlight range. The value of a literal from the `ParserLiteral` fallback is moved instead of copied. Suggested by snelheidai in ClickHouse#132285 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Folded in as d64f1ed with the |
Closes: #132157
Related: #133041
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Parsing long lists of literals, such as
x IN ('a', 'b', ...)or[1, 2, ...], is faster: numbers and strings in the list are read straight into it, without first trying theNULLand boolean keywords and without a separate literal per element.formatQueryof a query with a 10000-stringINlist takes about 40% less time.Description
ParserCollectionOfLiteralsparsed every element of a literal list withParserLiteral, which tries theNULLkeyword before a number and, for a string, also a number and two boolean keywords: three extra parser calls per number and seven per string. Each element also became anASTLiteral, freed right after its value was copied into the list.ParserNumberandParserStringLiteralnow wrapreadNumberLiteralandreadStringLiteral, which hold their old bodies. For number, sign and string tokens the list calls these directly and puts the value straight into the list, keeping theExpectedentry, depth count and highlight range thatIParserBase::parsemade; an element they reject, and any other token, still goes throughParserLiteral. Analysis and first patch: #132157; the in-place reading: comment.The first version of this PR also made the cast parser look for
::before building the text of a collection. #133041 rewrites that code, so that part is dropped here; this change merges with #133041 without conflicts.Release build, PR / master (95% CI):
parse_long_literal_list.xml(formatQueryof a query with a 10000-element list, 200 timings per side): strings 0.575 (0.570-0.584), numbers 0.696 (0.684-0.700): 1.57 / 0.92 ms less per listformatQueryof 100000 queries with two 10-elementINlists: 0.892 (0.887-0.898)INlist builds a discarded::cast string and tries keyword parsers for every element #132157: 2-4% faster on three of four queries on top of Fix quadratic parsing of nested literals, grouped tuples and multi-statement scripts #133041 (1), the in-place reading saves another 1.6-4.1% (2)No new stateless test: no result changes.
formatandhighlightQueryoutput of 13672 stateless.sqlfiles is identical to master. At a rejected list elementExpected one of:may namenumberfirst, a-xor+xelement that is not a number costs one more parser backtrack, and nested literal collections may go one level deeper under the samemax_parser_depth.Workflow [PR]
Sync PR [sync-upstream/pr/132285]