Skip to content

Parse small JSON documents without heap allocations when simdjson is disabled - #123755

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:rapidjson-parse-stack-inline-buffer
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:rapidjson-parse-stack-inline-buffer

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118008 (comment)

Changelog category (leave one):

  • Performance Improvement

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

JSONExtract* functions and the JSON type with allow_simdjson = 0 no longer allocate memory for each parsed document: rapidjson's parse stacks now start in a buffer inside the parser, which makes JSONExtract* on small documents about 15% faster.

Description

json_extract_rapidjson #4 was red in Performance Comparison (amd_release, master_head, 3/6) on #118008 (report, +28%) and on 8 other PRs the same day. The slow PR binaries run the same instructions as fast ones but miss the uop cache 80x more often, and most of those misses are in the per-document allocation code of the rapidjson parser.

That code runs because each RapidJSONParser::parse makes rapidjson allocate and free two stacks through the memory tracker: the stack of the reader that ParseStream creates, and the document's own stack, which ParseStream frees after every document. It is 14% of the cycles of that query in a fast build and 19% in a slow one.

RapidJSONStackAllocator serves both stacks from a 2 KB buffer inside the parser, rewound before each document. Blocks that do not fit go to RapidJSONMemoryTrackerAllocator as before, so large documents are tracked and bounded as today.

Validation, non-LTO release build, one CPU, medians of 3 rounds:

  • json_extract_rapidjson queries #0..doc: fix typo #4: 0.82-0.87x time (instructions of doc: fix typo #4: -20%); Extra include for std::mt19937_64 #5..Update Docker files for Docker Hub #13: 0.95-0.99x; Comparison with ElasticSearch #14 (200 members): 1.01x across 9 link layouts.
  • The smallest max_memory_usage that parses a 2M-element array or a 20 MB string is unchanged (80 MB, 122 MB).
  • Relinking each build with 9 --shuffle-sections layouts did not reproduce the CI slowdown (base spread 1.05x), so this makes the query faster and removes the allocator code from its hot loop, but I cannot show that it makes the query immune to such layout flips.
  • New test 05320_rapidjson_parse_stack_reuse mixes documents that fit the buffer with ones that outgrow it in one block.

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

groeneai and others added 2 commits October 3, 2026 20:23
…disabled

Every `RapidJSONParser::parse` called `document.ParseStream`, which builds a
fresh `GenericReader` whose 256-byte stack is allocated on first push and freed
when the reader dies, and which frees the document's own 1024-byte stack in
`ClearStack` -> `ShrinkToFit` after every document. So each parsed document
cost two malloc/free pairs through `RapidJSONMemoryTrackerAllocator`,
`DB::Allocator`, the memory tracker and jemalloc: about 19% of the cycles of
`json_extract_rapidjson` query ClickHouse#4, and the code where the slow CI layouts of
that query take their uop-cache misses (the red `Performance Comparison` job on
ClickHouse#118008: same instructions as a fast PR build, 80x more DSB misses).

`RapidJSONStackAllocator` is the document's `StackAllocator`; rapidjson passes
the same instance to the reader it creates in `ParseStream`. Blocks come from a
2 KB buffer inside the parser that `parse` rewinds before each document. Blocks
that do not fit, and every growth past the buffer, go to
`RapidJSONMemoryTrackerAllocator` as before, so large documents are tracked
and bounded exactly as today. Inline blocks carry a zero size header, which is
how the static `Free` tells them from heap blocks (whose size is never 0).

Rewinding is safe because nothing outlives `ParseStream` in those stacks: the
document stack is freed by `ClearStackOnExit` on every exit, including
exceptions, the reader is a local of `ParseStream`, and strings and members are
copied into the value pool.

Alternatives not taken: `MemoryPoolAllocator` as the stack allocator never
frees a block on `Realloc`, which roughly doubles peak tracked memory for a
large flat document; a persistent reader with `Populate` keeps the document
stack being freed; patching rapidjson's `ShrinkToFit` changes every user of
the library.

Measured on a non-LTO release build, one pinned CPU: `json_extract_rapidjson`
#0..ClickHouse#4 take 0.82-0.87x the time (instructions of ClickHouse#4 -20%), ClickHouse#5..ClickHouse#13 0.95-0.99x,
ClickHouse#14 1.01x across 9 link layouts; the smallest `max_memory_usage` that parses a
2M-element array (80 MB) or a 20 MB string (122 MB) is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the RapidJSONStackAllocator class and header-tag comments to one line each; drop the Realloc note implied by the class comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ 05320_rapidjson_parse_stack_reuse checks parse results only, so it would still pass if small documents allocated again DISAGREE The test guards the inline-to-heap transitions (dropping the copy on growth aborts it, freeing inline blocks segfaults it). Allocation count is not observable from SQL; the speed claim is checked by json_extract_rapidjson.xml #0..#4 in this PR's performance comparison, large documents by 04340_rapidjson_memory_tracking.
2 💡 Stacks of small documents now live in a buffer ASan does not red-zone noted, not blocking Same trade-off as the parser's inline 8 KB value pool; rapidjson reserves before every push.
3 💡 RapidJSONParser grows by 2 KB (to about 10 KB) and is a stack local of the JSONExtract* executor noted, not blocking Parsing is iterative and these frames do not recurse.

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

Session id: cron:clickhouse-review-slot-10:20261003-203100

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On one pinned CPU the slow and fast CI binaries of the red job differ 1.28x on every round; this change vs its base is 0.85x on json_extract_rapidjson #4 on every round and on all 9 link layouts.
b Root cause explained? Each RapidJSONParser::parse makes rapidjson allocate and free two stacks through the memory tracker (the reader's, and the document's, which ParseStream frees after every document): about 19% of the query's cycles, and where the slow CI layout's uop-cache misses land.
c Fix matches root cause? Yes. The stacks come from a 2 KB buffer inside the parser through rapidjson's StackAllocator parameter; no perf test, threshold or alignment change.
d Test intent preserved / new tests added? New 05320_rapidjson_parse_stack_reuse mixes documents that fit the buffer with ones that outgrow it; dropping the copy on growth or freeing inline blocks makes it fail. Existing JSON tests pass.
e Both directions demonstrated? Yes: base vs change timings and perf stat (instructions -20% on #4); the two mutations fail the new test, the unmodified change passes it.
f Fix is general across code paths? Every RapidJSONParser user gets it (JSONExtract*, the JSON type, fuzzJSON). prettyPrintJSON and JSONMergePatch use their own rapidjson types and are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Small, long-string, many-member, deeply nested and invalid documents give identical results; large documents take the same tracked heap path, and the smallest passing max_memory_usage for a 2M-element array and a 20 MB string is unchanged.
h Backward compatible? (maintainer-approved exception only) Yes, in-memory only: no setting, format or on-disk change.
i Invariants and contracts preserved? When the buffer is rewound no block from it is live: ParseStream frees both stacks on every exit, including exceptions, and the parsed document never points into them.

Session id: cron:clickhouse-impl-slot-5:20261003-184000

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2f5e7a]

Summary: ✅


AI Review

Summary

The PR serves RapidJSON parsing stacks from a reusable 2 KB inline buffer, retaining memory-tracked heap allocation for larger documents. Reviewed all changed files, the pinned RapidJSON implementation, affected callers, and all prior discussion against head f2f5e7a21abec4958a8f305bbba1e0cc6ffe55a9. No actionable findings. The performance claim has supporting measurements, including recorded CI improvements of approximately 17% on AMD and 20–21% on ARM for affected queries.

Missing context / blind spots
  • ⚠️ Full stateless, sanitizer, and performance results for the current head are still pending. The earlier targeted ASan/UBSan run passed; current-head CI will close this validation gap. No local tests were run because this checkout has no ClickHouse binary or configured build.
Final Verdict

Status: ✅ Approve. No code changes requested; current-head CI remains pending.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Oct 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f2f5e7a21abec4958a8f305bbba1e0cc6ffe55a9 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: c24702d6-9939-43b2-8216-1b0c16cd0fcb
  • MIRAI run: ef01c5d6-13ed-4a05-b98e-6fefad99e2a4
  • PR check IDs:
    • clickbench_3152762_1791087190
    • clickbench_3152768_1791087190
    • clickbench_3152779_1791087190
    • tpch_adapted_1_official_3152804_1791087190
    • tpch_adapted_1_official_3152818_1791087191
    • tpch_adapted_1_official_3152832_1791087191

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0095713

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (amd_fuzzers) / Build ClickHouse not from this PR: the clickhouse_fuzzer link fails with relocation R_X86_64_PC32 out of range; the same job is red on master and on 166 PRs in the last 24h #123738 (external, merged 2026-10-04 01:14Z). This workflow was dispatched at 20:55Z, before that merge, so the fix is not in the tree that ran; a master merge to pick it up follows
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / 05293_keeper_map_replica_recovery_keeps_data not from this PR (this PR changes only the RapidJSON allocator): the test was killed at the 600 s timeout; the job's own rerun reproduced it with the same randomized settings and passed 19 of 19 without them a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04819_dynamic_aggregate_function_state_version not from this PR: the medianDeterministicMerge state crosses the replica wire at state version 0 and loses the reservoir's skip degree, so the lopsided Dynamic split returns 506014 instead of 492708 #123070 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04825_quantile_deterministic_alter_add_modify_column not from this PR: same state-version-0 -Merge across replicas, 506014 instead of 492708; 25 PRs in 24h #123070 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05257_sql_security_view_sealed not from this PR: a replica cannot run the SQL SECURITY DEFINER view's read as the definer, so the row policy check fails with ACCESS_DENIED; 88 PRs in 24h #123729 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant not from this PR: under a Replicated database the replicated CREATE VIEW stores the nested WITH alias qualified with the database, so the view reads the same-named table (view 10 instead of 100); 180 PRs in 24h #123790 (external, open)
Mergeable Check, PR rollups, red only because of the rows above #123738, #123070, #123729, #123790 and the fix task above

05320_rapidjson_parse_stack_reuse passed. The three arm_binary lanes above come from #122853, which #123789 reverted on master at 00:14Z; #123790 re-lands them. All 157 checks completed and CH Inc sync passed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261004-013156

…ck-inline-buffer

Picks up ClickHouse#123738 (Build (amd_fuzzers) clickhouse_fuzzer link overflow).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05293_keeper_map_replica_recovery_keeps_data (timeout in the arm_binary AsyncInsert lane) created: #123816

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b6604bb

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (amd_release, master_head, 1/6) / uint64_to_string #4 dashboard confirmed_regression, client_time 0.206 -> 0.243 s (+18.0%), still +16.4% after the harness restarted both servers, and the shard's own report also calls it slower. The query is toString(rand64() % 1000) over zeros(50000000): it parses no JSON, so the RapidJSON code this PR changes never runs. The same query was slower on 2 other PRs and 5 master runs in the last 7 days a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (the same one as above)

All 146 check runs completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261004-070344

Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Oct 6, 2026
05293_keeper_map_replica_recovery_keeps_data and 04651_timeseries_recover_lost_replica
detected the end of a forced Replicated database recovery by counting the line
"All tables are created successfully" in system.text_log. The filter is on
logger_name/message, not on the table key, so every count was a full scan of the
server-wide log: 3 per run in 05293, 7 in 04651. In Stateless tests (arm_binary,
AsyncInsert, s3 storage, parallel) on ClickHouse#123755 the log had 12-14M rows on the s3 disk
and, with the randomized read settings, each scan took about 220 s, so 05293 hit the
600 s timeout while the recovery itself had finished in about 30 ms. 04651 failed
8 times in 30 days in the amd_tsan flaky check with "Test runs too long".

DatabaseReplicated::recoverLostReplica rewrites the replica digest node as its last
step, and both tests arm the recovery by setting that node to 42 right before
DETACH/ATTACH DATABASE. Poll that node through system.zookeeper instead: one Keeper
read per poll, independent of the log size and of the storage. The signal is later
than the old log line, so the assertions that follow see at least as much finished
state. 04651 keeps its three log-line checks and bounds them to rows written since
the test started.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the amd_release 1/6 perf red (uint64_to_string #4): #125278 (closed unmerged: the release binaries stay PIE). A fix task is moved to pending; the fixing-PR link will follow here.

@groeneai

groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the amd_release 1/6 perf red (uint64_to_string #4): #125949. Correction: #125949 is not shown to fix this red. Slowdowns like this one are new since PIE (one side at least 15% slower in 0 of 679 master runs from Jul 1 to Sep 9, 4.4% since Sep 15), but I have no mechanism for it on x86-64. Per-query numbers: #125949 (comment)

@clickhouse-gh clickhouse-gh Bot added comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 19, 2026

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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants