Skip to content

Account initial query contexts in MySQL, PostgreSQL, gRPC and Flight - #123112

Draft
qoega wants to merge 52 commits into
masterfrom
codex/protocol-query-context-accounting
Draft

qoega wants to merge 52 commits into
masterfrom
codex/protocol-query-context-accounting

Conversation

@qoega

@qoega qoega commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Extend initial Context accounting to SQL execution in MySQL, PostgreSQL, gRPC and Arrow Flight, preserving each context's tracker through cleanup. Coverage checks 19 SQL paths, limits, query-log visibility and context release. Flight session-option updates use the existing session directly, retaining credential validation.

Targets master and includes the Native/HTTP prerequisite until it merges.

Related: #120422

Changelog category (leave one):

  • Improvement

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

Include initial query-context allocations in memory usage and limits at query admission for MySQL, PostgreSQL, gRPC and Arrow Flight queries.


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

qoega and others added 30 commits September 16, 2026 17:32
Start query accounting before the Native and HTTP initial `Context` copy,
then admit retained setup memory into the user tracker without charging
its existing global ancestor twice.

Keep bookkeeping that outlives query detachment in global accounting,
and cover setup peaks, admission rejection, lifetime cleanup, and repeated
synchronous-query balance.
Initialize admission snapshot variables and make the allocator-rebinding
constructors of `GlobalMemoryAllocator` and
`QueryContextControlBlockAllocator` explicit.

Targeted compiler and clang-tidy checks pass for the four affected
translation units on `dev`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=3b3b592ae1f2756d6a50c5971e872e2b3ecd8ebe&name_0=PR&name_1=Build%20%28arm_tidy%29
Related: #120422
Sanitizer runtimes supply their own `new` and `delete`, so ordinary
allocation deltas remain zero in the context accounting tests. Skip the
two accounting-only unit cases and integration scenarios for sanitizer
builds, while preserving failure-cleanup and cross-thread weak-release
coverage. Keep all ordinary-build accounting assertions unchanged.

Validated both normal and sanitizer compilation and six integration
cases on `dev`; full sanitizer runtime validation remains with CI.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=b616fd15ca456c3882f9f4a156a9ada7a7de5521&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%29
#120422
Check retained setup memory against the query limit without rechecking the
global limit at admission. Preserve the configured batching allowance for
authenticated recovery users during `Native` query reception.

Return queued async-insert key allocations to their originating query
tracker when a background thread destroys them. Keep the tracker alive
through key ownership and keep shared-pointer bookkeeping global.

Give the rejected-admission fixture room for a successful small query and
verify that precondition. Let malformed async inserts reach the queue so
the failure-counter test exercises queue failures instead of setup rejection.

#120422
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=e54ae894387ca398fde8294d81d1a30e47792194&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%207%2F8%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=e54ae894387ca398fde8294d81d1a30e47792194&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%204%2F6%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=e54ae894387ca398fde8294d81d1a30e47792194&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%204%2F4%29

Validation on `dev`: 16 focused checks, 9 context/failed-insert cases,
unchanged async user-memory drift test (14,096-byte growth), recovery
queries under total memory pressure, and both explicit async flush paths.
Runtime used a targeted relink of the feature baseline; merged-head CI
remains required.
Allow error reporting in `HTTPHandler` to allocate after setup or
authentication rejects a request at a memory limit. Keep allocations
tracked while `LockMemoryExceptionInThread` prevents a second memory-limit
exception from suppressing the original response.

Cover GET and POST in the early-memory-limit integration test and bound
curl requests so a missing response produces a prompt transport failure.

#120422
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=71f5cde010d02c3a6078a366a6303a0e135a9441&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20targeted%29

Validation on `dev`: GET and POST return the expected Code `241` under
2 GB memory pressure; both full pressure-test cases and all nine context
and async-insert regression cases passed without skips. Real server
restarts and config reloads used a standalone transport harness.
Runtime used a targeted relink of the feature baseline; full CI is required.
Start `QueryScope` before copying the query `Context` in MySQL,
PostgreSQL, gRPC, Arrow Flight, and Prometheus handlers. Give each
PostgreSQL statement its own context and release retained contexts
under their original tracker, including Flight polling and cancellation.

Preserve memory-limit errors during Flight preparation and gRPC error
delivery. Add query/user setup-limit, recovery, and cleanup coverage for
24 protocol paths, plus session-setting and multi-statement checks.

Related: #120422 (comment)
Register Prometheus remote reads, formatting and empty writes, plus Arrow
Flight session options and non-SELECT preparation, before using their query
contexts. Tear down cancelled Flight pipelines under their original tracker.

Preserve inherited profiles with `MODIFY SETTINGS` in endpoint tests, wait
for context cleanup before sampling the baseline, and cover 33 operations
with 200 regression cases.

Related: #120422
Release query-owned buffers in `Call::close` before detaching their memory tracker. Destroy the responder after detachment, matching its allocation before query setup.

The endpoint cleanup regression detects excess user-memory credits across repeated gRPC calls.
Compare identical Prometheus writes with a small-context control while
keeping the 64 KiB tolerance for memory retained by the 8 MiB setup value.
Other endpoint cleanup checks still require zero drift.

The unchanged test already accumulated 192864/192576 bytes on the
pre-endpoint binary. Paired checks on the newer binary differ by only
-1152/4392 bytes and pass in both batching modes.
Extend `QueryScope` through response finalization and destruction instead
of allocating live response buffers globally. Allocate write responses
before admission so their memory is checked before the user tracker resets.
Keep error delivery bounded and tracked after a memory-limit exception.

Add 16 response-buffer limit and recovery cases across query, format,
read, and empty-write handlers, covering query/user limits and batching.
All 16 detect missing rejection on the prior binary; the changed source
compiles cleanly. Full endpoint runtime validation remains pending.
Apply query and user limits to unsupported routes and parsing errors. Preserve
the original memory-limit exception and close plain remote-write error
responses so clients can read their complete body.

Add 32 limit and recovery cases covering early context and response allocation.
Disable `query_metric_log` collection only for endpoint cleanup-test users.
The pre-endpoint binary also retains metric bookkeeping on PostgreSQL
`COPY` and Flight cancellation/schema-preparation paths. Keep all endpoint
cases and the 64 KiB cleanup tolerance unchanged.

Validation: reproduce all eight CI failures by enabling `query_metric_log`
on the current CI binary; confirm retained bookkeeping with an empty
context payload on the pre-endpoint binary. All 248 endpoint cases passed
on `dev` in 110.42 seconds with CI-style logging, profiling, and pool size.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=d4c8618b8e10d1497b3aaba18f75a8547c1cbff5&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%202%2F4%29
Related: #120422
Keep `query_id`, `query_for_logs`, and Native query objects charged
to the query until cleanup. Add assertions for live master and worker
metadata charges.

Remove unrelated async queue ownership, cache initialization, and
performance-counter accounting changes; the latter also removes
extra flushes observed by the pre-attachment CI regression. Shorten
comments around the remaining lifetime and admission constraints.
Compare initial balance and subsequent request drift against small-context
controls for insert endpoints. Warm shared protocol state before measuring
the copied context; retain the 64 KiB tolerance and live sentinel.

Validated together with the gRPC teardown fix: 261 protocol/context tests
and 17 focused unit tests pass on dev.

Related: #120422
Destroy retained `Context` owners and flush frees before clearing the last
`ProcessListEntry`. This prevents late cleanup from subtracting memory
charged to the next query from the same user.

Add deterministic success and exception coverage with both batching modes.
The original teardown undercounts by 8.1 MiB in all four cases; the fix
passes within 4 KiB. All 17 focused units and 261 protocol/context tests
pass on dev using the local protocol adapter (Docker is unavailable).

Related: #120422 (comment)
Initial `Context` accounting exposed a previously offset charge from
`InsertQuery` settings copied into the async queue. Retained queue and
scheduler keys now allocate and release through the global tracker,
including destruction by the producer, flush query, or deadline thread.

The unchanged CI test reproduced about 5.73 MB of drift; the fixed
scheduled-flush run leaves 2720 bytes; immediate flush differs by
-4048 bytes. The test and its threshold are unchanged. Focused units
pass 22/22; protocol, context, and queue tests pass 265/265 using the
local adapter (Docker unavailable on dev).

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=7276bc4be4f666c39c3a2c57b46dbff5e4a613ae&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%204%2F4%29
#120422
Retain the `Prometheus` request entry until its context and response buffer
are released, and keep the `Arrow Flight` action entry through context
cleanup. Flush deferred memory accounting before releasing the last entry.
Cover manual admission and prepared-statement schema inference with
last-query cleanup tests and both memory batching settings.

#120422
#120422 (comment)
#120422 (comment)
Resolve the `ArrowFlightServer` session-options conflict by keeping
upstream profile ordering and checks against `session_context`, while
retaining global accounting for persistent session mutations.

Preserve the existing early query tracking and admission cleanup.

Related: #120422
Queue and scheduler copies of `InsertQuery` outlive their producer and can
be freed on another query or background thread. Give these retained copies
matching global allocation and destruction, including their shared ownership
control blocks. Temporary lookup keys and insert payloads keep their existing
accounting. Add focused coverage for producer and cleanup tracker balances.

Related: #120422
Release the thread-local query id, query text, and callback before detaching.
Release the group-owned query text under its original tracker, including
when the last group reference is dropped after thread detachment. Reset
pre-attachment metadata before it can be freed against the next query.

Add a repeated thread-reuse regression through existing attachment APIs;
initial contexts are constructed outside the measured query tracker.

Related: #120422
Move additional SQL protocol paths into a separate change. Withdraw new
admission for non-executing protocol operations and Prometheus responses;
that behavior is outside the original query-memory visibility goal.
Add direct `SELECT 1` query-log coverage for inherited context allocations.

Related: #120422
Extend early `Context` accounting to MySQL, PostgreSQL, gRPC and Arrow
Flight SQL paths. Keep context destruction within its query tracker, including
cross-thread polling and last-query cleanup. Cover 19 execution paths,
query/user limits, reuse, query-log visibility and last-query cleanup.

Do not add admission for session-option updates, insert-only preparation
or Prometheus requests.

Related: #120422
qoega added a commit to qoega/ClickHouse that referenced this pull request Nov 4, 2026
The first request and a later keep-alive request differed by 80120 bytes in
Fast tests even with the connection metadata fix. Issue one small-header
request before collecting the baseline, keeping the 64 KiB tolerance and
the large-to-small `User-Agent` replacement check.

The updated test passes five repetitions on each fixed CI binary with both
batching settings. The unfixed binary still fails by 130992 bytes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=d4aea6d1d5d5c1083ab70c8ec25ede2772b3fe51&name_0=PR&name_1=Fast%20test
ClickHouse#120422
ClickHouse#123112
The first request and a later keep-alive request differed by 80120 bytes in
Fast tests even with the connection metadata fix. Issue one small-header
request before collecting the baseline, keeping the 64 KiB tolerance and
the large-to-small `User-Agent` replacement check.

The updated test passes five repetitions on each fixed CI binary with both
batching settings. The unfixed binary still fails by 130992 bytes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=d4aea6d1d5d5c1083ab70c8ec25ede2772b3fe51&name_0=PR&name_1=Fast%20test
#120422
#123112
@CLAassistant

CLAassistant commented Nov 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

qoega added a commit to qoega/ClickHouse that referenced this pull request Nov 5, 2026
Reading `system.processes` copies other running queries before filtering,
so measuring its own `memory_usage` varies with parallel test activity.
Read the final peak for `SELECT 1` from `X-ClickHouse-Summary` instead.
Keep the 64 KiB tolerance and large-to-small header replacement check.

Both fixed CI binaries pass five repetitions with two batching modes under
four concurrent workers. The old binary still fails by 130992 bytes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123112&sha=49aeb75b88e1a6554499bdc6a9ab105f0f750ea4&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123112&sha=49aeb75b88e1a6554499bdc6a9ab105f0f750ea4&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
ClickHouse#123112
ClickHouse#120422
qoega added 8 commits November 5, 2026 01:59
Reading `system.processes` copies other running queries before filtering,
so measuring its own `memory_usage` varies with parallel test activity.
Read the final peak for `SELECT 1` from `X-ClickHouse-Summary` instead.
Keep the 64 KiB tolerance and large-to-small header replacement check.

Both fixed CI binaries pass five repetitions with two batching modes under
four concurrent workers. The old binary still fails by 130992 bytes.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123112&sha=49aeb75b88e1a6554499bdc6a9ab105f0f750ea4&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123112&sha=49aeb75b88e1a6554499bdc6a9ab105f0f750ea4&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
#123112
#120422
Copy the retained context inside the worker QueryScope and keep its admission entry until context cleanup is flushed. Preserve the source context tracker across the handoff and allocate shared task bookkeeping globally.

Add Native/HTTP coverage for setup admission, live memory and cleanup with another query active. The previous ARM CI binary fails the setup-admission assertion on both protocols.
Use `QueryScope::initialized` for the two profile-event guards added by master. This PR uses a direct scope object instead of an optional scope.
Preserve the `Call::onException` memory exception guard before master
stops the output format writer. Keep master's `addOutputToResult` locking
and the PR's context/admission cleanup.

Related: #128292
Related: #123112
Comment thread src/Interpreters/executeQuery.cpp Resolved
The master header cleanup leaves only a forward declaration through
`Context.h`, so the numeric `setSetting` arguments cannot convert to
`Field`. Include its definition directly.

CI: https://github.com/ClickHouse/ClickHouse/actions/runs/43296896988/job/131459060994
Related: #123112
Copy the retained SQL buffer under the worker setup tracker and release
the global handoff copy before admission. Destroy the worker buffer
before its process-list entry so inline `INSERT` data is charged and
released with the query. Keep scheduler and promise bookkeeping global.

Add a Native inline-data regression for query/user setup limits, live
usage and cleanup with another query still active.

Review: #123112 (comment)
Related: #123112
qoega added a commit to qoega/ClickHouse that referenced this pull request Nov 15, 2026
Copy the retained SQL buffer under the worker setup tracker and release
the global handoff copy before admission. Destroy the worker buffer
before its process-list entry so inline `INSERT` data is charged and
released with the query. Keep scheduler and promise bookkeeping global.

Add a Native inline-data regression for query/user setup limits, live
usage and cleanup with another query still active.

Review: ClickHouse#123112 (comment)
Related: ClickHouse#120422
qoega added a commit to qoega/ClickHouse that referenced this pull request Nov 15, 2026
Disable `async_insert` explicitly so the regression covers the retained
Native `Query` buffer. Accept `NOTHING_TO_KILL` only during cleanup,
where it is expected after an admission failure.

The historical CI binary accepts the 8 MiB inline payload under a 4 MiB
query limit, reproducing the missing setup charge.

Review: ClickHouse#123112 (comment)
Related: ClickHouse#120422
The materialized `sleepEachRow` expression receives all 1024 rows in one
block despite `max_insert_block_size=16`, so its 5.12-second observation
window exceeds the default three-second per-block limit. Allow six seconds
in this test so the worker remains observable instead of throwing `TOO_SLOW`.
Keep the query/user limits and accounting assertions unchanged.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123112&sha=af84af429e9f0718bed1d64484b1b9c83f90ae1a&name_0=PR&name_1=Fast%20test
Related: #123112
A protocol override can clear an inherited `log_comment` while the request
context retains its allocation. Nest the idle request tracker under the
worker tracker before admission, and retain that parent through request
cleanup. Preserve the source peak without charging server memory again.

The request flushes before scheduling and waits under global accounting,
so the worker can move the setup charge while it is stable. Query and user
limits still apply at the usual `ProcessList` admission point.

Add a stateless regression for Native/HTTP query and user admission,
reported peak after an override, and cleanup with another active query.

Related: #120422 (comment)
Related: #120422
Replace the dedicated single-server integration cluster with a stateless
shell test. Preserve inherited settings, Native/HTTP peaks, query and user
admission, batching and cleanup assertions with another query active.

All 11 former parameterizations run through the default stateless server.
The protocol-specific integration module remains for configured endpoints.

Related: #120422 (comment)
Related: #120422
Filter `system.query_log` by `current_database = currentDatabase()` and
send HTTP requests to `CLICKHOUSE_DATABASE`, matching Native requests.
This keeps both new stateless regressions compatible with database
isolation and the CI query-log style check.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123112&sha=caff684cfc9c823553fc5a748b729d65d0f22e6f&name_0=PR&name_1=Style%20check
#123112
An HTTP response can finish before the handler releases its query context,
and the user and sentinel counters are independent snapshots. Wait for
server EOF and three stable counter pairs before comparing cleanup balances.
Keep the 2 KiB bound, positive floor and both batching modes. Reduce cleanup
requests from 832 to 304; 144 queries after each baseline still expose a
persistent 16-byte per-query residue above that bound.

Validated 20 runs with uninterrupted concurrent load on current AMD debug
and binary CI builds. A retained-query control still fails by 33,663,880 bytes.
This is standalone validation; the original CI jitter did not reproduce
in five bounded original-test runs.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123112&sha=e1cf00b7786aae554ec54f632e210eb667443217&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20flaky%20check)
#123112
Comment thread src/Interpreters/ProcessList.cpp Resolved
An admission failure can leave the query context above its limit. With
`min_allocation_size_to_throw_on_memory_limit=1`, copying the exception in
`TCPHandler::runImpl` then throws before the error packet reaches the client.
Keep memory-limit exceptions blocked from exception capture through delivery
and context cleanup; successful query execution keeps normal limit checks.

Reuse the existing memory-limit integration server with a temporary config
change. The focused test requires the original setup error and a successful
subsequent query. Three bounded query-limit attempts on the published AMD
binary returned transport EOF with the setting enabled and the original
setup error when disabled; the server stack identifies `Exception::clone`.
The exact new test also detects the missing error packet. Fixed-code build
and runtime validation remain for CI; standalone evidence is not full CI.

#123112 (comment)
#123112
qoega added a commit to qoega/ClickHouse that referenced this pull request Nov 23, 2026
An admission failure can leave the query context above its limit. With
`min_allocation_size_to_throw_on_memory_limit=1`, copying the exception in
`TCPHandler::runImpl` then throws before the error packet reaches the client.
Keep memory-limit exceptions blocked from exception capture through delivery
and context cleanup; successful query execution keeps normal limit checks.

Reuse the existing memory-limit integration server with a temporary config
change. The focused test requires the original setup error and a successful
subsequent query. Three bounded query-limit attempts on the published AMD
binary returned transport EOF with the setting enabled and the original
setup error when disabled; the server stack identifies `Exception::clone`.
The exact new test also detects the missing error packet. Fixed-code build
and runtime validation remain for CI; standalone evidence is not full CI.

ClickHouse#123112 (comment)
ClickHouse#120422
Comment thread src/Server/TCPHandler.cpp
}
catch (const Exception & e)
{
exception_memory_lock.emplace(VariableContext::Global);

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.

[Blocker] Keep memory limits enabled while draining client data

exception_memory_lock lives until the end of the loop iteration, so this also disables query, user and global memory-limit exceptions during the later skipData call at line 1338. That path does real deserialization: skipDataPacket calls NativeReader::read, which reserves columns and reaches SerializationNumber::deserializeBinaryBulk, whose x.resize(initial_size + limit) allocates before reading the values.

For example, follow the setup-rejected SELECT 1 from the new regression with an uncompressed Data packet declaring one UInt64 column and 100,000,000 rows. Admission fails before external-table input is consumed, so the packet is drained under this lock; its roughly 1 GiB column allocation bypasses every configured memory limit. The row count is below the reader's bound. Repeated connections or supplying the values can exhaust server memory even with a small server limit. This also affects ordinary query failures, with the default generic-allocation setting.

Please restrict the lock to exception capture/delivery and trusted cleanup. Deserialize drained packets with limits enabled, or close the connection when safe bounded draining is unavailable. Extend the Native rejection regression with a trailing data block larger than the memory limit.

This branch has not been deployed

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

Labels

ci-force-all Do not skip any jobs when running comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants