Skip to content

Memory-track the JSON FLATTENED path list read from Native - #117730

Merged
Avogar merged 10 commits into
masterfrom
json-native-flattened-paths-memory-tracking
Sep 29, 2026
Merged

Avogar merged 10 commits into
masterfrom
json-native-flattened-paths-memory-tracking

Conversation

@Avogar

@Avogar Avogar commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

SerializationObject's flattened_paths was a plain std::vector<String>, so its growth was accounted through the non-throwing MemoryTracker methods and never rejected. Reading a JSON column with the FLATTENED structure version from a Native stream therefore allocated its path list regardless of max_memory_usage and max_server_memory_usage, while the non-flat structure versions, which use VectorWithMemoryTracking for sorted_dynamic_paths, correctly throw MEMORY_LIMIT_EXCEEDED on the same input and the same limit.

With max_memory_usage = 10000000 and a path count of 1000000:

structure version before after
3 (FLATTENED) silently reserves ~23 MiB, then ATTEMPT_TO_READ_AFTER_EOF MEMORY_LIMIT_EXCEEDED
2 (non-flat) MEMORY_LIMIT_EXCEEDED unchanged

The path count itself is already capped by reserveOrThrowTooManyPaths, so this is not an out-of-memory fix; it only removes the asymmetry between the two structure versions.

The first commit is separate cleanup: the guards for corrupted Native path and type counts each carried 9 to 13 lines of comment restating their own two-line bodies, so they are reduced to the one thing that is not already in the code.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed max_memory_usage and max_server_memory_usage not being respected when reading a JSON column with the FLATTENED serialization version from the Native format.


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

Version info

  • Merged into: 26.10.1.998-master (included in 26.10 and later)
  • Backported to: 26.9.6.9, 26.8.16.25, 26.7.20.17, 26.3.39.12

Avogar and others added 2 commits September 2, 2026 16:24
The guards added for corrupted `Native` path/type counts carried 9 to 13 lines
of comment each, restating what `reserveOrThrowTooManyPaths`,
`reserveOrThrowTooManyTypes`, `reserveOrThrowTooMany` and
`throwIfInvalidNumberOfBuckets` and their two-line bodies already say. Keep only
the part that is not in the code, that the count is untrusted and therefore used
as a capped hint, and drop the call-site comments that repeated the same thing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`DeserializeBinaryBulkStateObjectStructure::flattened_paths` was a plain
`std::vector<String>`, so its growth was accounted through the non-throwing
`MemoryTracker` methods and never rejected: reading a `JSON` column with the
`FLATTENED` structure version from a `Native` stream allocated the reserve
regardless of `max_memory_usage` and `max_server_memory_usage`. Its sibling
`sorted_dynamic_paths`, used by the non-flat versions, is already a
`VectorWithMemoryTracking` and does throw `MEMORY_LIMIT_EXCEEDED` on the same
input and the same limit.

Use `VectorWithMemoryTracking` for `flattened_paths` too, so both structure
versions behave the same. The path count itself is capped separately by
`reserveOrThrowTooManyPaths`, so this is not an out-of-memory fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar Avogar added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eeee9f1]

Summary: ✅


AI Review

Summary

This PR switches the FLATTENED JSON / Object Native path-list reserve to VectorWithMemoryTracking and carries the same memory-accounting invariant through the nearby Dynamic and ADVANCED shared-data helper paths that were uncovered during review. On the current PR diff and code, I did not find an unresolved correctness or memory-accounting issue that still merits an inline review comment.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit eeee9f1.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
Addressing review on #117730. Two more containers in the same family were
plain `std::vector` and so accounted through the non-throwing `MemoryTracker`,
letting a reserve driven by a count from the stream push past
`max_memory_usage` without throwing:

- `DeserializeBinaryBulkStateDynamic::flattened_states`, reserved from the
  number of `FLATTENED` types decoded off a `Native` stream, and its
  serialize-side twin. Weaker than `flattened_paths`, since the size comes from
  types actually read rather than from the raw header count, but the reserve
  itself was still untracked.
- `SerializationObjectSharedData::StructureGranule::all_paths`, reserved from
  the per-granule path count, together with the compact and wide readers' full
  copies of that list and the `deserializeIndexesAndCollectPaths` signature
  consuming them. Reachable only from a corrupted MergeTree part written with
  `ADVANCED` shared data serialization, not from `Native`.

`PathInfo::substreams` is left plain: converting it needs the
`getSubcolumnsDeserializationOrder` parameter changed, which
`MergeTreeReaderCompact` also calls with a plain `std::vector<String>`.

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

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing eeee9f19a with master ac31ad694 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 13d023155; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

17 object files changed (+67.89 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/Serializations/getSubcolumnsDeserializationOrder.cpp.o 72.84 KiB 110.68 KiB +37.84 KiB (+51.96%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

22 translation units recompiled, 87 s compile time in total, 22 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +3.9 s (+5%) in total before that adjustment.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... label Sep 4, 2026
@ClickHouse ClickHouse deleted a comment from zlareb1 Sep 4, 2026
Conflicts in the `ADVANCED` shared data reader only. Master reworked the
per-granule path lists into per-chunk lists and renamed granule to chunk, while
this branch changed their container type. Kept master's structure and naming and
reapplied the memory tracking on top: `StructureChunk::all_paths` and the
per-chunk `chunks_paths` copies in both the Compact and Wide read paths are
`VectorWithMemoryTracking<String>`, matching the
`deserializeIndexesAndCollectPaths` signature they feed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@rienath rienath self-assigned this Sep 16, 2026
Addressing review on #117730, the last two containers on the `ADVANCED` shared
data read path that were still plain `std::vector` / `std::unordered_map`:

- `PathInfo::substreams`, whose `reserve` is driven by the `num_substreams`
  count read from `ObjectSharedDataSubstreams`, so a corrupted part could
  preallocate up to `DEFAULT_NATIVE_BINARY_MAX_NUM_COLUMNS` strings outside the
  throwing tracker.
- `PathInfo::substream_to_mark`, which gets one node per entry of that list.

`substreams` is passed to `getSubcolumnsDeserializationOrder`, which
`MergeTreeReaderCompact` also calls with a plain `std::vector<String>` from
`ColumnsSubstreams`. Rather than convert `ColumnsSubstreams` too, the paths
argument is now a template parameter, explicitly instantiated for both
containers, so nothing outside `DataTypes` changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Addressing review on #117730. `getSubcolumnsDeserializationOrder` builds a
lookup map over the substream list it is given, so on the `ADVANCED` shared data
read path its node allocations scale with the substream names read from a
possibly corrupted part while bypassing the throwing tracker. The list itself is
already tracked, so this was the last untracked step on that path.

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

Avogar commented Sep 17, 2026

Copy link
Copy Markdown
Member Author

@groeneai check the AST fuzzer failure, does it have existing fix?

@groeneai

Copy link
Copy Markdown
Collaborator

Yes, it has a fix: #120509 (the abort is STID 2508-436e).

The fuzzer query reads format(TSV, '\N\n...'). The first row's \N unescapes to an empty name, so header detection yields a structure whose every column name is empty; the emptiness guard in readSchemaFromFormatImpl runs before the filter that erases empty-named columns, so inference returns zero columns and RowInputFormatWithNamesAndTypes<TabSeparatedFormatReader>::readPrefix() then evaluates data_types.at(0) on an empty vector. std::out_of_range derives from std::logic_error, so the debug build aborts instead of returning the error.

It is not caused by your change: your diff touches no format or schema inference code, and it reproduces on stable 26.8.6.5 with SELECT * FROM format(CSV, '""\n42\n'). #120509 rejects such a result at the producer, in ReadSchemaUtils.cpp, before it reaches the reader. It is still open, so the abort can reappear on any branch until it merges.

alexey-milovidov and others added 3 commits September 26, 2026 02:51
The merge of master brought a new caller in `StorageGenerateRandom.cpp:1818`
that passes a plain `std::vector<String>`, which no longer converts after this
branch narrowed the parameter to `VectorWithMemoryTracking<String>`:

    error: no matching function for call to 'unflattenAndInsertPaths'
    note: no known conversion from 'vector<[...], (default) std::allocator<std::string>>'
          to 'const vector<[...], AllocatorWithMemoryTracking<String>>'

Take the paths container as a template parameter, explicitly instantiated for
both, the same way `getSubcolumnsDeserializationOrder` already handles its
`MergeTreeReaderCompact` caller. The generated paths in `StorageGenerateRandom`
come from a schema rather than from a stream, so there is no reason to track
them.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117730&sha=2ce73b92a4a69ae2f9c7126ecbad580f614b93af&name_0=PR&name_1=Fast%20test
#117730

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Name the property that makes the template necessary rather than the callers
that happen to exercise it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Sep 29, 2026
Merged via the queue into master with commit 7d517b8 Sep 29, 2026
149 checks passed
@Avogar
Avogar deleted the json-native-flattened-paths-memory-tracking branch September 29, 2026 13:20
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 29, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 29, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 29, 2026
Backport #117730 to 26.9: Memory-track the JSON `FLATTENED` path list read from `Native`
PedroTadim added a commit that referenced this pull request Oct 2, 2026
Cherry pick #117730 to 26.3: Memory-track the JSON `FLATTENED` path list read from `Native`
PedroTadim added a commit that referenced this pull request Oct 2, 2026
Cherry pick #117730 to 26.7: Memory-track the JSON `FLATTENED` path list read from `Native`
PedroTadim added a commit that referenced this pull request Oct 2, 2026
Cherry pick #117730 to 26.8: Memory-track the JSON `FLATTENED` path list read from `Native`
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
robot-clickhouse added a commit that referenced this pull request Oct 2, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 2, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #117730 to 26.7: Memory-track the JSON `FLATTENED` path list read from `Native`
clickhouse-gh Bot added a commit that referenced this pull request Oct 2, 2026
Backport #117730 to 26.8: Memory-track the JSON `FLATTENED` path list read from `Native`
PedroTadim added a commit that referenced this pull request Oct 2, 2026
Backport #117730 to 26.3: Memory-track the JSON `FLATTENED` path list read from `Native`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

7 participants