Skip to content

Parse nested literal collections in linear time - #108892

Merged
alexey-milovidov merged 1 commit into
masterfrom
parse-nested-literal-collections-linear
Jun 30, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
parse-nested-literal-collections-linear

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

ParserCollectionOfLiterals::parseImpl builds an array or tuple literal iteratively with an explicit stack of layers. When a nested collection was finished it was appended to its parent layer with layers.back().arr.push_back(literal->value), which deep-copies the whole nested Field accumulated so far. For a deeply nested literal such as [[[ ... ]]] this made parsing quadratic in the nesting depth.

literal is a local ASTLiteral that is discarded immediately after this line (only the outermost layer is kept as node), so its value can be moved into the parent instead of copied. This makes the parse linear and leaves the produced Field byte-identical.

ParserCollectionOfLiterals is instantiated only for Array and Tuple — it is what parses array and tuple literals inside expressions, e.g. SELECT [[[ ... ]]]. Map literals and the SET param_… = … collection path go through ParserAllCollectionsOfLiterals, which already moves nested values into their parent and was therefore already linear; this PR does not touch that path.

Motivation

Surfaced by the 26.6 backport #108832 of #108493. The quadratic parse showed up in the regression test 04412_deep_nested_literal_format (formatQuery($$SELECT [...]$$)), which is tagged no-fasttest, no-debug, no-sanitizers. The stress-test job deliberately ignores no-{build} tags (every test must run under stress), and there the quadratic parse of the depth-20000 literal was slow enough — ~1620s and non-cancellable under ThreadSanitizer — to trip the hung check. With the linear parse the literal is built quickly; the test still reports TOO_DEEP_RECURSION from the FieldVisitorToString stack guard, exactly as before.

The sibling test 04413_set_param_deep_collection (SET param_p = [...]) exercises the same TOO_DEEP_RECURSION guard through ParameterFieldVisitorToString, but its SET param_… value is parsed by ParserAllCollectionsOfLiterals (already linear), so it was not affected by the quadratic parse and is left unchanged here.

Changelog category (leave one):

  • Performance Improvement

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

Parse deeply nested array and tuple literals in linear instead of quadratic time.

Version info

  • Merged into: 26.7.1.291 (included in 26.7 and later)

`ParserCollectionOfLiterals::parseImpl` builds an array/tuple/map literal
iteratively with an explicit stack of layers. When a nested collection was
finished it was appended to its parent layer with
`layers.back().arr.push_back(literal->value)`, which deep-copies the whole
nested `Field` accumulated so far. For a deeply nested literal such as
`[[[ ... ]]]` this made parsing quadratic in the nesting depth.

`literal` is a local `ASTLiteral` that is discarded immediately after this
line (only the outermost layer is kept as `node`), so its value can be moved
into the parent instead of copied. This makes the parse linear and leaves the
produced `Field` byte-identical.

This also keeps the deeply nested literal regression tests
`04412_deep_nested_literal_format` and `04413_set_param_deep_collection` fast:
they are tagged `no-fasttest, no-debug, no-sanitizers`, but the stress-test job
ignores `no-{build}` tags and runs every test, where the quadratic parse of the
depth-20000/30000 literal was slow enough to trip the hung check under
ThreadSanitizer. Surfaced by the 26.6 backport #108832.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e1006c]

Summary: ✅


AI Review

Summary

This PR changes ParserCollectionOfLiterals to move a completed nested Field into its parent layer, avoiding the deep copy that made same-bracket array/tuple literal parsing quadratic in nesting depth. The code change itself matches the ownership invariant: the intermediate ASTLiteral is not retained after its value is inserted into the parent. I found one user-facing metadata mismatch.

PR Metadata
  • 💡 The Performance Improvement category is appropriate, and a changelog entry is required.
  • 💡 The changelog overclaims map coverage. The changed parser is instantiated only for Array and Tuple; map collections are parsed by ParserAllCollectionsOfLiterals, which already moves nested values. Suggested replacement: Parse deeply nested array and tuple literals in linear instead of quadratic time.
Missing context / blind spots
  • ⚠️ Full CI was still in progress when reviewed; the Praktika report had 2 passed, 0 failed, and 18 skipped. Completed CI would close this gap.
Findings
💡 Nits
  • [src/Parsers/ExpressionElementParsers.cpp:1504] The PR/changelog says the change covers Map, but this code path does not parse maps. Drop map from the changelog/description or include a map-path change/evidence.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: make the changelog/description match the actual changed surface by removing map from the performance claim, or add the intended map parser change/evidence.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 30, 2026
@Algunenano Algunenano self-assigned this Jun 30, 2026
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
`ParserCollectionOfLiterals::parseImpl` builds an array/tuple/map literal
iteratively with an explicit stack of layers. When a nested collection was
finished it was appended to its parent layer with
`layers.back().arr.push_back(literal->value)`, which deep-copies the whole
nested `Field` accumulated so far. For a deeply nested literal such as
`[[[ ... ]]]` this made parsing quadratic in the nesting depth.

`literal` is a local `ASTLiteral` that is discarded immediately after this
line (only the outermost layer is kept as `node`), so its value can be moved
into the parent instead of copied. This makes the parse linear.

This is needed for the backported test `04412_deep_nested_literal_format`.
It is tagged `no-fasttest, no-debug, no-sanitizers`, but the stress test job
deliberately ignores `no-{build}` tags (every test must run under stress), so
`04412` runs under `Stress test (amd_tsan)`. With the quadratic parse, building
the depth-20000 literal in `formatQuery` took ~1620s under ThreadSanitizer and,
being non-cancellable, tripped the hung-check ("Hung check failed, possible
deadlock found"). The same quadratic parse also made `04412` run for ~441s under
`Stateless tests (amd_asan, distributed plan, parallel)` and the server got
killed by signal. With the linear parse the literal is built quickly and
`formatQuery` still reports `TOO_DEEP_RECURSION` (code 306) from the
`FieldVisitorToString` stack guard, exactly as the test expects.

This mirrors the fix already applied to the 26.6 backport in
#108832 and the master change
#108892.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108896&sha=0a636f95b8f50b19259d8d0280d26e62639e47a4&name_0=BackportPR&name_1=Stress%20test%20%28amd_tsan%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
`ParserCollectionOfLiterals::parseImpl` builds an array/tuple/map literal
iteratively with an explicit stack of layers. When a nested collection was
finished it was appended to its parent layer with
`layers.back().arr.push_back(literal->value)`, which deep-copies the whole
nested `Field` accumulated so far. For a deeply nested literal such as
`[[[ ... ]]]` this made parsing quadratic in the nesting depth.

`literal` is a local `ASTLiteral` that is discarded immediately after this
line (only the outermost layer is kept as `node`), so its value can be moved
into the parent instead of copied. This makes the parse linear.

This is needed for the backported test `04412_deep_nested_literal_format`.
It is tagged `no-fasttest, no-debug, no-sanitizers`, but the stress test job
deliberately ignores `no-{build}` tags (every test must run under stress), so
`04412` runs under `Stress test (amd_tsan)`. With the quadratic parse, building
the depth-20000 literal in `formatQuery` took ~1620s under ThreadSanitizer and,
being non-cancellable, tripped the hung-check ("Hung check failed, possible
deadlock found"). With the linear parse the literal is built quickly and
`formatQuery` still reports `TOO_DEEP_RECURSION` (code 306) from the
`FieldVisitorToString` stack guard, exactly as the test expects.

This mirrors the same fix applied to the master change in #108892 and to the
26.6 backport in #108832.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108899&sha=573ba507851cfb5c2c745dee34924cbdbf4fe08a&name_0=BackportPR&name_1=Stress%20test%20%28amd_tsan%29

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

Copy link
Copy Markdown
Member

Also related: #108863

Since the stress tests are now fuzzers too (server fuzzer) we should cap some of the settings to avoid extreme queries. The stateless test detect that a crash is no longer possible, but sanitizers can make some of these recursive tests extremely slow.

alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
`ParserCollectionOfLiterals::parseImpl` copied the just-finished nested
collection into its parent layer on every closing bracket, making the
parsing of a deeply nested literal such as `[[[ ... ]]]` quadratic in its
depth.

The new test `04412_deep_nested_literal_format` builds
`formatQuery([...20000...])`. The `Stress test (amd_tsan)` runner ignores
the test's `no-*` tags and runs it anyway, so the quadratic build never
finishes in time and trips the "Hung check failed, possible deadlock found"
check.

Move the value into the parent instead of copying it. `literal` is a local
that is discarded right after (only the outermost layer is kept as `node`),
so moving its value out is safe and produces an identical `Field`.

This mirrors the master change in #108892
and the 26.6 backport in #108832.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108897&sha=cc66187446ca00eca7656b498616f904352d22eb&name_0=BackportPR&name_1=Stress%20test%20%28amd_tsan%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jun 30, 2026
The deeply-nested-expression tests added by this backport
(`04412_deep_nested_literal_format`, `04413_set_param_deep_collection`)
construct arrays nested ~20000 levels deep. Under the stress test,
which ignores the `no-debug`/`no-sanitizers`/`no-fasttest` tags and runs
every test, parsing such a literal under TSan took ~1620 seconds and was
reported as a hung query ("Hung check failed, possible deadlock found").

`ParserCollectionOfLiterals::parseImpl` iteratively builds the collection
with a stack of layers. On every closing bracket it copied the whole
just-completed nested `Field` into the parent layer with
`push_back(literal->value)`, deep-copying the entire subtree at each
level and making parsing O(d^2) in the nesting depth `d`.

The `literal` is a local `ASTLiteral` that is discarded immediately after
(only the outermost one is kept as `node`), so its value can be moved
instead of copied. This makes parsing O(d) while producing a byte-identical
`Field`. The formatting guard still trips the `FieldVisitorToString`
recursion check and returns `TOO_DEEP_RECURSION`; only the parse speed changes.

Same fix as master sibling #108892
and the 26.6 backport #108832.

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

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.70% 92.60% -0.10%
Branches 77.60% 77.70% +0.10%

Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is a one-line parser optimization: it moves (instead of copies) a finished nested collection into its parent, fixing quadratic-time parsing of deeply nested literals like [[[...]]]. ClickBench Q4, Q15, and Q33 contain no such nested literals and the change never touches query execution, so the flagged improvements on Q4 (-18.7%) and Q15 (-17.1%) cannot be attributed to this PR and read as run-to-run variance (note the source side has only 6 runs). No real per-query effect is expected from this change on this benchmark.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 262 213 -18.7% <0.0001 PR only speeds parsing of deeply nested array literals; Q4 has none, so -18.7% is run-to-run variance
⚠️ 15 not_sure 245 203 -17.1% <0.0001 Parser-only change for nested literals; Q15 doesn't exercise it, so -17% is unrelated to this PR
⚠️ 33 not_sure 1457 1383 -5.1% <0.0001 Already not_sure; -5% borderline and off the parser path this PR touches

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: 439dab58-b0ae-4e4a-97eb-6edb45b7003b
  • MIRAI run: f3f6e674-d8ae-4014-94d0-3a3b7ec4532e
  • PR check IDs:
    • clickbench_484671_1782817513
    • clickbench_484677_1782817513
    • clickbench_484687_1782817513
    • tpch_adapted_1_official_484695_1782817513
    • tpch_adapted_1_official_484708_1782817513
    • tpch_adapted_1_official_484720_1782817513

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 30, 2026
Merged via the queue into master with commit c09dfca Jun 30, 2026
343 of 345 checks passed
@alexey-milovidov
alexey-milovidov deleted the parse-nested-literal-collections-linear branch June 30, 2026 19:20
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 30, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov can add a performance test for this?

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…eral-collections-linear

Parse nested literal collections in linear time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants