Skip to content

Pin the JBOD least_used placement test to single-threaded inserts - #112500

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-jbod-least-used-next-disk-placement-pin
Jul 30, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-jbod-least-used-next-disk-placement-pin

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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

...

test_jbod_load_balancing_least_used_next_disk started failing on master and on unrelated PRs on
2026-07-29 (6 runs so far, 1 of them on master, against ~1500 passes that day). It asserts an exact
part-to-disk placement and got jbod1 where it expects jbod2. Master run:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=e0e5e04a027ed740ab3756d4853fb6d21126c077&name_0=MasterCI&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%203%2F6%29

That assertion is only well posed for single-threaded inserts. least_used picks the disk with the
most unreserved space at reserve time; getUnreservedSpace is statvfs f_bavail minus the
full reservation size (DiskLocal.cpp:308-313), and a reservation lives only while its own part
is written (MergeTreeTemporaryPart holds no ReservationPtr). So an in-flight part has its bytes
charged twice, and with several insert threads the choice depends on whether a concurrently writing
part's reservation is still live. Reproduced locally, byte-identical to CI:

[ 211 ] Reserved 108.00 MiB on local disk `jbod3`, having unreserved 300.00 MiB.
[ 209 ] Reserved 108.00 MiB on local disk `jbod2`, having unreserved 200.00 MiB.
[ 209 ] Reserved  92.99 MiB on local disk `jbod1`, having unreserved 100.00 MiB.   <-- wrong disk

jbod3 reports (300 - w) - 108, so idle jbod1 wins once ~92 MiB of jbod3's part has reached the
filesystem. The test passed for years because max_insert_threads defaulted to 1; #109006 changed
that default to auto, which exposed it. That change is correct and is not at fault.

This pins max_insert_threads = 1 on that one INSERT so the assertion runs in the mode where it is
deterministic. The assertion is unchanged and not weakened: with least_used deliberately broken to
always pick the first disk, the pinned test still fails.

The accounting error is conservative, so it cannot over-commit; separately it can refuse a
concurrent insert with NOT_ENOUGH_SPACE on tight disks. Neither is addressed here, both are filed
as follow-ups.

Validation

Pre-fix binary, arms alternated run by run so host load cannot bias either:

arm threads issuing the 3 reserves 3rd reserve chose diverged
default (auto) 2 29x jbod3 (unreserved 191.96 MiB), 1x jbod1 (100.00 MiB) 1/30
max_insert_threads = 1 1 30x jbod3 (unreserved 191.96 MiB) 0/30
  • Non-vacuity: mutating VolumeJBOD.cpp:172 to always take disks[0] reddens the pinned test with
    a real placement assertion failure; round_robin, which ignores free space, stays green. Because
    the natural divergence rate is well under 1%, this mutation, not a revert of this diff, is what
    shows the pinned test still catches a real regression.
  • Whole suite green post-fix (4 tests). 5 fresh clusters x 10 runs of the pinned test: 45 passed,
    0 assertion failures (5 runs lost to a container kill on a loaded host). Restoring the unfixed
    test file on the same host failed more often, also with 0 assertion failures, so those deaths are
    environmental.
  • GROUP BY disk_name appears in exactly one integration test file, this suite, out of the 31 that
    reference disk_name; test_jbod_balancer and test_ttl_move assert sets, not exact placement.
    No sibling test needs the same pin.

tests/integration/test_jbod_load_balancing/test.py::test_jbod_load_balancing_least_used_next_disk
asserts an exact part-to-disk placement. That assertion is only well posed when the
parts of one INSERT are written sequentially.

least_used picks the disk with the most unreserved space at reserve time.
DiskLocal::getUnreservedSpace is statvfs f_bavail minus the full reservation size
(DiskLocal.cpp:308-313), and a reservation lives only while its own part is being
written, because MergeTreeTemporaryPart holds no ReservationPtr. So while a part is
in flight its bytes are charged twice, and with several insert threads the chosen
disk depends on whether a concurrently writing part's reservation is still live.
With jbod3 mid-write it reports (300 - w) - 108 MiB, so the idle 100 MiB jbod1 wins
once about 92 MiB of jbod3's part has reached the filesystem, giving the observed
jbod1 placement.

The test passed for years because max_insert_threads defaulted to 1. Changing that
default to auto (number of CPU cores) made the reserves interleave and exposed the
latent ill-posedness. That default change is correct and is not at fault here.

Reproduced locally on a pristine master binary with the same log line CI shows
(Reserved 92.99 MiB on local disk `jbod1`, having unreserved 100.00 MiB). With the
two arms alternated run by run, 30 runs each: at the auto default two threads issue
the three reserves and placement diverged 1/30; at max_insert_threads = 1 a single
thread issues them and it diverged 0/30.

The assertion is unchanged and is not weakened. Mutating the LEAST_USED branch to
always take disks[0] still reddens the pinned test, while round_robin, which ignores
free space, stays green.

The accounting error direction is conservative, so it can never over-commit; it can
separately refuse a concurrent insert with NOT_ENOUGH_SPACE on tight disks. Both the
parallel-insert placement quality and that false rejection are tracked separately,
as is a dead DiskWithSize::reserve plus stale free_size on the
least_used_ttl_ms > 0 path.

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

groeneai commented Jul 30, 2026 •

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 findings) plus a cold
reviewer pass over the resulting code, run before this PR was opened.

# Sev Finding Verdict Evidence / action
1 💡 Independent gate pass over the diff, the whole test module, the fixture config, the insert threading path and the JBOD reservation path, including running the changed test no findings Diffstat reviewed matched the intended change exactly (1 file, +5/-2, 0 untracked), so the pass was against the right base
2 💡 A revert of this diff is not a usable liveness oracle, because the natural divergence rate is well under 1%, so the body must not imply one AGREE, fixed Body now states that the VolumeJBOD.cpp:172 mutation, not a revert, is what shows the pinned test still catches a real regression
3 💡 Countable claim wrong by one: "out of 30 integration files referencing disk_name" AGREE, fixed grep -rl disk_name tests/integration/ returns 31; corrected. The conclusion is unchanged, still exactly 1 file with GROUP BY disk_name
4 💡 No CI report URL for the failure this PR addresses AGREE, fixed Added the canonical master report URL taken from the CIDB report_url column. The same query showed breadth had grown 5 -> 6 runs, so the stale rate phrasing was replaced
5 ⚠️ black --check reports the changed file as "would reformat" DISAGREE Pre-existing: black --check fails identically on the merge-base revision. Blackening both revisions and diffing the two blackened outputs yields exactly and only the intended hunk, so zero new violations. No CI job invokes black on this tree
6 💡 Does a trailing SETTINGS on INSERT ... SELECT reach the sink at all, or only the SELECT context? verified, not a defect ParserInsertQuery.cpp:275 pushes the clause down, InterpreterInsertQuery.cpp:138 resolves it, InsertDependenciesBuilder.cpp:805 makes sink_stream_size 1. The pin is load-bearing
7 💡 Could the delayed-stream path keep two reservations live even single-threaded? verified, cannot DiskLocal does not override supportParallelWrite (IDisk.h:468), so max_insert_delayed_streams_for_parallel_write is 0 and each part is finalized before the next reserve
8 💡 Could the harness defeat the pin? verified, cannot The integration runner does no settings randomization (0 hits vs 11 in functional_tests.py), and applyCompatibilitySetting skips manually changed settings (Settings.cpp:9012)
9 💡 Carriers re-enumerated independently, then compared against the plan's list agreed, set closed GROUP BY disk_name in exactly 1 integration file; test_jbod_balancer and test_ttl_move assert sets; the other three tests here write kilobyte parts or ignore free space

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Items 2 to 4 were corrections to this PR's own description, applied
before publication.

Session id: cron:clickhouse-review-slot-9:20260730-001100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Reproduced locally on iteration 3 of 4 with the exact CI log line Reserved 92.99 MiB on local disk 'jbod1', having unreserved 100.00 MiB and placement 1@jbod1 1@jbod2 1@jbod3 vs the asserted 1@jbod2 2@jbod3. The trigger is a named structural condition, not a rate: two insert threads issue the three reserves, so one reserve observes another part's live reservation. Command: pytest test_jbod_load_balancing/test.py::test_jbod_load_balancing_least_used_next_disk --count N --repeat-scope=function against a pristine-master binary at the new max_insert_threads default.
b Root cause explained? Yes. DiskLocal::getUnreservedSpace (DiskLocal.cpp:308-313) is statvfs f_bavail minus the full reserved_bytes, and a reservation lives only while its own part is written (MergeTreeTemporaryPart holds no ReservationPtr). So an in-flight part's bytes are charged twice: unreserved(jbod3) = (300 - w) - 108 = 192 - w, and idle jbod1 (100 MiB) wins once w >= 92 MiB. With least_used_ttl_ms = 0 the queue is rebuilt on every reserve, so which disk is "least used at reserve time" depends on the interleaving. Measured margins matched: 91.96 MiB on passing runs, exactly 100.00 MiB reported for jbod3 on the failing one.
c Fix matches root cause? Yes. The failure is that an exact-placement assertion is ill-posed once reserves interleave with other parts' writes; the fix removes the interleaving variable at the assertion (max_insert_threads = 1 on that INSERT). It is not a widened bound, dataset reduction, skip, or no-random-* tag. The product-side accounting behaviour is not papered over: it is filed as a separate follow-up covering both placement quality and the spurious NOT_ENOUGH_SPACE half.
d Test intent preserved / new tests added? Yes. The assertion is byte-for-byte unchanged and still requires least_used to choose jbod3 then jbod2 then jbod3 by free space. Proven non-vacuous by mutation: with VolumeJBOD.cpp:172 changed to always take disks[0], the pinned test still fails with a real AssertionError: assert [['1','jbod1'...]] == [['1','jbod2'...]], while round_robin (which ignores free space) correctly stays green. No new test is added: this is a scoping change to an existing assertion, not a source fix.
e Both directions demonstrated? Yes, on the same pre-fix binary with the two arms alternated run by run so host load cannot bias either: default max_insert_threads (auto) gives 2 reserving threads and 1/30 divergence (the reproduction above); max_insert_threads = 1 gives 1 reserving thread and 0/30. An earlier 12-run matrix independently showed 1/12 versus 12/12. Post-fix the whole suite is green (4 tests, run twice), and 5 fresh clusters x 10 runs of the pinned test gave 45 passed with 0 assertion failures.
f Fix is general across code paths? Yes, carriers enumerated and each checked. least_used and least_used_detect_background_changes use several small separate INSERTs (bytes-scale parts, no long in-flight window) and are safe unpinned, confirmed green. round_robin ignores free space entirely (VolumeJBOD.cpp:146-157) and served as the regression control under the mutation. A dead DiskWithSize::reserve (zero call sites) plus stale free_size on the least_used_ttl_ms > 0 path is a distinct pre-existing defect, filed separately and deliberately untouched here.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for a test-scoping change: no code path, type wrapper or boundary value is affected. The equivalent sweep was done for the invariant instead ("an exact-placement assertion must pin the concurrency mode in which its placement is deterministic"): GROUP BY disk_name appears in exactly one integration test file, this suite, out of the 31 files referencing disk_name. test_jbod_balancer (:71) and test_ttl_move (:1208) assert sets, not exact per-disk counts, so neither is a carrier. No sibling test needs the same pin.
h Backward compatible? (maintainer-approved exception only) Yes, trivially: test-only. No setting default changes, no serialization format changes, so no SettingsChangesHistory.cpp entry is required. max_insert_threads is set per-statement inside a single test's INSERT and affects nothing else.
i Invariants and contracts preserved? Yes. No source contract is touched: git diff --name-only -- src/ is empty, and after the mutation arm was reverted src/Disks/VolumeJBOD.cpp hashes identically to git show HEAD: and the binary relinked back to the original Build ID. The test's own invariant is preserved and made explicit rather than weakened, and the previously implicit assumption (parts of one INSERT are written sequentially) is now stated in the SQL.

Session id: cron:clickhouse-impl-slot-6:20260729-231900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat, could you review this? The least_used volume rebuilds its free-space queue on every reserve, and getUnreservedSpace subtracts the full live reservation while statvfs already counts the flushed bytes, so once inserts run in parallel a reserve can see a mid-write part and the exact-placement assertion this test makes stops being well defined; this pins max_insert_threads = 1 on that one INSERT without touching the assertion.

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [969e444]

Summary: ✅


AI Review

Summary

This PR pins max_insert_threads = 1 on the exact-placement jbod_least_used integration test so the assertion stays deterministic after INSERT ... SELECT became parallel by default. I traced the current insert path and the JBOD reservation logic in the checked-out code: query-level SETTINGS are applied to the insert context, sink_stream_size comes from max_insert_threads, local disks do not enable delayed parallel writes, and the reservation used for disk choice is only held during writeTempPart. That makes the single-thread pin match the failure mode the PR describes, and I did not find an unresolved correctness or metadata issue in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 30, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I think the test test_jbod_load_balancing_least_used_next_disk got a fix merged into master yesterday. Do we still need this PR?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 969e444

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.

No failures on this commit. All 174 check-runs completed with zero non-success conclusions
(successes plus skips only), the workflow aggregator finished, and CIDB reports zero
FAIL/ERROR rows for this commit.

Session id: cron:our-pr-ci-monitor:20260730-163853

@azat
azat added this pull request to the merge queue Jul 30, 2026
@azat
azat removed this pull request from the merge queue due to a manual request Jul 30, 2026
@azat

azat commented Jul 30, 2026

Copy link
Copy Markdown
Member

@PedroTadim where?

@azat
azat added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 40ae807 Jul 30, 2026
178 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 Jul 30, 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.

5 participants