Skip to content

Fix server crash on quota with zero-length interval - #110346

Closed
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-quota-zero-interval-ubsan
Closed

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-quota-zero-interval-ubsan

Conversation

@groeneai

@groeneai groeneai commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fix a server crash (integer division by zero) when a quota with a zero-length interval (for example CREATE QUOTA q FOR INTERVAL 0 SECOND MAX queries = 1000) was consumed. A non-positive quota interval duration is now rejected at quota creation.

Description

Found by the fuzzer (STID 4141-5b13, Stress test (arm_asan_ubsan, s3), PR #110228, sha d463af4): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110228&sha=d463af42c39ba64e89709493b3e9aa2f0393e22f&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

Root cause: EnabledQuota::Interval::getEndOfInterval computes (current_time - end + duration) / duration. With a zero-length interval duration == 0, so consuming the quota divides by zero. In debug/UBSan builds this is reported as UB at libcxx/include/__chrono/duration.h; in release builds it is a real SIGFPE (signal 8, integer divide by zero) that terminates the server.

Repro:

CREATE QUOTA IF NOT EXISTS q_zero FOR INTERVAL 0 SECOND MAX queries = 1000 TO default;
SELECT 1; -- server crashes with SIGFPE

Fix: reject a non-positive interval duration at quota creation in updateQuotaFromQueryImpl, which is the single validation point used by both the SQL DDL path and the on-disk reload path (AccessEntityIO). The XML users-config path already skips non-positive durations. A fractional interval that rounds down to zero seconds (e.g. INTERVAL 0.4 SECOND) is rejected too, since it hits the same code path.

Closes #110343

A quota with a zero-length interval (CREATE QUOTA ... FOR INTERVAL 0 SECOND)
made the server divide by the interval duration when the quota was consumed,
crashing with SIGFPE (integer divide by zero) in
EnabledQuota::Interval::getEndOfInterval. Reject a non-positive interval
duration at quota creation instead. Both the SQL DDL path and the on-disk
reload path go through updateQuotaFromQueryImpl; the XML config path already
skips non-positive durations.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE QUOTA q FOR INTERVAL 0 SECOND MAX queries = 1000 TO default then any query as default crashes the server every time (SIGFPE, exit 136).
b Root cause explained? EnabledQuota::Interval::getEndOfInterval computes (current_time - end + duration) / duration. A zero-length interval has duration == 0, so consuming the quota divides by zero (UB in debug/UBSan at __chrono/duration.h, SIGFPE in release).
c Fix matches root cause? Yes. The bad state is a Quota entity with a zero-length interval. The fix rejects a non-positive interval duration at the source (quota creation), so EnabledQuota is never built with duration == 0.
d Test intent preserved / new tests added? New test 04000_quota_zero_interval.sh: zero and fractional-rounds-to-zero intervals are rejected with BAD_ARGUMENTS; a positive interval still works and the server stays up.
e Both directions demonstrated? Yes. Pristine master binary: server crashes with signal 8 (integer divide by zero) at EnabledQuota.cpp:237. With fix: CREATE is rejected, server survives, positive quota consumed fine.
f Fix is general across code paths? Yes. updateQuotaFromQueryImpl is the single point used by both the SQL DDL path and the on-disk reload path (AccessEntityIO). The XML users-config path already skips non-positive durations (UsersConfigParser.cpp).
g Fix generalizes across inputs? Covered: integer 0, and fractional values that round down to 0 seconds (e.g. 0.4 SECOND) both rejected. Any interval_kind maps to seconds via toAvgSeconds, so the single duration.count() <= 0 check covers all interval units.
h Backward compatible? Yes. Rejecting a zero-length quota (which was always a crash, never a working feature) does not change any valid existing behavior. No setting/format change.
i Invariants and contracts preserved? Yes. Downstream EnabledQuota::Interval assumes duration > 0 (it divides by it); the fix enforces that invariant at construction of the Quota entity. drop limits are exempt from the check (they carry no duration to validate).

Session id: cron:clickhouse-worker-slot-5:20260714-075100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @vitlibar for review: rejects a non-positive quota interval duration at CREATE QUOTA, fixing a SIGFPE (divide by zero) in EnabledQuota::getEndOfInterval when a zero-length quota is consumed.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 14, 2026
@PedroTadim PedroTadim self-assigned this Jul 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c94bb7a]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
03742_nested_loop_join_long FAIL cidb
00107_totals_after_having FAIL cidb
03927_autopr_input_bytes_estimation_prewhere_filter FAIL cidb
00065_loyalty_with_storage_join FAIL cidb
03996_map_subcolumns_large_wide FAIL cidb
01277_random_fixed_string FAIL cidb
03255_parallel_replicas_join_algo_and_analyzer_4 FAIL cidb
00078_group_by_arrays FAIL cidb
03100_lwu_19_nullable FAIL cidb
00541_to_start_of_fifteen_minutes FAIL cidb
147 more test cases not shown
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

This PR fixes the main crash path and closes most of the follow-up regressions around loading legacy invalid quotas, but one user-facing ALTER path still strips the inert sentinel from a legacy quota and recreates the per-hash cache/state growth the patch series is trying to eliminate.

Findings

⚠️ Majors

  • [src/Interpreters/Access/InterpreterCreateQuotaQuery.cpp:83] Non-positive intervals are only rejected when !query_limits.drop, so ALTER QUOTA q FOR INTERVAL 0 SECOND NO LIMITS is still accepted on a legacy inert quota loaded from disk. That erase leaves all_limits.empty(), so QuotaCache::setQuota stops marking the quota inert and a KEYED BY normalized_query_hash quota starts allocating empty key_to_intervals / resolved_intervals_cache entries per query hash again, along with stale system.quotas_usage rows. Suggested fix: reject non-positive durations on NO LIMITS clauses too, or preserve the inert 0 sentinel when dropping the last legacy-invalid interval without replacing it with a positive one.
Tests

⚠️ Add an integration case that seeds a persisted legacy KEYED BY normalized_query_hash FOR INTERVAL 0 SECOND quota, runs ALTER ... FOR INTERVAL 0 SECOND NO LIMITS, and proves the quota either stays inert with 0 usage rows after multiple query hashes or the ALTER is rejected with BAD_ARGUMENTS.

Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 14, 2026
@PedroTadim
PedroTadim enabled auto-merge July 14, 2026 08:23
The reject-non-positive-interval validation added in the previous commit runs
through updateQuotaFromQueryImpl, which is shared by the CREATE/ALTER DDL path
and the on-disk deserialization path (AccessEntityIO). After an upgrade a legacy
FOR INTERVAL 0 SECOND quota still lives in the access storage, and
QuotaCache::ensureAllQuotasRead eagerly reads every quota id at startup, so the
parse exception would propagate out of DiskAccessStorage::readImpl and break
access-storage load.

Scope the validation to the user-facing DDL path (validate=true) and skip it on
deserialization (validate=false). To keep a loaded legacy zero-interval quota
from dividing by zero on consumption, guard getEndOfInterval to treat a
non-positive duration as non-expiring, and skip the randomize path for it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
auto-merge was automatically disabled July 14, 2026 09:12

Head branch was pushed to by a user without write access

@groeneai

Copy link
Copy Markdown
Collaborator Author

Good catch. Fixed in e828767.

The reject validation went through updateQuotaFromQueryImpl, which is shared by the CREATE/ALTER DDL path and the on-disk deserialization path (AccessEntityIO). I added a validate flag: true on the user-facing DDL path, false on deserialization, so a legacy FOR INTERVAL 0 SECOND quota still loads on startup after upgrade and DiskAccessStorage::readImpl no longer propagates a parse exception.

To keep a loaded legacy zero-interval quota from dividing by zero on consumption, EnabledQuota::Interval::getEndOfInterval now treats a non-positive duration as non-expiring (returns the loaded end, never resets counters), and the Interval constructor skips the randomize path for it.

Verified on a debug build (build id ba3505c) via a real DiskAccessStorage restart: a quota edited on disk to FOR INTERVAL 0 SECOND now loads on startup, appears in system.quota_usage, and consuming it keeps the server alive (no SIGFPE); CREATE QUOTA FOR INTERVAL 0 SECOND is still rejected with BAD_ARGUMENTS.

Comment thread src/Access/EnabledQuota.cpp Resolved
Making a legacy on-disk zero-interval quota non-expiring kept one per_hash_used
entry forever for every normalized query shape, trading the divide-by-zero for
unbounded memory growth. Instead skip non-positive intervals in
QuotaCache::rebuildIntervals so they are never enforced (no division, no
per-hash bookkeeping), and drop the non-expiring branch in EnabledQuota. The
create-time rejection is unchanged; deserialization still loads the entity so
startup does not fail after upgrade. The regression test now assigns the quota
to a dedicated user instead of default so it is parallel-safe.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Access/QuotaCache.cpp Resolved
groeneai and others added 4 commits July 14, 2026 11:32
A legacy on-disk quota whose every interval has a non-positive duration is
skipped entirely at consumption setup, so it no longer caches an empty
Intervals per quota key nor a per-hash resolver entry, and the skip warning is
emitted once at load time instead of once per key. The regression test now runs
the positive-path query as the dedicated user so it actually consumes the
quota.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The prior rework skipped a quota in chooseQuotaToConsumeFor whenever it had
no enforceable interval, which also skipped a quota that simply has no limits
at all (a normal track-nothing quota). That made system.quota_usage return no
row for it and broke test_quota (test_simpliest_quota, test_add_remove_interval).

Only a quota that had limits but every one is non-positive (a legacy on-disk
zero-interval quota) is inert now; a quota with no limits is still set up and
reports an empty usage row.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
When a legacy FOR INTERVAL 0 SECOND quota becomes inert on a warm/rolling
upgrade path (SYSTEM RELOAD USERS or an older node sending a non-positive
interval), setQuota kept its previously cached per-key Intervals in
key_to_intervals. getAllQuotasUsage still surfaced those as stale NULL rows
in system.quotas_usage. Clear key_to_intervals when the quota flips inert so
no stale usage rows remain; nothing repopulates it while inert because
chooseQuotaToConsumeFor skips the quota before getOrBuildIntervals.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The NORMALIZED_QUERY_HASH interval_resolver lambda did not check is_inert.
A late in-flight query holding an old SingleQuota could miss the resolved
intervals cache and call getOrBuildIntervals for a new hash, which re-inserts
an empty Intervals into key_to_intervals and resurfaces stale NULL rows in
system.quotas_usage after the quota became inert. Return nullptr when the
owning quota is inert so nothing repopulates key_to_intervals while inert.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Access/QuotaCache.h Outdated
QuotaPtr quota;
UUID quota_id;
const RolesOrUsersSet * roles = nullptr;
/// True when the quota had at least one limit but every limit has a non-positive interval

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai trim down comments

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trimmed in 3b6a001 (comment-only, no behavior change).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
An ALTER cloned from a legacy inert quota still carried its non-positive
interval and wrote it back unchanged, so a user-facing ALTER/RENAME could
republish the crash-triggering definition on a mixed-version cluster. Drop
any non-positive interval from the final all_limits when validate is set.

Add an integration test that seeds a persisted FOR INTERVAL 0 SECOND quota,
reloads, and asserts it loads inert (server up, no quotas_usage rows) and
that a later ALTER does not republish the zero interval.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 79.80% 85.90% +6.10%
Functions 91.80% 92.70% +0.90%
Branches 72.10% 78.00% +5.90%

Changed lines: Changed C/C++ lines covered: 64/71 (90.14%) · Uncovered code

Full report · Diff report

groeneai and others added 2 commits July 15, 2026 04:32
A persisted FOR INTERVAL -1 SECOND quota reached the deserialize path as
duration = -1 and then wrapped to 4294967295 when system.quotas and
system.quota_limits cast the duration to UInt32. Keep only the genuine
legacy zero-interval carve-out inert on load; drop negatives.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A persisted FOR INTERVAL -1 SECOND quota was erased to empty all_limits on
the deserialize path, so QuotaCache::setQuota left is_inert=false and the
consumption path published an empty quota key, regrowing stale NULL rows in
system.quotas_usage (per key, including per normalized_query_hash). Normalize
negative durations to 0 on load instead of dropping them so they share the
existing inert zero carve-out; the quota stays inert with no usage rows and
system.quotas / system.quota_limits report 0 rather than the UInt32-wrapped
4294967295.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
auto duration = query_limits.duration;

/// Reject only on CREATE/ALTER; deserialization (validate=false) still loads legacy quotas.
if (validate && !query_limits.drop && duration.count() <= 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because this guard skips query_limits.drop, a legacy inert quota can still lose its sentinel through a user-facing NO LIMITS clause. Repro: load ATTACH QUOTA q KEYED BY normalized_query_hash FOR INTERVAL 0 SECOND MAX queries = 1000 TO ALL, then run ALTER QUOTA q FOR INTERVAL 0 SECOND NO LIMITS.

That hits the erase branch below, leaves all_limits.empty(), and QuotaCache::setQuota no longer marks the quota inert while chooseQuotaToConsumeFor reinstalls the normalized_query_hash resolver. The result is the same empty key_to_intervals / resolved_intervals_cache growth and stale system.quotas_usage rows that the earlier commits were fixing, just via an explicit NO LIMITS ALTER instead of TO / RENAME. We should either reject non-positive durations on NO LIMITS clauses too, or keep the 0 sentinel when dropping the last legacy-invalid interval without replacing it with a positive one.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai check this

@PedroTadim

Copy link
Copy Markdown
Member

@pufit @vitlibar, groeneai ended doing many more changes. Can you help me reviewing this PR?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c94bb7a

CI fully finished on this HEAD (rework commit). Only CH Inc sync still pending (private, exempt). Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) — ~157 unrelated tests, Code 241 host-OOM ((total) memory limit exceeded, OvercommitTracker — fleet-wide event on this lane since ~01:00 UTC 2026-07-15, hit master + 15+ unrelated PRs; our diff is quota-interpreter only, none of our tests are among the failures) #110503 (ours, open)
CH Inc sync private ClickHouse Inc sync CH Inc sync (private, not actionable by us)

Note: the earlier test_quota/test.py Bugfix-validation failures were on the pre-rework HEAD a4a2314 and are not present on this HEAD (that check is not re-run here).

Session id: cron:our-pr-ci-monitor:20260715-113000

@PedroTadim

Copy link
Copy Markdown
Member

I am going to ease this in another PR

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

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

UndefinedBehaviorSanitizer: undefined behavior (STID: 4141-5b13)

2 participants