Skip to content

Include the session time zone in the query condition cache key - #117302

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-qcc-key-session-timezone
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-qcc-key-session-timezone

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixes wrong results from the query condition cache when the same condition runs in sessions with different session_timezone values. The cache remembers which parts of a table held no matching rows, but its key did not include the time zone the condition is evaluated in, so a "nothing matched here" decision made in one time zone was reused in another and every matching row was silently dropped. The resolved session_timezone is now part of the cache key.

Description

Closes: #117186

On master, a condition primed under Asia/Tokyo and read under UTC shares one entry: the second query returns 0 of 1000000 rows, read_rows = 0.

makeKey keyed the verdict on the condition's plan. session_timezone is an input to evaluating it and need not appear in the plan, so no inspection can find it. Measured carriers: an omitted zone inside Nullable(DateTime) (#117186), a lambda body, a Dynamic subtype, and fromUnixTimestamp(x, '%H') over a UInt32, whose condition holds no temporal type.

So the change stops looking for it: time_zone becomes a required parameter of makeKey/write/read, resolved at each of the 13 key-producing sites from its own Settings. Required rather than defaulted, so an omission is a compile error, not a silent write/read key divergence. ActionsDAG::Node::updateHash is untouched, so the hash-table-size keys that also read the DAG hash never see a session setting. session_timezone is unset by default, so a deployment that does not vary it partitions nothing.

On master the new test returns 0 instead of 1000000 on six arms, as does an appended arm on the local-File test; deleting only the added hash.update(time_zone) line reproduces both byte for byte. 50/50 under randomized settings, and the *query_condition_cache* family is unchanged. A seventh arm covers the entries index analysis writes under its own profiled key; blanking the zone there alone returns 0 instead of 3600. The object-storage key sites read the zone from the same per-query FormatFilterInfo as the File ones, so they are covered by reading rather than by a test.

#117161 (mine, open) fixes the declared-type half one layer up; keying on the zone covers that half too, so only its cache test becomes redundant. Its disposition is for its reviewers.

Also outside the key: other settings a function reads while it runs, now tracked as #117308; and a DateTime under a Dynamic or JSON path rendering in a zone that is neither the reading session's nor stable across processes.


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

groeneai and others added 4 commits August 31, 2026 03:23
The query condition cache records, per mark, whether a filter condition
matched any row, keyed on the table UUID, the part name and a hash of the
condition. That hash describes the condition's plan: node kinds, names,
type names, function names and constant values. The time zone a date or
time function reads while the condition runs is an input to evaluating
the condition, it was not part of the key, and it does not have to be
visible in the plan at all, so a "nothing here matched" verdict computed
under one session_timezone was served to a session using another one.
Every matching row was then silently dropped: no error, read_rows = 0
and QueryConditionCacheHits = 1.

Four carriers were measured, and together they rule out fixing this by
inspecting the condition. An omitted time zone inside Nullable(DateTime)
is spelled the same in every session, because DataTypeNullable is no
TimezoneMixin and the inner name carries no zone. A lambda's body is not
part of its type: FunctionCapture holds a separate ActionsDAG that the
node hash never walks. A Dynamic value's concrete subtype exists only at
read time, so the declared type is just Dynamic. And
fromUnixTimestamp(x, '%H') = '00' over a UInt32 column reads the zone
while it executes with no temporal type anywhere in the condition.

So this does not try to detect whether the zone is read. The resolved
time zone becomes a required parameter of QueryConditionCache::makeKey,
write and read, and every key-producing site supplies it from its own
Settings through one helper. Required rather than defaulted, because the
failure mode this path is most exposed to is a write key and a read key
that disagree, and a required parameter turns that into a compile error;
it is also what proved the call-site set complete. Two sites had no
Settings in scope: the PREWHERE write in MergeTreeSelectProcessor takes
it from MergeTreeReaderSettings, and FilterTransform from a new sibling
field of FilterStep::condition. The five file-backed sites take it from
FormatFilterInfo, resolved once in its constructor next to
condition_hash, which makes their write and read keys agree by
construction.

ActionsDAG::Node::updateHash is deliberately untouched. The DAG hash is
also read by the hash-table-size and join-reordering statistics keys,
which must not depend on a session setting, and it must stay independent
of ambient thread state. For the same reason the helper names the server
time zone directly for an unset setting instead of delegating to
DateLUT::instance(), which would read the current thread's query
context.

session_timezone is unset by default and resolves to the server time
zone, so a deployment that does not vary it hashes one constant and no
entry is partitioned. Where sessions do use different zones, entries
partition per zone in use; for a zone-dependent condition that
partitioning is the fix, and for a zone-independent one it is a bounded
loss of sharing that the precise alternative cannot avoid soundly.

The new test pins dynamic_serialization_version = 'v3' because a Dynamic
value only resolves its subtype against the reading session from that
version on, which is unrelated to this change and is tracked separately.

Closes: ClickHouse#117186

Co-Authored-By: Claude Opus 5 <[email protected]>
The query condition cache is analyzer-only: it is gated on
allow_experimental_analyzer on the write side, on the read side and in
the plan optimization. tests/config/users.d/analyzer.xml turns that
setting off for the old-analyzer jobs, so without a pin the new test
wrote no entry at all there and eleven of its reference lines inverted,
including every "the cache really holds an entry" control. Pin the
setting, like the other tests in this family do.

The file-backed key producers, which take the time zone from
FormatFilterInfo, had no test that varies session_timezone: reverting
this fix left 04498 green. Append one section to it. It has its own file
and table so the existing arms are untouched, warms the cache in
Asia/Tokyo where toHour of the epoch is 9 and no row group holds a
matching row, then repeats the query in UTC where every row matches. Two
controls come with it, and without them the section would pass on a
build that cached nothing or filtered wrongly: the entry count after the
warm-up, and the same UTC query with the cache emptied first.

That section uses toHour rather than the fromUnixTimestamp shape the
MergeTree test uses, because a Parquet row group is excluded through
KeyCondition over the column statistics rather than by evaluating rows.
A two-argument formatting function is not a monotonic function chain, so
it excludes nothing, writes no cache entry, and the section would have
been vacuous.

Co-Authored-By: Claude Opus 5 <[email protected]>
The change to docs/reference/system-tables/query_condition_cache.mdx edited a
line between the AUTOGENERATED_START and AUTOGENERATED_END markers. Both
docs/AGENTS.md and docs/reference/AGENTS.md forbid that and name the system
table registration as the source of truth to update instead, and
ci/jobs/docs_job_mintlify.py enforces it via
ci/jobs/scripts/docs/check_autogenerated_regions.py, which fails unless the pull
request carries the pr-autogenerated-docs label. Both policy files resolve at
this branch's base, so they applied from the start. The edit was cleared earlier
on the incorrect ground that no such policy exists, citing a precedent commit
that predates both files; that was a miss, not a judgement call, so I am
recording it rather than fixing it silently. The file is reverted to base.
src/Storages/System/StorageSystemQueryConditionCache.cpp already carries the new
key composition and the nightly docs autogeneration workflow regenerates the
region from it, so nothing is left stale.

Four comments enumerating the cache key still listed three components after this
branch added the time zone to the key. Two of them are load-bearing: they
explain why non-deterministic virtual columns must be kept out of the filter,
and why the TopK salt folds in the whole part-set snapshot. An incomplete
enumeration misleads a reader reasoning about when a key goes stale.

Also removed a comment in 05054 claiming the cache stores nothing for much less
data than the test inserts. QueryConditionCache::write has no size or
marks-count threshold: after the table_id == UUIDHelpers::Nil guard the getOrSet
is unconditional, so a one-mark part is cached too.

The src changes are comment-only. Verified two independent ways: stripping
comments from both revisions leaves a token-identical stream, and building with
and without them produces byte-identical binaries.
…tradict

Adding the time zone to the query condition cache key on this branch turned four
comments false. Three still enumerated a three-component tuple: the doc comment
of `QueryConditionCache::read`, in the same header as three siblings that were
updated, and the rationale comments of `04338` and `02346`. The fourth is
`04498`'s header, which still claimed the test needs no global cache reset after
this branch's own time-zone section introduced two `SYSTEM CLEAR QUERY CONDITION
CACHE` statements. That reset is what makes the section's entry-count control
meaningful, so acting on the header would have silenced the control without any
test failing.

The earlier sweep for these sites was incomplete because its acceptance check was
a grep exit code. A non-zero status from a pattern matching
`(table_uuid, part_name, condition_hash)` says only that this pattern found
nothing; it cannot see `table + part id and predicate hash` or
`(table uuid, part, condition hash)`. The sweep now runs against the pre-fix tree
first, so a pattern that cannot find a known-stale site is rejected before its
silence is trusted.

Comment text only; no executable line changes.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Four review rounds before publication: my own cold review of the resulting tree each round plus an
independent second model (engine: codex), 27 findings adjudicated. Blockers and majors below; nits
and residuals summarised after.

Sev Finding Verdict Evidence / action
❌ The diff edited a generated documentation region AGREE, fixed docs/AGENTS.md:1 and docs/reference/AGENTS.md:1-3 both forbid editing between AUTOGENERATED_START/_END and name the system-table registration as the source of truth. The .mdx hunk is reverted; the C++ column description still changes, so the page picks it up on the next generation. My round-1 verdict on this was wrong and public in draft: it said no such policy exists. Both policy files resolve at this branch's base and postdate the 2026-07-30 precedent that verdict cited, so the precedent was superseded, not authorising
❌ The new test did not pin the analyzer, so old-analyzer lanes write no cache entry and eight reference lines invert AGREE, fixed The cache is analyzer-only at all three gates (MergeTreeIOSettings.cpp:136, MergeTreeDataSelectExecutor.cpp:1566, QueryPlanOptimizationSettings.cpp:242) and tests/config/users.d/analyzer.xml disables it in those lanes
⚠️ The file-backed key sites changed with no cross-time-zone coverage AGREE, fixed Append-only section on 04498_query_condition_cache_local_files.sh: own file and table, no existing statement, tag or reference line touched. Verified against an unmodified control on the same server: 0 result differences in 50 randomized runs on both
⚠️ Three object-storage key sites are covered by reading, not by a test, and the body implied otherwise AGREE, fixed They read the zone from the same per-query FormatFilterInfo as the File sites; the description now says so
⚠️ Seven comments still described the former three-component key AGREE, fixed Fixed across two rounds. The last three mattered because they self-contradicted: QueryConditionCache::read's doc sat 25 lines below three corrected siblings, 04338's rationale is the verbatim twin of a ReadFromMergeTree.cpp comment this branch did correct, and 04498's header told a contributor the test needs no cache reset when a live control there depends on one
⚠️ The description asserted an unmeasured mechanism, and omitted other settings read at execution time AGREE, fixed It now states only what was measured, and discloses that formatDateTime captures three formatdatetime_* settings from the session (src/Functions/formatDateTime.cpp:929-931) and sits outside the key the same way. Auditing those is deliberately not in this PR

DISAGREE, terminal, with evidence: the coexistence block's exact entry count stays at 2 (no insert
block setting is randomized and 1000000 rows squash into one part, and that count is what makes the
block fail without the fix); the skip-index-profiled write has no cross-zone arm because the test
pins use_skip_indexes = 0, and it needs none - its zone and the zone of the read that probes both
keys come from the same Settings object, so the pair agrees by construction; the relationship
links are present in both forms by design, since an HTML comment does not render.

Nits fixed: changelog entry moved to the present tense per docs/changelog_entry_guidelines.md;
four description corrections; a test comment claiming a size threshold that write does not have.

Noted, not addressed: FunctionCapture reports a lambda deterministic without walking its body
(isDeterministic is not overridden), which is pre-existing and outside this PR's contract;
tests/performance/query_condition_cache_topk.xml:33 still states the three-component tuple, missed
by three sweeps because the tuple wraps across two lines; the debug Entry and its three LOG_TEST
lines omit the zone, so two entries differing only by zone look identical in a debug build, and
adding a column there would regenerate the protected .mdx region; resolveTimeZone does not
canonicalise zone aliases, so UTC and Etc/UTC hold separate entries, which costs a miss and
never a wrong reuse.

Severity: ❌ blocker / ⚠️ major / 💡 nit. Final fix commit: 9bfd9f83c1eed4a.

Session id: cron:clickhouse-review-self-slot-58:20260831-083900

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6dab374]

Summary: ❌

job_name test_name status info comment
Docs examples FAIL
Documentation examples FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Bugfix validation (functional tests, amd64) ERROR
Bugfix validation (functional tests, aarch64) ERROR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) ERROR
Container memory budget exceeded (/docker) ERROR cidb

AI Review

Summary

This PR fixes a real correctness hole in the QueryConditionCache by partitioning entries on the resolved session_timezone everywhere the key is produced or consulted. The current tree threads that value through the MergeTree row-level path, the skip-index-analysis path, and the file/object-storage paths, and the added tests now cover the previously-missing index-analysis case as well. I did not find a remaining correctness or evidence gap in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 6dab374.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 147/155 (94.84%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on a server: prime SELECT count() FROM tab WHERE fromUnixTimestamp(x, '%H') = '00' SETTINGS session_timezone = 'Asia/Tokyo' (legitimately 0, writes one cache entry), then run the same query under session_timezone = 'UTC' and get 0 instead of 1000000. clickhouse local cannot reproduce it at all: it never populates the query condition cache, so every arm there returns the correct answer.
b Root cause explained? QueryConditionCache::makeKey keyed a per-mark "nothing here matched" verdict on the condition's plan: node kinds, names, type names, function names, constants. session_timezone is an input to evaluating that condition and was not in the key, and it does not have to be visible in the plan, so a verdict computed in one time zone was served to a session in another and the rows it excluded were never read.
c Fix matches root cause? Yes. The defect is a cache key that omits an input to the computation it keys; the change adds that input. No guard, no widened bound, no no-random-* tag, no cache disable.
d Test intent preserved / new tests added? New stateless test 05054_query_condition_cache_session_timezone, which pins allow_experimental_analyzer = 1 because the cache is analyzer-only and the old-analyzer jobs would otherwise write no entry and invert its controls. The file-backed key producers are covered by an append-only section on the existing 04498_query_condition_cache_local_files: own file and table, no existing statement, tag or reference line modified (the appended section removes nothing and the .reference has 0 removed lines; the test's only removed lines are two header-comment lines, updated because the new section does reset the cache), so the existing arms' output is provably unchanged. No test weakened or removed.
e Both directions demonstrated? Yes, three times. On pristine master six 05054 arms return 0 where the reference says 1000000 and the coexistence arm reports 1 cache entry instead of 2; the 04498 cross-zone arm returns 0 instead of 1000000 on pristine master; and replacing only hash.update(time_zone) with (void)time_zone; (every signature and all 13 call sites left in place) reproduces master's failure body byte for byte on both tests, so the one added line carries the fix and not the tests' setup. The fix build passes both, 50/50 with randomization. Each cross-zone arm ships two live controls: the cache-entry count after the warm-up (so a build that cached nothing cannot pass) and the same query with the cache emptied first (so the cache, not the filter, is what produced the wrong answer).
f Fix is general across code paths? All 13 key-producing sites supply the zone and the compiler enforced it: the parameter is required, so arity catches an omission at a call site and -Werror,-Wunused-parameter catches a definition that accepts the zone and ignores it. makeKey has no callers outside write/read. The two MergeTreeReaderSettings factories with no context never write to the cache, so no key can carry an empty zone. FilterStep::serialize/deserialize still omit the condition pair, so nothing new is serialized.
g Fix generalizes across inputs (params/datatypes/wrappers)? By construction: the design inspects no types at all, which is why it holds for carriers nobody has enumerated. Measured carriers, all zone-dependent and all fixed: an omitted zone inside Nullable(DateTime), a lambda body, a Dynamic runtime subtype, and fromUnixTimestamp(x, '%H') over a UInt32 whose condition contains no temporal type at all. Wrappers (Array, Map, LowCardinality) are irrelevant to a design that never reads a type.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry. The cache is memory-only and its key is never serialized. session_timezone is unset by default and resolves to the server time zone, so a deployment that does not vary it hashes one constant and partitions no entry. The system.query_condition_cache.key_hash description was updated to stay truthful.
i Invariants and contracts preserved? The invariant is that two queries which can compute different per-mark verdicts for the same condition must have different keys. Each write/read pair derives its zone from the same query Context, so the two agree by construction, and the same-session hit arm is the test for it: a write/read zone mismatch would show there as a permanent miss. The TopK-reuse probes use the same resolved zone as the plain probes, so a TopK read still reuses entries a plain SELECT ... WHERE wrote. No locking, lifetime or error-path change: the added value is a String passed by const reference and hashed.

Session id: cron:clickhouse-impl-self-slot-57:20260831-041600

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @antaljanosbenjamin, could you review this? The query condition cache keyed a per-mark "no matching rows" verdict on the condition's plan, but session_timezone is an input to evaluating it and need not appear in the plan (a lambda body, a Dynamic subtype, a zone omitted inside Nullable(DateTime)), so a verdict computed in one time zone was served to a session in another and the matching rows were never read. time_zone is now a required parameter of makeKey/write/read, resolved at each of the 13 key-producing sites.

@zlareb1

This comment was marked as low quality.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Separately, in #117308.

I reproduced both of your carriers on this PR's head (9bfd9f83), which is the part your report did not cover: the change here does not fix them.

arm primed flipped read after SYSTEM CLEAR QUERY CONDITION CACHE
formatdatetime_f_prints_single_zero 0 -> 1 0 0, QueryConditionCacheHits = 1, read_rows = 0 1000000
function_locate_has_mysql_compatible_argument_order 1 -> 0 0 0, QueryConditionCacheHits = 1, read_rows = 0 1000000
session_timezone Asia/Tokyo -> UTC (this PR) 0 1000000, cache miss n/a

The last row is the control: on the same binary the time-zone arm returns the right answer and takes a miss, so the first two are not an artifact of a build without the fix. Each priming left exactly one cache entry, and the last column shows the filters themselves are fine.

The reason to keep them apart is the shape of the fix, not scope. This PR keys on one resolved value, passed as a required parameter at the 13 key-producing sites. Your class has no such value: src/Functions/ reads 81 distinct settings through getSettingsRef()[Setting::...], only some of which can change a filter's verdict, so the key has to learn which settings the condition's functions actually consumed. The cheap alternative, mixing in every changed setting, would drop hits between sessions that differ in something unrelated. That choice deserves its own review.

I will take #117308 as its own change and put the key-content question there rather than here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6dab3747e with master 9f35a2b2a (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

433 translation units recompiled, 3987 s compile time in total, 432 of them have a recent master baseline.

Job report

…tests' shutdown gdb attach)

The CI finish ledger for 9bfd9f8 had three failures, all the
job-level row 'Container memory budget exceeded (/docker)' on the old-analyzer integration shards
2/6, 5/6 and 6/6, with no failing test. That row is fixed for shards 2/6 and 5/6 by ClickHouse#117202, merged
2026-08-31T11:05:36Z, which this branch predated. Shard 6/6 is a known residual of the same
signature and is not expected to clear.
groeneai and others added 2 commits September 1, 2026 00:13
05054 pinned use_skip_indexes = 0 and ORDER BY tuple(), so every arm
populated the query condition cache from the row-level filter and probed
only the bare condition hash. The exclusions index analysis records in
ReadFromMergeTree::selectRangesToRead live under a second key, salted with
the running skip-index profile, and nothing reached it: dropping the time
zone from that key pair alone left all seven existing arms byte-identical.

The new arm uses a set index, whose condition is evaluated over the values
the index stored and therefore in the reading session's time zone. With
use_skip_indexes_on_data_read = 0 that evaluation happens during index
analysis, so its exclusions are what gets cached. In Asia/Tokyo the index
drops every granule, so the same query in UTC must still see 3600 rows.

Two assertions keep the arm from degrading into a second row-level arm if
the index stops pruning, and they fail independently. The warm-up reading
zero rows is what pins the entry on index analysis, because the row-level
filter has to read a granule to find nothing in it: with
use_skip_indexes = 0 it reads 3600 instead. The repeat in the same zone
hitting is what proves the entry is reusable at all: with
use_skip_indexes_on_data_read = 1 the hit disappears.

Verified by mutation: passing a constant time zone at the index-analysis
write and at the two profiled-hash probes makes the arm return 0 instead
of 3600 while every pre-existing arm stays unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
The benchmark's rationale still spelled the key as the former
three-component tuple. It was the one description this branch missed when
it corrected the others, because the tuple wraps across two lines.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6dab3747ef4b4951a2bc60cb2ff2b81af6400c9a

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link I
will post here when it opens.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64) job-level abort at ci/jobs/functional_tests.py:734, AssertionError: Could not find master builds in S3, before any server starts, so nothing was validated and no test is attributed. Trunk-wide, byte identical on unrelated PRs #117433 (mine, open)
Bugfix validation (functional tests, aarch64) same Could not find master builds in S3 abort as the row above #117433 (mine, open)
Finish Workflow / Post Hooks (new_tests_check.py) pure cascade of the two rows above: the hook reds when no per-arch bugfix job reports OK or XFAIL, and its own output quotes both aborts #117433 (mine, open)
Docs examples / Documentation examples, Function/toYYYYMM#0 the example in src/Functions/toYYYYMM.cpp documents SELECT toYYYYMM(now(), 'US/Eastern') as 202608, so it began returning 202609 when the month rolled over in US/Eastern at 2026-09-01 04:00 UTC. Time triggered and trunk-wide: 27 unrelated PRs carry this row within three hours of that boundary, against 0 rows in the preceding 10 days #117459 (mine, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) job-level container-memory abort with no failing test assertion: the shard's nested containers breach the /docker cgroup leaf, which ci/jobs/integration_test_job.py then reports. #117202 is already an ancestor of this head (compare returns status=ahead, behind_by=0) and the shard failed anyway, so it is not the owner #117411 / #117412 (both open)

Session id: cron:our-pr-ci-monitor:20260901-070000

@rschu1ze rschu1ze left a comment

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 is all terribly wrong (overengineered).

Instead don't read from / write to the query condition cache if a non-default session_timezone is set.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed, and I will not defend the key threading. Dropping it: no read from and no write to the query
condition cache when a non-default session_timezone is set.

One decision first. Your shape generalized to the wider setting class on #117308 (skip the cache when
the query changes any setting outside a deny-list of ones that cannot change what an expression
returns) already covers session_timezone, so that guard would make this PR redundant. Separately,
@ alexey-milovidov's #117803, opened after your review, folds the formatdatetime_* settings into the
condition hash and its description says the resolved session time zone belongs in the same mechanism,
although it does not touch the time zone today.

So: the narrow guard here now, or close this in favour of one of those? I will push the narrow guard
unless you say otherwise.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

I measured the guard before pushing it, and the result changes the trade, so I am asking instead of pushing.

tests/clickhouse-test:1610 randomizes session_timezone on every functional test run: six choices, all non-empty (including get_localzone()), and a test escapes it only with the no-random-settings tag. So a guard that skips the query condition cache whenever a non-default session_timezone is set switches the cache off for practically every CI run. 16 existing tests assert QueryConditionCacheHits and none of them carries that tag; 03229_query_condition_cache_profile_events expects hits of 1 and would read 0. The per-setting Random settings limits: clamp only compares numeric bounds, so it cannot pin a string setting, which leaves the blanket tag on those 16 files as the only way to make the guard green.

Keying the zone does not have that problem: the randomizer draws one zone per run, so queries inside a run still share an entry.

The cheapest form of that is one more line in @ alexey-milovidov's queryConditionCacheSettingsSalt in #117803, whose description already says the resolved session time zone belongs there. I would then close this PR.

So: that, the guard plus the 16 tag additions, or something else? I will not push until you answer.

@clickhouse-gh clickhouse-gh Bot added the comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. label Sep 4, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Will be fixed by #120690

@rschu1ze rschu1ze closed this Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, thanks. Nothing further from me on this branch.

One measured thing about #120690 before it merges. It replaces the explicit salt list with settingDoesNotAffectQueryCache, which drops every output_format_* setting from the key, and at least one of those settings changes what a deterministic function returns inside a condition:

CREATE TABLE t (s String) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT 'a\'b' FROM numbers(200000);

SELECT hex(toString(tuple(s))) FROM t LIMIT 1;
-- 2827615C27622729, i.e. ('a\'b')
SELECT hex(toString(tuple(s))) FROM t LIMIT 1
SETTINGS output_format_values_escape_quote_with_quote = 1;
-- 2827612727622729, i.e. ('a''b')

so WHERE toString(tuple(s)) = '(''a''''b'')' matches 200000 rows under = 1 and none under = 0.

On master (bdd39260f887) the query condition cache separates the two, because that setting is on #117803's list: warming under = 0 returns 0 and leaves one entry, the same query text under = 1 returns 200000 with QueryConditionCacheMisses = 1, and a repeat under = 0 returns 0 with QueryConditionCacheHits = 1 and read_rows = 0.

The query result cache already uses the predicate #120690 adopts, and it gets the same pair wrong today: identical query text, the setting switched with SET between the two runs so the AST is unchanged, second run returns 0 instead of 200000 with QueryCacheHits = 1 and a single entry in system.query_cache. So the caution in that comment is already violated by the Values escaping in toString of a Tuple, and after #120690 the condition cache would inherit it.

Which side to fix is your call: keep that setting in the key, or stop toString reading a format setting. I have changed nothing.

@groeneai

Copy link
Copy Markdown
Collaborator Author

One correction to my comment above, measured on bdd39260f887: it is not one setting, and that changes which side is cheap to fix.

toString(<scalar>) goes through serializeText and ignores format settings; toString(<container>) serializes its elements through serializeTextQuoted and does not. Sweeping all 115 output_format_* settings over 46 expressions, five change what plain toString / CAST(... AS String) returns, every one of them only in the nested form:

setting example, default -> flipped
output_format_values_escape_quote_with_quote toString(tuple('a\'b')): ('a\'b') -> ('a''b')
output_format_decimal_trailing_zeros toString(tuple(toDecimal32(1, 2))): (1) -> (1.00)
output_format_always_write_decimal_point_in_float_and_decimal toString(tuple(2.0::Float64)): (2) -> (2.)
output_format_trim_fixed_string toString(tuple(toFixedString('ab', 5))): ('ab\0\0\0') -> ('ab')
output_format_json_quote_64bit_integers toString(tuple(CAST('{"a":1}' AS JSON))): ('{"a":1}') -> ('{"a":"1"}')

That also explains a negative result I reported earlier for three of them: I had measured the plain form. The query result cache gets three of these wrong today with the signature from my previous comment, and output_format_float_precision is confirmed not to be a carrier.

The part that bears on #120690 is the other side of the trade. Measured against the same sweep, #117803's list is already both incomplete (it omits output_format_json_quote_64bit_integers, output_format_json_quote_64bit_floats, output_format_json_quote_denormals, output_format_json_array_of_rows, output_format_csv_crlf_end_of_line and output_format_tsv_crlf_end_of_line, the last four reachable through formatRow and toJSONString, which system.functions reports deterministic = 1) and over-inclusive (output_format_float_precision and output_format_pretty_grid_charset change nothing in the battery). So the carrier set is not a property of setting names but of which serialization entry point a type takes, and it moves with no compile-time signal either way.

The single coupling point is getFormatSettings(context), which five function families capture whole: FunctionsConversion.h:153 (toString, CAST), formatRow.cpp:43, toJSONString.cpp:19, FunctionsJSON.cpp:705, ComparisonParams.cpp:19.

Still your call, and I have changed nothing.

@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. labels Nov 22, 2026
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Query condition cache serves another session's verdict when an omitted DateTime timezone hides inside a wrapper type: rows silently vanish

3 participants