Skip to content

Parse numbers and strings in long literal lists without keyword probes and per-element ASTs - #132285

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:faster-parsing-of-long-literal-lists
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:faster-parsing-of-long-literal-lists

Conversation

@groeneai

@groeneai groeneai commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #132157
Related: #133041

Changelog category (leave one):

  • Performance Improvement

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 the NULL and boolean keywords and without a separate literal per element. formatQuery of a query with a 10000-string IN list takes about 40% less time.

Description

ParserCollectionOfLiterals parsed every element of a literal list with ParserLiteral, which tries the NULL keyword 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 an ASTLiteral, freed right after its value was copied into the list. ParserNumber and ParserStringLiteral now wrap readNumberLiteral and readStringLiteral, 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 the Expected entry, depth count and highlight range that IParserBase::parse made; an element they reject, and any other token, still goes through ParserLiteral. 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):

No new stateless test: no result changes. format and highlightQuery output of 13672 stateless .sql files is identical to master. At a rejected list element Expected one of: may name number first, a -x or +x element that is not a number costs one more parser backtrack, and nested literal collections may go one level deeper under the same max_parser_depth.


Workflow [PR]
Sync PR [sync-upstream/pr/132285]

groeneai and others added 3 commits November 17, 2026 02:09
`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new perf queries run under 0.1 s on the PR side (parse_long_literal_list.xml) AGREE, fixed @ e0d8b6b numbers(30) -> numbers(100): master 0.366 / 0.300 s, PR 0.243 / 0.232 s per query (strings / numbers)
2 ⚠️ The perf test does not isolate the two parser changes DISAGREE Each part was measured alone (one-part builds, formatQuery strings / numbers vs master): cast scan 0.913 / 0.900, direct literal parsers 0.767 / 0.878. Both move the same two queries, so a later decline of either shows in this test.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261117-073100

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/performance/parse_long_literal_list.xml on Release, PR / master: 0.666 (0.664-0.668) for 10000 strings, 0.785 (0.783-0.788) for 10000 numbers; byte-identical A/A copies 1.008 / 1.012. 5x5 crossover, 1000 pooled pairs per query.
b Root cause explained? tryParseOperand tries the cast parser first at every bracket; parseLiteralAsText built the whole list as text before checking for ::, which an IN list lacks, so the text was dropped and the list parsed again. Each element then went through ParserLiteral, which tries NULL (and for a string a number and two boolean keywords) first.
c Fix matches root cause? Yes: the text is built only after :: is seen, and number/string tokens go straight to the parser that accepts them. No cache, limit or setting.
d Test intent preserved / new tests added? New perf test covering only the improved path. No stateless test: no result changes (format output of 13617 stateless .sql files identical to master).
e Both directions demonstrated? Yes: perf test as in (a). The format differential that shows 0 diffs for this PR reports 175 + 35 diffs for a mutant that drops the :: text path, so it can fail.
f Fix is general across code paths? Both costs are removed where they arise (ParserCastOperator, ParserCollectionOfLiterals). ParserLiteral is unchanged, so its other callers keep their Expected lists; ParserAllCollectionsOfLiterals is not on this path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked on integers, floats, signs, hex/binary, inf/nan, 1_000, strings, NULL/booleans, nested arrays and tuples, :: casts to Array/Tuple/String, non-literal elements, and 1115 generated valid and broken statements.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or AST change. At a rejected element Expected one of: may list number first; a -x/+x element costs one more parser backtrack; literal collections may nest one level deeper under the same max_parser_depth.
i Invariants and contracts preserved? AST and Expected set unchanged; the backtrack count is unchanged for the cast scan (measured on 9 query shapes); highlights and the literal token map come from the same parsers. 3163 related stateless tests give the same results as master; 252 parser gtests pass.

Session id: cron:clickhouse-impl-slot-4:20261117-060200

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d64f1ed]

Summary: ✅


AI Review

Summary

Reviewed PR #132285 at d64f1ed1e0c8ecd377d63d167e930c7588c3439b. ParserCollectionOfLiterals now reads numbers and strings directly into collections, avoiding keyword probes and temporary ASTLiteral objects. No actionable findings. The before/after measurements and output comparisons support the performance claim and preserved behavior.

Missing context / blind spots
  • ⚠️ Full CI for the current head is still pending. No local build or tests were run during this review; completed current-head CI would close this validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. labels Nov 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d64f1ed1e0c8ecd377d63d167e930c7588c3439b was not compared: the CI logs cluster did not answer (the endpoint never became ready: the readiness probe timed out: HTTPSConnectionPool(host='t6h0zvqlg…).

See the job log for details.

@snelheidai

Copy link
Copy Markdown

Part 1 of this PR overlaps #133041, which also checks for :: before building the collection text; the two PRs conflict in ExpressionElementParsers.cpp. Part 2 (numbers and strings go straight to ParserNumber / ParserStringLiteral) is independent and applies unchanged on top of #133041.

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.

Comparison 10000 String keys same, use_statistics = 0 10000 UInt64 keys same, use_statistics = 0 10000 numbers ::Array(UInt32)
this PR / master 0.931 (0.910–0.949) 0.916 (0.893–0.931) 0.954 (0.927–0.986) 0.945 (0.936–0.961) 0.969 (0.965–0.985)
#133041 / master ¹ 0.953 (0.936–0.977) 0.964 (0.922–0.981) 0.963 (0.948–0.977) 0.941 (0.928–0.956) 0.881 (0.868–0.903)
#133041 + part 2 / #133041 ¹ 0.979 (0.946–0.994) 0.962 (0.925–0.992) 0.988 (0.965–1.021) 0.960 (0.950–0.973) 1.006 (0.984–1.022)
#133041 + part 2 / this PR ¹ 0.974 (0.949–1.008) 0.970 (0.945–0.985) 1.006 (0.991–1.038) 0.982 (0.967–0.997) 0.900 (0.871–0.916)

¹ #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 IN and a scan without IN stayed within ±1.1% in every comparison, and results were identical.

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]>
@groeneai groeneai changed the title Parse long literal lists without building a discarded cast text and without keyword probes Parse numbers and strings in long literal lists without the keyword probes Nov 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Dropped part 1 in bd57a55, since #133041 covers it; this PR now only changes how ParserCollectionOfLiterals reads numbers and strings, and merges with #133041 without conflicts.

@stresshouse

stresshouse Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 28 queries analysed

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1004 1064 +5.9% <0.0001 cpu: The +5.9% is inside master's normal range, and the tested source run was noisy. The parser refactor costs microseconds per query, which cannot move a regex-heavy 1-second scan.
⚠️ 30 not_sure 155 189 +21.9% <0.0001 aggregation: The +21.9% sits inside master's normal range (152-205 ms), and this query has a noisy history. The PR only changes literal parsing, which this GROUP BY aggregation does not exercise at run time.
⚠️ 31 not_sure 208 245 +17.8% <0.0001 aggregation: The +17.8% is inside master's normal range (196-262 ms), and this query has a noisy history. The parser-only change does not touch the high-cardinality GROUP BY this query runs.

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
  • StressHouse run: 4375ce85-289c-4bee-b47c-2ddb3494b85e
  • MIRAI run: dcc3548d-58e1-4459-a8e6-55823e9a0bb5
  • PR check IDs:
    • clickbench_760997_1795330718
    • clickbench_761003_1795330718
    • tpch_adapted_1_official_761017_1795330718
    • tpch_adapted_1_official_761061_1795330719

@snelheidai

Copy link
Copy Markdown

Reading the numbers and strings of a literal list straight into the collection, without building and freeing an ASTLiteral for each element, makes this PR's parse_long_literal_list.xml queries about 20% faster. The 10000-key lookups from #132157 save about the same time per list, 0.9–1.1 ms, which is 1.6–4.1% of their total:

Query + patch / this PR (95% CI)
parse_long_literal_list.xml, strings 0.784 (0.776–0.792)
parse_long_literal_list.xml, numbers 0.799 (0.787–0.810)
10000 String keys 0.973 (0.948–0.999)
same, use_statistics = 0 0.959 (0.924–0.995)
10000 UInt64 keys 0.971 (0.942–1.001)
same, use_statistics = 0 0.984 (0.956–1.013)
10-value IN 1.023 (0.977–1.071)
scan without IN 1.004 (0.968–1.042)

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 (query_log) over 60 paired runs, half of them with the ports swapped; below 1 is faster. A 100-value IN list did not change measurably.

The bodies of ParserNumber::parseImpl and ParserStringLiteral::parseImpl move unchanged into readNumberLiteral and readStringLiteral, which the two parsers now wrap. The collection loop calls these directly and still does everything else parse did for an element: the Expected entry, the depth count and the highlight range. Query results, syntax-error messages, the max_parser_depth limit, EXPLAIN AST, formatQuery, INSERT ... VALUES and highlightQuery gave the same output with and without the patch, and so did 238 stateless tests on literals, parsing and highlighting. If it fits, feel free to fold it into this PR.

Patch on top of bd57a55
diff --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]>
@groeneai groeneai changed the title Parse numbers and strings in long literal lists without the keyword probes Parse numbers and strings in long literal lists without keyword probes and per-element ASTs Nov 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Folded in as d64f1ed with the readNumberLiteral comment corrected (a failed read can leave pos past a sign); measured here, the parse_long_literal_list.xml queries take 0.763 / 0.793 of the previous head and formatQuery of 10-element lists 0.938, with format and highlightQuery output of 13672 stateless .sql files unchanged.

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parsing a long literal IN list builds a discarded :: cast string and tries keyword parsers for every element

2 participants