Skip to content

Avoid per-value query-context lookup when decoding Dynamic/JSON types - #108797

Merged
seva-potapov merged 18 commits into
ClickHouse:masterfrom
seva-potapov:fix-decode-datatype-per-value-context-read
Jul 10, 2026
Merged

seva-potapov merged 18 commits into
ClickHouse:masterfrom
seva-potapov:fix-decode-datatype-per-value-context-read

Conversation

@seva-potapov

@seva-potapov seva-potapov commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Fix a performance regression when reading JSON/Dynamic columns with multiple threads. The per-value lookup of the input_format_binary_max_type_complexity setting caused shared_ptr reference-count contention on the shared query context, serializing parallel reads; the limit is now cached per thread.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Details

When reading JSON/Dynamic columns, the binary type of every shared-data value is decoded with decodeDataType, which reads the input_format_binary_max_type_complexity limit from the current query context on every call. CurrentThread::tryGetQueryContext() copies the query's ContextPtr, so every value bumps the reference count of the same shared Context. Under a multi-threaded read this turns into atomic cache-line contention on a single counter and
effectively serializes the threads — a query reading a JSON(max_dynamic_paths = 0) column could burn an order of magnitude more CPU than the same workload on 25.12, where this limit did not exist.

The limit is now resolved once and cached per thread, refreshed only when the thread attaches to a different query. The cache is keyed on a new monotonically increasing ThreadGroup sequence number (never reused, unlike the group address), so a different query, even one that reuses the client-supplied query_id, always re-reads its own setting. The decoded value is unchanged and
the complexity limit is still enforced per query.

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f03da1f]

Summary: ✅


AI Review

Summary

This PR replaces per-node query-context lookups with explicit max_type_complexity propagation at several binary type-decode boundaries and makes a number of stored Dynamic/JSON reads unlimited. The direction is reasonable, but I still see two correctness blockers around client-controlled payloads that can bypass input_format_binary_max_type_complexity, plus one remaining spec-sync issue.

PR Metadata
  • Changelog category: Performance Improvement is defensible for the original regression.
  • Changelog entry: required, but the current text is no longer accurate. The implementation no longer caches the limit per thread or keys anything on a ThreadGroup sequence; it now threads the limit explicitly through client-facing decode entry points and leaves trusted/stored Dynamic/JSON decodes unlimited.
  • Details: the explanatory section is stale for the same reason and still describes the removed per-thread cache design.
  • Exact replacement text:
    Avoid per-value query-context lookups when decoding binary \Dynamic`/`JSON` types by passing `input_format_binary_max_type_complexity` explicitly at client-facing binary-input boundaries and using unlimited decoding for already-stored `Dynamic`/`JSON` data.`
Missing context / blind spots
  • ⚠️ There is still no focused before/after benchmark or perf test for the actual regression path (JSON(max_dynamic_paths = 0) / Dynamic(max_types = 0) shared-data reads). The posted cloud benchmarks are off-path, so they do not validate the Performance Improvement claim.
Findings

❌ Blockers

  • [src/DataTypes/Serializations/SerializationObjectSharedData.cpp:1082-1109, src/Columns/ColumnObject.cpp:1081-1094] JSON(max_dynamic_paths = 0) / Object shared-data values from binary input are still stored without validating the embedded binary type header, and later reads decode those stored bytes with unlimited settings. That means a client can bypass input_format_binary_max_type_complexity by hiding a wide Dynamic type inside shared-data payloads, then trigger the expensive decode later during SELECT, merges, or materialization. Suggested fix: validate every shared-data value's binary type at the binary input boundary before storing it, or keep a limited decode path for any shared-data bytes that may still originate from client input.
  • [src/Columns/ColumnDynamic.cpp:827-835, src/Columns/ColumnObject.cpp:1045-1094, src/AggregateFunctions/KeyHolderHelpers.h:34-42, tests/queries/0_stateless/04303_binary_max_type_complexity_input_only.sh:29-33] The new "input-only" contract is still false for aggregate states. deserializeAndInsertFromArena is a user-input boundary, but both ColumnDynamic and ColumnObject now decode arena payloads with default-constructed FormatSettings (or no validation at all), so AggregateFunction(...Dynamic...) and AggregateFunction(...JSON/Object...) payloads can bypass input_format_binary_max_type_complexity on ingest. [dismissed by author -- https://github.com/Avoid per-value query-context lookup when decoding Dynamic/JSON types #108797#discussion_r3526306608] The current test codifies the Dynamic carve-out as expected behavior, but the same trusted/untrusted conflation still exists for ColumnObject. Suggested fix: either validate these aggregate-state payloads at the binary input boundary, or thread an explicit trusted/untrusted complexity policy through deserializeAndInsertFromArena instead of relying on default FormatSettings.

⚠️ Majors

  • [src/Formats/NativeReader.cpp:197] NativeReader now enforces input_format_binary_max_type_complexity when binary type names are enabled, but docs/en/interfaces/specs/NativeFormat.md still does not describe that decoder-side limit or the 0 compatibility/unlimited behavior. [dismissed by author -- https://github.com/Avoid per-value query-context lookup when decoding Dynamic/JSON types #108797#discussion_r3502763338] Given the repo rule that NativeReader / NativeWriter changes must update the Native spec in the same change, this should be documented here unless the guard is intentionally outside the format contract.
Final Verdict

Do not approve in the current state. The PR still leaves client-controlled aggregate-state and JSON/Object shared-data payloads outside the advertised malicious-input guard, and the Native spec plus PR metadata do not yet match the behavior that would ship.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 29, 2026
@seva-potapov seva-potapov added the can be tested Allows running workflows for external contributors label Jun 29, 2026
/// refcount contention on the shared Context across the reading threads, serializing the work. Cache the
/// resolved limit per thread and refresh it only when the query changes - getQueryId() is a cheap
/// thread-local read with no atomics, so the hot path no longer touches the shared Context.
size_t getMaxTypeDecodingComplexity()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This PR is categorized as Performance Improvement and the description claims the new cache removes an order-of-magnitude CPU regression, but the change does not include or link any before/after measurements, benchmark run, or focused perf test for the Dynamic/JSON shared-data decode path. The implementation is plausible, but without evidence we cannot verify the promised performance contract or catch a regression if this cache stops being effective.

Please add the benchmark numbers used to validate the claim, including the query, dataset shape, thread count, and before/after CPU or elapsed time, or add a focused benchmark covering multi-threaded reads of JSON(max_dynamic_paths = 0)/Dynamic values.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

cease and desist

@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only reworks how input_format_binary_max_type_complexity is threaded through binary type decoding (query-plan/native-format deserialization and untrusted-input guards); it does not touch the scan, group-by, or sort code that ClickBench Q15 actually executes. A -21.15% (-51.5 ms) improvement on a standard-typed aggregation query cannot plausibly come from this change, and with only 6 source runs and noisy underlying measurements the delta is most consistent with run-to-run variance. Downgraded Q15 from improvement to not-sure; no real per-query effect attributable to this PR.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 244 192 -21.1% <0.0001 Binary type-decode plumbing; Q15's scan/group-by hot path decodes no types. -21% reads as run-to-run variance.

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: 6476295f-76f4-4bec-add1-cb15633d0fb9
  • MIRAI run: ac019ffd-741b-4a43-b6e9-dd930082212e
  • PR check IDs:
    • clickbench_78917_1783607037
    • clickbench_78923_1783607037
    • clickbench_78929_1783607037
    • tpch_adapted_1_official_78936_1783607038
    • tpch_adapted_1_official_78947_1783607037
    • tpch_adapted_1_official_78958_1783607037

@fm4v
fm4v requested a review from Avogar June 29, 2026 23:25
Comment thread src/Common/ThreadStatus.cpp Outdated
@@ -168,6 +162,13 @@ ThreadStatus::ThreadStatus()
#endif
}

UInt64 nextThreadGroupSequenceNumber()

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.

This looks extremely complex for the task. Doesn't it make more sense to pass the max_complexity in the recursive call itself?

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.

@seva-potapov seva-potapov Jun 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

rename to decodeDataTypeImpl is fine, but it doesn't help the case this PR is about.

the cost isn't the recursion, it's that decodeDataType(buf) is called once per value. Dynamic/JSON store the type inline with each value, so reading shared data goes:

ColumnObject::fillPathColumnFromSharedData   // per row (ColumnObject.cpp:2030)
  -> SerializationDynamic::deserializeBinary // per row -> decodeDataType(istr) (:778)
     -> decodeDataType(buf)                  // your getMaxTypeDecodingComplexity() call is here

your version reads the setting once per decodeDataType(buf) call instead of once per type node. but a path value is usually a single node (Int64/String/...), so for this workload that's the same number of reads, and zero difference for scalars. the per-value tryGetQueryContext() (refcount bump on the shared Context) is what serializes the threads, and it's still there. moving it to the entry only helps when a single deeply nested type is decoded once, e.g. a column type from a Native/RowBinary header.

to make it O(1) the limit has to be read above the per-row loop and passed in. problem is the callers there (fillPathColumnFromSharedData, SerializationDynamicElement) only have a default FormatSettings from getFormatSettings() that doesn't carry input_format_binary_max_type_complexity, so threading it down that way just uses 1000 and stops honoring the setting. that's why it's cached per thread keyed on the thread group.

if you'd rather build on decodeDataTypeImpl and drop the ThreadGroup part, I'm fine with that as long as we thread the limit from the bulk read without going through the default FormatSettings.

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.

to make it O(1) the limit has to be read above the per-row loop and passed in.

Let's do that instead. I don't like having globals to respect a setting

(fillPathColumnFromSharedData, SerializationDynamicElement) only have a default FormatSettings from getFormatSettings() that doesn't carry input_format_binary_max_type_complexity

Let's make it respect it then

@Algunenano Algunenano self-assigned this Jun 30, 2026
@Avogar

Avogar commented Jun 30, 2026

Copy link
Copy Markdown
Member

I agree that the best approach is to propagate the limit from the caller side to decodeDataType function. For places where default FormatSettings are used we can propagate 0 as unlimited, because in such places we need to be able to deserialize regardless any limits (limits should be applied on input data deserialization, in ColumnObject methods we work with already deserialized data to change its in-memory representation if needed).

@Avogar

Avogar commented Jun 30, 2026

Copy link
Copy Markdown
Member

Also we have another problem with this setting:

  • Old value in SettingsChangesHistory is set to 1000 instead of 0 (unlimited)
  • We have hardcoded 1000 value if there is no query context, which is bad for merges in terms of compatibility

Set the previous value to 0 so that compatibility restores unlimited pre-26.1 behaviour
Comment thread src/Formats/NativeReader.cpp Resolved
@seva-potapov

Copy link
Copy Markdown
Contributor Author

Done — decodeDataType now takes the limit as an arg instead of reading the context per node.

However, I couldn't make internal decode uniformly 0. A few "internal" paths actually see client bytes, so they enforce the limit: query-plan deserialization (receiveQueryPlan decodes before rejecting), set data, and Dynamic shared-variant/arena decode (e.g. a client-supplied groupArray(Dynamic) state). Only the stored-shared_variant JSON read path, the one that caused the regression, stays 0.

Two notes. The arena/shared-variant paths still read the limit from the query context (like master), since threading it explicitly would touch IAggregateFunction::deserialize across ~77 functions. And those paths are dual-use (input vs stored read), so a SELECT can reject a stored Dynamic wider than the reader's limit, same as master. Doing it properly means validating shared-variant types at the Native input boundary, then 0 everywhere internal.

Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Columns/ColumnObject.cpp Outdated
/// This FormatSettings is used only for internal (de)serialization of already-stored Dynamic/JSON
/// data, which must always succeed. Do not apply the binary type-complexity guard here: it protects
/// against malicious *input*, not in-memory data we produced ourselves.
s.binary.max_binary_type_complexity = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This 0 limit is safe only if the shared-data value bytes were validated before they entered the column. Native input does not currently do that: SerializationObjectSharedData::deserializeBinaryBulkWithMultipleStreams reads shared data as Map(String, String) or copy strings and never decodes the embedded Dynamic value type. A client can therefore send a JSON(max_dynamic_paths = 0) Native block with a shared-data value whose binary type encoding exceeds input_format_binary_max_type_complexity; the insert stores the raw bytes, and a later fillPathColumnFromSharedData or deserializeValueFromSharedData decodes them through this unlimited setting. That bypasses the malicious-input guard and can spend unbounded CPU/memory on client-controlled type encodings.

Please either validate every shared-data Dynamic value at Native input deserialization with the effective input_format_binary_max_type_complexity before storing it, or keep a limited path for shared-data bytes that may originate from Native input until such validation exists.

@seva-potapov seva-potapov Jul 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@Avogar what do you think we should do with this comment? option 1 would effectively neuter this PR, while 2nd is a whole new can of worms. I believe the complication that we have arrived at after following @Algunenano request to remove cached complexity from thread storage is excessive. I am very tempted to just revert all the changes made since then and be done with this PR so we can unblock 26.2

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.

Please do a proper full fix or remove input_format_binary_max_type_complexity from the affected releases and ask for a proper fix. We should not made the code noticeable worse because we are unable to process settings properly.

Comment thread src/Columns/ColumnDynamic.cpp Resolved
@Avogar

Avogar commented Jul 2, 2026

Copy link
Copy Markdown
Member

Let's use unlimited complexity for calls from ColumnDynamic/ColumnObject. These methods can be called during background operations where we don't want to throw. Later if we want we can make a separate PR that will perform additional check for type complexity during Native format parsing of Dynamic/Object types.

@seva-potapov

Copy link
Copy Markdown
Contributor Author

@Avogar done as per your request, I'll leave Native parsing complexity check for Dynamic/Objects for a follow up PR

Comment thread src/DataTypes/DataTypesBinaryEncoding.h Resolved
Comment thread src/Columns/ColumnDynamic.cpp Resolved
Comment on lines +29 to +30
# Decoding a stored aggregate-function state holding Dynamic (e.g. groupArray(Dynamic)) goes through
# ColumnDynamic, which is not limited by the setting (it can run in background operations that must not throw).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This aggregate-state carve-out is still wider than the background-only case the new test comment describes. SerializationAggregateFunction::deserializeBinary accepts client-supplied AggregateFunction(...) states, and AggregateFunction(groupFormat('JSONEachRow'), Dynamic) deserializes them via AggregateFunctionGroupFormat::deserialize -> NativeReader::readData(..., nullptr, ...) (src/AggregateFunctions/AggregateFunctionGroupFormat.cpp:215). After this PR, the missing FormatSettings means max_binary_type_complexity == 0, so nested Dynamic / JSON types inside that input state bypass input_format_binary_max_type_complexity entirely on ingest.

Please either validate such aggregate states at the input boundary, or keep the limit enabled for aggregate-state deserializers that can still consume client bytes.

UInt64 max_object_size = 100000;
/// Max number of type nodes when decoding binary types. 0 == unlimited. The guard applies only to
/// untrusted input: FormatFactory populates this from input_format_binary_max_type_complexity for real
/// input formats. A default-constructed FormatSettings (internal decode of already-stored data) leaves

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This comment overstates where the default FormatSettings is used. It is not limited to trusted "already-stored" / background-only decode paths: client-supplied aggregate-state bytes still reach this default too.

Concrete path: KeyHolderHelpers::deserializeAndInsert calls IColumn::deserializeAndInsertFromArena for aggregate states (src/AggregateFunctions/KeyHolderHelpers.h:34-42), and ColumnObject::deserializeDynamicPathsAndSharedDataFromArena then deserializes dynamic paths with getDynamicSerialization()->deserializeBinary(..., getFormatSettings()) or copies shared-data bytes without any type validation (src/Columns/ColumnObject.cpp:1081-1094). Because this PR makes the default max_binary_type_complexity unlimited, an AggregateFunction(...JSON/Object...) payload can still bypass input_format_binary_max_type_complexity on ingest.

Please either validate ColumnObject arena payloads at the binary input boundary, or thread an explicit trusted/untrusted complexity policy through arena deserialization before documenting all default-constructed FormatSettings as internal-only.

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.90% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 246/276 (89.13%) · Uncovered code

Full report · Diff report

@fm4v

fm4v commented Jul 9, 2026

Copy link
Copy Markdown
Member

Can this be merged?

@seva-potapov
seva-potapov added this pull request to the merge queue Jul 10, 2026
Merged via the queue into ClickHouse:master with commit ce6357c Jul 10, 2026
849 of 855 checks passed
@seva-potapov
seva-potapov deleted the fix-decode-datatype-per-value-context-read branch July 10, 2026 07:17
@robot-ch-test-poll robot-ch-test-poll added pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Jul 10, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 20, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…atype-per-value-context-read

Avoid per-value query-context lookup when decoding Dynamic/JSON types
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants