Repository navigation
Avoid per-value query-context lookup when decoding Dynamic/JSON types - #108797
seva-potapov merged 18 commits into
Conversation
|
Workflow [PR], commit [f03da1f] Summary: ✅
AI ReviewSummaryThis PR replaces per-node query-context lookups with explicit PR Metadata
Missing context / blind spots
Findings❌ Blockers
Final VerdictDo not approve in the current state. The PR still leaves client-controlled aggregate-state and |
| /// 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() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
cease and desist
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
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
|
| @@ -168,6 +162,13 @@ ThreadStatus::ThreadStatus() | |||
| #endif | |||
| } | |||
|
|
|||
| UInt64 nextThreadGroupSequenceNumber() | |||
There was a problem hiding this comment.
This looks extremely complex for the task. Doesn't it make more sense to pass the max_complexity in the recursive call itself?
There was a problem hiding this comment.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
|
I agree that the best approach is to propagate the limit from the caller side to |
|
Also we have another problem with this setting:
|
Set the previous value to 0 so that compatibility restores unlimited pre-26.1 behaviour
|
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. |
| /// 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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
There was a problem hiding this comment.
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.
|
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. |
…m clients as per review
|
@Avogar done as per your request, I'll leave Native parsing complexity check for Dynamic/Objects for a follow up PR |
| # 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). |
There was a problem hiding this comment.
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.
…-per-value-context-read
| 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 |
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 246/276 (89.13%) · Uncovered code |
|
Can this be merged? |
ce6357c
…atype-per-value-context-read Avoid per-value query-context lookup when decoding Dynamic/JSON types
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a performance regression when reading
JSON/Dynamiccolumns with multiple threads. The per-value lookup of theinput_format_binary_max_type_complexitysetting causedshared_ptrreference-count contention on the shared query context, serializing parallel reads; the limit is now cached per thread.Documentation entry for user-facing changes
Details
When reading
JSON/Dynamiccolumns, the binary type of every shared-data value is decoded withdecodeDataType, which reads theinput_format_binary_max_type_complexitylimit from the current query context on every call.CurrentThread::tryGetQueryContext()copies the query'sContextPtr, so every value bumps the reference count of the same sharedContext. Under a multi-threaded read this turns into atomic cache-line contention on a single counter andeffectively 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
ThreadGroupsequence number (never reused, unlike the group address), so a different query, even one that reuses the client-suppliedquery_id, always re-reads its own setting. The decoded value is unchanged andthe complexity limit is still enforced per query.
Version info
26.7.1.737(included in26.7and later)