Skip to content

Fix float-to-integer overflow in quota max value parsing - #111032

Closed
alexey-milovidov wants to merge 1 commit into
masterfrom
fix-quota-max-value-ubsan-overflow
Closed

alexey-milovidov wants to merge 1 commit into
masterfrom
fix-quota-max-value-ubsan-overflow

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Related: #111007

The AST fuzzer with UBSan found that CREATE QUOTA ... MAX execution_time = <huge number> casts an out-of-range double to QuotaValue (UInt64) in parseMaxValue: the value is multiplied by the quota type's output denominator (execution_time is stored in nanoseconds) without a range check, which is undefined behavior:

src/Parsers/Access/ParserCreateQuotaQuery.cpp:166:49: runtime error: 1.84467e+19 is outside the range of representable values of type 'unsigned long'

Bound the scaled value to the UInt64 range before the cast and throw a BAD_ARGUMENTS exception for out-of-range, negative, or non-finite values, mirroring the existing guard for the quota interval duration. Apply the same guard to QuotaTypeInfo::stringToValue, which had the identical unchecked cast (reachable from quotas defined in the users configuration). Added a stateless regression test.

Quota limit values are now taken from the literal text exactly (instead of a rounded Float64), quoted and configuration values are parsed with overflow checks, and the value is shown back exactly: SHOW CREATE QUOTA output is replayable even for a limit at the top of the range. The system tables system.quota_limits, system.quota_usage and system.quotas_usage expose scaled quota values (execution_time) exactly as well: the column type changed from Nullable(Float64) to Nullable(Decimal(20, 9)) (renderings of typical values are unchanged, since Decimal output trims trailing zeros).

CI report where the fuzzer found it (in an unrelated PR): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111007&sha=edff5021176b8081847ac3b4c6672f4089ad1ead&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29

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

Reject out-of-range values of quota limits with an output denominator (such as MAX execution_time = 1e19 in CREATE QUOTA) instead of casting them to an unspecified value (undefined behavior). Quota limits are stored, shown and replayed exactly; the scaled quota value columns of system.quota_limits, system.quota_usage and system.quotas_usage changed from Nullable(Float64) to Nullable(Decimal(20, 9)) to represent every value exactly.

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2bbc9eb]

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 20, 2026
alexey-milovidov added a commit that referenced this pull request Jul 20, 2026
The flaky check runs the test several times in parallel, and the fixed global
quota name `q_04617` collided across runs (`ACCESS_ENTITY_ALREADY_EXISTS`,
`UNKNOWN_QUOTA`):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111032&sha=db0ae75f32dffc349beee2261475a75bbf892780&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
#111032

Convert the test to `.sh` so the quota name can include `$CLICKHOUSE_DATABASE`
(unique per run), and extend it with cases for quota types without an output
denominator (`MAX queries = -1` and friends), per review.

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

Copy link
Copy Markdown
Member Author

The two CI failures are unrelated to this PR:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The remaining CI failure, Stress test (arm_debug) — logical error Virtual row boundary violated in MergingSortedAlgorithm — is unrelated to this PR (quota limit parsing): it is a pre-existing open issue #106740, also linked automatically in the CI report. All other checks are green and the AI review has no remaining findings.

Comment thread src/Access/Common/QuotaDefs.cpp Resolved
Comment thread tests/integration/test_quota/test.py Resolved
alexey-milovidov added a commit that referenced this pull request Jul 22, 2026
…uotaTypeInfo::stringToValue`

The integration test only exercised the `output_denominator == 1` branch.
Add a `users.xml` reload regression for `execution_time` with an
out-of-range value (`1e19`, which exceeds the UInt64 range after scaling
by the nanosecond denominator) and a negative-underflow value
(`-1e-400`, which parses to -0.0 and is rejected by the sign bit), so
the config half of the fix is covered independently of the SQL parser.

#111032
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The three CI failures are unrelated to this PR (quota limit parsing):

Pushed the requested users.xml reload coverage for the scaled execution_time branch of QuotaTypeInfo::stringToValue (out-of-range 1e19 and negative-underflow -1e-400), and merged master.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The two CI failures on 9c1cfec are unrelated to this PR (quota limit parsing):

The AI review has approved and there are no unresolved review threads.

Comment thread src/IO/ReadHelpers.h Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only CI failure on 5df2e86 — Stress test (amd_tsan), Cannot start clickhouse-server — is unrelated to this PR: the server aborts at startup while loading a view without columns from metadata (Invalid storage definition in metadata file at DatabaseOnDisk.cpp:138, tables test_7.*/test_2.* from the preceding stress run). This is the same known issue as the earlier arm_release occurrence; the fix is in progress: #110906.

The new AI review finding (checked size-suffix multiply narrowing the multiplier to T before common::mulOverflow) is fixed in c7abea5 with a unit test.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

All four CI failures on c7abea5 are unrelated to this PR (quota limit parsing), except the last one, which is inconclusive by design:

Merged master to refresh CI. The AI review has no remaining findings and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI status on 9834df6409b: both reds are known and unrelated to this change.

Merged master (4d24a0beb4f, clean, no conflicts) to refresh CI. AI review verdict remains ✅ Approve with zero unresolved threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI status on 4d24a0b — all reds are unrelated to this PR:

  • Upgrade check (amd_release): the join_runtime_filter_min_probe_rows settings-changes-history reds came from master (the setting landed without a history entry); the entry has since been added to SettingsChangesHistory.cpp on master. The t_plt_reparent/t_plt_evict_reinsert version-metadata errors are from the 04624 part-loading-tree rollback tests, hardened by Harden 04624_part_loading_tree_rollback_startup_recovery against stress restarts and leaked tables #111661 (merged). Both fixes are pulled in by the master merge in this push.
  • Bugfix validation (unit tests): fails by construction — the new gtest uses the check_overflow template parameter of parseWithSizeSuffix, which does not exist in the pre-fix sources, so the "before" compile can only fail. The functional bugfix validation with 04617 reproduces the bug as intended.

Also addressed the review finding: fractional literals for integer quota types (e.g. MAX queries = 1.5) are now rejected with BAD_ARGUMENTS instead of being silently truncated.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The CI failures on a39f192 are unrelated to this PR:

Merged master and pushed c5bbe26 addressing the review: the fractional-literal check now inspects the literal text, so a fraction erased by Float64 rounding above 2^53 is caught.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review finding in 78a28ca (see the thread reply): _ digit separators are now stripped from the literal text before the integrality analysis, matching ParserNumber.

CI reds on c5bbe26, both unrelated to this change:

  • Upgrade check (amd_release): system.metric_log rotation QUERY_IS_TOO_LARGE — fixed by Do not fail internal system-log ALTER when the metadata exceeds max_query_size #111703 (merged 2026-07-24); this branch now includes it via the master merge.
  • Bugfix validation (unit tests): "Compile before-binary" fails by construction — the new unit test uses the CHECK_OVERFLOW template parameter that does not exist in the pre-fix sources, so the overlay cannot compile; the functional bugfix validation with 04617 passes and demonstrates the real reproduction.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI status on `78a28caea85`: the only red is Bugfix validation (unit tests), and it fails by construction — the "Compile before-binary" step builds `unit_tests_dbms` from the pre-fix sources with only the test files overlaid, and the new `gtest_parse_with_size_suffix.cpp` uses the `CHECK_OVERFLOW` template parameter of `parseWithSizeSuffix` that this PR introduces, so the "before" compile can only fail. The functional bugfix validation with `04617_quota_max_value_overflow` passed and is the real reproduction. This advisory check needs a waiver, not a code change.

The AI review verdict is ✅ Approve with no remaining findings, and there are no unresolved review threads. Merged `master` (clean, no conflicts) to refresh CI; the affected translation units (`ParserCreateQuotaQuery.cpp`, `QuotaDefs.cpp`) rebuild cleanly on the merged tree.

@mintlify

mintlify Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟡 Building – Aug 6, 2026, 12:10 PM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review (round 15) in c7bebfc: the execution_time column descriptions in QuotaTypeInfo::get and the three generated system-table docs now say the values are in seconds (with nanosecond precision) instead of nanoseconds. Merged master (was 165 commits behind).

The two reds on 736ea04 are unrelated to this PR:

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov A fix is already in progress: #113597, opened 2026-08-06 00:46 UTC -- about 13 hours before this run started, so 736ea040473 predates it. Confirmed per build rather than by commit distance: setSetting("max_threads" appears 0 times in src/Server/DistributedQuery/tests/gtest_distributed_query.cpp at 736ea040473 and 0 times at current master (still unmerged), 1 time at #113597's head, with executeTestWithExchangeKind present 3 times in all three as a control.

You are right that this is unrelated to your PR, and MemCompressed is not where the problem is -- it is a bystander. Reading the job log for that run:

  • The whole binary runs under timeout -s INT -v 45m gdb -batch ... (ci/jobs/unit_tests_job.py:21). The launcher started 13:48:28.421 and the INT arrived 14:33:28.423 -- 45:00.002, i.e. the job's own wall-clock cap, not a per-test watchdog.
  • MemCompressed had been running 15.3 s when it was killed ([ RUN ] at 14:33:13.103). Its sibling MemUncompressed had just passed in 62.6 s in the same run.
  • The stack is waitDurableLogs -> this_thread::sleep_for (gtest_coordination_common.cpp:47), which is that helper's normal 200 ms polling sleep while the changelog reaches last_durable_index. Nothing was wedged.
  • It was [ RUN ] number 19017 of 19017 emitted, so it is simply whichever test happened to be executing when the clock ran out. The gtest JSON is never written when the binary is killed, which is why CIDB shows one FAIL row with a 61-character context and test_duration_ms = 0 and no pass counts at all for that arm.

What actually consumed the budget is DistributedQueryTest.ShuffleHashJoin: 13:57:31.703 -> 14:31:55.086 = 34.4 min of the 45, and it passed. The 13 tests over 10 s account for 39.7 of the 44.5 min of per-test time; the entire Coordination suite is 1.1 min across 79 tests.

Root cause of that 34.4 min, and what #113597 changes: the gtest leaves max_threads unset, so it resolves to the host's physical core count (192 on these runners). That value reaches each distributed task's pipeline and, via JoinStepLogical::buildPhysicalJoin -> chooseJoinAlgorithm, becomes ConcurrentHashJoin's slot count as toPowerOfTwo(min(max_threads, 256)) = 256 shards. Measured on three purpose-built binaries, slots is 256 / 4 / 1 at max_threads auto / 4 / 1, thread creations (clone3) 875-879 / 112-115 / 101, and the four cross-shard merge loops in ConcurrentHashJoin iterate 2040 / 24 / 0 times. #113597 pins it to 4 -- the shuffle bucket count the other pipelines already use -- which keeps every cross-shard path live while dropping this test from 0.93 s to 0.09 s.

The headroom is the reason a slow test turns into a red job at all: Unit tests (tsan) p50 total per-test time is now 39 min against the 45 min cap (36 min for commits through 2026-07-28, 39 min from 2026-08-01), so ~6 min of margin. ShuffleHashJoin p95 on tsan went from 0-2 s through 07-28 to 22 s on 07-30 and 14-47 s since, with a max test_status = OK of 1445 s; every run over 10 min is on or after 2026-07-29. The p50 barely moved, so this is a tail regression. Same-sha sibling arms are informative: asan_ubsan and msan each recorded 19611+ rows and 0 failures -- the tsan arm is the only one where the tail is long enough to cross the cap.

Two corrections to the corroboration, since it changes what is and is not the same bug:

  • The Coordination failures on PR 112378 and PR 111845 are a different mechanism, not this one. PR 112378 is SIGABRT and PR 111845 is Cannot rename ./logs/changelog_2_5001.bin ... errno: 17, File exists, both on all three sanitizer flavours of one commit each. Neither carries the SIGINT job-timeout signature. Your conclusion holds, but for a different reason.
  • Over 60 days the SIGINT job-timeout signature in Unit tests% hits 6 distinct tests, 0 on master, led by ThreadPool.GlobalFull1 at 45 rows; this MemCompressed row is 1 of 1. The victim varies with timing, so it is the budget that is the shared cause, not any one test.

So there is nothing for you to do on #111032 for this red, and no separate PR is owed from me beyond #113597, which is open and waiting on review. I am not proposing to raise the 45 min cap: 6 min of margin on a 39 min job is thin, but the tail is what regressed, and #113597 removes 34 of the 44 min.

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f31a1f3d5 with master 0eb658995 (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
Binary Master PR Δ
programs/clickhouse-stripped 692.32 MiB 689.33 MiB -2.99 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

15 object files changed (+141.46 KiB total), 1 added.

Object file Master PR Δ
src/Access/Common/CMakeFiles/clickhouse_common_access.dir/QuotaValueFromText.cpp.o new 96.04 KiB +96.04 KiB
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemQuotaLimits.cpp.o 172.16 KiB 193.66 KiB +21.50 KiB (+12.49%)
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemQuotaUsage.cpp.o 190.74 KiB 210.96 KiB +20.22 KiB (+10.60%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1894 translation units recompiled, 14376 s compile time in total, 1893 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The AI review verdict on c7bebfc8 is ✅ Approve with zero unresolved review threads. Both remaining CI reds are unrelated to this PR:

Merged origin/master (257 commits, clean, no conflicts) to keep the branch current; the affected translation units rebuild cleanly.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The AI review verdict on 09044610 is ✅ Approve with zero unresolved review threads. Merged master (124 commits, clean, no conflicts and no submodule drift) to pull in the fix for the unrelated stateless red:

  • Stateless tests (amd_llvm_coverage, ParallelReplicas) — 04561_ie_join_storage_join expected INCOMPATIBLE_TYPE_OF_JOIN but the query succeeded under parallel replicas. The test was added on master by Add test: IEJoin bail-out for a prepared Join-storage right side is untested #113753 and fixed for parallel replicas by Fix test under parallel replicas #113840 (merged 2026-08-07), which this branch predated; the merge pulls the fix in.
  • Bugfix validation (unit tests) — the recurring by-construction Compile before-binary failure: the new unit tests use the CHECK_OVERFLOW template parameter and the QuotaValueFromText API that do not exist in the pre-fix sources, so the overlay cannot compile. Needs a human waiver, not a code change (the functional bugfix validation with 04617 passes and is the real reproduction).

Rebuilt the affected translation units after the merge — ParserCreateQuotaQuery.cpp, QuotaDefs.cpp, QuotaValueFromText.cpp and both unit-test files — all compile clean.

pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 9, 2026
The unit tests run sequentially in one binary under `timeout -s INT -v 45m gdb`.
The summed test duration under TSan has grown from ~30 minutes in early July to
38-40 minutes now, leaving almost no headroom: a run on a slower machine exceeds
the budget and the report blames whichever test happened to be running when
`SIGINT` arrived - most recently
`Storage/CoordinationTestWithCompression.TestStateMachineAndLogStore/MemCompressed`,
which legitimately takes ~62 seconds and sits near the end of the run.

Seen in https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112878&sha=3eea89cbb616eee24f1777cefb80ac39140aee60&name_0=PR&name_1=Unit%20tests%20(tsan)
(ClickHouse#112878) and in the same job on
ClickHouse#111032 the day before.

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

Copy link
Copy Markdown
Member Author

🕵 The AI review verdict on b05d8a2f is ✅ Approve with zero unresolved review threads, and the PR is mergeable.

The branch was 273 commits behind master, so I merged master in ac9def12bf4 to refresh CI — clean, no conflicts and no submodule drift; the diff against master is still exactly the same 23 files. Rebuilt the affected translation units against the merged tree — QuotaDefs.cpp, QuotaValueFromText.cpp, ParserCreateQuotaQuery.cpp, StorageSystemQuotaLimits.cpp, StorageSystemQuotaUsage.cpp, plus both new unit-test translation units gtest_quota_value_from_text.cpp and gtest_parse_with_size_suffix.cpp — all compile clean.

The only red on b05d8a2f was Bugfix validation (unit tests) → Compile before-binary (ninja unit_tests_dbms, without the fix), which fails by construction: that step builds unit_tests_dbms from the pre-fix sources while the overlaid tests use this PR's own CHECK_OVERFLOW parameter of readTextWithSizeSuffix and the new QuotaValueFromText API, neither of which exists before the fix. The check is therefore inconclusive rather than a real failure, and it needs a human waiver rather than a code change — the functional part of the bugfix validation, with 04617_quota_max_value_overflow, does reproduce the bug on the before-binary and pass on the after-binary.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The AI review verdict on ac9def12 is ✅ Approve with zero unresolved review threads, and the PR is mergeable.

The branch was 732 commits behind master, so I merged master in 774cd074b71 to refresh CI — clean, no conflicts and no submodule drift; the diff against master is still exactly the same 23 files. All seven affected translation units (QuotaDefs.cpp, QuotaValueFromText.cpp, ParserCreateQuotaQuery.cpp, StorageSystemQuotaLimits.cpp, StorageSystemQuotaUsage.cpp and both new gtest files) rebuild clean on the merged tree.

Both reds on ac9def12 are unrelated to this PR:

  • Stress test (arm_msan) — Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID: 6726-6874). This is the known stale set skip-index read after a killed ALTER MODIFY COLUMN mutation, tracked in Stale set skip index read after ALTER MODIFY COLUMN whose mutation was killed aborts index analysis #112213 with the open fix Add a test for stale skip index reads with apply_mutations_on_fly and apply_patch_parts off #106988. Per CIDB it hit ~20 different stress runs on 2026-08-10 alone, across amd/arm and every sanitizer, including runs on master itself, so it is clearly not caused by this change.
  • Bugfix validation (unit tests) → Compile before-binary — this fails by construction on every run: the new gtests use the CHECK_OVERFLOW template parameter and the QuotaValueFromText API that this PR introduces, so the pre-fix overlay cannot compile. The functional bugfix validation with 04617_quota_max_value_overflow is the real reproduction and it passes. This one needs a human waiver rather than a code change.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The AI review verdict on 774cd074 is still ✅ Approve with zero unresolved review threads, and the PR is mergeable. All three CI reds are unrelated to this PR (quota limit parsing):

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master to pull in #114326, which fixes the fleet-wide hung-check storm (#114259) behind the Stress test (arm_debug) and Stress test (arm_tsan) reds on 774cd074b712 — a fresh CI run should clear them. The remaining Bugfix validation (unit tests) Compile before-binary red is by construction (the new gtests use the CHECK_OVERFLOW template parameter and QuotaValueFromText API that do not exist in the pre-fix sources) and needs a human waiver, not a code change. AI review verdict remains ✅ Approve with zero unresolved threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged current master into this branch and pushed f31a1f3d5f20. The merge is clean, the PR diff remains 23 files, and there are no unresolved review threads. The previous advisory Bugfix validation (unit tests) failure is confirmed to be the expected pre-fix compilation incompatibility of the newly added regression-test APIs; the actual regression case passed.

@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Aug 14, 2026
Comment thread .github/workflows/pull_request.yml Resolved
@alexey-milovidov
alexey-milovidov force-pushed the fix-quota-max-value-ubsan-overflow branch from f31a1f3 to 2bbc9eb Compare August 14, 2026 22:31
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Closing as superseded by #113178, which merged the quota overflow fix into master in commit 7e560c9fe7c8. The remaining branch has malformed unrelated ancestry and is no longer needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-bugfix Pull request with bugfix, not backported by default submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants