Repository navigation
Fix signed integer overflow in FillingTransform interval-kind WITH FILL STEP - #110158
Conversation
…LL STEP FillingRow::doLongJump binary-searches how far to jump over a WITH FILL gap by doubling an internal jump length up to 2^62 and calling the step function as step * jumps_count. It detects an overflowed jump by observing the wrapped result, so it relies on well-defined wraparound. The interval-kind (Date/DateTime) step lambda in getStepFunction and its Decimal64 (DateTime64) sibling did the multiply as a signed Int64 (step * jumps_count), so a large WITH FILL STEP interval combined with a wide value range produced e.g. 2147483648 * 4294967296 = 2^63, undefined behavior under UBSan (silent wrap in release). This mirrors the earlier fix for the plain-numeric branch (FieldVisitorScale), which the interval-kind path had missed. Multiply through common::mulIgnoreOverflow so the wrap doLongJump depends on is well-defined. Behavior is preserved. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260712-134000 |
|
cc @KochetovNicolai @vdimir — could you review? Small UBSan fix: the interval-kind (and Decimal64) |
|
Workflow [PR], commit [440bbbb] Summary: ✅
AI ReviewSummaryThis PR hardens interval-kind Final VerdictStatus: ✅ Approve |
mulIgnoreOverflow is only a NO_SANITIZE_UNDEFINED wrapper around x * y, so the signed Int64 multiply still has UB semantics that the optimizer may assume never overflows. FillingRow::doLongJump relies on well-defined wraparound to detect the overflowed jump, so multiply through UInt64 and cast back, mirroring the FieldVisitorScale fix. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Good catch, reworked in 33ea71f. Both the interval-kind (Date/DateTime) step lambda and the |
CI finish ledger — 33ea71fFinish Workflow and Mergeable Check complete. This PR is a signed-overflow fix in
Session id: cron:our-pr-ci-monitor:20260712-210000 |
CI finish ledger — 33ea71fFinish Workflow and Mergeable Check complete. This PR is a signed-overflow fix in
(Correction of the prior ledger line for the replicated-alter test: it is owned by fixing PR #110030, not a fix task.) Session id: cron:our-pr-ci-monitor:20260712-210000 |
…ill-interval-step-int64-overflow
The mulStepWrapping helper already covers every interval kind via the FOR_EACH_INTERVAL_KIND macro, but the regression test only exercised SECOND. Add MINUTE, HOUR and WEEK cases whose step * jumps_count exceeds Int64 range inside doLongJump, so the wrap-by-construction multiply is verified for those kinds too. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — fec5566CI is fully finished on this head (Finish Workflow + Mergeable Check green; all Stress tests passed). One flaky failure, owned by a fixing PR. Not PR-caused (a FillingTransform interval-overflow fix cannot affect replicated-DDL alter).
Session id: cron:our-pr-ci-monitor:20260714-110000 |
| /// well-defined wraparound to detect the overflowed jump). A signed Int64 multiply is UB on overflow. | ||
| static Int64 mulStepWrapping(Int64 step, Int64 jumps_count) | ||
| { | ||
| return static_cast<Int64>(static_cast<UInt64>(step) * static_cast<UInt64>(jumps_count)); |
There was a problem hiding this comment.
Can it overflow uint64? Does it properly handle negative singed? Why not to use mul_overflow or saturated multiplication?
There was a problem hiding this comment.
The wraparound is load-bearing here, not a hazard to avoid:
-
Yes, the
UInt64product can wrap, and that is intended.UInt64overflow is well-defined modular arithmetic (wrap mod 2^64), unlike the original signedInt64multiply which is UB.FillingRow::doLongJumpdoublesstep_lenexponentially and detects an overflowed jump by observing thatnext_valuewrapped to a smaller value (less(next_value, shifted_value, direction)setsoverflowed), then halvesstep_len. The wrap is exactly the signal it relies on. -
Negative
stepis handled.static_cast<UInt64>(neg Int64)is well-defined (adds 2^64, i.e. the two's-complement bit pattern); multiplying inUInt64and casting back reproduces the exact two's-complement signed product, negatives included (in C++20 the narrowing conversion back toInt64is well-defined, not just implementation-defined). WITH FILL descending uses negative steps and the direction-awareless()covers both directions. This mirrors the already-accepted sibling on the plain-numeric path,FieldVisitorScale.cpp:14. -
mulOverflow/ saturated would break the detection.mulOverflowreports overflow but does not produce the wrapped value, so we would have to throw (regressing valid queries wheredoLongJumpdeliberately probes past the range then backs off) or reconstruct the wrap anyway. Saturation clamps toINT64_MIN/MAX, which does not wrap backwards, soless(next_value, shifted_value)never flagsoverflowedand the doubling loop misbehaves. Wrap-by-construction is the required semantic.
Happy to rename the helper or expand the comment if you prefer it more explicit, but keeping the wrap (not checked/saturated) is deliberate.
…ill-interval-step-int64-overflow
CH Inc sync red — cause found, fixed by merging master (
|
The added MINUTE/HOUR/WEEK cases did not reach the overflowing step * jumps_count multiply in FillingRow::doLongJump. doLongJump is reached only via the STALENESS shift path; the WEEK case had no STALENESS, and the previous MINUTE/HOUR steps let the UInt32 timestamp wrap long before jumps_count grew large enough to overflow Int64. Pick MINUTE/HOUR steps whose per-jump delta is 2^31 in the DateTime domain so doLongJump doubles step_len up to the Int64 overflow point, and drop the WEEK case (calendar arithmetic converges via DateLUT and cannot reach it). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…iply The MINUTE/HOUR/SECOND DateTime cases genuinely drive doLongJump to the Int64 step*jumps_count overflow (confirmed via a mul_overflow probe). The DateTime64 case cannot: DateTime64 execute() works in the full Int64 tick domain with no small-domain wrap, so a large delta immediately overshoots the target or overflows Int64 and doLongJump stops doubling. Keep it as a correctness smoke test of the same code path (the Decimal64 branch uses the identical mulStepWrapping via the same FOR_EACH_INTERVAL_KIND macro, protected by construction) and document the coverage precisely. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — 9cacf49Every failure below has an owner: a fixing PR, or the private-sync exemption.
Report messages (warnings) and Finish Workflow "Post Hooks" are the non-blocking rollup reflection of the above, not separate failures. Session id: cron:our-pr-ci-monitor:20260715-033000 |
…ill-interval-step-int64-overflow
…nstruction The AI review pointed out that `mulStepWrapping` only fixes the outer `step * jumps_count` multiply: `FillingRow::doLongJump` can still hand `delta == -2^63` to `AddMinutesImpl` / `AddHoursImpl`, whose `UInt32` (`DateTime`) and `DateTime64` overloads multiplied it again as signed `Int64` (`delta * 60`, `delta * 3600`) - undefined behavior that was merely uninstrumented via `NO_SANITIZE_UNDEFINED`, not defined. Compute those overloads (and the `AddSecondsImpl` addition) in the `UInt64` domain instead: bit-identical to the previous two's complement behavior for all inputs, but well-defined. Drop `NO_SANITIZE_UNDEFINED` from the rewritten overloads so UBSan now enforces the property - the existing MINUTE/HOUR cases in `04512_with_fill_interval_step_int64_overflow` drive `delta` to `-2^63` and exercise the helper multiplies under the sanitizer. ClickHouse#110158 Co-Authored-By: Claude Fable 5 <[email protected]>
…oads `WITH FILL STEP INTERVAL 32768 WEEK STALENESS INTERVAL 1 DAY` on a `Date` column stalls `FillingRow::doLongJump` the same way the DateTime MINUTE/HOUR cases do (`32768 * 7 == 2^15 (mod 2^16)`: odd jumps advance, even jumps stall), so `AddWeeksImpl::execute` for `UInt16` received deltas up to the wrapped `-2^63` and multiplied them by 7 as signed `Int64` - verified empirically with a `__builtin_mul_overflow` probe (overflows at delta = 2^61, 2^62, -2^63). Rewrite the `UInt16`/`Int32` overloads of `AddDaysImpl` and `AddWeeksImpl` in the `UInt64` domain as well (bit-identical for all inputs) and add the `WEEK` regression case. ClickHouse#110158 Co-Authored-By: Claude Fable 5 <[email protected]>
Pass ledger — 1dd9526 (2026-07-15)AI review Block verdict addressed (see the thread reply): the CI state before this push, all failures owned:
Both failing sub-checks get a fresh run from this push. |
…ction The wrap-by-construction fix for the WITH FILL interval-step chain covered the Add*Impl execute() overloads, but the DateTime WEEK path routes through DateLUTImpl::addWeeks (delta * 7) and the quarter path through addQuarters (delta * 3), both still signed Int64 multiplies. FillingRow::doLongJump passes deltas from the whole Int64 range and relies on defined wraparound, so a signed multiply is UB on overflow even under NO_SANITIZE_UNDEFINED. Compute these in the UInt64 domain; bit-identical two's complement for all inputs. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ill-interval-step-int64-overflow
…epro Bugfix validation runs the changed tests against the master-HEAD binaries, asan_ubsan first. This PR's regression test reproduces a UBSan signed-overflow on master, and with `-fno-sanitize-recover=all` that kills the server outright: `clickhouse-test` aborts with `StopTesting` (exit code 2), the surviving per-test rows are recorded as `ERROR`, and `invert_bugfix_validation_status` deliberately preserves a runner-level `ERROR` as inconclusive (ClickHouse#105789). Net effect: a bugfix whose reproduction crashes the sanitizer server could never validate, and `new_tests_check.py` blocked the PR: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110158&sha=6fac17e25bee062f2c959964c0a4df8400576de8&name_0=PR&name_1=Bugfix%20validation%20%28functional%20tests%2C%20amd64%29 When `check_fatal_messages_in_logs` finds a sanitizer/fatal failure (a `BLOCKER`-labelled row) in the master-HEAD server logs, attribute the runner abort to that crash: downgrade the runner-level `ERROR` and the per-row `ERROR`s to `FAIL`, which the inverter then flips into a successful reproduction. A run that ends in `ERROR` without a fatal in the server logs (a genuine infra failure) is still preserved as inconclusive. OOM kills are excluded because the dmesg OOM row carries no `BLOCKER` label. Also harden the `FuzzerLogParser` call site: when only one of the server/stderr logs exists, `str(None)` became the literal path "None" and `get_stack_trace` failed with `FileNotFoundError`; fall back to whichever log exists. Co-Authored-By: Claude Fable 5 <[email protected]>
…gregate status A per-test `ERROR` row caused by the master-HEAD server crash should be downgraded to `FAIL` even when `FTResultsProcessor` did not set the aggregate status to `ERROR` - the inverter treats any per-row `ERROR` as inconclusive, not only the aggregate one. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Continued work on this PR (2026-07-19):
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110158&sha=6fac17e25bee062f2c959964c0a4df8400576de8&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 ( |
|
The fix is already in progress and is ours: #109429 "Fix flaky tests 03100_lwu_15_future_reads and 03100_lwu_16_future_reads" (open, not draft). CI-fix only, no engine changes. Two independent races, both reproduced and validated locally in both directions:
CIDB matches your observation: 03100_lwu_15_future_reads failed on master on 2026-07-17 and 2026-07-19, plus 5 unrelated PRs in the last 14 days. |
The master-HEAD crash downgrade (a BLOCKER fatal in the server logs means the changed tests reproduced the bug and crashed the server, so its ERROR rows must become FAIL for the inverter to count a reproduction) only ran for build_types[0]. A crash-only repro on a later build type (amd_tsan / amd_msan / amd_debug) still arrived as a runner-level ERROR plus a BLOCKER fatal, was recomputed to FAIL by extend_sub_results, then unconditionally restored to ERROR, and invert_bugfix_validation_status preserved it as inconclusive (ClickHouse#105789) instead of a valid reproduction. Factor the build_types[0] reconciliation into reconcile_bugfix_crash_repro and reuse it for the build_types[1:] loop so the crash-as-reproduction handling is identical across all bugfix-validation build types. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The later build types (build_types[1:]) reconciliation added in the previous commit had no focused coverage: the WITH FILL overflow this PR fixes reproduces on build_types[0], so a bugfix-validation run short-circuits before the later loop, and the existing inverter suite starts after reconciliation. Add four tests around reconcile_bugfix_crash_repro that start from runner_level_error + per-test ERROR rows + a BLOCKER fatal and assert the later-build-type result becomes FAIL (then OK via the inverter), while a genuine infra ERROR without a BLOCKER fatal is preserved as inconclusive. The tests call the helper directly (not through main's build-type loop, which swaps binaries and reads real server logs), so they guard the reconciliation logic itself rather than the caller wiring. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger —
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
| Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter | flaky (chronic DDL-recovery race: 506 PRs / 1120 hits / 103 master, 30d) | #111029 (external, open) |
Session id: cron:our-pr-ci-monitor:20260720-163000
|
@groeneai, please resolve conflicts. |
…ill-interval-step-int64-overflow # Conflicts: # src/Functions/FunctionDateOrDateTimeAddInterval.h
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 84/93 (90.32%) · Uncovered code |
CI finish ledger —
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter |
flaky (chronic DatabaseReplicated DDL-recovery race) | #111029 (external, open) |
| Performance Comparison (arm_release, master_head, 6/6) | perf-runner shard-level ERROR (no artifacts uploaded; siblings 1/6-5/6 OK) | a fix task is created (investigating at full effort; fixing-PR link to follow here) |
| Mergeable Check / PR | rollup of the above | owned via the two lines above |
| CH Inc sync | private upstream sync | CH Inc sync (private, not actionable by us) |
Session id: cron:our-pr-ci-monitor:20260722-013000
becbbea
…nstruction The AI review pointed out that `mulStepWrapping` only fixes the outer `step * jumps_count` multiply: `FillingRow::doLongJump` can still hand `delta == -2^63` to `AddMinutesImpl` / `AddHoursImpl`, whose `UInt32` (`DateTime`) and `DateTime64` overloads multiplied it again as signed `Int64` (`delta * 60`, `delta * 3600`) - undefined behavior that was merely uninstrumented via `NO_SANITIZE_UNDEFINED`, not defined. Compute those overloads (and the `AddSecondsImpl` addition) in the `UInt64` domain instead: bit-identical to the previous two's complement behavior for all inputs, but well-defined. Drop `NO_SANITIZE_UNDEFINED` from the rewritten overloads so UBSan now enforces the property - the existing MINUTE/HOUR cases in `04512_with_fill_interval_step_int64_overflow` drive `delta` to `-2^63` and exercise the helper multiplies under the sanitizer. ClickHouse#110158 Co-Authored-By: Claude Fable 5 <[email protected]>
…oads `WITH FILL STEP INTERVAL 32768 WEEK STALENESS INTERVAL 1 DAY` on a `Date` column stalls `FillingRow::doLongJump` the same way the DateTime MINUTE/HOUR cases do (`32768 * 7 == 2^15 (mod 2^16)`: odd jumps advance, even jumps stall), so `AddWeeksImpl::execute` for `UInt16` received deltas up to the wrapped `-2^63` and multiplied them by 7 as signed `Int64` - verified empirically with a `__builtin_mul_overflow` probe (overflows at delta = 2^61, 2^62, -2^63). Rewrite the `UInt16`/`Int32` overloads of `AddDaysImpl` and `AddWeeksImpl` in the `UInt64` domain as well (bit-identical for all inputs) and add the `WEEK` regression case. ClickHouse#110158 Co-Authored-By: Claude Fable 5 <[email protected]>
…fill-interval-step-int64-overflow Fix signed integer overflow in FillingTransform interval-kind WITH FILL STEP
No related open issue found.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed undefined signed-overflow paths in interval arithmetic for interval-kind
WITH FILL STEPand foradd*/subtract*date/time interval functions with extreme deltas, making extreme interval values deterministic instead of relying on signed overflow. Also fixed a stall of interval-kindWITH FILLwith a hugeYEARstep, which previously ran the calendar backward.Description
FillingRow::doLongJumpbinary-searches how far to jump over aWITH FILLgap by doubling an internal jump length up to 2^62 and calling the step function asstep * jumps_count. It detects an overflowed jump by observing the wrapped result, so it relies on well-defined wraparound.The interval-kind (Date/DateTime) step lambda in
getStepFunctionand itsDecimal64(DateTime64) sibling did the multiply as a signedInt64, so a largeWITH FILL STEPinterval combined with a wide value range produced e.g.2147483648 * 4294967296 = 2^63->signed integer overflow ... cannot be represented in type 'Int64'atFillingTransform.cpp:72under UBSan (silent wrap in release). The sibling plain-numeric branch was already fixed the same way (viaFieldVisitorScale); the interval-kind path had been missed.Fix: multiply
step * jumps_countin theUInt64domain via themulStepWrappinghelper, then cast back toInt64, so the wrap thatdoLongJumprelies on is produced by construction (mirroringFieldVisitorScale).In addition (per review), the interval helpers that
doLongJumpcan feed with an unbounded wrapped delta now compute their internal unit scaling (delta * 60,delta * 3600,delta * 7,delta * 86400, theDateTime64/Time64tick rescale, and thesubtract*negation ofINT64_MIN) and the final addition in the unsigned domain: theAddSecondsImpl/AddMinutesImpl/AddHoursImpl/AddDaysImpl/AddWeeksImploverloads forDate/Date32/DateTime/DateTime64/Time/Time64, theDateLUTImpladdWeeks/addQuartersunit multiplies, and theSubtractIntervalImpldelta negation. Previously these were signed operations whose overflow was merely uninstrumented viaNO_SANITIZE_UNDEFINED, not defined. The rewritten overloads are bit-identical to the previous two's-complement behavior for all inputs and no longer carryNO_SANITIZE_UNDEFINED, so UBSan now enforces the wrap-by-construction property.One deliberate behavior change on huge non-representable deltas:
addYearsIndexnarrowed its delta toInt16, so a large positiveYEARstep (e.g.WITH FILL STEP INTERVAL 32768 YEAR, oraddYearswith a huge delta as covered by01662_date_ubsan) wrapped to a negative year count and ran the calendar backward, saturating to 1970 and stalling the fill loop. The delta is now clamped to the representable year range before the add (mirroring theaddMonthsIndexclamp), which is result-identical for every representable delta but changes the (previously nonsensical, overflow-dependent) result for huge deltas —tests/queries/0_stateless/01662_date_ubsan.referenceis updated accordingly.Regression test
04512_with_fill_interval_step_int64_overflowdrives the overflowingstep * jumps_countmultiply for the plain-modular kinds that can reach it throughdoLongJump: SECOND/MINUTE/HOUR onDateTimeand WEEK onDate. The MINUTE/HOUR/WEEK cases also drive the wrapped delta past theInt64range inside theAdd*Implhelpers (probe-verified), enforcing the helper fix under UBSan. TheDecimal64/DateTime64sibling uses the identicalmulStepWrappingvia the sameFOR_EACH_INTERVAL_KINDmacro, so it is fixed by construction; theDateTime64case in the test is a correctness smoke test of that branch (its fullInt64tick domain cannot be driven to the overflow in a terminating query). The remaining kinds (DAY/MONTH/QUARTER, and WEEK onDateTime) converge through the saturating DateLUT arithmetic and cannot reach the overflow.The PR also fixes a Bugfix validation harness gap that this PR exposed: the regression test reproduces the UBSan overflow on the master-HEAD
asan_ubsanbinary, and with-fno-sanitize-recover=allthat kills the server, aborting the test runner with a runner-levelERRORthatinvert_bugfix_validation_statuspreserved as "inconclusive" — so a bugfix whose reproduction crashes the sanitizer server could never validate (report). Now, whencheck_fatal_messages_in_logsfinds a sanitizer/fatal failure in the master-HEAD server logs, the runner abort is attributed to that crash and counted as the bug reproducing; a runnerERRORwithout a fatal (a genuine infra failure) is still preserved as inconclusive.