Skip to content

Support quotas over any profile event - #117004

Merged
alexey-milovidov merged 79 commits into
masterfrom
profile-event-quotas
Nov 5, 2026
Merged

alexey-milovidov merged 79 commits into
masterfrom
profile-event-quotas

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Quotas can now be defined over any profile event by its name, e.g. CREATE QUOTA network_egress FOR INTERVAL 1 day MAX S3GetObject = 100000, NetworkSendBytes = '100G' TO user1, in both the SQL syntax and the users.xml configuration. The current consumption is reported in the new profile_events / max_profile_events Map columns of the system.quota_usage, system.quotas_usage and system.quota_limits tables.


Previously quotas could count only a fixed set of resources (queries, errors, read_rows, execution_time, ...). This PR extends the mechanism to accept any profile event, which makes it possible to put per-user limits on things like S3 API calls, network traffic, failed queries, disk reads, and every other counter in system.events. It is fine that some profile events duplicate the predefined counters (e.g. SelectedRows vs read_rows): the predefined ones keep their existing, more incremental accounting.

Syntax. A limit name in the MAX clause that is not one of the predefined resource types is looked up among the profile events (case-sensitively): CREATE QUOTA q FOR INTERVAL 1 hour MAX queries = 100, S3GetObject = 1000 TO user1. An unknown name is rejected with a helpful error, except in attach mode: a quota written by a version with a different set of profile events still loads, keeps the unknown limit in its definition, so it survives a reload of the metadata and is displayed by SHOW CREATE QUOTA, but the limit is inert and a warning is logged. Replaying such a SHOW CREATE QUOTA output as a plain CREATE QUOTA on a server that does not know the event is still rejected on purpose - that is the same check that catches typos, and there is no ATTACH QUOTA form available to a client to bypass it. In users.xml, any tag inside <interval> that names a profile event works the same way: <S3GetObject>1000</S3GetObject>; an unknown tag logs a warning and is ignored (such tags have always been ignored, so a typo cannot break the server startup).

Semantics. Profile events are accounted once per query, at the moment the query finishes — successfully or with an error — from the query's thread group counters. For a failed query the snapshot is taken after the failure itself has been recorded (FailedQuery, FailedSelectQuery, ... are incremented first), on both the "failed during execution" and the "failed before start" paths, so MAX FailedQuery = 10 works as expected; a query rejected before it was even registered (e.g. a syntax error) is charged its failed-query events directly. A query that crosses the limit is therefore allowed to finish, and the subsequent queries are rejected at the start until the interval ends (the same "soft" style the predefined quotas already have). Queries exempt from quotas (e.g. SELECT reading only system.quota_usage or system.one) stay exempt, so the quota state can be inspected even when the quota is exhausted.

For a distributed query, the ProfileEvents packets the remote servers send back (the initiator forces send_profile_events = 1 in every secondary query, so a user cannot turn them off) are summed into a query-scoped counter in QueryStatus (allocated only when a governing quota has profile-event limits) and charged to the initiating user together with the local counters; SelectedRows/SelectedBytes are skipped there because the initiator already counts them from the remote progress. A remote server that fails a query sends the ProfileEvents accumulated since its last periodic report right before the Exception, so short failing distributed queries are charged too. A synchronous INSERT into a Distributed table or the remote table function is charged the same way: RemoteInserter forces send_profile_events too, and the remote server sends the insert-side report of a secondary query once, after it has received all the data, before EndOfStream or, if the query fails after that point, before the Exception (periodic reports during the upload would risk a deadlock, because the initiator does not read packets while sending data). The background sends of Distributed tables are not part of any user query and are not charged. The deferred flush of asynchronous inserts, an internal query run on behalf of the submitting user, is charged to that user's quota. When the whole flush fails, FailedAsyncInsertQuery of its entries is counted inside the flush before the snapshot, so it is charged too.

Close to zero cost when unused. The per-interval limits are stored sparsely — an interval carries entries only for the events its quota explicitly mentions — and EnabledQuota keeps an atomic has_profile_event_limits flag maintained by QuotaCache. The flag is a conservative hint: it is raised before a quota set with such limits is published and lowered only after a set without them is, so a query racing with an ALTER QUOTA can never skip a freshly installed limit. When no governing quota defines a limit over a profile event, the per-query overhead is a single relaxed atomic load; the snapshot of the counters is not even taken. Nothing at all is added to the per-block/per-chunk hot paths.

Introspection. system.quota_limits gains a max_profile_events Map(String, UInt64) column; system.quota_usage and system.quotas_usage gain profile_events and max_profile_events Map columns. A max of 0 means the event is tracked but not limited, consistent with the predefined counters. (The autogenerated regions of the system table docs will be refreshed by the nightly docs job from the new column descriptions.)

Also fixes the FAILED_SEQUENTIAL_AUtheNTICATIONS casing typo in the raw name of the corresponding quota type.

Example:

CREATE USER analyst;
CREATE QUOTA s3_budget FOR INTERVAL 1 day MAX S3GetObject = 100000, FailedQuery = 50 TO analyst;

-- later:
SELECT profile_events, max_profile_events FROM system.quotas_usage WHERE quota_name = 's3_budget';

When the limit is exceeded:

Code: 201. DB::Exception: Quota for user `analyst` for 86400s has been exceeded: S3GetObject = 100503/100000.
Interval will end at 2026-08-30 00:00:00. Name of quota template: `s3_budget`. (QUOTA_EXCEEDED)

Tested by the new stateless tests 05054_quota_on_profile_events (rejection of unknown names, SHOW CREATE QUOTA round trip, enforcement, keeping the consumption across ALTER QUOTA, the system table columns) and 05218_quota_on_query_error_profile_events (MAX FailedQuery / MAX FailedSelectQuery over a failure during execution, a syntax error and a failure before start), 05257_quota_on_profile_events_remote_and_async_insert (remote-server events of a remote(...) query, and a deferred async insert flush), 05339_quota_async_insert_flush_error (MAX FailedAsyncInsertQuery over a failed flush), 05385_quota_on_profile_events_remote_insert (MAX InsertedRows over INSERT INTO FUNCTION remote(...)), 05442_quota_on_profile_events_remote_insert_exception (FailedInsertQuery of a remote INSERT that fails after receiving all the data), and by test_quota/test.py::test_quota_on_profile_events_from_users_xml for the users.xml path; the attach tolerance for unknown event names was verified manually against a local server.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1471-master (included in 26.11 and later)

alexey-milovidov and others added 2 commits August 29, 2026 02:47
A quota limit can now be defined over any profile event by its name, e.g.
`CREATE QUOTA q FOR INTERVAL 1 day MAX S3GetObject = 100000 TO user`, in both
the SQL syntax and the `users.xml` configuration.

Profile events are tracked sparsely: an `EnabledQuota` interval only carries
entries for the events its quota explicitly mentions, and the consumption is
accounted once per query at its end, guarded by an atomic flag, so the
mechanism costs nothing when no such quota is defined.

The limits are stored by event name, so a quota referencing an event unknown
to the current build still loads (the limit is inert). The current consumption
is reported in the new `profile_events` / `max_profile_events` Map columns of
`system.quota_usage`, `system.quotas_usage` and `system.quota_limits`.

Also fix the `FAILED_SEQUENTIAL_AUtheNTICATIONS` casing typo in the raw name
of the corresponding quota type.

Co-Authored-By: Claude Fable 5 <[email protected]>
…style check

Constant `SELECT`s without `FROM` read only `system.one` and are exempt from
quotas by design, so the test must consume the quota with queries that read a
real table. Also add `ProfileEvents::tryGetByName` and `ProfileEvents::getByName`
to the style check whitelist, and fuzz the new profile-event limits in
`QueryFuzzer`.

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

mintlify Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 4, 2026, 9:47 PM

@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [028fcda]

Summary: ✅


AI Review

Summary

The PR adds quotas over arbitrary profile events, including local, remote, and asynchronous-insert accounting, plus usage maps in the quota system tables. Review of head 028fcda16517731c8b133fd86b1fbcfa3cb113ca and focused reproductions with its Fast test binary confirm three remaining quota-enforcement gaps. The top-level cache and scalar-subquery regressions 05507 and 05508 pass, but do not cover these paths.

Findings

❌ Blockers

  • Non-exempt set-subquery reads remain unmetered. src/Interpreters/executeQuery.cpp:3773 — [dismissed by author -- https://github.com/Support quotas over any profile event #117004#discussion_r4473777731]. The new exception to outer-query exemption covers scalar subqueries only. With a ten-row MergeTree table t(x UInt64) and MAX SelectedRows = 1, SelectedParts = 1, three executions of SELECT 1 IN (SELECT x FROM t) succeed while both quota counters remain zero. The issue remains real because the exempt outer system.one does not make the table reads needed to build the set exempt. Determine exemption/accounting from all resource-consuming subqueries, rather than only the scalar-execution flag, and cover this query in a regression.

  • Rejected schema inference still performs external requests. src/Interpreters/executeQuery.cpp:3581 — [dismissed by author -- https://github.com/Support quotas over any profile event #117004#discussion_r4473777738]. Interpreter construction and planning still infer a url table function's structure before checking the quota. Reproduced with MAX ReadWriteBufferFromHTTPRequestsSent = 1, a CSV endpoint, distinct URLs, and schema_inference_use_cache_for_url = 0: the first query succeeds; two subsequent queries return QUOTA_EXCEEDED but each sends another GET, increasing quota usage from 5 to 6 to 7. The issue remains real because recording the excess does not prevent further requests, so the configured request budget cannot stop this work. Check exhausted quotas before external schema inference for non-exempt sources, preserving quota-inspection queries, and assert that rejection sends no request. The same planning order on master explains the scope but does not enforce the new event limit.

⚠️ Majors

  • Subquery cache probes still consume and bill reads after exhaustion. src/Interpreters/executeQuery.cpp:3581, src/Planner/Planner.cpp:2649 and :2655 — the top-level caller defers cache events, but tryAddReadFromQueryResultCacheStep still records them during planning, before quota admission. Populate a ten-row subquery cache entry with SELECT sum(x) FROM (SELECT x FROM t SETTINGS use_query_cache = 1, query_cache_min_query_duration = 0, query_cache_min_query_runs = 0, query_cache_ttl = 3600) SETTINGS use_query_cache = 0, then create MAX QueryCacheReadRows = 1, QueryCacheHits = 100. The first hit charges 10 rows / 1 hit; two rejected executions raise usage to 20 / 2 and 30 / 3. This is another caller of the same cache-admission mechanism, so handle admission and event recording consistently across both cache paths instead of another top-level-only fix. Reproduction was posted on the existing thread.
Tests
  • ⚠️ Extend 05507 with an explicitly cached subquery and verify rejected hits and misses leave billed cache counters unchanged.
  • ⚠️ Extend exemption coverage beyond scalar subqueries to IN (SELECT ...), and add a URL-inference regression that counts actual requests after exhaustion.
Final Verdict

Status: ❌ Block. Enforce and account profile-event quotas across set subqueries, subquery-cache probes, and external schema inference while preserving inspection-query exemptions; add the focused regressions above. The dismissed findings are retained here for a maintainer decision and were not reposted to their threads.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 29, 2026
Comment thread src/Access/UsersConfigParser.cpp Resolved
Parse the value with the same rules as the DDL path, so size suffixes such
as `1G` work, and always create an entry for an explicitly written tag: a
value of 0 means "track this event but do not limit it", the same as for the
predefined resource types.

Also fix a `cert-oop54-cpp` `clang-tidy` error: `ProfileEventLimit::operator =`
did not handle self-assignment.
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Access/QuotaCache.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 028fcda16 with master ec74a8554 (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.

Object file sizes

235 object files changed (+299.13 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/executeQuery.cpp.o 1.04 MiB 1.07 MiB +33.98 KiB (+3.20%)
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemQuotaUsage.cpp.o 200.33 KiB 233.03 KiB +32.70 KiB (+16.32%)
src/CMakeFiles/dbms.dir/Access/UsersConfigParser.cpp.o 336.48 KiB 367.87 KiB +31.39 KiB (+9.33%)
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemQuotaLimits.cpp.o 181.60 KiB 212.26 KiB +30.66 KiB (+16.88%)
src/CMakeFiles/dbms.dir/Access/EnabledQuota.cpp.o 132.34 KiB 159.80 KiB +27.46 KiB (+20.75%)
src/CMakeFiles/dbms.dir/QueryPipeline/RemoteInserter.cpp.o 102.82 KiB 122.06 KiB +19.24 KiB (+18.71%)
src/Parsers/CMakeFiles/clickhouse_parsers.dir/Access/ParserCreateQuotaQuery.cpp.o 158.18 KiB 176.98 KiB +18.80 KiB (+11.89%)
src/CMakeFiles/dbms.dir/Interpreters/Access/InterpreterCreateQuotaQuery.cpp.o 91.41 KiB 107.50 KiB +16.09 KiB (+17.60%)

719 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

1786 translation units recompiled, 11639 s compile time in total, 1785 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 8.2 s

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 4, 2026
alexey-milovidov and others added 6 commits September 16, 2026 07:30
…ure is recorded

The quota snapshot of a failed query was taken in the exception callback before
`logQueryException` finalized the performance counters and incremented the
`FailedQuery` family of profile events, so quotas such as `MAX FailedQuery = 1`
never saw failures during execution, and failures before the query started
(`logExceptionBeforeStart`) were not accounted at all.

Now the accounting lives in `logQueryException` and `logExceptionBeforeStart`,
right after `incrementFailedQueryProfileEvents`. A query that failed before it was
registered in the process list has no thread group to take its counters from, so
the failed-query events are mirrored into a local `ProfileEvents::Counters` and
the quota is charged with those. On the success path the accounting is the last
step of the finish callback, so a failing finish callback is accounted exactly
once by the exception path; the shared dedup flag is gone.

A query rejected by a quota is charged its own `Query` event, as the predefined
`queries` counter already counts it; the `05054` reference follows.

Adds `05218_quota_on_failed_query_profile_events` covering a failure during
execution, a syntax error (over HTTP, since the native client parses locally),
and a failure after registration but before start.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…lags the quota set

`EnabledQuota::has_profile_event_limits` was stored after `quotas`, so a query
racing with an `ALTER QUOTA` or a config reload that adds the first profile-event
limit could observe the new set with the old `false` flag and skip both the
start-of-query check and the end-of-query accounting.

The flag is now raised before a set with such limits is published and lowered
only after a set without them is, so it is never `false` while the published set
has limits. A reader that sees `true` with the older set iterates over it and
finds nothing to account, which is harmless.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…al `1G` suffix

`SHOW QUOTA` now ends with the `profile_events` and `max_profile_events` maps, so
the anchored regexes in `test_dcl_introspection` / `test_dcl_management` need the
two `{}` columns. `readTextWithSizeSuffix` treats `1G` as 10^9 (`1Gi` is 2^30), so
`test_quota_on_profile_events_from_users_xml` expected the wrong value.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117004&sha=e8f96f66ff0a44f709a89d15c7e6d17c2a30c7fb&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29
PR: #117004

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`ParserCreateQuotaQuery` now looks profile event names up to tell them from
typos, and the table of events lives in `ProfileEvents.cpp`, which the standalone
parser module does not compile, so the link failed with an undefined symbol. The
module accepts any name and leaves the check to the server.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117004&sha=e8f96f66ff0a44f709a89d15c7e6d17c2a30c7fb&name_0=PR&name_1=Build%20%28wasm_parser%29
PR: #117004

Co-Authored-By: Claude Fable 5.1 <[email protected]>
A test whose file name contains `fail` makes every log scanner that greps
for a failure report it, so the style check rejects such a name.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 5 commits November 3, 2026 14:25
…charge thread group counters before registration

A scalar subquery is executed while the query is analyzed, before the quotas of
the query are checked, so an exhausted quota over profile events did not stop
it from reading. Check the quota before executing the scalar subquery, in both
the analyzer (`evaluateScalarSubqueryIfNeeded`) and the legacy
(`ExecuteScalarSubqueriesVisitor`) paths, unless the subquery is exempt.

A query failing before it is registered in the process list may already have a
thread group (`QueryScope` of `HTTPHandler` and `TCPHandler`), which
accumulated e.g. `QueryParseMicroseconds` of a failed parsing. Charge its
counters instead of only the mirrored `FailedQuery` events.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…regression tests

The `FailedQuery` family of events, incremented after the counters of the
thread have been finalized, is not necessarily in the counters of the thread
group, so take each event as the maximum of the group and the mirror.

Add tests: a scalar subquery of a query whose quota over profile events is
exhausted is rejected before it reads (with and without the analyzer), and the
parsing time of malformed HTTP queries is charged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the two remaining review threads:

  • A scalar subquery is now rejected before it executes when the quota over profile events is exhausted, with and without the analyzer (test 05493_quota_on_profile_events_scalar_subquery).
  • A query that fails before it is registered in the process list is now charged with the counters of its own thread group, for example QueryParseMicroseconds of a malformed HTTP query (test 05494_quota_on_profile_events_malformed_http_query).

The thread about the origin fields of queued async inserts already has a reasoned reply above. I left it open for a human decision.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117004&sha=02dc0fb48c07e06df0704f2b2d8d0bee597c370d&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 (05024_local_listener_survives_handler_exception fails with return code 56 in Fast test (arm_darwin). It tests clickhouse-local listeners and does not touch quotas) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

The clickhouse-local under test died, so the next curl got rc 56. This job uploaded 7 macOS crash reports, all EXC_BAD_ACCESS "Thread stack size exceeded" in thread Suggest with the same stack: the suggestion query is planned on Suggest::loading_thread and its regexp JIT codegen (getRegexpJITMatcher -> LLVM AArch64AsmPrinter) overflows that thread's stack. It is a plain std::thread, which macOS gives 512 KiB. The 05024 listener runs with --interactive, so it loads suggestions. Same failure as in #88234, unrelated to quotas.

Fix: #129026 (8 MiB stack for that thread on Darwin, approved, CI running).

Comment thread src/Interpreters/executeQuery.cpp Outdated
if (!quota_ignored)
query_result_cache_hit_quota = context->getQuota();
if (query_result_cache_hit_quota)
query_result_cache_hit_quota->checkExceededProfileEvents(normalized_query_hash);

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.

This checkExceededProfileEvents still runs after get_result_from_query_result_cache() has already probed the cache. That helper records QueryCacheHits / QueryCacheMisses via QueryResultCacheReader::recordProbeResult(...), and an on-disk hit or miss also updates the per-backend QueryCacheOnDisk* events inside hasCacheEntryForKey(), before control reaches this line. So once MAX QueryCacheHits / QueryCacheMisses / QueryCacheOnDiskHits is exhausted, a user can keep issuing cacheable queries and each one will consume another probe (and on a hit, fully read/decompress the cached entry) before QUOTA_EXCEEDED is raised.

Please move the exhausted-profile-event check ahead of the cache probe for non-exempt queries, or split the probe so the ignoreQuota decision is known without incrementing any cache events first. A focused regression here should assert that the first rejected cache hit/miss does not bump the corresponding system.quotas_usage.profile_events counter.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Done in 4055c02. The probes of the in-memory and on-disk caches now run with hasCacheEntryForKey(false), so they record nothing. On a hit, checkExceededProfileEvents runs first (the ignore_quota flag of the entry is known by then), and only after that are QueryCacheHits, QueryCacheOnDiskHits and QueryCacheAgeSeconds recorded and the pipeline built. On a miss, QueryCacheMisses / QueryCacheOnDiskMisses are recorded only after the quota checks of the query that runs instead. Test 05507_quota_on_profile_events_query_result_cache_rejected_probe checks that a rejected hit and a rejected miss leave system.quotas_usage.profile_events unchanged. A rejected hit still reads the entry: the reader builds its source in the constructor. Avoiding that would need a separate lookup API, and the counters, which are what the quota bills, are no longer bumped.

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.

4055c025a2c4 still increments billed cache-read counters on a rejected hit. src/Interpreters/executeQuery.cpp:3432 constructs the reader before the check at line 3459, and QueryResultCacheReader::buildSourceFromChunks unconditionally increments QueryCacheReadRows and QueryCacheReadBytes at src/Interpreters/Cache/QueryResultCache.cpp:1018. The on-disk reader also increments QueryCacheOnDiskReadBytes before returning, at src/Interpreters/Cache/QueryResultCacheOnDisk.cpp:804.

Reproduced on this head: populate a 10-row cache entry before creating MAX QueryCacheReadRows = 1; the first hit succeeds and charges 10 rows. Two further hits each return QUOTA_EXCEEDED, but system.quotas_usage.profile_events['QueryCacheReadRows'] rises to 20 and then 30, while QueryCacheHits stays at 1. This is still billed consumption, beyond the acknowledged physical read. A metadata-only lookup followed by reader construction after the check would cover these counters too; please extend 05507_quota_on_profile_events_query_result_cache_rejected_probe to include a read-row or read-byte limit.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Done in 028fcda. QueryResultCacheReader no longer increments QueryCacheReadRows / QueryCacheReadBytes (in buildSourceFromChunks) or QueryCacheOnDiskReadBytes (in the on-disk reader) when it is constructed. It stores the amounts, and hasCacheEntryForKey(true) records them on a hit. executeQuery calls that only after checkExceededProfileEvents, and the subquery cache in Planner calls it once per probe, as before. 05507 now has a MAX QueryCacheReadRows = 1 case: the first hit charges 10 rows, and two rejected hits leave it at 10. The rejected hit still copies or decompresses the entry in memory, because the reader builds its source in the constructor, but it is no longer billed for that.

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.

The top-level path is fixed, but the same rejected-probe issue remains for the subquery cache. src/Planner/Planner.cpp:2649 and :2655 still call hasCacheEntryForKey with event recording enabled while getQueryPlan runs, before the check at src/Interpreters/executeQuery.cpp:3581.

Reproduced with the Fast test binary for 028fcda1651, using a ten-row MergeTree table t(x UInt64):

SELECT sum(x)
FROM
(
    SELECT x FROM t
    SETTINGS use_query_cache = 1, query_cache_min_query_duration = 0,
             query_cache_min_query_runs = 0, query_cache_ttl = 3600
)
SETTINGS use_query_cache = 0;

Populate that subquery entry before creating MAX QueryCacheReadRows = 1, QueryCacheHits = 100. The first hit succeeds and charges 10 rows / 1 hit. Two further executions return QUOTA_EXCEEDED, but usage rises to 20 / 2 and then 30 / 3. This still consumes and bills protected cache reads after exhaustion.

Please handle quota admission consistently for both cache callers, preserving exemptions, and extend 05507 with an explicitly cached subquery. Deferring counters only in the top-level caller leaves this class of issue open.

wilkermichael pushed a commit to Shopify/ClickHouse that referenced this pull request Nov 3, 2026
For `LocalConnection` (interactive `clickhouse-local`) the whole suggestion
query runs in-process in `Suggest::loading_thread`: analyzer, planner, and the
regexp JIT that `extractAll(word, '[\\w_]{2,}')` triggers during header
evaluation. The thread was a plain `std::thread`, which macOS gives a 512 KiB
stack, and LLVM codegen does not cooperate with `checkStackSize`, so it ran
into the guard page (`EXC_BAD_ACCESS "Thread stack size exceeded"` in thread
`Suggest`). This killed the `clickhouse-local` under test in
`Fast test (arm_darwin)` for `05024_local_listener_survives_handler_exception`
(curl rc 56) and `04892_client_dialect_command` (`spawn id not open`) on
PRs ClickHouse#95355, ClickHouse#88234, ClickHouse#117004 and ClickHouse#117636: 26 of 26 macOS crash reports of those
jobs show this stack.

ClickHouse#107033 gave the global thread pool and the server pools
`DEFAULT_THREAD_STACK_SIZE` via `ThreadWithStackSize`, and 3510173 did
the same for the `clickhouse-local` listener pool; the suggestion loader was
missed. Use `ThreadWithStackSize` for it on Darwin; other platforms keep
`std::thread`, whose default stack follows `RLIMIT_STACK`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 4, 2026 19:58
…ejected by a quota over profile events

The probe of the query result cache incremented `QueryCacheHits` / `QueryCacheMisses` / `QueryCacheOnDisk*`
before `checkExceededProfileEvents` ran, so once a quota over these events was exhausted, each rejected query
still consumed another probe and was charged for it. The probes now run with `hasCacheEntryForKey(false)`;
a hit is recorded after the quota check of the cached result, a miss after the quota check of the query that
is executed instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master, which includes the fix for the 05024_local_listener_survives_handler_exception failure in Fast test (arm_darwin) (#129026). Addressed the review thread about the query result cache probe: a query rejected by an exhausted quota over profile events no longer records QueryCacheHits / QueryCacheMisses / QueryCacheOnDisk* (test 05507_quota_on_profile_events_query_result_cache_rejected_probe). The thread about the origin fields of queued async inserts still has its reasoned reply and stays open for a human decision.

Comment thread src/Interpreters/executeQuery.cpp Resolved
quota->usedForQuery(normalized_query_hash, QuotaType::QUERY_INSERTS, 1);
quota->usedForQuery(normalized_query_hash, QuotaType::QUERIES, 1);
quota->usedForQuery(normalized_query_hash, QuotaType::ERRORS, 0, /* check_exceeded = */ true);
quota->checkExceededProfileEvents(normalized_query_hash);

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.

[P1] Check exhausted quotas before table-function schema inference

This check runs after interpreter construction and getQueryPlan, which can already perform external reads to infer a table function's schema. Reproduced with a local CSV endpoint and MAX ReadWriteBufferFromHTTPRequestsSent = 1: the first SELECT sum(a) FROM url('http://host/file.csv', 'CSVWithNames') records three requests; each subsequent query returns QUOTA_EXCEEDED but still sends another GET, advancing quota usage from 3 to 4, 5, and 6. The reproduction disables schema_inference_use_cache_for_url and uses distinct paths. Supplying the explicit structure 'a UInt64' is rejected without another request. An exhausted user can therefore continue consuming HTTP requests and inference reads indefinitely. Please enforce the quota before resource-consuming table-function analysis, preserving genuinely exempt queries, and add a regression asserting that rejected schema inference performs no request.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Not changing this. Every quota is checked at this point, after the interpreter is constructed and the query plan is built. On master the predefined counters work the same way: with an exhausted MAX queries or MAX errors quota, SELECT ... FROM url(...) without a structure also infers the schema (and sends the request) before it is rejected with QUOTA_EXCEEDED. The plan has to be built first because that is where the query learns whether it is exempt (ignoreQuota, e.g. a SELECT from system.quotas_usage). An earlier check would also reject the queries a user runs to look at an exhausted quota.

The work a rejected query does is not free, either: it is charged to the quota, which is why the usage in your reproduction goes up from 3 to 4, 5, 6. So it shows in system.quotas_usage, and the errors counter of the user grows with every rejected query, which a MAX errors limit can cap. Each rejected query costs one schema inference, and the schema cache removes even that unless it is disabled. Running the check before analysis would need a separate, conservative test for "this query can only be exempt", and table functions would need their own quota checks. That is a change to how all quotas work, not specific to profile events, and it should be done separately if it is needed.

…eries correctly

Two findings of the review of the quotas over profile events:

1. A query rejected by an exhausted quota over profile events after a hit in the
   query result cache was still charged with `QueryCacheReadRows`,
   `QueryCacheReadBytes` and `QueryCacheOnDiskReadBytes`, because
   `QueryResultCacheReader` recorded them when it was constructed, before the
   quota check. They are now recorded by `hasCacheEntryForKey(true)`, which
   `executeQuery` calls only after the check (and the subquery cache in
   `Planner` calls once per probe, as before). Test `05507` covers a
   `MAX QueryCacheReadRows` limit.

2. A query exempt from quotas on its own, e.g. `SELECT (SELECT sum(x) FROM t)`,
   which reads only `system.one`, was not charged with what its scalar subquery
   consumed, so it could scan tables without ever exhausting a quota over
   profile events. A scalar subquery that is not exempt now marks the
   `QueryStatus` of the query, and the query is charged with its profile events
   on success, failure and cancellation. The predefined counters (`queries`,
   ...) still exempt it, and the query result cache does not store it as
   exempt. New test `05508` covers both analyzers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 5, 2026
Merged via the queue into master with commit a71ae7a Nov 5, 2026
186 checks passed
@alexey-milovidov
alexey-milovidov deleted the profile-event-quotas branch November 5, 2026 23:39
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 2026
PedroTadim pushed a commit to ylw510/ClickHouse that referenced this pull request Nov 6, 2026
…parallel replicas

The ParallelReplicas CI job enables parallel replicas in the server `default`
profile, which the test's SQL-created quota user inherits. When the coordinator
hands the table's only mark to a remote replica, that replica's interpreter
reports `SelectQuery = 1` back, and remote `ProfileEvents` are charged to the
initiating user (the designed behaviour of ClickHouse#117004, asserted by the `remote()`
quota tests). The populating query then costs `SelectQuery = 2` against
`MAX SelectQuery = 1`, the next cache hit is rejected, and the reference shifts;
with `optimize_trivial_count_query = 0` the `count()` fans out the same way.

Pin `enable_parallel_replicas = 0` on the two `MergeTree` reads of the quota
user. The `.reference` is unchanged.

Locally, with the job's server config emulated: unchanged test 10/10 red with
`parallel_replicas_local_plan = 0`, 13/50 with `= 1`, 18/20 with
`optimize_trivial_count_query = 0`; fixed test 10/10, 50/50, 20/20 green, plus
50/50 randomized without parallel replicas.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
…rt-quota-keyed-by-address

ClickHouse#117004 (commit e4314b2) landed the same fix in master: the client
address and the last forwarded address are part of the async insert
batching key and are restored on the flush context when a quota is keyed
by an address. All five conflicting files (EnabledQuota.{h,cpp},
QuotaCache.cpp, AsynchronousInsertQueue.{h,cpp}) are resolved to master's
version, and gtest_async_insert_key.cpp is taken from master as well,
since master's InsertQuery constructor has the address arguments at the
end with defaults. The branch now only adds the regression test 05331.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. pr-feature Pull request with new product feature 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.

3 participants