Skip to content

Account initial query context memory for Native and HTTP - #120422

Draft
qoega wants to merge 47 commits into
ClickHouse:masterfrom
qoega:codex/query-context-memory
Draft

qoega wants to merge 47 commits into
ClickHouse:masterfrom
qoega:codex/query-context-memory

Conversation

@qoega

@qoega qoega commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Include the initial Context in Native and HTTP query memory usage, including SELECT 1. Start tracking before copying the context, then use the existing query admission and MemoryTracker::reparent to apply query/user limits without charging the server total twice.

Reuses the lifetime accounting merged in #113647; no async-queue or system-table changes remain. Coverage checks inherited context bytes, limits, cleanup and recovery-user batching. Errors before query admission retain their existing precedence.

Related: #113647
Related: #123112

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 Native and HTTP queries.


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

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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e9032f6]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, distributed plan, targeted) FAIL
test_memory_limit/test.py::test_native_context_setup_error_with_throwing_allocations FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
05871_query_context_memory FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) FAIL
05872_query_context_memory_background_override FAIL cidb
Integration tests (arm_binary, 1/5) FAIL
test_memory_limit/test.py::test_native_context_setup_error_with_throwing_allocations FAIL cidb
Integration tests (amd_binary_excluded_from_llvm) FAIL
test_memory_limit/test.py::test_native_context_setup_error_with_throwing_allocations FAIL cidb

AI Review

Summary

Reviewed #120422 at e9032f6bf1fb25d9ca282835152fe9d46aa4963d, including all prior discussion. The change accounts for initial Context allocations in Native and HTTP queries, carries setup memory into background admission, and preserves exception delivery under memory pressure. No unresolved blockers or majors remain in the current diff. No local build or tests were run.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit e9032f6.

Metric Baseline Current Δ
Lines 91.80% 91.80% +0.00%
Functions 92.20% 92.20% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 324/329 (98.48%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 16, 2026
@qoega
qoega marked this pull request as ready for review September 16, 2026 15:44
Comment thread src/Server/TCPHandler.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label Sep 16, 2026
@qoega
qoega marked this pull request as draft September 16, 2026 17:21
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: ClickHouse#120422
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
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
ClickHouse#120422
Comment thread src/Interpreters/Session.cpp Resolved
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.

ClickHouse#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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit e9032f6bf1fb25d9ca282835152fe9d46aa4963d was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

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.

ClickHouse#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: ClickHouse#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: ClickHouse#120422
Comment thread src/Common/ThreadStatus.cpp Resolved
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.
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
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.
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
qoega and others added 3 commits September 18, 2026 06:20
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: ClickHouse#120422
Comment thread src/Server/ArrowFlight/PollSession.cpp Resolved
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 21, 2026
1 task done
qoega added a commit that referenced this pull request Nov 4, 2026
Construct and replace `ConnectionPeer` under `total_memory_tracker` because
its strings survive the request. Otherwise replacing a retained `User-Agent`
can debit the next query's setup tracker. Add a stateless keep-alive regression
for unbatched and batched accounting.

The published CI binary undercounts the reused request by 131568 bytes in
both modes. The exact new test fails on it; the modified translation unit
passes a supplemental syntax-only check. Fixed runtime validation awaits CI.

#123112 (comment)
#120422
qoega added 2 commits November 5, 2026 00:07
Construct and replace `ConnectionPeer` under `total_memory_tracker` because
its strings survive the request. Otherwise replacing a retained `User-Agent`
can debit the next query's setup tracker. Add a stateless keep-alive regression
for unbatched and batched accounting.

The published CI binary undercounts the reused request by 131568 bytes in
both modes. The exact new test fails on it; the modified translation unit
passes a supplemental syntax-only check. Fixed runtime validation awaits CI.

ClickHouse#123112 (comment)
ClickHouse#120422
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
qoega added a commit 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
#120422
#123112
@CLAassistant

CLAassistant commented Nov 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

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 a commit 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
#123112
#120422
qoega added 9 commits November 6, 2026 10:56
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.
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/43296931202/job/131458994429
Related: ClickHouse#120422
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
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=120422&sha=6edbc2a3559cf8e2482a10047bb48d7917cddaa4&name_0=PR&name_1=Fast%20test
Related: ClickHouse#120422
@qoega qoega added the ci-force-all Do not skip any jobs when running label Nov 16, 2026 — with ChatGPT Codex Connector
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: ClickHouse#120422 (comment)
Related: ClickHouse#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: ClickHouse#120422 (comment)
Related: ClickHouse#120422
qoega added a commit that referenced this pull request Nov 23, 2026
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
qoega added a commit that referenced this pull request Nov 23, 2026
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=120422&sha=0c066193b2f2e50ec7cea1ef6c7228ea0bfc5c21&name_0=PR&name_1=Style%20check
ClickHouse#120422
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=120422&sha=7e6fd6daa71e2c549d616593fa60887e3ac9300a&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20flaky%20check)
ClickHouse#120422
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

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