Skip to content

Read the sanitizer build flavour before the memory-limit tests run in test_max_bytes_ratio_before_external_* - #120751

Merged
nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:sanitizer-flavour-probe-before-memory-limit-tests
Sep 18, 2026
Merged

nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:sanitizer-flavour-probe-before-memory-limit-tests

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116569

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Fixed test_max_bytes_ratio_before_external_* failing instead of skipping on sanitizer builds.

Description

On MSan builds these tests fail at their own skip guard, not at an assertion. is_built_with_sanitizer answers by querying the running node. The three tests share one module-scoped cluster; test_..._sort guards TSan only, so on MSan it runs and deliberately drives the node to MEMORY_LIMIT_EXCEEDED. MSan builds have no jemalloc, so RSS stays tens of MiB above the cap afterwards, and MemoryTracker::allocImpl enforces the total limit against RSS rather than tracked bytes. The next connection handshake is therefore refused, and the guard's probe is that connection, so Code: 241 escapes as a FAIL two lines before pytest.skip(). The guard is unreachable on exactly the builds it exists for.

This reads the flavour once in the module fixture, right after cluster.start(), while both nodes are still at their floor RSS, into a dict the three tests consult. Skip conditions and messages are unchanged. sort keeps its TSan-only guard deliberately: it passes 110/110 on MSan, so adding an MSan skip would delete real coverage. Not fixed in helpers/cluster.py: 27 upgrade-test modules swap the binary mid-module, so caching CXX_FLAGS there would need invalidation at every one of them, for a defect with one instance in the tree. Not fixed server-side either: the refusal is the total-memory limit working as configured, and a guard that decides whether to skip has no reason to query the server.

Measured (CIDB, 30 days, Code: 241 on this module): 7 failures on 7 distinct PRs in one 8-hour window on 2026-09-17, 0 on master, on both the [server] and [user] arms. group_by and sort carry the pattern latently and are converted too.

Validated with a fault-injected probe oracle: 6/6 FAIL before, 0 test-body probes after, across 3 MSan runs plus TSan and -k-filtered arms; on a plain debug build the file is 6 passed / 0 skipped.

CI traceback (PR #119465, Integration tests (amd_msan, 1/8))
test_max_bytes_ratio_before_external_order_group_by_for_server/test.py:101:
    in test_max_bytes_ratio_before_external_distinct
        if node.is_built_with_thread_sanitizer():
helpers/cluster.py:5165: in is_built_with_sanitizer
        build_opts = self.query(          <-- the guard issues a QUERY to the node

E   helpers.client.QueryRuntimeException: Client failed! Return code: 241,
E   Code: 241. DB::Exception: (total) memory limit exceeded: would use 10.40 MiB
E     (attempt to allocate chunk of 0.00 B), current RSS: 10.03 GiB, maximum: 10.00 GiB.
E     Untracked memory across all threads: -3.40 MiB.
E   5. src/Common/MemoryTracker.cpp:439:27: MemoryTracker::allocImpl(...)
E   7. src/Server/TCPHandler.cpp:2180:9: DB::TCPHandler::receiveHello()

Report: https://github.com/ClickHouse/ClickHouse/actions/runs/35189935944/job/105133216579


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

Version info

  • Merged into: 26.10.1.103 (included in 26.10 and later)

On MSan builds the three tests in
test_max_bytes_ratio_before_external_order_group_by_for_server fail at their
own skip guard rather than at an assertion.

ClickHouseInstance.is_built_with_sanitizer answers by issuing a live query to
the running node (SELECT value FROM system.build_options WHERE name =
'CXX_FLAGS'), uncached, on every call. The three tests share one module-scoped
cluster and run in declaration order. test_..._sort guards TSan only, so on an
MSan build it runs, and its second phase deliberately drives the node to
MEMORY_LIMIT_EXCEEDED on a ~12 GiB-peak ORDER BY. Sanitizer builds other than
UBSan have no jemalloc (contrib/jemalloc-cmake/CMakeLists.txt:1-10), so no
arena purge returns those pages and RSS stays tens of MiB above the cap.
MemoryTracker::allocImpl enforces the total limit against RSS rather than
tracked bytes (src/Common/MemoryTracker.cpp:348), so while RSS is above the cap
the server rejects every allocation, including the tiny one in
TCPHandler::receiveHello(), i.e. the connection handshake. The first statement
of test_..._distinct is its own skip-guard probe; that probe is refused with
Code: 241, and the QueryRuntimeException escapes as a FAIL two lines before the
MSan pytest.skip() can run. The guard is unreachable on exactly the builds it
exists for.

Read the flavour once in the module fixture, immediately after cluster.start(),
while both nodes are still at their floor RSS, into a module-level dict the
three tests consult. No test has allocated at that point, so the probe can no
longer be defeated by state a later test creates. test_keeper_profiler and
test_trace_collector_serverwide already probe the build flavour at this same
point. Note that cluster.start() only waits for the TCP port (9000 by default)
to accept a connection (ClickHouseInstance.wait_until_port_is_ready), so "the
port is open" never implied "a query will be answered": Code: 241 is raised in
TCPHandler::receiveHello(), after the socket has been accepted.

Skip semantics are preserved case for case and message for message: group_by
and distinct keep their TSan and MSan skips, sort keeps its TSan-only skip.
sort is deliberately not given an MSan skip: it passes 110/110 on MSan and has
never failed there, so adding one would delete real coverage to silence a
failure that is not its fault. The fix is deliberately not in
helpers/cluster.py either: 27 upgrade-test modules swap the binary mid-module
(restart_with_latest_version, with_installed_binary), so caching CXX_FLAGS
there would need invalidation on every one of them, a harness-wide change
across 161 call sites in 69 files to close a defect with exactly one instance
in the tree. Of the integration modules that cap server/user memory and probe
the build flavour, exactly one has more than one test function, and it is this
one, so group_by and sort were latent carriers of the same pattern and are
converted too.

Measured (CIDB, 30 days, memory-limit failures of this module): 7 failures on
7 distinct PRs, all on 2026-09-17 between 06:06Z and 14:20Z, 0 on master, all
in Integration tests (amd_msan, 1/8), hitting both the [server] and [user]
arms. Exposure opened when ClickHouse#116569 merged, adding the distinct case after sort
in the file.

Validated with a fault-injected probe oracle: 6/6 FAIL and 6 test-body probe
calls before, 0 test-body probe calls after, across 3 MSan runs plus TSan and
-k-filtered arms. On a plain debug build the full file is 6 passed, 0 skipped.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 gate findings) plus two separate
cold reads of the diff, one per review round.

# Sev Finding Verdict Evidence / action
1 ⚠️ The commit message justified the new probe site by claiming cluster.start() requires the nodes to answer queries AGREE It waits for a TCP connect on the server port (ClickHouseInstance.wait_until_port_is_ready), and Code: 241 is raised in TCPHandler::receiveHello() after the socket is accepted. Reworded and re-verified from source in round 2: ClickHouseCluster.start() issues no query at all, so the probe's safety rests on floor RSS, plus test_keeper_profiler and test_trace_collector_serverwide already probing the flavour at the same point
2 💡 The identical TSan guard in all three tests could be a single fixture-level pytest.skip() DISAGREE Both shapes are correct. A fixture-level skip cannot express the file's asymmetry (sort keeps a TSan-only guard while the other two also skip MSan), so the MSan arm would still need the dict; the current shape keeps the diff at +12/-5 and every skip message byte-identical to master's. Declined as churn
3 💡 sanitizer_build["thread"] would raise KeyError if the fixture never populated it DISAGREE That is the wanted loud failure: the fixture is autouse, so an exception there errors all six cases, whereas a defaulted read would silently run a 12-16 GiB memory-limit test on a sanitizer build. The -k-filtered arm confirms the dict is populated even for a single selected case
4 💡 The commit message's figures for the rejected harness-level fix are off basis NOTED Fresh count: is_built_with* appears 159 times in 69 files (the message says 161 in 69), and restart_with_latest_version( appears in 27 files across 21 module directories rather than 27 modules. The conclusion (a harness-wide cache would need invalidation at every binary-swap site) is unchanged, so this was not worth a round on a byte-identical tree
5 💡 The census in the description is a snapshot and has already grown NOTED Re-measured at 2026-09-18 07:45Z, same filter: 9 failures on 9 distinct PRs, 0 on master, 2026-09-17 06:06Z to 22:57Z, all Integration tests (amd_msan, 1/8), distinct[server] x2 and distinct[user] x7. The two carriers after the snapshot are #117943 and #120684. The test is still failing on unrelated pull requests roughly hourly

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Gate B ran on this exact tree and patch-id (0 findings); round 2 changed only the commit
message, so the tree, the patch-id and the description are byte-identical to the gated content.

Session id: cron:clickhouse-review-slot-11:20260918-073144

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. A pytest plugin injects the one precondition CIDB proves present in CI (the flavour probe issued from a test body against a node whose RSS is over its cap) and nothing else: 6/6 FAILED, on 2 of 2 runs, tracebacks landing on the guard line at test.py:101 with the verbatim Code: 241 text. Not "~1%".
b Root cause explained? YES. is_built_with_sanitizer answers by querying the running node. The 3 tests share one module cluster; test_..._sort guards TSan only, so on MSan it runs and its 2nd phase drives the node to MEMORY_LIMIT_EXCEEDED on purpose. Sanitizer builds other than UBSan have no jemalloc, so RSS stays tens of MiB above the cap, and MemoryTracker::allocImpl enforces the total limit against RSS, not tracked bytes. The next connection handshake (TCPHandler::receiveHello) is refused, and the guard's own probe is that connection, so Code: 241 escapes as a FAIL two lines before pytest.skip() can run. The guard is unreachable on exactly the builds it exists for.
c Fix matches root cause? YES. The root cause is the probe's placement, and the fix moves the probe to the module fixture, right after cluster.start(), when both nodes are at floor RSS. No band-aid: no widened bound, no no-random-* tag, no dataset reduction, no try/except around the probe, no new skip added to silence anything. Queries, settings and assertions are untouched.
d Test intent preserved / new tests added? PRESERVED; no new test warranted. All 6 cases still run and still assert what they did (plain debug build: 6 passed, 0 skipped). Skip semantics preserved case for case and message for message. The change is to a test's own skip plumbing, so a test-for-the-test would be test volume out of proportion to the fix; the negative-control arm is itself the on-demand proof that the guard is now reachable.
e Both directions demonstrated? YES. Pre-fix: 6 FAILED, 6 test-body probe calls. Post-fix: 0 test-body probe calls in every arm, with the correct skip/run decision, across 3 MSan runs plus a TSan arm and a -k-filtered arm.
f Fix is general across code paths? YES. All three test functions are converted, not only the failing distinct: sort and group_by are latent carriers that become the next victim on any reordering or appended case. Fixed at the source (the probe's placement), not guarded at the failure site. Sibling enumeration re-measured cold: of the integration modules that cap server/user memory and probe the build flavour, exactly one has more than one test function, and it is this one, so the defect class has one instance in the tree and this closes it.
g Fix generalizes across inputs (params/datatypes/wrappers)? YES. The input space is (flavour) x (node) x (invocation shape). Flavour: memory skips group_by/distinct and runs sort; thread skips all three; neither (plain debug, and equally ASan since no test guards ASan) runs all six. All 3 classes exercised. Node: both [server] and [user] in every arm. Invocation: full file and -k-filtered subset. Both dict keys are written by two consecutive statements before any test body runs and never mutated, so no partially-populated read exists.
h Backward compatible? YES, vacuously, and verified: git diff --name-only -- src/ programs/ base/ contrib/ cmake/ is empty. Tests only. No setting, no SettingsChangesHistory.cpp, no server behaviour, no serialization, no public API. Nothing to gate or version.
i Invariants and contracts preserved? YES, walked including error paths. Invariant: a build-flavour skip predicate is evaluated while the servers are still at their startup RSS, never after a test that drove a node to its memory limit. cluster.start() raising still reaches finally: cluster.shutdown(), unchanged. The one new failure path is the probe itself raising, which aborts the fixture and ERRORs all 6 cases at setup; pre-fix the same broken-cluster condition failed the same 6 cases individually, so the red count is unchanged and only the shape differs. Net strictly safer: the probe runs immediately after cluster.start(), when no test has allocated and both nodes are at floor RSS, which is what the memory limit reads. (cluster.start() itself waits only for a TCP connect, ClickHouseInstance.wait_until_port_is_ready; it does not require a query to be answered, which is why Code: 241 from TCPHandler::receiveHello() is invisible to it.) autouse=True populates the dict even for a single -k-selected case, so no KeyError path exists. Single-threaded module-scoped fixture: no lock ordering or atomicity contract involved; no persisted state, so no crash-restart path.

Session id: cron:clickhouse-impl-slot-5:20260918-064502

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b437b56]

Summary: ✅


AI Review

Summary

This PR moves the sanitizer-flavour probe for test_max_bytes_ratio_before_external_* into the module fixture so the skip checks run before any test can push a node over its memory cap and make later system.build_options queries fail during the connection handshake. I did not find a correctness, coverage, or skip-semantics regression in the current diff: caching the build flavour once is sufficient here because both parametrized instances run the same binary, and the skip matrix stays unchanged (group_by / distinct still skip on MSan and TSan, while sort still skips only on TSan).

Missing context / blind spots
  • ⚠️ I did not run the full integration module locally. Confidence is based on code inspection, python3 -m py_compile for the modified file, and the current PR rerun status on 2026-09-18, where the fresh integration checks are still in progress.
Final Verdict

✅ No review findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 18, 2026
@nihalzp nihalzp self-assigned this Sep 18, 2026
The PR workflow run on this head aborted inside Config Workflow: praktika's
Check CI DB step could not reach the CI database (Code: 202, too many
simultaneous queries; three retries, all HTTP 500), the job failed, and every
downstream job was set to DROPPED, so not one test ran on this head. The
database answers again, so this empty commit re-triggers the workflow.

No code change: the tree is identical to the previous commit.
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 18, 2026
@nihalzp
nihalzp added this pull request to the merge queue Sep 18, 2026
Merged via the queue into ClickHouse:master with commit b201776 Sep 18, 2026
349 of 350 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 18, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 3, 2026
Resolve the conflict in
test_max_bytes_ratio_before_external_order_group_by_for_server/test.py.
26.9 has neither ClickHouse#120751 (the `sanitizer_build` dict) nor ClickHouse#121454 (the
`limit_follows_rss` parameter and the ASan skip of the `[server]` case),
so only the change of ClickHouse#122494 itself is ported: each case's query moves
into its parametrize row, and the `[user]` row runs the 7M x 800-byte
query with `max_memory_usage_for_user = '4Gi'`. The 26.9 sanitizer
checks and the `[server]` query are kept as they are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-testing Test content only (no production code). labels Nov 22, 2026
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-ci 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