Skip to content

Fix the global memory tracker getting pinned at the previous peak after a one-shot correction to resident memory - #117738

Open
alexey-milovidov wants to merge 51 commits into
masterfrom
fix-117681-stale-memory-usage-in-total-limit-check
Open

alexey-milovidov wants to merge 51 commits into
masterfrom
fix-117681-stale-memory-usage-in-total-limit-check

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Closes: #117681
Related: #83981

MemoryWorker corrects the global MemoryTracker once on its first tick and whenever the tracker goes negative (memory allocated before the tracker was initialized and freed later). Since #83981 that one-shot correction used resident (jemalloc stats.resident or the cgroup memory usage). Right after a large query finishes, resident is still close to the query's peak because jemalloc keeps the freed pages dirty until they decay, so the tracker got pinned at that peak, and with the default memory_worker_correct_memory_tracker = 0 nothing lowers it afterwards. Every allocation, including the zero-byte check at connection start, then failed with MEMORY_LIMIT_EXCEEDED until the dynamic hard limit rose above the stale value. This is the picture from the issue: the "would use" side of the message frozen at the previous peak, while current RSS and maximum kept moving, because the rss side is refreshed on every tick.

The one-shot corrections now use jemalloc stats.allocated, which is the quantity the tracker accumulates (this is also what the code did before #83981). The continuous correction enabled by memory_worker_correct_memory_tracker keeps using resident, as it is re-applied on every tick and cannot get stuck.

Builds without jemalloc and without a sanitizer (ENABLE_JEMALLOC=0, LoongArch) have no counter of live allocations, so there the first-tick correction is skipped and a negative tracker is reset to zero; the description of memory_worker_correct_memory_tracker says so.

A gtest frees a lot of memory, drives the tracker negative and checks that the worker re-baselines it near the live allocations rather than near the resident memory. Without the fix it fails with the tracker corrected to 658 MiB while live allocations were 1.6 MiB.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix the server rejecting all queries with MEMORY_LIMIT_EXCEEDED for minutes after a large query: when the global memory tracker went transiently negative, the background memory worker re-baselined it to the resident memory, which right after a large query is still close to the query's peak, and nothing lowered it afterwards. The tracker is now re-baselined to jemalloc's live allocations.

🤖 Generated with Claude Code


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

…, not resident memory

`MemoryWorker` corrects the global `MemoryTracker` once on its first tick
and whenever the tracker goes negative (memory allocated before the
tracker was initialized and freed later). Since #83981 that one-shot
correction used `resident` (jemalloc `stats.resident` or the cgroup
memory usage). Right after a large query finishes, `resident` is still
close to the query's peak, because jemalloc keeps the freed pages dirty
until they decay, so the tracker got pinned at that peak. Nothing lowers
it afterwards with the default `memory_worker_correct_memory_tracker = 0`,
so every allocation, including the zero-byte check at connection start,
failed with `MEMORY_LIMIT_EXCEEDED` until the (dynamic) hard limit rose
above the stale value. The `rss` side of the check is refreshed on every
tick, which is why only the "would use" side of the message was frozen.

Use jemalloc `stats.allocated` for the one-shot corrections, which is the
quantity the tracker accumulates. The continuous correction enabled by
`memory_worker_correct_memory_tracker` keeps using `resident`, as it is
re-applied on every tick and cannot get stuck.

Add a gtest that frees a lot of memory, drives the tracker negative and
checks that the worker re-baselines it near the live allocations rather
than near the resident memory.

Closes: #117681
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4bdd095]

Summary: ❌

job_name test_name status info comment
Bugfix validation (unit tests) ERROR
Bugfix validation verdict ERROR

AI Review

Summary

The change prevents one-shot MemoryTracker corrections from retaining a freed allocation peak by using fresh jemalloc stats.allocated. It preserves sanitizer allocator accounting and documents the behavior without an allocator counter. Reviewed PR head 4bdd095da3636d1e850a88b99236e315f2f820b8; the previous findings are addressed, and no new actionable findings remain.

Missing context / blind spots
  • ⚠️ Current-head CI is still running, and this checkout has no local build for rerunning tests. Both MemoryWorker regression cases passed in the previous-head debug unit-test report. The relevant implementation and test files are unchanged since that run. Completed current-head CI will close the remaining validation gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4bdd095da with master 3dac6f430 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +13.0 s (+10%) in total before that adjustment.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117738&sha=d0ba6cd869c7df8a833bc583459b26c11969dd46&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The job failed with Container memory budget exceeded (/docker) plus test_s3_plain_rewritable/test.py::test[cache_s3_plain_rewritable-data/] and test_s3_plain_rewritable/test.py::test[s3_plain_rewritable_with_metadata_cache-data_with_cache/] (Connection refused, i.e. the servers were gone). These are unrelated to this pull request, which only changes which jemalloc statistic the one-shot global MemoryTracker correction uses in MemoryWorker. The same test_s3_plain_rewritable tests fail on master regularly - the CIDB history over the last 14 days shows failures on master on 2026-08-29, 2026-08-30, 2026-08-31, 2026-09-01, 2026-09-02, 2026-09-04 and 2026-09-06 - and I could not find an open issue tracking them.

master has been merged into the branch, so the next run will show whether the reds persist.

@groeneai

Copy link
Copy Markdown
Collaborator

The tree that failed predates the fix, so there is nothing new to author here.

Placement. The job's own log records Merge d0ba6cd8 into e6439467, and e6439467 (2026-09-02T15:49:09Z) compares ahead_by=0, behind_by=327 against 54b113db, the merge commit of #117564, so that fix is not in the tree that ran. #117202 (7fc3004e) and #117412 (d65ba26a) are both ancestors of it, confirmed independently by the job's own CI_DIND_INIT_RESERVE=8589934592 and 48.78 GiB /docker cap, which are the post-#117412 arm. The job finished 2026-09-02T22:03:30Z, 15h04m before #117564's merge commit existed, and your current head 847b15a8 carries it (ahead_by=4245, behind_by=0).

The two test_s3_plain_rewritable reds are that same breach, not a second failure. Five CONSTRAINT_MEMCG kills in oom_memcg=/docker/<dind>/docker at 21:07:12, 21:07:25, 21:07:33, 21:07:40 and 21:07:42, four task=clickhouse plus one task=gdb, with the /docker leaf at 48.78 of 48.78 GiB. On gw1, test[s3_plain_rewritable-data/] passed at 21:07:23 between two of those kills, then test[cache_s3_plain_rewritable-data/] failed at 21:07:44 and test[s3_plain_rewritable_with_metadata_cache-data_with_cache/] at 21:07:54, refusing 172.16.3.9:9000 and 172.16.3.6:9000, which are the test's own cluster nodes on the native port and not the object storage endpoint. Both were retried inside the same job and passed in 163.76 s (2 failed, 1279 passed, 23 skipped overall), so the CIDB rows are the first attempt only.

The leak arm is named by the interval rather than by victim identity: the two scope="session" modules #117564 rescopes both ran on this shard and left gw1 at 20:25:15 and 20:33:04, 34m08s before the first kill, so their clusters were resident and idle across the whole kill window.

Rate, measured now on old analyzer, 6/6, trees carrying the guard row over trees seen, 08-31 to 09-10: 311/534, 214/473, 76/458, 52/534, 0/488, 1/335, 0/284, 1/386, 0/467, 0/503, 0/204. The other five shards sit at 0 of about 2,760 trees each since the merge. Eight trees carried the row after 2026-09-03T13:07:47Z, and each one built a base that is a strict ancestor of 54b113db (ahead_by=0 in all eight, behind_by from 9 to 799), so no tree containing the fix has produced the row yet.

On the master history. With head_ref = 'master' AND pull_request_number = 0 these tests failed on two days out of the last 14, three rows in total (08-29 twice, 08-31 once), all Code: 210 Connection refused on this same shard. The seven dates appear once PR runs are included: 87 Connection refused rows over 45 trees between 08-29 and 09-02, plus 8 Connection reset and 8 Code: 32 Attempt to read after eof rows, all the same "the server went away" shape, the last of them on 09-04. The only later red is 09-06, and it is a different shape: six errors in wait_for_start at cluster start, on a tree that does carry 54b113db, in a job whose /docker leaf peaked at 31.68 of 48.78 GiB with zero kills. Nothing in the window carries NO_SUCH_KEY, so this is not the plain rewritable metadata class.

So the answer to the conditional is a link and not a PR: #117564, merged 2026-09-03T13:07:47Z. There is still no open issue for the class, and I have not filed one because the fix is merged and post-fix trees are at zero; say so if you would rather have one on the record.

alexey-milovidov and others added 2 commits September 18, 2026 00:24
…the cgroup-backed source

The one-shot re-baseline of the global `MemoryTracker` now goes through
`MemoryWorker::getJemallocAllocated`, which always advances the jemalloc
statistics epoch before reading `stats.allocated`, instead of doing so only
when the memory usage source is not jemalloc. The previous test used
`use_cgroup = false`, so it exercised only the `MemoryUsageSource::Jemalloc`
path, where `getMemoryUsage` refreshes the epoch anyway; the shipped
cgroup-backed configuration was uncovered.

The test body is now shared by two tests, one per memory usage source. The
cgroup one is skipped where no cgroup memory controller is available. The last
epoch refresh done by the test itself happens while the memory is still live,
so a worker that does not refresh the epoch re-baselines the tracker to the
stale peak snapshot and the cgroup test fails (verified with the refresh
removed: corrected to 654 MiB instead of 152 MiB). Dirty-page decay is disabled
per arena for the duration of the test, because jemalloc's background threads
purged the freed pages within the test's runtime often enough to break the
resident-vs-allocated premise.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 19, 2026
…obal memory tracker

A server whose global MemoryTracker::amount has drifted far above its real
memory usage refuses every allocation, down to the zero-byte
CurrentMemoryTracker::check() at connection start, while using a fraction of
its limit. In CI this lands as "Hung check failed, possible deadlock found",
so a real deadlock in the same run is invisible. ClickHouse#118094 and ClickHouse#117738 correct
the counter and ClickHouse#117995 stops the harness calling it a deadlock, but as
ClickHouse#118094 says itself, where the phantom bytes come from is still unknown.

Nothing records the add, for two structural reasons rather than bad luck.
The blocked-Global branch of allocImpl does amount.fetch_add, rss.fetch_add,
updatePeak and CurrentMetrics::add, then returns without ever reaching
commitAllocation, so it emits no hard-limit check, no trace, no ProfileEvent.
Everything that does reach commitAllocation is reported by
incrementAllocationWithoutCheck, whose payload lands in system.trace_log,
the sink the wedge itself breaks: in the measured run, 109 failed trace_log
flushes, 112 metric_log, 109 query_log, and not one memory trace of 1 GiB or
more in the whole run. The one channel that survives is the log file, which
carried all 31,310 refusal messages through the full 14-minute wedge.

So detect a single allocation at or above the new server setting
min_allocation_size_to_log_stack_trace on the two places where the global
amount grows and is not reverted, report it through TraceSender as a new
TraceType::MemoryLargeAllocation, and let TraceCollector symbolize it and
mirror one LOG_ERROR before the trace_log insert, so the stack survives when
the insert does not. This follows the pattern azat established in
e7a58e7, which added MemoryAllocatedWithoutCheck to trace_log and
deliberately removed direct logging from MemoryTracker because it can
deadlock: the send site captures an unsymbolized stack, since
StackTrace::toString takes the symbolizer cache mutex and allocates.

The wire format is deliberately untouched. The record is already 510 of the
512 bytes that keep the pipe write atomic, so the tracker total is read by
the collector at log time and labelled as such rather than carried in the
record, and no field is repurposed.

Traces are budgeted at 10 because symbolizing is expensive and the trigger
repeats. The budget refills only when the setting transitions from 0 to a
nonzero value: the config-reload callback calls the setter on every reload,
so refilling per call would have left no bound at all on a server that
reloads periodically.

The setter refuses a nonzero threshold when no trace collector is running
and warns once, because the collector only exists when trace_log is
configured and clickhouse-local never creates one; without it the setting
could only capture a stack and discard it. It is registered in
collectChangeableServerSettings through its getter so system.server_settings
reports the effective value after such a refusal.

Only the global tracker is instrumented. Process, User and Thread trackers
die with their query and their drift is already visible in
query_log.memory_usage, so instrumenting them would fire once per large
query. adjustOnBackgroundTaskEnd and updateAllocated are left alone because
measurement excludes them: both write amount and never rss, so neither can
produce the inflated rss reading these reports carry.

Default 0 keeps the diagnostic off; 8Gi under tests/config so CI gets it.
This does not fix the drift. It makes the next occurrence carry the stack,
which is the input issue ClickHouse#117681 is missing.

Related: ClickHouse#117681

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov and others added 2 commits September 24, 2026 11:00
…mory-usage-in-total-limit-check

Conflict in `src/Common/MemoryWorker.cpp` with f4e7b31 (`MemoryUsage{resident, allocated}`):
the one-shot re-baseline keeps `getJemallocAllocated` with jemalloc, and falls back to master's
`memory_usage.allocated` (sanitizer allocator bytes, otherwise resident) in builds without jemalloc.
`CurrentMemoryTracker::free` on the gtest main thread (which has a `MainThreadStatus`) also charged the
thread's own tracker, and the worker only re-baselines `total_memory_tracker`, so the thread tracker stayed
negative for later tests in `unit_tests_dbms`. Adjust the global tracker from a helper thread without
`ThreadStatus`, where `CurrentMemoryTracker` accounts to `total_memory_tracker` directly.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (it conflicted with f4e7b31 MemoryUsage{resident, allocated} in MemoryWorker.cpp). With jemalloc, the one-shot re-baseline still uses getJemallocAllocated. Without jemalloc, it now uses master's memory_usage.allocated. I also addressed the AI review's test-isolation Major: the synthetic late free now runs on a helper thread without ThreadStatus, so the gtest main thread's tracker stays intact. MemoryWorker.* gtests pass 5/5 locally.

About the previous reds: Bugfix validation (unit tests) is structurally inconclusive for this PR. It builds only ASan/TSan before-binaries, which have no jemalloc, so the USE_JEMALLOC-only regression test is compiled out. That's expected: sanitizer builds already re-baseline from sanitizer allocator bytes, so the bug doesn't exist there. Build profile diff failed on a CI logs cluster query (infra).

Comment thread src/Common/MemoryWorker.cpp Resolved
alexey-milovidov and others added 4 commits October 2, 2026 16:19
…n builds without jemalloc

Builds without jemalloc and without a sanitizer (`ENABLE_JEMALLOC=0`, LoongArch) have no
counter of live allocations: `memory_usage.allocated` is `resident` there, so correcting a
negative tracker to it could pin the tracker near the RSS peak of a finished query. Reset a
negative tracker to zero instead; keep `resident` only for the first run at startup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…acker in builds without jemalloc

`updateResidentMemoryThread` sleeps for one `rss_update_period_ms` before its first tick, so
memory can be allocated and freed before the first run; in builds without jemalloc and without
a sanitizer `memory_usage.allocated` is `resident`, which could still pin the tracker at a stale
peak. Do not re-baseline on the first run there; a negative tracker is still reset to zero.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the remaining review thread (the non-jemalloc, non-sanitizer path no longer re-baselines the tracker to resident on the first run).

About the red Bugfix validation (unit tests): it is inconclusive, not a refutation. The regression test in gtest_memory_worker.cpp is guarded by USE_JEMALLOC because the bug is about jemalloc's stats.resident vs stats.allocated, while the validator builds the "before" binary only on amd_asan_ubsan and amd_tsan, where jemalloc is disabled, so the cases are compiled out on both arms. In sanitizer builds the affected code path (re-baseline to sanitizer allocator bytes) is unchanged by this PR, so no sanitizer-only regression test can reproduce the bug. This needs a human decision (accept the inconclusive verdict) or a validator arm with jemalloc.

alexey-milovidov and others added 2 commits November 3, 2026 02:03
The started `MemoryWorker` publishes the fixture's resident memory (which
deliberately includes hundreds of MiB of dirty freed pages) via
`MemoryTracker::updateRSS`. Nothing refreshes it after the worker is
destroyed in the gtest binary, and `MemoryTracker::resetCounters` does not
reset it, so the stale RSS could fail the hard limit check in
`MemoryTracker::allocImpl` in later tests. Restore the previous value with a
scope guard declared before the worker and the allocations, so it runs on
every exit path, including skips and failed assertions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The red Bugfix validation (unit tests) check is inconclusive by construction, not a refutation: the bug only exists in jemalloc builds (the one-shot correction used jemalloc/cgroup resident instead of stats.allocated), so the regression gtest is guarded by USE_JEMALLOC. The validator builds the before-binary only for amd_asan_ubsan and amd_tsan, which have no jemalloc, so the cases are not registered there. In sanitizer builds, the correction used the sanitizer allocator bytes both before and after this change, so no regression test can fail on those arms. Mergeable Check is green. The test was verified to fail without the fix on a jemalloc build (the tracker was corrected to 658 MiB while live allocations were 1.6 MiB). Merged the latest master (which adds the OS memory usage source for builds without jemalloc; that is consistent with the non-jemalloc path here, which resets a negative tracker to zero).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (f4ca3f4334c2, no conflicts). master did not touch any of this PR's files, and the PR diff is still the same 4 files.

The red checks on c565a8cc do not come from this PR:

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117738&sha=c565a8cc94a9dd0a5261b8d2a40994f2b3540acf&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator

This is the row-policy route again (#112891): with serialize_query_plan = 1 only the initiator applies the row policy, so the initiator and the replicas plan different reads. The fix in progress is #114955 (mine, open, in review).

From this run (tree 71153b01aacf, query 1f71c6f4): the aborted query is the GROUP BY sensor_id ... ORDER BY sensor_id query of 4060_row_policy_projection_not_found_column.sql, with serialize_query_plan = 1 and 3 parallel replicas. The AST fuzzer had altered the test's policy to 'testtest' = tenant, which matches no part.

  • Initiator: MinMax index condition: (column 0 in ['testtest', 'testtest']), 0/1 parts selected by partition key, coordinator created as WithOrder with an empty announcement.
  • Both replicas (261d81a7, 1b1fd03e), deserialized plan without the policy: MinMax index condition: unknown, 1/1 parts, default reading, so they announce Default and getOrCreateCoordinator throws.

It is the same shape as the 2026-10-23 master run of this test. #114955 covers it in 04908_row_policy_serialized_plan_parallel_replicas.sql (a policy that matches no row, ORDER BY on the second key column): on its head 65fe8430, Bugfix validation hits this exact error with the master binary (got Default, expected WithOrder), and the test passes in the PR's own stateless runs, including the 5x flaky-check runs under ASan, TSan and MSan.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai. The Stress test (arm_asan_ubsan) failure (Coordination mode mismatch in ParallelReplicasReadingCoordinator) is the row-policy case that #114955 fixes, so nothing in this PR needs to change for it.

On f4ca3f43 the only red check is Bugfix validation (unit tests). Its result is inconclusive, not a refutation: the regression gtests are under #if USE_JEMALLOC, and the validator builds only amd_asan_ubsan and amd_tsan, which have no jemalloc. There are no conflicts and no unresolved review threads. I did not merge master again, because a merge cannot change that verdict. The PR now needs a human to review and merge it, accepting the inconclusive validation.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (8c333d7f8a19, no conflicts, the PR diff is still the same 4 files); MemoryWorker.cpp and gtest_memory_worker.cpp build locally.

The only red check on f4ca3f43 was Bugfix validation (unit tests), and it is inconclusive, not a refutation. The regression gtests are under #if USE_JEMALLOC, and the validator only builds amd_asan_ubsan and amd_tsan, which have no jemalloc. In sanitizer builds this PR deliberately keeps the old behavior (the tracker is re-baselined to the sanitizer allocator bytes), so no gtest there could fail without the fix. The groeneai comment was already answered: the Stress test failure is covered by #114955. There are no unresolved review threads. A human still needs to review and merge this.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (269db857df87, no conflicts; the PR diff is still the same 4 files). MemoryWorker.cpp (master moved the cgroup v2 level discovery into openCgroupsV2MemoryLevels) and gtest_memory_worker.cpp still compile. The only red check on the previous head was Bugfix validation (unit tests). As noted earlier, it is inconclusive by construction: that job validates only on amd_asan_ubsan and amd_tsan, which are built without jemalloc, so the #if USE_JEMALLOC regression test is not registered there. The bug and the fix only affect jemalloc builds, and the sanitizer path is unchanged. A human needs to decide whether to accept that check as inconclusive.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (0365c1d22b29, no conflicts). The PR diff is still the same 4 files. unit_tests_dbms builds on the merged tree, and both MemoryWorker.* cases pass locally (release build with jemalloc).

On 269db857 the only red check was Bugfix validation (unit tests). As explained above, that result is inconclusive, not a refutation: the validator only builds amd_asan_ubsan and amd_tsan. Those builds have no jemalloc, so the #if USE_JEMALLOC regression cases are not registered there, and the bug does not exist in sanitizer builds anyway.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (2b455a5cf2c2, no conflicts; the PR diff is still the same 4 files). MemoryWorker.cpp, ServerSettings.cpp and gtest_memory_worker.cpp compile on the merged tree.

Red checks on 9511adc0:

  • Stress test (arm_asan_ubsan, s3): heap-use-after-free in DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat (iterating a ColumnsDescription while ColumnsDescription::rename frees its nodes). This PR does not cause it. It is fixed by Fix use-after-free on renaming Delta Lake columns to their physical names #131029, which landed on master after the previous merge and is now in this branch.
  • Bugfix validation (unit tests): inconclusive, not a refutation, as explained above. The bug exists only in jemalloc builds, so the regression gtests are under #if USE_JEMALLOC. The validator builds only amd_asan_ubsan and amd_tsan, which have no jemalloc, so the cases are not registered there. Sanitizer builds already corrected the tracker from the sanitizer allocator bytes, so no test can fail on them without the fix. Unit tests (amd_debug) runs the new cases and passes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (e87f0995d83a, no conflicts; the PR diff is still the same 4 files). MemoryWorker.cpp, ServerSettings.cpp and gtest_memory_worker.cpp compile on the merged tree.

The only red check on 1a2e4248 was Bugfix validation (unit tests) (report). It is inconclusive, not a refutation, for the same reason as before. The validator builds the "before" binary only for amd_asan_ubsan and amd_tsan. Those builds have no jemalloc, so the #if USE_JEMALLOC cases in gtest_memory_worker.cpp are not registered. The bug and the fix exist only in jemalloc builds, and the sanitizer code path is unchanged. A human has to accept this check, or the validator needs a jemalloc arm. No code change in this PR can turn it green.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (573bbb2a8c90, no conflicts; the PR diff is still the same 4 files). MemoryWorker.cpp, ServerSettings.cpp and gtest_memory_worker.cpp compile on the merged tree (release build with jemalloc).

Red checks on 37d8562c:

  • Build profile diff: LogClusterNotReady: the endpoint never became ready. This is CI infrastructure, not this PR. CI: classify a timed-out "Build profile diff" readiness probe as a CI logs cluster outage #129675 classifies a timed-out readiness probe as a CI logs cluster outage; it landed on master after the previous merge and is now in this branch.
  • Bugfix validation (unit tests) (report): inconclusive, not a refutation, for the same reason as before. The validator builds the "before" binary only for amd_asan_ubsan and amd_tsan, which have no jemalloc, so the #if USE_JEMALLOC regression cases are not registered there, and the bug does not exist in sanitizer builds. This check will stay red on every run and cannot be fixed inside this PR; Mergeable Check is green.

There are no unresolved review threads. The PR is waiting for a human review and merge decision.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (0b5613b71424, no conflicts; the PR diff is still the same 4 files). MemoryWorker.cpp, ServerSettings.cpp and gtest_memory_worker.cpp compile on the merged tree (release build with jemalloc).

The only red check on 1d373177 was Bugfix validation (unit tests): inconclusive, not a refutation, for the same reason as before. The validator builds the "before" binary only for amd_asan_ubsan and amd_tsan, which have no jemalloc, so the #if USE_JEMALLOC regression cases are not registered there, and the bug does not exist in sanitizer builds. It will stay red on every run and cannot be fixed inside this PR. There are no unresolved review threads; the PR is waiting for a human review and merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (3dac6f430242, no conflicts; the PR diff is still the same 4 files). MemoryWorker.cpp and gtest_memory_worker.cpp compile on the merged tree (release build with jemalloc).

Red checks on a07b289a:

  • Fast test (arm_darwin): 05319_file_log_rename_in_reused_inode was killed by the test timeout (report). It is a FileLog test and this PR only touches MemoryWorker. In the last 14 days it failed one other time, on 2026-11-16 in Stateless tests (amd_debug, parallel) of another PR, and I found no open issue or PR for it. This was the only check failing Mergeable Check.
  • CH Inc sync (tests failed (1 new, 3 known)): the status was written by a private CI run on the previous head 1d373177, which started at the same time as the run on a07b289a. The run on a07b289a itself passed all jobs. In the stale run, Stress test (amd_tsan, SharedCatalog, meta in keeper) had a server abort with signal 6 whose core dump is from a MergeMutate thread. I could not read the stack trace, because the private report is not accessible from here. This PR does not change the code path of sanitizer builds (they still re-baseline the tracker from the sanitizer allocator bytes), so I treat it as unrelated; the new run will show whether it repeats.
  • Bugfix validation (unit tests): inconclusive, not a refutation, for the same reason as before. The validator builds only amd_asan_ubsan and amd_tsan, which have no jemalloc, so the #if USE_JEMALLOC regression cases are not registered there. It will stay red on every run and cannot be fixed inside this PR.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117738&sha=a07b289ad8179d88c10552564e08a39f4f7d2ca4&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 (05319_file_log_rename_in_reused_inode timeout) and provide a fix in a separate PR. If the fix is already in progress, link it here.

There are no unresolved review threads, and the PR is approved by the bot review. It still needs a human to merge it and to accept the inconclusive bugfix validation.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the 05319_file_log_rename_in_reused_inode timeout; I'll follow up here with a PR (or my findings) shortly.

@clickhouse-gh

clickhouse-gh Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Dear @azat, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@groeneai

Copy link
Copy Markdown
Collaborator

This is a real regression on macOS: since #125794 the watcher no longer records the unlink of a name whose file keeps another link, so b.csv, moved in from the link outside the directory, was paired with the removed a.csv and read from its offset (the server log shows onItemMovedFrom a.csv and onItemMovedTo b.csv in one batch; the test got 30, 40 instead of 10 to 40, then waited until the timeout). Fix: #133904. Reverting #125794 would also remove it. The 2026-11-16 failure is unrelated: that PR's randomizer set reader_executor_plan_look_ahead below twice reader_executor_window_size.

Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Nov 24, 2026
05319_file_log_rename_in_reused_inode timed out in Fast test (arm_darwin) of ClickHouse#117738:
one macOS scan saw a.csv gone and b.csv, moved in from a hard link outside the
directory, with the same inode, diffed them as MOVED_FROM a.csv + MOVED_TO b.csv,
and StorageFileLog kept a.csv's offset, skipping rows of b.csv.

ClickHouse#123593 made is_rename refuse a name in deleted_files as a rename source. Before
ClickHouse#125794 every NOTE_DELETE of a watched descriptor put its name there; ClickHouse#125794
(4d75ef8) returns early while the file still has links, because kqueue reports
an unlink of any name to every descriptor of the file and the scan has to find
which name went away (hidden excluded aliases of 05316_file_log_globs). When the
remaining link is outside the directory, nothing recorded the unlink any more.

Record the inode in that branch (unlinked_inodes), and in is_rename refuse the pair
when the inode's current name matches the path: the scan lists every matching name
and is_rename requires one listed name per side, so such a name was not a link of the
file at the last scan and the file came back, i.e. it is new here, as on Linux (an
IN_MOVED_TO without its IN_MOVED_FROM is ADDED). An excluded current name can be a
hidden alias and keeps ClickHouse#125794's behaviour. The set lives next to deleted_files: kept
across discarded and failed passes, cleared after a committed one, the first snapshot
included (its listing already reflects every unlink recorded before it, and it pairs
nothing). The unlink is drained before the diff (scanFilesAndUpdateWatches drains
before syncFileWatches closes descriptors), so the decision does not depend on scan
timing.

The test gains the same steps in one process so a macOS scan sees the unlink and
the move-in together; the new content is longer than c.csv's offset, so a carried-
over offset gives wrong rows (checked on Linux with a same-inode rename, which keeps
the offset: only 110 is read).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Server rejects all queries for minutes: the usage side of the total memory limit check freezes at the previous peak while the limit keeps updating

3 participants