Repository navigation
Conversation
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]>
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
DISAGREE, terminal, with evidence: the coexistence block's exact entry count stays at 2 (no insert Nits fixed: changelog entry moved to the present tense per Noted, not addressed: Severity: ❌ blocker / Session id: cron:clickhouse-review-self-slot-58:20260831-083900 |
|
Workflow [PR], commit [6dab374] Summary: ❌
AI ReviewSummaryThis PR fixes a real correctness hole in the Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 6dab374.
Changed lines: Changed C/C++ lines covered: 147/155 (94.84%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260831-041600 |
|
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 |
This comment was marked as low quality.
This comment was marked as low quality.
|
Separately, in #117308. I reproduced both of your carriers on this PR's head (
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: I will take #117308 as its own change and put the key-content question there rather than here. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units433 translation units recompiled, 3987 s compile time in total, 432 of them have a recent master baseline. |
…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.
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]>
CI finish ledger -
|
| 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
left a comment
There was a problem hiding this comment.
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.
|
Agreed, and I will not defend the key threading. Dropping it: no read from and no write to the query One decision first. Your shape generalized to the wider setting class on #117308 (skip the cache when So: the narrow guard here now, or close this in favour of one of those? I will push the narrow guard |
|
I measured the guard before pushing it, and the result changes the trade, so I am asking instead of pushing.
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 So: that, the guard plus the 16 tag additions, or something else? I will not push until you answer. |
|
Will be fixed by #120690 |
|
Understood, thanks. Nothing further from me on this branch. One measured thing about #120690 before it merges. It replaces the explicit salt list with 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 On master ( 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 Which side to fix is your call: keep that setting in the key, or stop |
|
One correction to my comment above, measured on
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 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 The single coupling point is Still your call, and I have changed nothing. |
Changelog category (leave one):
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_timezonevalues. 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 resolvedsession_timezoneis now part of the cache key.Description
Closes: #117186
On master, a condition primed under
Asia/Tokyoand read underUTCshares one entry: the second query returns 0 of 1000000 rows,read_rows = 0.makeKeykeyed the verdict on the condition's plan.session_timezoneis an input to evaluating it and need not appear in the plan, so no inspection can find it. Measured carriers: an omitted zone insideNullable(DateTime)(#117186), a lambda body, aDynamicsubtype, andfromUnixTimestamp(x, '%H')over aUInt32, whose condition holds no temporal type.So the change stops looking for it:
time_zonebecomes a required parameter ofmakeKey/write/read, resolved at each of the 13 key-producing sites from its ownSettings. Required rather than defaulted, so an omission is a compile error, not a silent write/read key divergence.ActionsDAG::Node::updateHashis untouched, so the hash-table-size keys that also read the DAG hash never see a session setting.session_timezoneis 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-
Filetest; deleting only the addedhash.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-queryFormatFilterInfoas theFileones, 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
DateTimeunder aDynamicorJSONpath rendering in a zone that is neither the reading session's nor stable across processes.Workflow [PR]
Sync PR [sync-upstream/pr/117302]