Skip to content

Saturate toLastDayOfMonth and toLastDayOfWeek at the Date maximum - #118642

Merged
alexey-milovidov merged 3 commits into
masterfrom
to-last-day-of-date-maximum-117697
Sep 12, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
to-last-day-of-date-maximum-117697

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Closes: #117697

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

toLastDayOfMonth and toLastDayOfWeek of a Date argument now saturate at the Date maximum (2149-06-06) instead of wrapping around to 1970. The wrapped result also silently dropped matching rows through primary-key pruning.

Description

toLastDayOfMonth(toDate('2149-06-04')) returned 1970-01-24 and toLastDayOfWeek(toDate('2149-06-02')) returned 1970-01-01: the last day of the month or of the week is past the Date maximum and the DayNum result wrapped around 65535. Both functions declare themselves always monotonic, so KeyCondition used them for primary-key range analysis and the wrapped value inverted the mapped range - SELECT count() FROM t WHERE toLastDayOfWeek(d) = toDate('2149-05-31') returned 0 where countIf counts 7, so rows were lost even for a result value that is perfectly in range.

Both functions already clamp for Date32/DateTime64 arguments; the Date overloads did not, because they computed through DayNum, which is 16-bit. They now compute in the extended range and clamp the same way, which is also what the same call on a Date32 argument returns. With saturation the monotonicity claim holds, so the pruning is correct again.


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

Version info

  • Merged into: 26.9.1.1303 (included in 26.9 and later)

`toLastDayOfMonth(toDate('2149-06-04'))` returned `1970-01-24` and
`toLastDayOfWeek(toDate('2149-06-02'))` returned `1970-01-01`: the last day of
the month or of the week is past the `Date` maximum (2149-06-06) and the
`DayNum` result wrapped around 65535.

Both functions declare themselves always monotonic, so `KeyCondition` uses them
for primary-key range analysis, and the wrapped value inverted the mapped range:
`SELECT count() FROM t WHERE toLastDayOfWeek(d) = toDate('2149-05-31')` returned
`0` where `countIf` counts 7, so rows were lost even for a result that is in
range.

The `Date32` and `DateTime64` overloads of both functions already clamp; the
`Date` ones did not, because they compute through the 16-bit `DayNum`. They now
compute in the extended range and clamp the same way, which is also what the
same call on a `Date32` argument returns. Saturation keeps the functions
monotonic, so the pruning is correct again.

Closes: #117697

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

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [11d272d]

Summary: ✅


AI Review

Summary

This PR fixes the Date overloads of toLastDayOfMonth and toLastDayOfWeek by computing in ExtendedDayNum and clamping at the Date maximum (2149-06-06) instead of wrapping through UInt16. That matches the existing wider-type behavior and restores the monotonicity contract those functions advertise for primary-key analysis. The added stateless test covers both the direct boundary results and the wrong-answer pruning repro near the upper Date limit. I did not find any remaining correctness, safety, or coverage issues in the current diff.

Final Verdict

✅ Approve. No inline review comments posted.

LLVM Coverage Report

Measured on commit 11d272d.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. labels Sep 7, 2026
@yariks5s yariks5s self-assigned this Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 11d272dbb with master 817a2afd1 (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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118642&sha=d05289ca7ceccc88e1e83da605fd187fba311356&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The failing test is test_storage_kafka/test_multi_consumer_quota.py::test_multi_consumer_with_partition_affinity (kafka_aff_s1_r2 never acquired any partition within 240s). It is unrelated to this pull request, which only changes the Date overloads of toLastDayOfMonth and toLastDayOfWeek in src/Functions/DateTimeTransforms.h. The test also fails on master and on other unrelated pull requests:

2026-09-12 03:10:26  PR 118642
2026-09-11 20:23:32  PR 119474
2026-09-10 19:44:52  master
2026-09-09 13:28:05  PR 118994
2026-09-09 02:15:29  PR 118928
2026-09-07 13:04:50  PR 118532
2026-09-03 18:08:16  PR 116843

I could not find an open issue tracking this flakiness (the related feature issue #116844 is about the quota accounting, not the flaky wait).

@groeneai

Copy link
Copy Markdown
Collaborator

Not open as a PR yet, and the reason is on the record. I root-caused this on 2026-09-09 and posted the write-up as a comment on #116844 rather than as a new issue, which is why the search did not turn it up:

#116844 (comment)

Short version: this is a server-side bug in the temporary-lock path, not a test bug and not #116843's quota formula. KeeperHandlingConsumer::lockTemporaryLocksLocked gates the anti-starvation rule on the consumer's own previous-round quota:

if (tmp_locks_quota > 0 && has_replica_without_locks)
{
    tmp_locks_quota = 0;
    return;
}

A consumer that arrives with tmp_locks_quota == 0 skips the rule, falls through to tmp_locks_quota = min(available, quota + 1) = 1, and takes a temporary lock while a same-shard replica holds nothing. prepareToPoll clears tmp_locks at the top of a refresh and re-locks in the same call, so a partition a sibling releases is gone again within one Keeper round trip. In the #118928 run the starved replica logged Consumer N has no partitions 2344 times and created zero locks over 5.5 minutes, while every one of the 5000+ node_quota trace lines in that run was correct.

Five narrow fixes do not hold (all refuted in that comment): is_active as a demand signal, dropping the tmp_locks_quota > 0 conjunct, a refresh-counted budget, a wall-clock deadline armed on the condition, and excluding consumers entitled to nothing. The last one is refuted by the log directly: the consumers that re-take a released partition are the entitled ones, already holding their permanent share. So per-consumer state cannot express the yield, because the decision is per consumer and the contest is per node.

What survives is yield state scoped to the storage and shared by every KeeperHandlingConsumer created in StorageKafka2::startup, with the existing alternating probe moved to that scope. That is new cross-consumer coordination state, so I asked the rule's author (@ antaljanosbenjamin) on #116844 whether it is the direction he wants; that question is still open.

I will take your instruction as the go-ahead for that shape, implement it, and link the PR here. If you want the flaky wait tracked apart from #116844, I can open a dedicated issue for it.

@groeneai

Copy link
Copy Markdown
Collaborator

No fix PR yet, and I want to say why rather than leave the request open.

I designed the fix I committed to above (yield state shared by all KeeperHandlingConsumers of one
storage) and then found two defects in it that I do not think are repairable at that layer:

  1. the abstention has to be bounded, or a replica that is registered but never consumes suppresses its
    peers forever, and the only bound available locally is the incumbent's kafka_consumer_reschedule_ms.
    Each replica table has its own KafkaSettings and nothing relates them, so an incumbent with that
    setting at 0 stops abstaining long before a peer configured to retry hundreds of seconds later polls;
  2. temporary locks contend over one Keeper-wide lock set, so with three or more replicas each storage's
    state is independent and a partition one releases can be taken by another.

Both come from the same gap: nothing tells an incumbent that the lockless replica actually wants a
partition. has_replica_without_locks reports registration and is_active reports liveness, so a sound
fix needs an explicit demand signal in Keeper, which is a protocol addition with several defensible
shapes.

I have written the analysis, the options and a recommendation up on the tracking issue:
#116844 (comment)

Happy to implement whichever shape the Kafka owners prefer. Two narrowings worth having here: the test
failure is an unreleased regression (not reachable on 26.6, 26.7 or 26.8), and it needs
kafka_num_consumers > 1, so it does not affect single-consumer setups.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you for the thorough write-up on both counts — the root cause in KeeperHandlingConsumer::lockTemporaryLocksLocked and the follow-up explaining why the storage-scoped yield state does not hold either. The two defects you found (an unbounded abstention whose only local bound is the incumbent's kafka_consumer_reschedule_ms, and three-or-more replicas contending over one Keeper-wide lock set) look right to me, and I agree with your conclusion that a sound fix needs an explicit demand signal in Keeper rather than more per-consumer or per-storage state. That is a protocol addition and the Kafka owners' call, so please do not force it from this side — waiting on @antaljanosbenjamin on #116844 is the correct thing to do.

Yes, please do open a dedicated issue for the flaky wait itself. #116844 is about the quota accounting, so the flakiness of test_multi_consumer_quota.py::test_multi_consumer_with_partition_affinity should be tracked separately and linked to your analysis — otherwise the next person hitting this red repeats the search I did and finds nothing. Please record in it the two narrowings you noted: it is an unreleased regression (not reachable on 26.6, 26.7 or 26.8) and it requires kafka_num_consumers > 1, so single-consumer setups are unaffected.

Nothing here blocks this pull request — the failure is unrelated to it, and the integration test passed on the current commit after the latest merge from master, so all checks are green.

@groeneai

Copy link
Copy Markdown
Collaborator

Filed: #119632, tracking the flaky wait itself rather than the quota accounting. It leads with the test
name so the search you ran will land on it, and it records both narrowings you asked for: an unreleased
regression, not reachable on 26.6, 26.7 or 26.8 (the zero-entitlement consumer class needs
computeConsumerQuota, which reached master only in #116843), and it requires kafka_num_consumers > 1,
so single-consumer setups are unaffected. It also carries the failure signature, the root cause in
lockTemporaryLocksLocked, the current CI breadth, and links to both analysis comments on #116844.

Understood on the rest: I am not forcing the protocol change from this side, and the design question stays
with the Kafka owners on #116844. I am happy to implement whichever shape they choose once there is a
direction.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into master with commit 1f1cadc Sep 12, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the to-last-day-of-date-maximum-117697 branch September 12, 2026 19:13
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. 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.

toLastDayOfWeek / toLastDayOfMonth wrap past the Date maximum but claim monotonicity, silently dropping rows via primary-key pruning

4 participants