Skip to content

Speed up flattenAndBucketSharedDataPaths for sparse JSON shared data - #109341

Merged
Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/flatten-shared-data-paths-quadratic
Jul 7, 2026
Merged

Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/flatten-shared-data-paths-quadratic

Conversation

@groeneai

@groeneai groeneai commented Jul 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107941

Changelog category (leave one):

  • Performance Improvement

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

Speed up serialization and merges of JSON columns whose shared data contains many sparse paths. When flattening shared data into per-path columns, flattenAndBucketSharedDataPaths no longer scans every accumulated path column on every row and no longer inserts a default one cell at a time; the per-row scan over all paths is removed and gaps are backfilled in bulk.

Description

flattenAndBucketSharedDataPaths (src/DataTypes/Serializations/SerializationObjectHelpers.cpp) collects each JSON shared-data path into its own dense column with one entry per row. It did this by iterating over all accumulated path columns for every row and inserting a default into each column that had no value in that row, i.e. O(rows * paths) iterations with an individual insertDefault call per gap.

When a JSON column's shared data holds many sparse paths (each present in only a few rows), this per-row scan over all paths dominates part serialization during merges/mutations. Under sanitizer builds one such merge can run for many minutes.

This also shows up as the stress-test hung check. MergeTreeBackgroundExecutor::wait() (called from ContextSharedPart::shutdown) does not cancel an in-flight merge/mutation, it only waits for the pool thread to finish. If that thread is stuck in this serialization, shutdown blocks past the 90s hung-check window and the run is reported as Possible deadlock on shutdown. This PR removes the per-row scan over all paths and the per-cell default insertions; it does not change the general shutdown-cancellation behaviour, which is a separate item.

The fix backfills missing defaults lazily: a path column is padded with a single bulk insertManyDefaults right before storing a real value (and every column is padded once at the end), and each row only touches the paths actually present in it. The produced columns are identical (shared-data paths are unique and sorted within a row), only faster.

This is a large constant-factor and scan-removal win, not an asymptotic reduction of the whole operation: the number of defaults materialized is unchanged. ColumnDynamic::insertManyDefaults forwards to ColumnVariant::insertManyDefaults, which resize_fills one NULL row per padded cell, so the dense output still holds O(rows * paths) cells in the sparse worst case. What is removed is the per-row scan over every accumulated path and the per-cell virtual insertDefault dispatch (replaced by a bulk fill).

Measured on OPTIMIZE TABLE ... FINAL of a 60000-row granule with object_shared_data_serialization_version = 'advanced' (compact part, debug build):

distinct paths before after
2000 3.8s 1.7s
4000 14.4s 3.0s
8000 31.9s 6.5s

Correctness: the existing 0355x JSON shared-data advanced-serialization tests pass unchanged, a byte-for-byte comparison of read-back data between the old and new code on varied JSON is identical, and a new unit test ObjectSerialization.FlattenAndBucketSharedDataPaths asserts the densified output for full and partial row ranges (including empty and trailing-gap rows).

Version info

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

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar for review. This removes an O(rows * paths) densification in flattenAndBucketSharedDataPaths that dominates merge/serialization of JSON columns with many sparse shared-data paths (a recurring source of the Possible deadlock on shutdown stress-test hung check, since the merge executor is not cancelled on shutdown until the in-flight task finishes). Output is unchanged; validated with the existing 0355x advanced-serialization tests, a byte-identical old-vs-new read-back diff, and a new unit test.

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. OPTIMIZE TABLE ... FINAL of a 60000-row granule of JSON(max_dynamic_paths=1) with object_shared_data_serialization_version='advanced' where each row carries one of P distinct shared-data paths. Merge time scales with rows*P deterministically: P=2000/4000/8000 → 3.8s/14.4s/31.9s on a debug build.
b Root cause explained? flattenAndBucketSharedDataPaths densified each path column by iterating over ALL P accumulated path columns for EVERY row and inserting one default into each column absent that row → O(rows*paths) individual insertDefault calls. With many sparse shared-data paths this dominates part serialization; under sanitizers a single merge runs minutes. Since MergeTreeBackgroundExecutor::wait() (from ContextSharedPart::shutdown) does not cancel an in-flight task, that slow serialization blocks shutdown past the 90s stress hung-check window.
c Fix matches root cause? Yes. Removes the per-row scan-all-columns loop; defaults are backfilled with a single bulk insertManyDefaults (an O(gap) resize_fill) right before storing a real value and once at the end → O(total_stored_values + paths). Directly eliminates the quadratic term identified in (b).
d Test intent preserved / new tests added? Yes. Existing 0355x advanced shared-data serialization tests unchanged and passing. Added unit test ObjectSerialization.FlattenAndBucketSharedDataPaths asserting the densified output (value where present, default where absent, exact size) over the full range and two sub-ranges incl. a trailing empty row. Confirmed it fails if the densification is broken.
e Both directions demonstrated? Yes. Same-input read-back is byte-identical between the pre-fix and post-fix binaries on varied JSON (350 rows: empty/single/many/overlapping/gap, 3 buckets); the perf table shows before/after on the deterministic repro; the new unit test passes with the fix and fails without the trailing backfill.
f Fix is general across code paths? Yes. flattenAndBucketSharedDataPaths is the only densification loop of this shape; flattenPaths() calls it directly and benefits automatically. Not a defensive guard — it corrects the algorithm at its source.
g Fix generalizes across inputs? Yes. The densification is value-type agnostic (each path column is a Dynamic); correctness verified across empty rows, single/multi/overlapping paths and partial row ranges. Results are unchanged for all inputs (this is a performance fix), only the default-padding cost changes.
h Backward compatible? Yes. No on-disk/wire format, setting, or default change. The serialized bytes are identical (verified byte-for-byte), so parts written before and after are interchangeable.
i Invariants and contracts preserved? Yes. Postcondition upheld: every returned path column has exactly end - start rows, with the stored value at each row where the path is present and a default elsewhere (shared-data paths are unique and sorted within a row, so a path is seen at most once per row). Bucketing and per-bucket sort order are unchanged.

Session id: cron:clickhouse-worker-slot-2:20260703-162300

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3a22898]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-308a) FAIL cidb, issue ISSUE EXISTS
Stress test (arm_release) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 2228-453d) FAIL cidb IGNORED

AI Review

Summary

This PR replaces the per-row scan in flattenAndBucketSharedDataPaths with lazy bulk backfilling for absent rows, and adds a focused unit test for full-range and subrange densification. After reviewing the current diff, prior discussion, and the relevant SerializationObjectSharedData / ColumnObject call chain, I did not find any new correctness, compatibility, or test-coverage issues in the current patch.

Missing context / blind spots
  • ⚠️ I did not reproduce the performance measurements or run the unit tests locally because this checkout has no existing build directory. Confidence comes from code inspection, the added regression test, and the posted LLVM coverage report for the changed lines.
Final Verdict

✅ No new inline findings. The current patch preserves the shared-data densification contract while removing the expensive per-row scan, and the earlier review concern about overstating the asymptotic improvement has already been addressed in the current code and PR text.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 3, 2026
flattenAndBucketSharedDataPaths densified each collected shared-data path
into a column with one entry per row. It did this by iterating over ALL
accumulated path columns for every row and inserting a default into each
column that had no value in that row. With P distinct paths over N rows
that is O(N * P) iterations, each with an individual insertDefault call.

JSON columns whose shared data holds many sparse paths (each present in
only a few rows) hit this per-row scan during merges and part
serialization. Under sanitizer builds a single such merge can take many
minutes; because the background merge/mutation executor is not cancelled
on shutdown until its in-flight task finishes, a slow serialization here
can hold up server shutdown long enough to trip the stress-test hung
check.

Backfill the missing defaults lazily instead: pad a path column with a
single bulk insertManyDefaults right before storing a real value (and pad
every column once at the end), and touch only the paths present in each
row. This removes the per-row scan over every accumulated path and the
per-cell insertDefault calls.

This is a constant-factor and scan-removal win, not an asymptotic
reduction. insertManyDefaults forwards to ColumnVariant::insertManyDefaults,
which resize_fills one NULL row per padded cell, so the dense output still
materializes O(N * P) cells in the sparse worst case. The produced columns
are identical (shared-data paths are unique and sorted within a row), only
faster.
@groeneai
groeneai force-pushed the groeneai/flatten-shared-data-paths-quadratic branch from 591a1ef to 720996b Compare July 3, 2026 18:33
@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 720996b

Every failure below has an owner: a fixing PR (ours 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
Fast test (arm_darwin) / 04056_npy_large_shape_validation flaky (macOS runner missing numpy) #108859 (external, merged) — merge master to pick it up (this branch predates it by ~5978 commits)
Fast test (arm_darwin) / 03321_forwarded_for flaky (macOS python helper import) #108859 (external, merged) — merge master to pick it up
Mergeable Check / PR rollup of the above resolved once master is merged
CH Inc sync - CH Inc sync (private, not actionable)

Both arm_darwin failures are the macOS Fast-test Python-environment class fixed by #108859 (merged 2026-07-03 18:32Z, "Darwin fast test: prune/classify skips, portability fixes, provision Python deps"): it provisions numpy in the fasttest image and prunes the affected skips. This PR's diff is SerializationObjectHelpers.cpp only and cannot cause a macOS numpy/import failure. The failing build ran on a base predating the fix; merging current master picks it up.

Session id: cron:our-pr-ci-monitor:20260703-223000

@clickhouse-gh

clickhouse-gh Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.70% +0.10%
Branches 77.70% 77.70% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3a22898

Every failure below has an owner: a fixing PR (ours 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
Stress test (amd_tsan) / Block structure mismatch in A stream: different number of columns (STID 0993-308a) logical error (chronic trunk JoinStep duplicate-column, fuzzer-surfaced; not this PR's comment/changelog reword) #109114 (ours, open)
Stress test (arm_release) / Block structure mismatch in A stream: different number of columns (STID 2228-453d) logical error (same JoinStep duplicate-column family, arm_release build hash) #109114 (ours, open)
Mergeable Check / PR rollup of the above resolved once #109114 lands
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260704-030000

@Avogar
Avogar added this pull request to the merge queue Jul 7, 2026
Merged via the queue into ClickHouse:master with commit 0cb025a Jul 7, 2026
171 of 174 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…hared-data-paths-quadratic

Speed up flattenAndBucketSharedDataPaths for sparse JSON shared data
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 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