Skip to content

Do not claim toDayOfWeek monotonicity for the Sunday-first modes - #117683

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-to-day-of-week-mode-monotonicity-117264
Sep 20, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-to-day-of-week-mode-monotonicity-117264

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

ToDayOfWeekImpl declares monotonicity with ToMondayImpl as its factor transform, which means "monotonic inside the enclosing Monday-based week". That is true for the Monday-first modes 0 and 1, but not for the Sunday-first modes 2 and 3: there the value drops back at Sunday, in the middle of the factor's interval.

KeyCondition consults that claim for the two-argument form through FunctionWithOptionalConstArg, so a range predicate on toDayOfWeek(key, 2) over a date key pruned granules that hold matching rows, at default settings:

CREATE TABLE t (d Date) ENGINE = MergeTree ORDER BY d SETTINGS index_granularity = 1;
INSERT INTO t SELECT toDate('2026-08-03') + number FROM numbers(14);

SELECT count() FROM t WHERE toDayOfWeek(d, 2) >= 5;    -- 1, wrong
SELECT countIf(toDayOfWeek(d, 2) >= 5) FROM t;         -- 4, correct

The wrapper knows the constant mode, so it now declines monotonicity for the Sunday-first modes (only the two lowest bits of the mode are significant, as in DateLUTImpl::check_week_day_mode). The Monday-first modes keep pruning as before, which the test asserts.

Closes: #117264

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 to CHANGELOG.md):

Fixed silently missing rows for a range predicate on toDayOfWeek(key, mode) with the Sunday-first modes 2 and 3 over a date primary key: the primary key analysis assumed a monotonicity that does not hold for those modes and pruned granules holding matching rows.


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

Version info

  • Merged into: 26.10.1.277-master (included in 26.10 and later)

`ToDayOfWeekImpl` declares monotonicity with `ToMondayImpl` as its factor transform,
which means "monotonic inside the enclosing Monday-based week". That is true for the
Monday-first modes 0 and 1, but not for the Sunday-first modes 2 and 3: there the
value drops back at Sunday, in the middle of the factor's interval.

`KeyCondition` consults that claim for the two-argument form through
`FunctionWithOptionalConstArg`, so a range predicate on `toDayOfWeek(key, 2)` over a
date key pruned granules that hold matching rows, at default settings:

    SELECT count() FROM t WHERE toDayOfWeek(d, 2) >= 5;    -- 1
    SELECT countIf(toDayOfWeek(d, 2) >= 5) FROM t;         -- 4

The wrapper knows the constant mode, so it now declines monotonicity for the
Sunday-first modes. The Monday-first modes keep pruning as before.

Closes: #117264
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b8626cb]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR teaches KeyCondition to stop trusting toDayOfWeek(key, mode) monotonicity for the Sunday-first modes, which is the condition that caused incorrect granule pruning and silently missing rows. I did not find a remaining correctness issue in the current patch, and the added stateless test covers both the Sunday-first regression and the previously discussed 3-argument overload behavior.

Final Verdict

✅ No new review findings.

LLVM Coverage Report

Measured on commit b8626cb.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.50% 80.50% +0.00%

Changed lines: Changed C/C++ lines covered: 10/13 (76.92%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@zlareb1

zlareb1 commented Sep 2, 2026

Copy link
Copy Markdown
Member

While looking at this fix I found two adjacent monotonicity-liar cases in the same KeyCondition path that this PR does not cover, both silently dropping rows at pure defaults; filed separately as #117696 and #117697.

Flagging in case the maintainers prefer to address the custom-week monotonicity in IFunctionCustomWeek rather than function-by-function in the wrapper — a timezone-aware factor there would also close #117696.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 2 commits September 10, 2026 10:31
…nt form

`arm_tidy` failed with `variable 'mode_value' is not initialized`
(`cppcoreguidelines-init-variables`) - initialize it.

Master meanwhile added `05058_max_joined_block_size_rows_zero_with_bytes`,
so renumber the test to `05175`.

Address the review comment asking about `toDayOfWeek(key, mode, timezone)`:
both monotonic-chain builders in `KeyCondition` reject functions of arity
greater than two (`isKeyPossiblyWrappedByMonotonicFunctionsImpl` bails on
`arguments_size > 2`, and `extractMonotonicFunctionsChainFromKey` requires
`children.size() <= 2`), so the 3-argument overload never enters a chain and
never prunes at all - in either numbering. Add explicit test coverage that
pins this down, checking both the row counts and that the 3-argument form
reads every mark while the 2-argument Monday-first form still prunes.

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

Copy link
Copy Markdown
Member Author

🕵 Thanks — both are real and both are genuinely orthogonal to this PR, so I would rather keep them separate than widen this change.

On the placement question: I agree that a timezone-aware factor in IFunctionCustomWeek::getMonotonicityForRange is the right home for #117696, since that is where the server-timezone DateLUT::instance() comparison actually lives. The mode gate here cannot live there, though — at that level the function does not know its bound mode constant. KeyCondition is where the constant argument gets curried into FunctionWithOptionalConstArg, so it is the first point that can see the mode at all. The two fixes compose rather than compete: this one declines the unsound claim for the Sunday-first modes, and a timezone-aware factor would additionally fix the single-argument form across every mode.

#117697 (toLastDayOfWeek / toLastDayOfMonth wrapping past 2149-06-06 with is_always_monotonic = true) is a separate saturation bug in the functions themselves and does not touch this path.

Left both as filed.

…equests

Several other in-flight pull requests also renumbered their tests to `05175`
against the same master state, so pick a number that is free in all of them.

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

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit b8626cbe163b065a886605e5e1c42a7df4560601 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

alexey-milovidov and others added 2 commits September 15, 2026 19:26
… old analyzer

The old analyzer fails with `Unknown column: _subquery721 (UNKNOWN_IDENTIFIER)` when scalar
subqueries are used inside a `UNION ALL` of constant rows, which made the test fail in the
`old analyzer` stateless configuration. One statement per mode produces the same reference output.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117683&sha=214ad2f8f99323968f5c03640170eafe288a83bf&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F3%29
PR: #117683

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117683&sha=214ad2f8f99323968f5c03640170eafe288a83bf&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The server did not come back after the stress restart, aborting with Logical error: Cannot append mark after final in MergeTreeDataPartCompact::loadIndexGranularityImpl while loading a part. This PR only touches KeyCondition monotonicity, so it cannot affect part loading. It looks like the open issue #115198 (startup rejects a corrupted marks file that ATTACH TABLE tolerates), which has no fix PR yet.

@groeneai

Copy link
Copy Markdown
Collaborator

That failure is already fixed on master, so there is no new PR to send for it; the engine defect underneath it is still open, with a fix in review that is not mine. All of the below is measured from that job's own artifacts.

Producer: 04935_optimize_functions_to_subcolumns_name_collision, not #115198. The test declares ENGINE = Memory on purpose ("the Map cases collide on file names in MergeTree") and the stress lane's --replace-log-memory-with-mergetree substituted MergeTree. The job's server log schedules load table test_2.t_shadowed_map_keys at 16:31:56.961 and aborts at 16:31:57.097, on all 11 start attempts; the same table had already returned Code: 33. Too many marks in file .../all_1_1_0/data.cmrk4, marks expected 2 (bytes size 144) at 16:16:11 in the stress phase, so its part was unreadable before the restart. #115198 is a different signature (Code: 246 CORRUPTED_DATA, Bad size of marks file ... skp_idx_idx.mrk4: 25, must be: 24, one load job failing with the server up), and Bad size of marks file and t_text_idx_empty each appear 0 times in that job's error log.

Mechanism. getNameForSubstreamPath escapes a tuple element name as a whole, so the element a.keys and the chain a then keys both render to c%2Ea%2Ekeys. For such a column the Compact writer emits one mark per substream occurrence for data granules (MergeTreeDataPartWriterCompact.cpp:353-360) but the deduplicated columns_substreams.getTotalSubstreams() for the final mark row (:427), while columns_substreams.txt keeps only the first occurrence of a name and every reader takes its stride from it. The file here is 5 marks at granularity 1 followed by 4 at 0, read with stride 4, so appendMark(0) sets the final mark and the next one throws.

Fix for the CI failure: #119188, merged 2026-09-10 18:12:21Z, tagging 04935 memory-engine so the lane stops substituting the engine. 214ad2f8 was committed 2026-09-10 11:09:44Z, so the run you linked predates it, while your current head b8626cbe already contains merge commit 9b9f4d3. In CIDB the signature was 19 rows over 15 PRs including 5 true master on 2026-09-10, and 0 rows in the five days since.

Open, engine side: #115632, which refuses such a CREATE with BAD_ARGUMENTS; its own test asserts this exact schema. Master still accepts it, because checkColumnFilenamesForCollision builds column_streams per column and the emplace at MergeTreeData.cpp:11836 drops the second colliding path, so only cross column collisions are reported. At default settings:

CREATE TABLE t (c Tuple(`a.keys` Array(String), a Map(String, UInt64)))
ENGINE = MergeTree ORDER BY tuple() SETTINGS min_bytes_for_wide_part = 1073741824;
INSERT INTO t VALUES ((['x', 'y'], {'k': 1}));

Measured on 2026-09-10 at master c445b2ef: after a restart a debug build aborts on 3/3 start attempts in loadIndexGranularityImpl, and a release build starts but logs the part as broken and needing manual correction.

One gap #115632 leaves: it only logs on attach, so an existing table keeps accepting inserts that write an unreadable part. I have a measured write side refusal for that case (one function, 0 false positives across 2342 stateless tests), dropped rather than put a second design against an open PR. If you want it, I will send it as a separate PR.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thank you for the precise attribution. Agreed on all three points: the producer was 04935_optimize_functions_to_subcolumns_name_collision under the stress lane's --replace-log-memory-with-mergetree substitution rather than #115198, the CI-side fix #119188 (the memory-engine tag) is already contained in this branch's head b8626cbe, and the engine-side defect in the Compact writer's per-occurrence marks for colliding tuple-element stream names is tracked by #115632. Nothing further to do here; this PR is in the merge queue.

Merged via the queue into master with commit db3f74f Sep 20, 2026
346 of 349 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-to-day-of-week-mode-monotonicity-117264 branch September 20, 2026 05:23
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
alexey-milovidov added a commit that referenced this pull request Sep 24, 2026
#117683 declined monotonicity for `toDayOfWeek` with a
Sunday-first mode in `FunctionWithOptionalConstArg`, because the factor transform was `ToMondayImpl`.
This branch replaces that factor with `ToDayOfWeekFactorImpl`, which pairs the Monday-week with the
Sunday-week and is sound for every mode, so the carve-out is redundant and only disabled the pruning
that `05230` pins for modes 2 and 3. `05186` keeps checking that no row is lost; its last assertion
now checks that both numberings prune.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

toDayOfWeek with mode 2 or 3 falsely claims monotonicity within a Monday-based week — primary-key pruning silently drops matching rows

5 participants