Skip to content

Make 01548_parallel_parsing_max_memory actually test the memory guard, and stop writing 1 GB - #113080

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-01548-parallel-parsing-guard
Aug 4, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-01548-parallel-parsing-guard

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #109408

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

...

Description

01548_parallel_parsing_max_memory has been timing out at the 60 s Fast test per-test cap on
Fast test (arm_darwin): 8 failures across 8 unrelated PRs in 30 days, 0 on master, durations
clustered within 0.8 s of 60.0 s, so it is the runner's --timeout 60. Every arm_darwin fast test
with p50 > 3 s inflated in that window while this test's own p50 never moved, so the trigger is runner
disk contention. Its contribution is IO volume: a 1 GB fixture per run, never removed. That drops to
128 MiB and is now deleted. Paired against master under the Fast test invocation, median falls to 7.7 s
from 10.2 s, worst round to 10.9 s from 33.3 s.

While shrinking the fixture I found the test had not asserted anything since ce7eca06159
(2023-10-16). Its SELECT count() references no column, which sets need_only_count, and
FormatFactory.cpp:558 declines parallel parsing on that flag before the max_memory_usage guard at
:560-562. The trace confirms it: (from 0.00 B), no bytes read.

The test now aggregates over values (sum(length(URL))), which no trivial-count shortcut can serve,
and asserts at two caps so both branches of the guard are taken and must agree. The 50 MiB cap and
max_threads=1 are unchanged: they are the oracle. All four settings the guard reads are pinned, since
max_parsing_threads otherwise follows core count. Removing the guard now raises
Code: 241 ... While executing ParallelParsingBlockInputFormat on the low arm, where the old shape
stayed green. Since two equal sums cannot say which format was built, a third arm asserts an error only
a file segmentation engine raises, and those run solely inside ParallelParsingInputFormat: a
control-flow fact with no numeric margin. It breaks if a precondition ahead of the guard again declines
parallel parsing. max_memory_usage_for_user at :563-565 stays uncovered: clickhouse-local cannot
set it per query.

Version info

  • Merged into: 26.8.1.731 (included in 26.8 and later)

groeneai and others added 3 commits August 3, 2026 00:21
…p writing 1 GB

The test has been timing out at the 60 s Fast test per-test cap on
Fast test (arm_darwin): 8 failures across 8 unrelated PRs in 30 days, 6 of
them on 2026-08-01, 0 on master. Durations cluster within 0.8 s of 60.0 s, so
it is the runner's --timeout 60 (ci/jobs/fast_test.py:375), not a resource
error. The test wrote a 1 GB fixture per run and write+flush dominates its
wall time (6.40 s for 1 GiB against 0.12 s for 128 MiB), so it stretches
under macOS-runner disk contention until it crosses the cap. Every arm_darwin
fast test with p50 > 3 s inflated in that window while p50 itself never
moved, so the trigger is the runner rather than the test.

While shrinking the fixture I found the test had not been asserting anything
since 2023. Its SELECT count() references no column, which makes
StorageFile.cpp set need_only_count, and FormatFactory.cpp:558 disables
parallel parsing on that flag before the max_memory_usage guard at :560-562
is consulted. The trace reports "(from 0.00 B)", and running the query twice
in one session collapses from 0.399 s to 0.003 s via the count-from-files
cache. An instrumented build confirms it directly: the guard is never
reached, and removing the guard entirely does not change the result. It was
hollowed on 2023-10-16 by ce7eca0, a change unrelated to this test.

So instead of only shrinking the fixture, the test now aggregates over column
values with sum(length(URL)), which no trivial-count shortcut can serve; pins
the four settings the guard reads, all of which CI randomizes today; and
asserts at two caps so both branches of the guard are taken and must agree.
The 50 MiB cap and max_threads=1 are unchanged because they are the oracle.
max_parsing_threads=1 would also make the guard unreachable via the
max_parsing_threads > 1 conjunct, so pinning it is load-bearing rather than
hygiene. The fixture drops to 128 MiB, which cuts 87.5 % of the bytes written
per run, and is now removed at the end.

The parallel-parsing decision is not observable from SQL, since
ParallelParsingInputFormat emits no log line and no ProfileEvent and EXPLAIN
PIPELINE is byte-identical for both branches, and the guard is conservative
so whenever it permits parallel parsing the memory is genuinely fine. The
oracle can therefore only be validated by mutating the guard away: with it
present the low arm reaches and fires it and prints the correct value, and
with lines 560-565 bypassed the same query fails MEMORY_LIMIT_EXCEEDED while
executing ParallelParsingBlockInputFormat. The old query shape does not
redden under that same mutation, including with all four settings pinned.

max_memory_usage_for_user, the symmetric branch at :563-565, is deliberately
still not covered: clickhouse-local cannot set a user-level setting per
query, and widening the oracle to a path with no reported defect would add a
redden burden the instrumentation-only limitation cannot discharge.
The two sums the test prints agree whichever input format was built, because
the memory guard at FormatFactory.cpp:560-562 changes only the parsing
strategy, never the result. So on their own they would stay green if any of
the five preconditions ANDed at :556-559 started declining parallel parsing
before the guard is consulted, which is exactly how ce7eca0 silently
hollowed this test for two years.

Add a third arm that pins the constructed format down. ParallelParsingInput-
Format allocates max_threads + 2 processing units while the guard budgets
min_chunk * max_threads * 2, so with max_parsing_threads=2 the guard under-
estimates and there is a window where it permits parallel parsing yet that
path cannot fit the cap. The resulting Code: 241 names the format, and the
sequential path completes at the same cap, so the line breaks the moment
parallel parsing stops being chosen. Feasible caps measured 16-24 MiB; the
arm uses 20 MiB, mid-window.

No in-test observable of the format exists to assert instead: clickhouse-local
has no system log tables at all, EXPLAIN PIPELINE is byte-identical between
the arms, normalized trace output is identical, and the ProfileEvents key sets
differ only by scheduling counters.

Verified by mutation on a local debug build. Forcing one upstream conjunct
false flips the arm from PARALLEL to NOT PARALLEL and the test fails, while
the pristine tree passes; neutering the memory guard itself still reddens, so
no oracle was traded away.

Co-Authored-By: Claude Fable 5 <[email protected]>
…lel parsing ran

The third arm proved which input format was constructed by requiring the parallel
path to exceed a 20 MiB memory cap. That peak is not a constant.
ParallelParsingInputFormat.h:106 allocates max_threads + 2 processing units, each
holding a min_chunk-sized segment, giving a structural floor of 16 MiB just 4 MiB
below the cap; everything above that floor comes from a scheduling-dependent
number of units whose segments and parsed chunks coexist
(ParallelParsingInputFormat.cpp:33, .cpp:225-235). So wherever the peak lands in
[16 MiB, 20 MiB) the arm printed NOT PARALLEL and the test went red on master.

Measured on one build, varying only max_block_size:

  8000 / 16000 / 32000  -> NOT PARALLEL
  65536 / 100000        -> PARALLEL

Smaller parsed chunks lower the peak below the cap. Both earlier validations ran
on a loaded 96-core box, the condition that inflates the peak, so the arm was
validated exactly where its failure mode is masked. This test runs on 21
check_names, so a flaky canary here is worse than the timeout it replaces.

Pinning max_block_size would not fix it: that removes one input to the peak and
leaves the concurrent-unit term, so the margin stays load-dependent.

Instead the arm now asserts an error that only a file segmentation engine raises.
file_segmentation_engine has exactly one runtime call site in the tree,
ParallelParsingInputFormat.cpp:37, so such an error is reachable only if that
format was built. That is a control-flow fact rather than a byte count: no margin
to tune, and no dependence on build flavor, allocator, core count, block size or
load. The error is the INCORRECT_DATA at JSONUtils.cpp:48-52, raised when one JSON
object exceeds 10 * min_chunk_bytes; 01701_parallel_parsing_infinite_segmentation
already greps for the same token, and the sequential path never emits it.

The fixture is a single 32 KB JSONEachRow object against
min_chunk_bytes_for_parallel_parsing=1024, so the threshold is cleared by exact
integer arithmetic on a byte count the test controls. It starts with { because
nonTrivialPrefixAndSuffixCheckerJSONEachRowImpl (JSONUtils.cpp:259-264) returns
true for [. The memory cap is deliberately high, 1024 * 2 * 2 = 4096 against
1000000000, so the guard permits and the arm cannot degenerate back into a memory
oracle; its error was verified to be INCORRECT_DATA and not MEMORY_LIMIT_EXCEEDED.

The new oracle prints PARALLEL at max_block_size 8000, 16000, 32000, 65536 and
100000 and at max_parsing_threads 2, 4 and 16. Hollowing an upstream conjunct
(&& !need_only_count -> && (need_only_count && false)) still flips it to
NOT PARALLEL and fails the test, and neutering the max_memory_usage guard still
fails arm 1 with Code 241 naming ParallelParsingBlockInputFormat, so no oracle was
traded away. Arms 1 and 2 and the reference are unchanged. 50 runs randomized and
50 in the Fast test shape pass, worst case 14.5 s against the 60 s cap.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, 0 unresolved) - click to expand

Before opening this PR I reviewed the change myself and with an independent second model, three
rounds. Two rounds found a substantive problem and sent it back; this round found none.

Round 1 (major, fixed)

⚠️ The two sums agree whichever input format was built. FormatFactory.cpp:556-558 ANDs five
preconditions ahead of the memory guard at :560. If any one goes false, parallel parsing is
declined before the guard, the ordinary creator is built, and both arms still print the same value.
That is precisely how ce7eca06159 hollowed this test in 2023, so a PR whose purpose is to un-hollow
it must not leave it re-hollowable by the identical mechanism.

Fixed by adding a third arm that pins down which format was constructed.

Round 2 (major, fixed)

⚠️ That third arm's first form asserted a memory peak, and the peak is not a constant.
ParallelParsingInputFormat.h:106 allocates max_threads + 2 units, giving a structural floor
4 MiB under the cap it used; everything above that floor depends on how many units' segments and
parsed chunks coexist. Varying only max_block_size on one build: at 8000 / 16000 / 32000 the arm
succeeded and the test printed NOT PARALLEL, i.e. it would have gone red on master. This test runs
on 21 check names, so a flaky arm here is worse than the timeout it replaces.

Fixed by replacing the numeric oracle with a control-flow one: file_segmentation_engine has exactly
one runtime call site (ParallelParsingInputFormat.cpp:37), so an error raised inside a segmentation
engine is reachable only if that format was built. No margin to tune. The new form holds at all five
max_block_size values and all three max_parsing_threads values.

Round 3 (this round): no blockers, no majors

Three nits, all recorded and accepted rather than fixed:

💡 The canary reads JSONEachRow, so it proves construction for that read, not for the TSV reads in
arms 1 and 2. Two of the five preconditions are per-format. Not live today (TSV registers a
segmentation engine and no random-access creator), and the three settings-driven preconditions plus
the guard, which are the class that actually broke this test, are covered. TSV has no data-driven
segmentation error to assert against, so closing this would need a different mechanism for no gain
against any observed failure mode.

💡 The grep matches the setting name, which also appears in the UNKNOWN_SETTING diagnostic, so a
future rename would make the arm pass vacuously instead of failing. The in-tree prior art
01701_parallel_parsing_infinite_segmentation.sh greps the same token the same way.

💡 The fixture uses tr '\0', which no other test in the suite does. Both GNU and BSD tr document
the octal escape, and the recorded error says "current is 32775 bytes per row", so the expansion
worked. Had it not, the object would have collapsed to 9 bytes and the test would have failed loudly
rather than silently.

Re-derived independently from source, all confirmed

Guard arithmetic by hand (arms 1-2: 10485760 * 16 * 2 = 335544320 against caps 52428800 and
1000000000, so both branches are genuinely taken; canary: 1024 * 2 * 2 = 4096 against 1000000000,
so the guard permits and the arm cannot become a memory oracle) · the single segmentation-engine call
site · exception attribution (ExecutionThreadContext.cpp:81 appends the processor name, which is
ParallelParsingBlockInputFormat) · every JSONEachRow precondition, including why the fixture starts
with { · max_threads=1 keeping the divisor in getParsingThreadsPerReader at 1, and
max_parsing_threads otherwise following core count · the reference value from first principles
(2485513 newlines in 134217728 bytes, so 131732215), with the same model reproducing the old
19884108 · vacuity of the old shape from StorageFile.cpp:2182 · sibling sweep enumerated before
reading the plan, no sibling fix owed · ${CLICKHOUSE_TMP} per-test, so no no-parallel tag needed ·
CIDB breadth re-measured: 8 failures across 8 unrelated PRs in 30 days, 0 on master, and the acute
window has receded, so this is preventive.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for both defects. Vacuity: an instrumented build prints pre_guard=false for the old query shape, 100 % deterministic. Cost: fixture write plus explicit flush measured deterministically at both sizes (1 GiB 1.24 s write + 5.16 s sync, 128 MiB 0.10 s + 0.02 s); the test itself never calls sync, so the durable claim is the IO volume, 87.5 % fewer bytes written per run. The 60 s timeout itself is runner-contention dependent and deliberately not chased.
b Root cause explained? The runner kills at --timeout 60 (ci/jobs/fast_test.py:375, kill message tests/clickhouse-test:695). The test's dominant cost was a 1 GB fixture write+flush that stretches under macOS-runner disk contention until it crosses the cap. Separately, the assertion it was paying that cost for had been dead since ce7eca06159: SELECT count() with no column reference sets need_only_count, and FormatFactory.cpp:558 disables parallel parsing on that flag before the max_memory_usage guard at :560-562 is consulted.
c Fix matches root cause? Yes, and it is not a band-aid: the 50 MiB cap and max_threads=1 (the oracle) are preserved, no no-fasttest / long / no-random-settings tag was added, and the fixture cut rests on a measured size-invariance of the parser's footprint rather than on making the assertion easier to satisfy.
d Test intent preserved / new tests added? Strengthened. The test now actually reaches the guard it was written for in 2020 (dabb23b6680f) and asserts that both branches, guard-fires and guard-permits, agree, where the old version asserted neither. A third arm additionally pins down which input format was constructed, by asserting an error that only a file segmentation engine raises and that those engines run solely inside ParallelParsingInputFormat, so the test detects a future re-hollowing by a precondition ahead of the guard, not only the defect it was written for.
e Both directions demonstrated? Yes, twice. (1) With the guard present the low arm reaches it and fires and prints the correct value; with the max_memory_usage guard neutered it fails Code: 241 ... While executing ParallelParsingBlockInputFormat (Build ID 23343318), and the OLD query text does NOT redden under that same mutation. (2) Forcing one precondition ahead of the guard false (&& !need_only_count to && (need_only_count && false), what ce7eca06159 effectively did) flips the third arm from PARALLEL to NOT PARALLEL and the test FAILS (Build ID 4dd507b4), while the pristine tree PASSES (b943cc2d). Each direction ran on its own rebuild with the Build ID recorded and confirmed in the server's own startup line.
f Fix is general across code paths? Swept. grep "head -c[0-9]*[GM]" over 0_stateless finds only 01621_clickhouse_compressor.sh (1M) besides this test, so no sibling shrink is owed. Of the tests referencing the three parallel-parsing settings, the ones also setting max_memory_usage are 02455 (reaches the guard via having no aggregate at all, so not vacuous), 01701_parallel_parsing_infinite_segmentation.sh (sets max_memory_usage=0, deliberately disabling the guard) and three fuzzer settings-dumps asserting unrelated properties. No sibling fix owed, so the PR is deliberately not widened.
g Fix generalizes across inputs (params/datatypes/wrappers)? The guard is integer arithmetic over three settings, so the input axis is the settings matrix, and both sides of the predicate are now exercised (10485760*16*2 = 335544320 against caps 52428800 and 1000000000). Probed the threshold directly at 335544319 / 335544320 / 335544321: all return the same correct value, confirming the guard changes only the parsing strategy and never the result, which is exactly the invariant the two arms assert. The third arm asserts a control-flow fact rather than a byte count, so it has no numeric margin to generalize over; it was nevertheless swept over max_block_size 8000 / 16000 / 32000 / 65536 / 100000 and max_parsing_threads 2 / 4 / 16, printing PARALLEL in all eight. Its error is INCORRECT_DATA, verified not MEMORY_LIMIT_EXCEEDED, so it is not a memory oracle in disguise.
h Backward compatible? (maintainer-approved exception only) N/A, test-only. No setting default, no SettingsChangesHistory.cpp entry, no format or serialization change, no compatibility surface.
i Invariants and contracts preserved? The invariant under test, that parallel parsing must not be used when min_chunk_bytes_for_parallel_parsing * max_parsing_threads * 2 would exceed the query memory cap, is now actually asserted rather than bypassed. The test also removes both of its fixtures, so it no longer leaves one behind in ${CLICKHOUSE_TMP}. That directory is already per-test, keyed on the unique test database (tests/clickhouse-test:2185-2188), so both fixtures stay parallel-safe and no no-parallel tag was added.

Session id: cron:clickhouse-impl-slot-41:20260803-070200

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar, could you review this? It is test-only. 01548_parallel_parsing_max_memory had stopped asserting anything in 2023: its SELECT count() sets need_only_count, which FormatFactory.cpp:558 uses to decline parallel parsing before the max_memory_usage guard at :560-562 is reached, so the test paid for a 1 GB fixture to exercise nothing and was timing out at the 60 s Fast test cap on arm_darwin.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c6beda1]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
02015_async_inserts_5 FAIL cidb IGNORED

AI Review

Summary

This PR rewrites 01548_parallel_parsing_max_memory so it stops creating a 1 GiB fixture and actually exercises the max_memory_usage branch in FormatFactory. The current TSV-based observability arm closes the earlier blind spot, the updated reference matches the 128 MiB fixture, and I did not find a remaining correctness, coverage, or metadata issue in the diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 3, 2026
@PedroTadim PedroTadim self-assigned this Aug 3, 2026
The observability arm read JSONEachRow, so it proved ParallelParsingInputFormat
was constructed for that format, not for the TSV reads the two sum() checks
perform. Two of the five preconditions at FormatFactory.cpp:556-558 are
per-format registrations, so a TSV-only change could send both guarded queries
back to sequential parsing while the arm still printed PARALLEL.

The arm now reads the same TSV path with the same settings as the second
guarded query. A malformed row raises a parse error, and
ExecutionThreadContext.cpp:81 appends the raising node's getName(), which is
ParallelParsingBlockInputFormat only when that format was constructed. The
token occurs once in src/, where the previous one occurred nine times.

Verified: PARALLEL at max_block_size 8000/16000/32000/65536/100000 and at
max_parsing_threads 2/4/16; NOT PARALLEL when input_format_parallel_parsing=0,
when count() sets need_only_count, and when the memory guard fires. Forcing
!need_only_count false makes the test fail; neutering the guard makes it fail.
50/50 both shapes, no failures. The fixture drops from 32777 to 17 bytes.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

The TSV blind spot is fixed in c6beda1: the observability arm now reads the same TSV path and settings as the second guarded query, and asserts the constructed processor's name (ParallelParsingBlockInputFormat, which appears once in src/) rather than a segmentation-engine message on a different format. Mutation and sweep evidence is in the inline thread: #113080 (comment)

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c6beda1

CI is fully finished on this head (175 check-runs, 0 incomplete, Config Workflow and
Finish Workflow both success). Every failure below has an owner: a fixing PR (ours or
external), or a full-effort fix task whose fixing-PR link will be posted here when it
opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / 02015_async_inserts_5 Not PR-caused: the INSERT is rejected with Code: 252 Too many parts (1 with average size of 195.00 B) on a table at parts_to_throw_insert = 1, i.e. it counts the part it wrote itself. This PR only touches 01548_parallel_parsing_max_memory. The runner's own diagnosis agrees it is not attributable here: 12 reruns with the same randomized settings all passed #113045 (external, open)

The fixing PR names this exact test as one of four carriers of the same cause: since #109000
a plain INSERT writes through up to max_insert_threads sinks and every one of them runs
the parts_to_throw_insert check, unordered with respect to the other sinks' writes.

The Build (arm_release) / Post Hooks CIDB row is not a check failure: the
Build (arm_release) check itself concluded success. The build-profile hook logs
WARNING: LogCluster query failed with code 500 from the reporting sink, which is
infrastructure-side and does not affect the build artifact. It is fleet-wide right now
(963 rows across 315 distinct PRs in the last 3 days), and a separate fix task owns it.

The other 173 checks are green (the Bugfix validation nodes and the AST fuzzer are skipped:
this is a test-only change with no pr-bugfix category).

Session id: cron:our-pr-ci-monitor:20260803-220000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit 9804292 Aug 4, 2026
179 of 181 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 4, 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 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