Skip to content

Don't share a query-context-dependent serialization through DataTypesCache - #120403

Open
Avogar wants to merge 6 commits into
masterfrom
data-types-cache-refactor
Open

Avogar wants to merge 6 commits into
masterfrom
data-types-cache-refactor

Conversation

@Avogar

@Avogar Avogar commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Related: #115852
Related: #117655

DataTypesCache memoizes types and serializations by type name on a thread that serves many queries. A DateTime with no declared zone resolves session_timezone in doGetSerialization and keeps it, while getName stays the bare DateTime, so a name cannot tell two such serializations apart.

That is currently prevented by clearing the whole cache whenever the thread's query context changes, or session_timezone is mutated on the same context. The check runs on every lookup, which for text output and binary (de)serialization of Dynamic and JSON means per value: it locks a weak_ptr to the query context — two atomics on a control block shared by every thread of the query — and compares a setting string.

This asks the type instead. IDataType::serializationDependsOnQueryContext reports whether building a serialization from it reads the query context; only DataTypeDateTime and DataTypeDateTime64 answer yes, and only without a declared zone. Containers delegate to what they nest, as they already do for hasDynamicStructure, so Nullable(DateTime), Array(DateTime), Map(String, Array(DateTime)) and a JSON typed path are covered. DataTypeDynamic answers no by default: its variants are resolved by name per use and each is asked for itself.

Such a type is not stored at all — neither it nor its serialization — and both are rebuilt per request. Everything else keeps its entry, and the per-value paths no longer touch the query context.

Excluding the type matters and not only the serialization, because a type hands its captured context to whoever reads it: extractTimeZoneFromFunctionArguments returns a DateTime argument's zone unconditionally. Keeping types cached while dropping the clearing left toString on a Dynamic column of a v2 part — whose variant types are rebuilt from their names through this cache — answered in the zone of whichever query first built that type on the thread. Reading one part alternately under Asia/Tokyo and UTC, 5 of 12 reads came back in the other query's zone; it crossed tables, and did not affect v3 parts or text-format output. All 12 are correct now.

Also replaces getSerialization(type_name, type), whose unchecked contract was that the two arguments agree, with getSerialization(type) deriving the name itself. One call site passed two parallel arrays indexed by the same discriminator, which on drift would have stored a type under another name's key for the rest of the thread's life.

Query results are unchanged relative to master: the clearing this replaces already prevented the leak, just coarsely. What does change is the cache's own contract — a serialization that reports supportsPooling() == false now outlives the query, which is safe because what makes it unpoolable is mutable state reached only when parsing, and nothing that takes a serialization from here parses. gtest_data_types_cache.cpp is rewritten because it pinned the previous contract directly.

Filed as not-for-changelog; once CI produces a release build I will measure tests/performance/json_to_string.xml and re-categorise as a Performance Improvement if the gain is real.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

…Cache

`DataTypesCache` memoizes types and serializations by type name on a thread that
serves many queries. A `DateTime` with no declared zone resolves `session_timezone`
in `doGetSerialization` and keeps it, while `getName` stays the bare `DateTime`, so
a name cannot tell two such serializations apart and one query could be handed the
zone another had resolved.

That was prevented by clearing the whole cache whenever the thread's query context
changed, or `session_timezone` was mutated on the same context. The check ran on
every lookup, which for text output and binary (de)serialization of `Dynamic` and
`JSON` means per value: it locked a `weak_ptr` to the query context - two atomics on
a control block every thread of the query shares - and compared a setting string.

Ask the type instead. `IDataType::serializationDependsOnQueryContext` reports whether
building a serialization from it reads the query context; only `DataTypeDateTime` and
`DataTypeDateTime64` answer yes, and only without a declared zone. Containers delegate
to what they nest, as they already do for `hasDynamicStructure`, so `Nullable(DateTime)`,
`Array(DateTime)`, `Map(String, Array(DateTime))` and a `JSON` typed path are reported
too. `DataTypeDynamic` answers no: its variants are not built into its own serialization
but resolved by name per use, and each is then asked for itself.

Such serializations are no longer cached and are rebuilt per request, which is the
`doGetSerialization` call that re-resolves the zone. Everything else keeps its entry,
and the per-value paths no longer touch the query context at all.

The type is still cached in every case, because nothing reads the zone it captured:
`doGetSerialization` re-resolves it, `encodeDataType` records only whether a zone was
declared so the zone never reaches stored data, and the types that reach a function's
arguments come from query analysis rather than from this cache.

Also replace `getSerialization(type_name, type)`, whose contract was that the two
arguments agree, with `getSerialization(type)` that derives the name itself. The two
callers holding a decoded type use it and stop building the name; the callers holding
a precomputed variant name keep the name overload. The pair could previously disagree
- one call site passed two parallel arrays indexed by the same discriminator - which
would have stored a type under another name's key for the rest of the thread's life.

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

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [123d8ad]

Summary: ❌

job_name test_name status info comment
Unit tests (asan_ubsan) FAIL
DataTypesCache.DoesNotPoolSerializationsThatCapturedTheQueryContext FAIL cidb
AllTests FAIL cidb
Unit tests (tsan) FAIL
DataTypesCache.DoesNotPoolSerializationsThatCapturedTheQueryContext FAIL cidb
AllTests FAIL cidb
Unit tests (msan) FAIL
DataTypesCache.DoesNotPoolSerializationsThatCapturedTheQueryContext FAIL cidb
AllTests FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED

AI Review

Summary

This PR refactors DataTypesCache so types and serializations that depend on the query context are rebuilt per use instead of clearing the whole thread-local cache on every query change. The implementation itself looks consistent, but one of the replacement unit-test blocks is still asserting the wrong contract, so the regression coverage is not reliable yet.

Findings

⚠️ Majors

  • [src/DataTypes/tests/gtest_data_types_cache.cpp:132-138] poolsSerialization only compares the returned SerializationPtr addresses. That no longer tells you whether the entry was stored in DataTypesCache: on every miss getSerialization(type_name) falls back to type->getDefaultSerialization(), and those default factories are globally pooled for DateTime, DateTime64, Nullable, Array, Tuple, and Map. Two lookups in the same session_timezone can therefore legitimately return the same pointer even when the cache correctly rebuilds the type/serialization for each request. This leaves the test checking a pre-fix artifact instead of the contract the PR is trying to protect. Replace these assertions with behavioral checks like the alternating-session_timezone renderEpoch checks, or with direct type non-reuse checks if the goal is to prove the "not stored" branch.
Final Verdict

Changes requested: the cache change looks reasonable, but the remaining unit-test block above still does not prove the intended behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 16, 2026
It returned the default, so it only restated it. The apparent omission needs no
comment either: `Dynamic` has no statically known nested types to delegate to, which
is why it does not implement `forEachChild` either.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 16, 2026
The previous commit kept caching such a type, on the grounds that nothing reads the
context it captured. That is wrong: `extractTimeZoneFromFunctionArguments` returns the
time zone of a `DateTime` argument unconditionally, so a function reads it. For a `v2`
part, whose variant types are rebuilt from their names through this cache, `toString`
on a `Dynamic` column was therefore answered in the zone of whichever query first built
that type on the thread.

Measured on one process, reading the same `v2` part alternately under `Asia/Tokyo` and
`UTC`, 12 reads: 5 answered in the other query's zone. It crosses tables, since the key
is the type name alone, and it does not affect `v3` parts, which decode their types per
read, nor output through a text format, which re-resolves the zone in
`doGetSerialization`. Clearing the whole cache on a query-context change, which this
branch replaced, had kept the cached type belonging to the current query, so the
previous commit was a regression against master rather than a missing fix.

Such a type is no longer stored at all, which is what `getElement` returning by value is
for. After it, the same 12 reads are all in their own zone, as are 20 reads of the same
pair and 12 reads alternating between two tables.

`05183` did not catch this: two alternating reads rarely land on a thread whose cache is
already warm, so it passed on master, on the regression and on the fix alike. Its
`DateTime` fixture also declared a zone, which made its arms duplicate the declared-zone
control, and its `JSON` arm depended on parse-side behaviour this branch does not change
and on a zone the runner randomizes. The fixture is now zone-less and the `JSON` arm is
gone; making it detect the regression needs the repeated form and is left for a
follow-up.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment on lines +128 to +136
/// Without one, the zone comes from the session and the serialization is rebuilt per request,
/// including when it is reached through a container or a `JSON` typed path.
ASSERT_FALSE(poolsSerialization("DateTime"));
ASSERT_FALSE(poolsSerialization("DateTime64(3)"));
ASSERT_FALSE(poolsSerialization("Nullable(DateTime)"));
ASSERT_FALSE(poolsSerialization("Array(DateTime)"));
ASSERT_FALSE(poolsSerialization("Tuple(DateTime, String)"));
ASSERT_FALSE(poolsSerialization("Map(String, Array(DateTime))"));
ASSERT_FALSE(poolsSerialization("JSON(ts DateTime)"));

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.

These ASSERT_FALSE(poolsSerialization(...)) checks are no longer testing the contract this PR implements. getSerialization(type_name) does avoid storing query-context-dependent entries in DataTypesCache, but the fallback path still builds the default serialization through globally pooled helpers such as SerializationDateTime::create, SerializationDateTime64::create, and the pooled container wrappers on top of them. Two lookups in the same session_timezone can therefore legitimately return the same pointer even when the per-query leak is fixed.

This block needs behavioral assertions like the renderEpoch checks under alternating session_timezones, not get() != get().

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 123d8ad9f with master daa7bdbd3 (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Compile time of recompiled translation units

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

Job report

Avogar and others added 2 commits September 28, 2026 16:02
Three defects, all in the test, all consequences of the previous commit not being
carried through it.

`renderEpoch` built a `ColumnUInt32` and passed it to whichever serialization the name
resolved to, so asking it for `DateTime64(3)` hit `Bad cast from DB::ColumnVector<unsigned
int> to DB::ColumnDecimal<DB::DateTime64>`. That threw before gtest could write its
result file, which is why the job reported `No test result file` rather than a failed
assertion, and why only the first failure was visible. The column now comes from the
type, whose default is the epoch.

`ReusesEntriesWithinOneQuery` asserted that `getType("DateTime64(3)")` returns one
object, which the previous commit deliberately made false. It now uses `Array(String)`,
which is stored, so it still pins that ordinary entries are reused, and it is renamed to
`ReusesStoredEntries`: entries are no longer scoped to a query, so the old name described
a contract this branch removed.

The last assertion of `DoesNotPoolSerializationsThatCapturedTheQueryContext` still
required the type to be pooled. It is inverted, with the reason the previous commit
established: whoever reads such a type is handed the context it resolved.

https://s3.amazonaws.com/clickhouse-test-reports/PRs/120403/e19d93e0cb34d7d483c30508c5bd79a42f4dbb43/pr/unit_tests_asan_ubsan/unit_tests_asan_ubsan.log
#120403

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`SerializationDynamic` conflicted where this branch had replaced
`getSerialization(type_name, type)` with an overload deriving the name from the type.
Master has since moved more call sites onto the two-argument form, so that form is kept
and the overload is dropped: where a caller already holds both the name and the type,
passing both avoids building the name string per value as well as parsing it on a miss,
which neither one-argument form can do at once. Only the per-type predicate remains,
which is what this branch is for, so `SerializationDynamic` is now identical to master.

The precondition that the two arguments agree stays unchecked, as it was before.
@matanper

matanper commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Observation: with this PR applied (backported onto 26.9 for testing), inserting JSON text into a JSON column whose values include date-time strings regresses insert CPU by ~22% (31.75s -> 38.87s server CPU, 5 alternating runs, identical data) and merge CPU by ~6%.

Cause, from perf: the JSON parser infers such strings as DateTime64(9) (no time zone) and requests that type (and its serialization) from DataTypesCache once per value, e.g. JSONExtractTree's insertIntoSharedData -> getType("DateTime64(9)"), and SerializationDynamic::serializeBinary. Since those types are no longer cached, every call re-parses the type name through DataTypeFactory (parseQuery / ParserDataType). DataTypesCache::getElement goes to ~14% of insert CPU and DataTypeFactory::getImpl to ~13.7%.

Minimal repro idea: CREATE TABLE t (j JSON(max_dynamic_paths=64)) ENGINE=MergeTree ORDER BY tuple(), then insert ~200k JSONEachRow rows with a few hundred distinct keys whose values are date-time strings like "2024-05-01 12:34:56.123456789", most of them overflowing into shared data. Compare server CPU before and after this PR.

Suggestion: keep caching time-zone-less DateTime/DateTime64 (their meaning doesn't depend on context beyond the session time zone, which could be part of the cache key), or cache per query context, so hot per-value paths don't re-parse type names.

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

comp-data-types Type system & core datatypes used across query planning/execution. pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants