Skip to content

Bound the integration tests' nested containers by the job's memory limit - #112984

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-integration-job-host-memory-margin
Aug 29, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-integration-job-host-memory-margin

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

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

Integration test jobs now charge their nested Docker containers to a cgroup bounded by the job's own --memory limit, instead of a cgroup outside it.

Description

Related: #112625

The bug. Under --cgroupns=host dockerd parents the nested containers at the host's /docker,
a sibling of the job's cgroup, so they are charged outside the job's --memory limit. Measured: a
limited child overran its cap with the job's cgroup at oom_kill 0.

The fix. The job asks for --cgroupns=private, making its own cgroup the namespace root;
docker_in_docker.sh caps three leaves there (/init, /dockerd, /docker) and refuses to start
the daemon rather than run uncontained. /init is capped by the job
limit less the leaves it does not overlap: its share alone killed two shards of this branch's CI, in
bursts of ~50-60 host-side clients, while four identical shards passed at 11.5-12.5 GiB. The caps
therefore no longer partition the job limit, so a breach of the job's own cgroup is reported too:
neither a leaf nor a host OOM, it had no owner.

Hard-timeout diagnosability. A run the backstop kills is past its budget, so the runner cancels it
mid-archive and nothing is uploaded: on job 95139621296 the archive got 13.3 s, and every diagnostic
sat behind it, which is why that wedge could not be attributed. The counters and the dmesg dump were
already collected, so only their order was wrong; they now print to stdout, the one channel a
cancelled job keeps, ahead of the archive. No row is derived from that buffer, which is neither
cleared nor scoped there. Only the hard backstop counts, as the graceful session-timeout leaves hours
of the job deadline. The archive is bounded there so a stuck one cannot reach that deadline, sized to
finish an ordinary archive rather than to fit the cancellation window, as no bound does both.

Behavior change. --dist=each drops from 3 workers to 2, concurrency now deriving from the
nested budget rather than host memory.

Validation detail

Every arm runs the real script in the runner image with children that request resource limits
(mem_limit: 12g, cpus: 5, pids_limit: 5000, as helpers/cluster.py applies); a limit-less
child cannot discriminate. The v1 arms run on a cgroup-v1 kernel booted with the runners' own
cmdline, since the unit fixture always has cgroup.controllers and so cannot see a v1 host.

Client.query forks one host-side client per concurrent query, which is what those bursts are, and
both killed shards died with the aggregate still inside the job limit. /init's charge is anon, so
unlike /docker reclaim cannot meet its cap. On v1 the leaves cap swap as well. The worker count is
40 GiB of nested budget on the 59.8 GiB carrier, against the 60 GiB that 3 workers budgeted.

check result
Escape reproduces without the fix 1900 MiB written past a 1500 MiB cap, job cgroup oom_kill 0
v1: before this change rc=3, daemon refused to start (the production failure)
v1: after containment active; 3 limited children vs a 2 GiB leaf give oom_memcg=.../docker, CONSTRAINT_NONE count 0, daemon alive
v1: harness placement migrated from the uncapped root into the capped /init
v2 unchanged: same caps, same leaf, delegation intact
Limited children start docker run and docker compose both rc=0
Harness overruns rc 137, kill in /init; other leaves clean; daemon alive
Parent-cgroup breach reported from the root counter and from dmesg, including a nested-container victim on v1
Archive bound enforced archiving into a reader-less FIFO is killed at its deadline, reporting no artifact
Ordinary archive fits the bound 413 MiB of logs archive in ~15 s

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

Version info

  • Merged into: 26.9.1.334 (included in 26.9 and later)

@groeneai

groeneai commented Aug 2, 2026

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

Pre-publication review by an independent reviewer plus an independent second-model gate, run
cold on the resulting code. This is round 7. The gate returned 0 findings at this head; my
own cold review returned 4 nits and no blocker or major, so nothing is being changed.

# Sev Finding Verdict Evidence / action
1 💡 Two sentences of measurement narrative remain in source where the commit message already carries the figures (_cgroup_own_limit_ooms), and leaf_oom_report repeats the Connection reset by peer chain stated four lines earlier AGREE, not fixed ~4 lines across a 1681-line diff. Both stated comment criteria are met: zero # blocks over 3 lines, and 73 added comment lines against 241 added code lines. I first graded this a major on a 59% ratio that wrongly counted docstrings as comments; corrected on re-measurement
2 💡 The dmesg backstop matches any oom_memcg= whose last path component is a leaf name, over a host-wide buffer, so in principle a second contained job's kill could be attributed here AGREE, not fixed Unreachable: clear_dmesg runs before the tests, a job reserves physical memory minus 2 GiB so two cannot co-reside, memory.events.local is the correctly scoped primary signal, and the pre-existing host-OOM scan has identical scope
3 💡 force_ok_exit is computed before the second leaf scan appends its row, so on a non-coverage job the pipeline-blocking metadata can be one row stale AGREE, not fixed Cannot report success: complete_job exits non-zero on any non-OK status regardless of that flag, and on coverage jobs, where the second scan matters, the flag is set unconditionally
4 💡 The ceiling on collective container memory drops to the nested budget, so a shard peaking between it and host memory now reports an ERROR where it was green AGREE, not fixed That narrowing is the fix. The harness's own model claims at most 33 GiB (loadfile) or 40 GiB (--dist=each), both inside the budget, and the failure mode changes from a 60 minute runner wedge to a named error. Disclosed in the body

Severity: 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.
Earlier rounds produced 1 blocker and 6 majors, all AGREEd and fixed; the last three rounds
carried no blocker.

Session id: cron:clickhouse-review-slot-9:20260802-060300

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for the defect this fixes. Outer docker run --privileged --cgroupns=host --memory=1500m -v <vol>:/var/lib/docker <runner image>, start the unmodified docker_in_docker.sh, then a nested --memory=4g --tmpfs /big:size=2g child writing 1900 MiB: it succeeds while the job's own cgroup reports oom_kill 0. The child's own limit can never fire, so only an ancestor's can. Not deterministic and not claimed: the runner-host wedge on #112625, which needs the real 61 GiB runner and its 144-module shard.
b Root cause explained? Nothing delegates cgroup controllers on the job container's own cgroup, so cgroup v2's no-internal-process rule leaves no delegated subtree inside the --memory limit for containers to go to. Under --cgroupns=host dockerd therefore parents them at the host's already-delegated top-level /docker, a sibling of the job's cgroup rather than a child, so the sum of the nested mem_limit: 12g defaults has no ceiling from the job's limit.
c Fix matches root cause? Yes: it delegates controllers inside the job's own cgroup (via a private namespace, which makes that cgroup the namespace root) and caps the leaf that parents the containers. No bound is widened, no dataset reduced, and no limit lowered. The earlier promise of shrinking --memory alone is measured to be inert, since the containers were never inside it, and is retracted in the body rather than shipped.
d Test intent preserved / new tests added? No existing test is weakened. ci/tests/test_integration_memory_limit.py now holds 129 tests, zero skips: the reserve invariants that can actually fail (the sum assertion alone is an algebraic identity, so a 20 GiB INIT_RESERVE used to pass everything and now reddens 20 tests), the worker-sizing invariant parametrized over 16/24/32/61 GiB rather than one hard-coded carrier size, the small-host boundary at 8 and 13 GiB, the leaf-overrun reporting including the tolerated per-container mem_limit case that must NOT be reported, and the containment shell block itself run against a fake cgroup tree. Both production wirings are driven, not only their helpers, because that is where the change's two headline behaviours live: restoring host memory at the worker-sizing call site or in the module global, re-implementing that sizing inline, deleting the leaf-OOM reporting block, keeping it while dropping either has_error or the test_results append, and removing the permissive guard are 7 separate mutants and each reddens at least one test. Every mutant tried reddens; an inert containment block reddens 32, deleting the EBUSY retry 1. The job's status decision is covered too: a leaf overrun makes the top-level status non-green on an LLVM-coverage shard as well as an ordinary one, while a clean run, a failure that passed on retry, and a real test failure each keep their existing status. The /init work that runs after the first leaf scan - the coverage shards' llvm-profdata merge, which is only printed on failure, never raised - gets its own second scan, and the production tail is driven by ast: deleting that scan, hoisting it above the merge, completing the job between the two, dropping the escalation, dropping the dedupe, or escalating a merge that failed on its own are 6 further mutants and each reddens at least one test. Delegation and process migration are asserted directly, since turning either into a no-op left every other test passing. Two oracle defects that mutation testing exposed were fixed: the budget helper mirrored the small-host clamp instead of reading production (so removing that clamp changed nothing observable), and two source-level assertions were string-sliced at the first ) rather than parsed with ast.
e Both directions demonstrated? Yes, same probe both ways. Without the fix the 1900 MiB write succeeds at oom_kill 0; with it the container is Killed and /docker reports the kill. Both overrun directions run: containers overrunning kills only in /docker, the harness overrunning only in /init, dockerd alive and responsive in each; a negative control leaving /docker uncapped kills the daemon. For the new reporting, three arms against the production functions: a clean run emits no result, a container reaching its own --memory emits no result (the pre-existing tolerated case), and a collective budget breach emits ERROR naming /docker. The late-scan path is driven both ways on a real fake tree: a leaf that breaches only between the two scans moves a green coverage shard to ERROR, while a clean tree, a merge that failed on its own, and a run without containment all leave it OK.
f Fix is general across code paths? Carriers enumerated programmatically, not by eye: every user of docker_in_docker.sh, and every run_in_docker combining --memory with a nested daemon. Only the integration job qualifies, and all 45 of its jobs get the fix, including the flaky and targeted --dist=each ParamSets, both Bugfix Validation jobs, and the eight amd_llvm_coverage shards whose status rules needed a separate fix so a contained overrun cannot report success there either. ci_tests (nested daemon, no --memory) and Keeper Stress stay on the byte-identical permissive path, verified both textually and at runtime.
g Fix generalizes across inputs? The parameter matrix is the runner carrier and the host size. Nothing in the repo maps a runner label to a memory size, so instead of pinning 61 GiB the invariant is asserted across 16/24/32/61 GiB x all four labels x both dist branches; worker_plan reports the honest per-worker share so it holds even where one modeled worker exceeds the whole budget, and warns rather than silently overcommitting. Boundaries: the reserves are absolute, so a host below their 11 GiB total is covered at both 8 and 13 GiB, where the budget is clamped to zero and the script refuses naming the host size and the reserve total instead of reporting a malformed variable; 16 GiB, one step above the break, is asserted to still run. A negative or zero budget still yields exactly one worker (previously -1, because -1 is truthy); an absent or empty budget falls back to host memory; a malformed one raises rather than silently restoring the overcommit. For the reporting: missing, unreadable and malformed memory.events files are all non-errors, each of the three leaves is named in its own result, and a host OOM is not double-reported as a leaf overrun. The dmesg backstop is per leaf and names the leaf it finds, so one leaf's counter firing cannot suppress another's dmesg record and a leaf present in both signals still yields exactly one row; restoring the per-report gate, discarding the name, or dropping the dedupe reddens 1, 4 and 4 tests.
h Backward compatible? Yes. No setting default and no serialization or format change, so no SettingsChangesHistory.cpp implication. LIMITED_MEM is untouched and still shared with the stateless job, so no memory limit moves. Non-cgroup-v2, cgroup v1, local and macOS runs are carried by the unchanged permissive path. python3 -m praktika yaml regenerates every workflow with zero .github/ drift. Two deliberate behavior changes are stated in the body: the --dist=each worker count dropping from 3 to 2, and a pytest session error on a coverage shard now reporting ERROR instead of green. A host below the 11 GiB reserve total is a third: praktika/runner.py imports the job configs on whichever machine runs the job, so a developer under 13 GiB now gets a refusal naming the host size rather than an uncontained run. CI is unaffected, measured: all four runner labels report 61.65-61.78 GiB, including both *_SMALL_MEM rows.
i Invariants and contracts preserved? The invariant added: the reserves plus leaf budgets never exceed the job's limit, so a leaf always reaches its limit before the job's cgroup does, keeping the daemon out of the OOM scan. It is asserted in the script and refused if violated. On every error path the script exits non-zero without starting a daemon, which the degrade arms assert directly by checking that neither the socket nor the process exists. The delegation is race-safe: it retries the migrate-then-enable pair, because a process appearing in the root cgroup between those steps makes the enable fail with EBUSY.

Session id: cron:clickhouse-impl-slot-7:20260802-030900

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Felixoid @fedotovalexei, could you review this? Integration jobs run a nested Docker daemon under --cgroupns=host, so it parents its containers at the host's /docker, a sibling of the job's own cgroup, and the job's --memory bounds only the harness while each test container defaults to 12g. This switches the job to --cgroupns=private and has docker_in_docker.sh delegate controllers at the namespace root and cap three leaves whose sum stays inside the job limit.

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

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18428a0]

Summary: ✅


AI Review

Summary

This PR moves the integration-test job family onto cgroup-contained nested Docker, derives worker concurrency from the nested-container budget, adds synthetic OOM reporting/diagnostics, and bounds the image pre-pull path. The current head fixes many earlier review issues, but I do not think it is ready to merge yet: part of the new containment contract can still regress without scheduling the relevant jobs, Keeper Stress remains on the old uncontained nested-Docker path, and the focused regression suite for the new cgroup logic was dropped without replacement.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Bound the integration tests' nested containers by the job's memory limit #112984#discussion_r3787564325] [ci/defs/job_configs.py:219-234] The containment contract now partly lives in common_integration_test_job_config.run_in_docker, but this job still does not treat ci/defs/job_configs.py as affecting. The earlier dismissal relied on ci/tests/test_integration_memory_limit.py catching config-only regressions; that suite is now gone and there are no remaining focused ci/tests for the CI_DIND_* wiring, so a config-only regression here can merge without either the integration shards or a focused harness test running.
  • [dismissed by author -- https://github.com/Bound the integration tests' nested containers by the job's memory limit #112984#discussion_r3845487344] [ci/defs/job_configs.py:1397-1404] The same nested-Docker-under---memory escape this PR fixes for the integration shards is still present in Keeper Stress: the job runs integration-tests-runner under --memory, starts docker_in_docker.sh, and then launches nested containers via docker compose up -d, but it never opts into --cgroupns=private or the CI_DIND_* containment env. That leaves one sibling job on the exact unsafe path the PR documents as broken.
Tests
  • ⚠️ [ci/jobs/integration_test_job.py:111-418] After the dedicated ci/tests/test_integration_memory_limit.py arm was dropped, nothing in-tree now pins the new CI_DIND_* worker-budgeting, v1/v2 cgroup parsing, or synthetic OOM/job-cgroup reporting. The surviving ci/tests cover adjacent helpers (Shell.run retry/timeout behavior, RabbitMQ reporting), not this contract. A focused regression suite for the containment shell block plus nested_budget_gb / leaf_oom_report / job_cgroup_oom would close the main evidence gap.
Final Verdict

Needs changes before merge.

LLVM Coverage Report

⚠️ No coverage measurement for commit 18428a0: no coverable C/C++ source files changed (contrib/ is excluded from coverage).

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 2, 2026
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI on this PR is red in a way that refutes the change, so I am reporting that rather than
pushing a fix.

All six Integration tests (amd_asan_ubsan, db disk, old analyzer, N/6) shards failed at
startup, each with the same RuntimeError: docker_in_docker.sh exited early (rc=3) and the
same docker-in-docker.log line, which is my own precondition firing:

cgroup containment is required but [/sys/fs/cgroup/cgroup.controllers] is missing
(not cgroup v2); refusing to start an uncontained daemon

The runners boot with cgroup v1. From the job's dmesg.log:

Command line: BOOT_IMAGE=/boot/vmlinuz-6.8.0-1055-aws ... ro systemd.unified_cgroup_hierarchy=0

systemd.unified_cgroup_hierarchy=0 disables the unified hierarchy, so there is no
cgroup.controllers, no cgroup.subtree_control, no memory.max and no
memory.events.local. Every mechanism this PR relies on needs cgroup v2. It is not
per-instance: the six shards ran on six distinct m7i.4xlarge instances
(i-033f55db2060092d2, i-0d0b110d97b2af59d, i-020a215c021fbf3c7,
i-0631c8a88014a4872, i-0dca16298338c6207, i-002b2b4cf142cc42a) and all six report the
same kernel command line. The host df in each job.log agrees: tmpfs 4.0M /sys/fs/cgroup,
where a v2 host shows cgroup2.

--cgroupns=private itself is fine. The container started and pulled its image; the refusal
is mine, inside it. Cgroup version is inherited from the host, so the flag has nothing to make
private on a v1 runner.

This is why the block I re-enabled was left commented out in 2e12131a1de236a rather than
deleted: on a v1 host its [ -f /sys/fs/cgroup/cgroup.controllers ] guard made it a silent
no-op, which is the state master is in today.

My local measurements could not have caught this. They were taken on a cgroup v2 machine, and
ci/tests/test_integration_memory_limit.py drives the script against a fake tree via
CI_DIND_CGROUP_ROOT, which always has cgroup.controllers.

45 jobs carry the containment environment (43 Integration tests, 2 Bugfix validation), so
all 45 fail this way, not just the six that ran here.

Two questions, because I would rather ask than guess:

  1. Is moving the Linux runner AMI to cgroup v2 (dropping
    systemd.unified_cgroup_hierarchy=0) something the CI team wants? The AMI is not in this
    repo (ci/infra/cloud.py pins only the macOS images), so I cannot do it in a PR, and I
    found no issue or PR tracking such a migration.
  2. If v1 must keep working, the containment has to be rewritten against
    memory.limit_in_bytes under /sys/fs/cgroup/memory/, which is a different mechanism with
    different OOM reporting. That is a redesign, and I would want agreement before building it.

What I will not do is make the precondition fail open. The PR promises that the nested
containers are bounded by the job's limit; on these runners nothing would bound them, so
failing open would ship a guarantee that is not there. One behaviour change does survive
regardless of containment, and it is worth knowing: worker concurrency is derived from
CI_DIND_NESTED_BUDGET, which is set from the job config rather than measured from the
cgroup, so --dist=each jobs go from 3 workers to 2 whether or not the cgroup work succeeds.

@clickhouse-gh[bot]'s finding on ci/tests/test_integration_memory_limit.py is separately
correct: the file reads the importing machine's live Utils.physical_memory(), so on a host
below the reserve floor the budget clamps to 0 and two assertions fail. I will fix it with
the _budget_for / reload pattern the rest of the file uses, and add a small-host case
asserting the clean refusal, once the question above is settled. Fixing it now would only
make a suite green for a mechanism that cannot run.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0c997e9

All 174 checks completed: 11 success, 157 skipped, 6 failure. Every failure is PR-caused and
owned by this PR. Nothing here is flaky or infrastructure.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) PR-caused: this PR's cgroup-v2 precondition refuses on a cgroup-v1 runner (docker_in_docker.sh rc=3) fixed in this PR, pending the design decision asked for in issuecomment-5158203603
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) same signature, different instance as above
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) same signature, different instance as above
Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) same signature, different instance as above
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) same signature, different instance as above
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) same signature, different instance as above

The 45 jobs carrying the containment environment (43 Integration tests, 2
Bugfix validation) would fail identically; these six are the ones this workflow selected.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cgroup v1 rewrite done, and the refusal is gone

Taking the fork back per #113719 (comment):
route 2, containment rewritten against cgroup v1, pushed as 58b0a8d. Route 1 (moving the Linux
runner AMI to cgroup v2) is still the cleaner end state and still belongs to the CI team; this
change becomes dead code on the day that happens, which I think is the right trade against 45 jobs
being down.

Verified on an actual cgroup-v1 kernel, not the fake tree. That matters here: the unit suite
drives the script against CI_DIND_CGROUP_ROOT, which by construction always has
cgroup.controllers, so no arm of it, and none of the 8 mutants, could ever have seen a v1 host.
That is precisely why this blocker survived the earlier review rounds. So I booted a guest with the
runners' own cmdline (systemd.unified_cgroup_hierarchy=0, giving the same tmpfs 4.0M /sys/fs/cgroup and cgroupfs / 1 driver the jobs report) and ran the real script there:

before after
cgroup v1 (production) rc=3, cgroup.controllers is missing, daemon refused containment active, all leaves capped
cgroup v2 works unchanged: same caps, same leaf, delegation intact

With production's own container flags (--memory=12g --cpus=5 --pids-limit=5000, as
helpers/cluster.py applies) and a nested daemon, three children overrunning a 2 GiB /docker
leaf give the kernel's own attribution:

oom_memcg =/docker/b78c9852c0cf/docker              <- the capped leaf was breached
task_memcg=/docker/b78c9852c0cf/docker/f782d8974bda  <- a test container was the victim
CONSTRAINT_NONE count = 0                            <- no host OOM

The daemon stayed alive and serving. A 300 MiB control in the same limited container reaches its
target, so the kill is attributable to the cap and not to a broken probe.

One asymmetry worth flagging rather than burying. Enforcement ports and gets simpler, but
reporting does not, so v1's guarantee is deliberately weaker in one place. There is no v1 counter
that answers "was THIS leaf's limit breached": memory.oom_control's oom_kill is charged to the
cgroup of the killed task, so a collective overrun of a leaf leaves that leaf's own counter at 0;
and memory.failcnt counts limit hits that reclaim satisfied, which I measured at 775428 on a
cache-heavy run that killed nothing, against 61 on a run that did. Wiring either one up would
respectively miss every breach or fail healthy jobs, so on v1 the dmesg scan is the whole detector.
oom_memcg= does name the breached cgroup on both versions, so that scan needed no change, and I
confirmed it against real v1 kernel lines for both a collective breach and a container hitting its
own mem_limit. The practical loss is the counter backstop for a mid-run daemon restart.

Also in this push: the harness now moves into the capped /init on v1 too. On v2 that happens
as a side effect of the delegation loop, which is v2-only, so my first version left pytest and its
xdist workers in the uncapped root with an empty 8 GiB /init leaf, meaning a harness overrun
would still have hit the job's own limit. That is the outer OOM this PR exists to prevent, so it
would have shipped a change that did not do its main job on the very hosts it targets. Measured
before and after on the v1 guest.

The review comment about the regression suite reading live host memory is fixed in the same push
and answered inline. 149 tests pass as both root and an unprivileged user.

Session id: cron:clickhouse-maint-slot-13:20260809-024502

Comment thread ci/jobs/integration_test_job.py Resolved
Comment thread ci/defs/job_configs.py
# a sibling of this cgroup, so `--memory` bounds only the harness. Explicit because the
# daemon default is configurable and `host` would silently restore that leak.
run_in_docker=f"clickhouse/integration-tests-runner+root+--memory={LIMITED_MEM}+--privileged+--dns-search='.'+--security-opt seccomp=unconfined+--cap-add=SYS_PTRACE+{docker_sock_mount}+--volume=clickhouse_integration_tests_volume:/var/lib/docker+--cgroupns=private+--ulimit nofile=262144:262144{integration_dind_env}",
post_hooks=[

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.

This change moves a critical part of the containment contract into common_integration_test_job_config.run_in_docker, but the integration job still does not treat ci/defs/job_configs.py as an affecting path. Right now:

common_integration_test_job_config.is_affected_by(["ci/defs/job_configs.py"])
# False

So a future config-only regression here, such as dropping --cgroupns=private or one of the CI_DIND_* envs, will skip the end-to-end integration shards entirely. Please add ./ci/defs/job_configs.py to this job's digest_config.include_paths.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your is_affected_by measurement is correct: common_integration_test_job_config.is_affected_by(["ci/defs/job_configs.py"])
is False, with ci/jobs/integration_test_job.py, ci/jobs/scripts/docker_in_docker.sh and
tests/integration/ all returning True as controls. I am not making the change, for two
measured reasons.

The regressions you name are already caught. JobConfigs.ci_tests has ./ci in its
include_paths, so ci_tests.is_affected_by(["ci/defs/job_configs.py"]) is True, and
ci_tests_job.py runs pytest ci/tests/. Two of those tests pin this contract, so I mutated
the file to check they are not vacuous:

  • deleting +--cgroupns=private fails test_job_requests_a_private_cgroup_namespace
  • deleting the CI_DIND_NESTED_BUDGET env fails test_job_passes_the_budget_and_reserves_to_the_script

Both mutants were killed, and the tree was restored and re-verified green after each. A
config-only regression therefore reddens CI Tests, not silently nothing.

The cost is also concrete. ci/defs/job_configs.py took 88 commits in the last 30 days, and
every one of those touched no path currently in this job's include_paths, so the change would
newly trigger the full six-shard integration matrix 88 times a month, on this specific family.
That is the family the parent PR exists to stop wedging its runners.

Convention agrees: of 220 job configs, 210 have non-empty include_paths and 0 include
ci/defs/job_configs.py. CI Tests is where config-shape regressions are meant to land, and it
covers this one.

@groeneai
groeneai force-pushed the fix-integration-job-host-memory-margin branch from 58b0a8d to e24d46c Compare August 15, 2026 05:01
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed a fix for the /init overrun this branch's own CI hit, plus the defects an internal review round found on the way. Squashed to one commit (the tree is byte-identical to the 16-commit version).

The failure. Shards 4/6 and 5/6 of run 31299101298 reported Harness memory limit exceeded (/init), with 17 and 10 cgroup OOM kills against /init, zero CONSTRAINT_NONE host OOMs, and zero kills against /docker, whose budget was never breached. pytest itself was killed while tests were still passing, so the accompanying test_ttl_move / test_jbod_balancer / azure failures on those shards are collateral rather than independent defects.

Cause. The 8 GiB /init reserve modelled the leaf as pytest, its xdist workers and the post-teardown steps. It missed the dominant term: helpers/cluster.py builds every node's Client around a host-side clickhouse-client, and helpers/iceberg_utils.py runs Spark with a local master, so the per-test clients and the driver JVM are charged to /init and not to a container. That tracks xdist concurrency, which a single constant cannot follow. The reserve is now a third of the job limit, floored at 8 GiB and capped at 16; the cap is the largest value that costs the container budget no worker in either distribution mode.

One correction to my own earlier note. I first put the demand at 12-15 GiB by summing the kernel's OOM task dump. That is wrong: on cgroup v1 the dump enumerates the whole hierarchy, not the breached cgroup. The cgroup-scoped figure is total_rss 7.89-7.91 GiB against an 8388608 kB limit, i.e. every observation is censored at the cap it broke. So 8 GiB is provably insufficient, but the true requirement is not recorded anywhere in that run, and 16 GiB is a headroom choice rather than a measured peak. Each leaf's peak is now printed against its cap and flagged when the two are equal, so the next sizing decision can come from a number instead of a bound - this run should produce the first such reading.

Also fixed, each with a mutation-verified test:

  • v1 and v2 both limit swap per leaf now. v1's memory.memsw.limit_in_bytes failures were all suppressed and v2's separate memory.swap.max was never written, so a leaf could exceed its advertised budget by swapping; a leaf that cannot be swap-limited refuses unless the host provably has no swap.
  • The peak readout looked under <root>/<leaf>, but on v1 the leaves live at <root>/memory/<leaf> and the runners are v1, so it would have reported nothing exactly where the reserves are enforced.
  • The leaf-OOM report sat behind the local-run guard that only the host-wide dmesg dump needs, so a contained kill was invisible on a local run - including one during the coverage merge, which is not raised on failure.
  • test_job_passes_the_budget_and_reserves_to_the_script asserted the job limit and nested budget but none of the three reserves it also exports; a stale exported /init reinstated this bug with the suite green.
  • On v1, /docker's counter moves on the killed container and that cgroup is gone by teardown, so a collective breach there is only visible in dmesg. A run without dmesg now says so rather than implying it checked.

ci/tests is 722 passing locally; the 7 failures on this host are pre-existing and reproduce identically on a clean checkout of the previous head (they need a live server binary).

Comment thread ci/jobs/integration_test_job.py Resolved
Comment thread ci/jobs/integration_test_job.py Resolved
Comment thread ci/jobs/integration_test_job.py Resolved
Comment thread ci/jobs/integration_test_job.py Resolved
Comment thread ci/jobs/scripts/docker_in_docker.sh Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 94e55494b with master 762e8e123 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 709.21 MiB 706.16 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

6 translation units recompiled, 4 s compile time in total, 6 of them have a recent master baseline.

Job report

_SHELL_INT_MAX = 2**63 - 1


def nested_budget_gb(env=None, physical_memory=None) -> int:

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.

After 3f8ebf8 dropped the dedicated ci/tests/test_integration_memory_limit.py arm, there is no focused regression coverage left for this whole CI_DIND_* path. I checked the current ci/tests/ tree and there are no remaining references to CI_DIND_*, leaf_oom_report, job_cgroup_oom, dind_unreportable_ooms, or the containment shell block; the surviving tests only cover adjacent helpers like the outer image-pull retry path and timeout plumbing.

That leaves the v1/v2 cgroup parsing, worker-budget wiring, and synthetic OOM/job-cgroup reporting to be validated only by the full integration matrix, which is exactly the kind of coverage gap that let several earlier regressions on this PR survive until they hit real shards. Please keep a focused regression suite for this contract before merging.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and already disclosed in #112984 (comment) at 03:00Z, 71 minutes before this comment: at 18428a05 there are 0 references under ci/tests/ to CI_DIND_, leaf_oom_report, job_cgroup_oom or dind_unreportable_ooms.

The causal premise does not hold, though. That arm ran on 6 heads of this PR between 08-15 and 08-25: 328 cases at the last of them, 1768 case executions, 0 failures. The defect the previous round here found (the archive block keyed on failed_suits, with the synthetic rows appended after the relabel) was present in all six of those heads and the arm passed on every one; the only red CI Tests rows on this PR come from ci/tests/test_settings_history_source_gate.py, a different file.

I am not restoring it, because there will be nothing left to run it. #114675 merged on 08-15 (+0/-6543, 32 files, all under ci/tests/), and #115650 removes the rest of the directory (64 files on master today) together with the only executor: ci/jobs/ci_tests_job.py, plus JobNames.CI_TESTS, the ci_tests job config and its entry in .github/workflows/pull_request.yml. Nothing else in the tree runs pytest over ci/ python; tests/ci has no test files and is mypy-only, ci/praktika has none. #115650 is still open as of this comment, last synced with master at 01:41Z today.

The gap is narrower than the whole CI_DIND_* path. The containment block is fail-closed at 18 refusal sites in docker_in_docker.sh and runs in all 35 integration job instances of the PR workflow, so a regression in the env contract, the v1-vs-v2 detection, the private-namespace check or the budget arithmetic turns those jobs red. What is only exercised is the reporting side: leaf_oom_report and job_cgroup_oom execute when a leaf actually breaches, so a regression there stays silent until one does, and by that function's own contract a killed run could then finish green.

If a home for a focused suite survives #115650, name it and I will add a small one for that reporting side; those helpers take env and cgroup_root arguments, so they need no docker.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into ClickHouse:master with commit 2e51746 Aug 29, 2026
174 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Aug 31, 2026
`docker compose stop` signals every container of a cluster at once, so every node whose
server outlives the entrypoint's 60 second deadline attaches gdb at the same moment. gdb
has to read the whole binary's debug info to walk the stacks, measured at 3.4 GiB of
anonymous memory on an ASan build and 4.3 GiB on the coverage one, so a nine node cluster
asks for around 40 GiB - the entire budget `docker_in_docker.sh` gives the cgroup that
holds the nested containers. The kernel kills the gdb processes and the job reports
`Container memory budget exceeded (/docker)` with no stacktrace to show for it: on
2026-08-30 that failed `Integration tests (amd_llvm_coverage, 4/8)` four times and
`Integration tests (amd_asan_ubsan, flaky)` once, every time with 8 to 10 gdb processes
alive at the instant of the kill and every test in the batch otherwise green.

The attach is now taken under a lock on the repository mount, the only path every
ClickHouse container of every pytest worker shares, so the job as a whole holds one gdb at
a time instead of one per node. The pid is re-checked once the lock is held, which is what
keeps the common case free: a server that was merely slow rather than stuck exits while its
turn is waited for, and then there is nothing to attach to. A node that does not get its
turn within 240s says so and is skipped, because the wait has to leave room inside the
container's 10 minute `stop_grace_period` for the deadline and for gdb itself.

The `/docker` cap that turns this pre-existing overrun into a reported failure arrived with
the pull request below; before it the nested containers were charged outside the job's
memory limit.

Related: ClickHouse#112984

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=f14f29dd31bbb4861b7c9a4d47cd65750145d8a0&name_0=MasterCI&name_1=Integration%20tests%20%28amd_llvm_coverage%2C%204%2F8%29
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 1, 2026
…y use

`docker_in_docker.sh` splits the integration job's memory limit into three capped cgroup leaves,
and `/docker` - the one that parents every nested test container - is sized last, from whatever
the other reserves leave. On the 61.78 GiB runner that is 40.78 GiB, and it is not enough: over
58 job runs `/docker` peaked at exactly its cap in all 58, so the kernel is picking a victim
whenever anything asks for more. The job then reports `Container memory budget exceeded
(/docker)` while every test in the batch passes - 15 of the 26 master runs of
`Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6)` after 2026-08-31 12:00, and
before that shards 2/6 and 5/6 as well.

The sizing rests on an assumption the kernel's own OOM report refutes. It gives `/init` a third
of the job limit and `/docker` the remainder, on the grounds that `/init`'s charge is anonymous
while `/docker` holds page cache reclaim can give back. Measured at the kill, `/docker` holds
40.35 GiB of anonymous memory against 753664 bytes of cache - not one page of it is reclaimable.
`/init` and `/dockerd` are the ones running on cache: they peak at 20.8 GiB and 18.3 GiB against
reserves of 16 GiB and 2 GiB, 20 GiB above what the partition promises them, and the job cgroup
still never breaches, because reclaim takes that back. The only leaf that cannot give anything
back is the one being sized last.

So `/init` keeps the floor instead of the share, and `/docker` gets the 8 GiB that frees:
48.78 GiB against a measured peak of 40.35 GiB of servers plus the 3.4 to 4.3 GiB a shutdown
`gdb` attach adds on top of them. `/init`'s own ceiling is unchanged - the reserve was never its
cap - so this takes away none of the room it uses. Worker concurrency is unchanged too: the plan
derived from the budget stays at 3 workers (and 2 under `--dist=each`), so no job runs longer for
this.

This is the remainder of the same overrun ClickHouse#117202 addressed. Serializing the shutdown `gdb`
attaches removed the 4-at-once pile-up and fixed shards 2/6 and 5/6, but in 6/6 the servers alone
reach 39.30 GiB across 34 processes, so a single 4 GiB attach no longer fits either - and half
the kills there have no `gdb` in them at all.

Related: ClickHouse#117202
Related: ClickHouse#112984

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=25dfbdb6c5dd3c0bd78c7134c14045ddb7647bcf&name_0=MasterCI&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai manual approve Manual approve required to run CI 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.

4 participants