Skip to content

Fix deadlock on concurrent resolution of one Filesystem or HDFS table - #112495

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-databasefilesystem-mutex-convoy
Aug 7, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-databasefilesystem-mutex-convoy

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107941

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

Fixes a deadlock that permanently wedges a Filesystem or HDFS database when two queries resolve the same table name at the same time. Every later query against that database blocks forever and cannot be interrupted, so the server needs a restart to recover.

Description

DatabaseFilesystem::getTableImpl probes the table cache and inserts into it under two separate mutex acquisitions, with schema inference between. Two same-name queries both miss, both build a storage, and the loser reaches a throw in addTable whose message calls IDatabase::getDatabaseName, which locks the non-recursive IDatabase::mutex addTable already holds, so the thread parks forever holding it.

Every later access blocks in tryGetTableFromCache, and a std::mutex wait has no cancellation point, so neither KILL QUERY nor the hung-check breaks it. DatabaseHDFS has a byte-identical addTable.

One mechanical change per engine: addTable returns loaded_tables.emplace(...).first->second and getTableImpl returns that, yielding the cached storage whether or not the insert happened. Losing the race becomes benign, and deleting the throw takes the accessor out from under the lock.

Found by Stress test (arm_debug) on an unrelated PR (report): 56 of 61 stuck queries queued behind one self-deadlocked thread. It recurred on 111990 (amd_debug), 62 of 74 stuck rows on this mutex.

A new stateless test hangs on unmodified master. Restoring the original addTable makes it hang in 20 of 20 runs, against 20 of 20 green with the fix. 50 randomized runs pass. Sweeping every mutex scope in src/Databases/ for calls to the four IDatabase accessors that relock it finds these two.

It drives those 16 resolutions from one clickhouse-benchmark process, not 16 background clients: the flaky check runs nproc-1 copies at once, so a client per racing query exhausted the runner's memory cgroup, reporting Server died with no results. Peak clients go 121 to 8; --concurrency connections are independent, so the race is unchanged and throwIf checks all 16.

Coverage boundary: the oracle is the deadlock, not which storage a loser gets, since a Filesystem database exposes no table cache to SQL. DatabaseHDFS has no test coverage, so its identical fix rests on that sweep.

groeneai and others added 2 commits July 29, 2026 20:33
DatabaseFilesystem::addTable took the base IDatabase::mutex and then, inside
the still-held scope, called IDatabase::getDatabaseName from the throw's
argument list. That accessor locks the same non-recursive mutex, so the thread
parked forever while holding it and every later access to the database blocked
in tryGetTableFromCache. A std::mutex wait has no cancellation point, so
neither KILL QUERY nor the hung check could break it.

The throw was reachable because getTableImpl probes the table cache and
inserts into it under two separate lock acquisitions, with schema inference in
between: two queries naming the same table both miss, both build a storage,
and the loser's emplace reports the key already present.

addTable now returns loaded_tables.emplace(...).first->second and getTableImpl
returns that, so losing the race yields the storage the winner cached and no
accessor runs under the lock. DatabaseHDFS carried a byte-identical copy of
the same addTable and is fixed the same way. ErrorCodes::LOGICAL_ERROR becomes
unused in both files.

Surfaced by Stress test (arm_debug) on an unrelated pull request, where 56 of
61 stuck queries were queued behind one such self-deadlocked thread.

Related: ClickHouse#107941

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The tag's stated reason was wrong: Fast test does not run stateless tests
through clickhouse-local, and it does provide user_files. ci/jobs/fast_test.py
starts a real ClickHouseProc server and runs clickhouse-test against it, while
ci/jobs/scripts/clickhouse_proc.py passes --user_files_path to the server and
exports CLICKHOUSE_USER_FILES, which shell_config.sh maps to USER_FILES_PATH.
registerDatabaseFilesystem is unconditional, unlike registerDatabaseHDFS behind
USE_HDFS, so -DENABLE_LIBRARIES=0 does not remove the engine either. The direct
sibling 02722_database_filesystem.sh uses the identical mechanism with no tags
at all, so the tag is dropped rather than re-justified. Tag-free 50/50 is green
and the mutation arm still times out, so the test remains load-bearing.

The comments now also state the one coverage boundary explicitly. The oracle is
the deadlock itself: that all 16 clients return and the database stays usable.
Which of the racing storages the loser of the race receives is deliberately not
asserted, because a Filesystem database exposes no table cache to SQL -
loaded_tables has no reference outside the engine and getTablesIterator returns
an empty snapshot. The glob name is chosen for the width of the race window and
not for cache residency, since tryGetTableFromCache calls fs::exists on the
literal glob pattern, which never exists, so the entry is dropped on every
lookup.

Literal identifiers in the new comments are wrapped in inline code blocks per
the repository conventions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 1 fix round; 34 findings raised, 0 open)

Before opening this PR I ran two independent review rounds over it: my own cold read of the
resulting code, plus a separate model reviewing the diff without access to my notes. Round 1
raised 9 findings and sent the PR back for a fix round; round 2 raised 1 and is clean. Both
rounds are recorded below with the verdict I reached and the measurement behind it.

Round 1 (commit 53847920bde8) - 5 AGREE / 2 DISAGREE / 3 dropped, all fixed in 8ee89633d498

❌ no-fasttest tag reason was factually false. The test shipped with
"needs the user_files directory, which clickhouse-local in Fast test does not provide". Fast test
does not use clickhouse-local for stateless tests: ci/jobs/fast_test.py:343 starts a real
server and :378 runs clickhouse-test against it, while clickhouse_proc.py:80 passes
--user_files_path and :123 exports CLICKHOUSE_USER_FILES, which shell_config.sh:70 maps to
USER_FILES_PATH. The direct sibling 02722_database_filesystem.sh uses the identical mechanism
with no tags at all. The tag is gone. Before accepting that, I measured the lane it newly
enters rather than assuming: over 14 days 02722 is 7001 OK in Fast test and 4078 OK in
Fast test (arm_darwin); its p95 is 3.3 s against the 60 s per-test timeout, and this test runs
in 1.1-1.2 s. Two tag-free tests spawning 15 and 20 concurrent clients are likewise green in both
lanes (14001 + 8148 runs), and tests/config/install.sh:112 installs
max_concurrent_queries.xml before the Fast test guard, so 16 clients are not throttled there.

⚠️ Cache-winner identity is not assertable, so it is disclosed instead. The second model asked for
an oracle proving a race loser receives the cached winner. That is unsatisfiable from SQL here:
nothing outside the engine references loaded_tables, getTablesIterator returns an empty
snapshot, and for a glob name tryGetTableFromCache erases the entry on every lookup because
fs::exists is called on the literal pattern (getTablePath does no expansion). Winner and loser
read the same files with the same schema, so no query can tell them apart. The proposed mutations
also all delete the throw, i.e. they probe caching efficiency rather than the deadlock this PR
fixes. The test's comments and the description now state that boundary explicitly, and the
three-arm evidence (master hangs, fix passes, restored addTable hangs again) is discriminating
for the property actually claimed.

⚠️ DatabaseHDFS has no database-engine test in the repo, so its identical fix rests on the sweep
rather than on execution. Stated in the description as a coverage boundary.

❌ The #107941 link sat inside the non-rendering HTML comment block. Both reviews found this
independently; it is now a visible Related: line, together with the CI report URL.

💡 The sweep denominator was wrong: it read 95 scopes, which is not reproducible under any
counting rule. Re-measured with two independently written scripts: 118 lock scopes on mutex
across src/Databases/**/*.{cpp,h} (117 declaration-form plus one assignment-form -
DatabaseAtomic::renameTable assigns the same lock in three mutually exclusive branches). The
offender counts were always right: 2 on master, 0 with the fix.

💡 Literal names in the new test's comments were not in code blocks, against .claude/CLAUDE.md.
Fixed and re-audited mechanically.

Round 2 (commit 8ee89633d498) - clean

The second model returned no findings. My own read re-verified every claim in the new comment
block against source, confirmed the delta touches only tag and comment lines with the reference
file and all three assertions unchanged, and re-ran the mutation arm against the final tag-free
test: with the original addTable restored it still hangs (killed at 300 s), so the test remains
load-bearing after the tag removal. One nit remains open and is not PR-facing: an internal
investigation log still quotes the superseded 95 figure in one place, while every published
surface states 118.

Reviewer never edited source: the fix in src/Databases/ is byte-identical to what it was when
review began.

Session id: cron:clickhouse-review-slot-10:20260729-220800

@groeneai

groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 16 concurrent SELECT count(DISTINCT _path) FROM <fs_db>./**/*.csv`` clients against one ENGINE = Filesystem database. No thread fuzzer, no randomization needed; hung on the first attempt (11 of 16 clients timed out, a later query of the same table also hung, `SELECT 1` still worked).
b Root cause explained? Yes. getTableImpl probes the cache and inserts under two separate acquisitions of the database mutex, with schema inference in between, so two same-name queries both miss and the loser's emplace reports the key present. That path throws, and the throw's message calls IDatabase::getDatabaseName, which locks the same non-recursive base IDatabase::mutex that addTable is already holding. The thread parks forever holding it; everything else queues in tryGetTableFromCache. gdb on the wedged server shows getDatabaseName (IDatabase.h:452) beneath addTable (DatabaseFilesystem.cpp:79), plus 9 frames in tryGetTableFromCache all on the same mutex address.
c Fix matches root cause? Yes. The accessor call under the lock is deleted rather than guarded: addTable returns loaded_tables.emplace(...).first->second and getTableImpl returns that, so losing the race is benign and no accessor runs under the lock. The lock scope shrinks to a single map operation. No widened bound, no tag, no defensive check.
d Test intent preserved / new tests added? New test 04653_database_filesystem_concurrent_resolve.{sh,reference} added, tag-free like its sibling 02722_database_filesystem.sh. 02722_database_filesystem unchanged and passing (5.64 s); it is the existing coverage for addTable's success path and getTableImpl's return value. No test asserted the removed error: grep -rn "already exists in database" tests/ returns zero hits. The new test's oracle is the deadlock itself (all 16 clients return, database still usable afterwards); its comments state the one coverage boundary explicitly, that cache-winner identity is not asserted because a Filesystem database exposes no table cache to SQL (loaded_tables has no reference outside the two engines and getTablesIterator returns an empty snapshot).
e Both directions demonstrated? Yes, all three arms through the real clickhouse-test harness. Unmodified master (Build ID 92c132ad): FAIL, Timeout! Killing process group at 600.01 s with 15 clients still parked. With the fix (e43eedef): OK, 1.23 s. Mutation (original addTable restored on top of the fix, test kept, Build ID back to 92c132ad): FAIL, Timeout! at 600.02 s. The mutation arm was re-run against the final test, so the new test is load-bearing.
f Fix is general across code paths? Verified mechanically, not by inspection. A comment-stripped sweep of every lock scope on the mutex member in all of src/Databases/ (including DataLake/, MySQL/, PostgreSQL/, SQLite/) for calls to the locking base accessors getDatabaseName, getDatabaseComment, setDatabaseComment, getCreateDatabaseQuery: on master, 118 scopes with exactly 2 offenders (DatabaseFilesystem.cpp:73 -> :79, DatabaseHDFS.cpp:71 -> :77); with the fix, 118 scopes and 0 offenders. Counting rule: **/*.{cpp,h} recursive, comments and string literals stripped, both the declaration form (117 scopes) and the assignment form (1 scope, DatabaseAtomic::renameTable assigns the same db_lock in three mutually-exclusive branches, so it counts once). The second carrier class was swept too, since a TSA_REQUIRES(mutex) body runs with the lock held and shows no lock_guard: 28 such declarations, 14 distinct methods, 1 apparent hit at DatabasesCommon.cpp:528 which is StorageID::getDatabaseName (a plain field accessor, grep -c mutex src/Interpreters/StorageID.h = 0), not the IDatabase one. DatabaseS3 is not a carrier: grep -c addTable src/Databases/DatabaseS3.cpp = 0.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. addTable takes const std::string & and StoragePtr, so there are no type wrappers on this path; the input space is table-name shape plus concurrency. Measured on the fixed build: single file 1, nested single file 1, flat glob 2, recursive glob 3, brace glob 2, nonexistent file still Code: 60, path traversal still PATH_ACCESS_DENIED, glob matching nothing still CANNOT_EXTRACT_TABLE_STRUCTURE. The concurrency dimension is the new test itself.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format, no serialization, no public API. Both addTable methods are protected with exactly one caller each and neither class has a subclass (grep -rn "public DatabaseFilesystem|: DatabaseFilesystem|public DatabaseHDFS|: DatabaseHDFS" src/ is empty), so the return-type change is contained; the whole tree recompiles clean. No SettingsChangesHistory.cpp entry applies. The one behaviour change is that a case which previously raised LOGICAL_ERROR, and in practice deadlocked, now succeeds and returns the concurrently inserted storage. That is strictly more permissive and no test asserted the old error.
i Invariants and contracts preserved? Invariant: no method holding the base IDatabase::mutex may call a base accessor that locks it. It now holds by construction here, since the only statement inside the lock is the emplace and there is no error or early-return path left inside it. Measured on the fixed build: the cache is still populated and repeat queries are idempotent; cache invalidation on file removal still fires through tryGetTableFromCache's erase path; DROP DATABASE still succeeds and the server stays alive, so the shutdown path that snapshots then clears loaded_tables is intact; system.tables for a Filesystem database still reports 0, as getTablesIterator deliberately returns an empty iterator. No I/O moved under the lock: table_function->execute and fs::exists both remain outside it.

Session id: cron:clickhouse-impl-slot-41:20260729-214300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach @tavplubix, could you review this? DatabaseFilesystem::getTableImpl probes and fills its table cache under two separate acquisitions of the database mutex, so two queries resolving the same name race; the loser reached a throw in addTable whose message calls IDatabase::getDatabaseName, which relocks the already-held non-recursive IDatabase::mutex and wedges the database permanently. DatabaseHDFS had a byte-identical copy.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [21e3353]

Summary: ✅


AI Review

Summary

This PR removes the self-deadlock in DatabaseFilesystem/DatabaseHDFS by making duplicate cache inserts return the already-cached StoragePtr, and it reshapes the new stateless regression to avoid the flaky-check OOM. The Filesystem half looks well covered, but the PR still does not provide executable proof for the HDFS half of the promised fix, so I would not sign off on the current scope yet.

Findings

⚠️ Majors

  • [src/Databases/DatabaseHDFS.cpp:74] The PR contract says the HDFS database deadlock is fixed too, but the added regression only exercises DatabaseFilesystem; DatabaseHDFS still has no executable coverage for the duplicate-addTable path. That means half of the fix currently rests only on source similarity, so a future drift between the siblings can reintroduce the deadlock on HDFS with no test catching it. Suggested fix: add an HDFS-backed regression for concurrent resolution of one table name, or narrow the PR scope/changelog/description to the Filesystem engine until that proof exists.
Final Verdict

⚠️ Changes requested

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 7/13 (53.85%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.30% -0.10%
Functions 91.90% 91.80% -0.10%
Branches 78.50% 78.40% -0.10%

Changed lines: Changed C/C++ lines covered: 7/13 (53.85%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8ee8963

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica A for unknown stream B. (STID: 5217-505b) Got read request from replica 1 for unknown stream test_x0l5s0k5a3x0.'.inner_id.7b14b94f-...' — the parallel-replicas reading coordinator is asked for a stream it never registered, and the server dies (the same job's Server died row is the consequence, not a second defect) #111689 (ours, merged 2026-07-31) - this build predates it: the fix landed a day after this run, and its test 04545_parallel_replicas_projection_short_circuit_unknown_stream.sql is absent at this head (404 at this ref)
Stateless tests (amd_asan_ubsan, flaky check) / Server died + OOM in dmesg host OOM, proven from dmesg rather than inferred: oom_reaper: reaped process 3617 (clickhouse-serv), now anon-rss:0kB. The job reports Failed: 0, Passed: 0, Skipped: 0 because the server was killed before any test could report, so the red is the OOM itself and not a test result. 30-day breadth on this job class: 23 hits across 20 distinct PRs, 0 on master a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)

Gates: 174 check-runs, 0 queued or in progress; Config Workflow and Finish Workflow both
completed successfully.

Neither failure is PR-caused. This PR fixes the DatabaseFilesystem / DatabaseHDFS
self-deadlock on a same-name concurrent cache insertion; it touches no parallel-replicas
coordinator code and nothing memory-related, and neither failing job ran its new test.

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

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stateless tests (amd_asan_ubsan, flaky check) / Server died + OOM in dmesg line on my CI finish ledger above: #110574 (external, merged 2026-07-18).

It fixes both contributors to that host OOM: it propagates the build type into prepare_stateful_data on regular sanitizer runs (so the stateful-load INSERT uses 4 instead of 16 insert threads), re-applies the sanitizer max_server_memory_usage_to_ram_ratio of 0.7, and lowers the concurrency of the heaviest leg so the aggregate fits under the lowered cap.

Verified by CIDB: OOM in dmesg failures across the whole database went from 56 in the month before that merge to 2 after, at a comparable number of inspected runs (314k vs 235k detector rows). Both of those 2 are accounted for. Since 2026-07-31 there are 0 anywhere, including 1416 runs of this exact flaky check leg and 1812 of distributed plan, parallel.

This PR's head 8ee89633 already contains the fix, so no master merge is needed for this line. The 2026-07-30 occurrence recorded here was the single event that had the fix and still OOMed; the leg has been clean for the 5 days since.

Note the Server died shape still appears on these legs, but it is now a different failure: recent occurrences abort on Bad cast from type DB::ColumnNullable to DB::ColumnString (STIDs 4350-5ca2, 4350-6700, 5793-6360), which is tracked separately and is not a host OOM.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to my previous comment. I re-measured the dmesg from that run and got the attribution wrong: the OOM on this PR's flaky check leg is not the host-OOM class that #110574 fixed, and #110574 is not the owner of this line.

The kernel's own task list at the kill shows where the memory went:

process count sum RSS
clickhouse-client 128 48.5 GiB
clickhouse-server 1 11.3 GiB
everything else 38 1.5 GiB

Total 61.3 GiB in a CONSTRAINT_MEMCG kill on an m7i.4xlarge (64 GiB). The server was only at 11.3 GiB, so the server-side levers that #110574 tuned (insert threads, memory ratio) were not the binding constraint here. The clients were.

The arithmetic is specific to the test this PR adds: 04653_database_filesystem_concurrent_resolve.sh launches 16 background clickhouse-client processes to race getTableImpl, and the flaky-check leg runs it under --jobs 8 (Workers count set to nproc-1 for flaky check: 8), so 8 concurrent copies of the test means 128 concurrent ASan clients — matching the 128 in the table exactly. Under ASan each client's own RSS is large enough that 128 of them alone exceed the cgroup.

So this is my test's own resource shape, not infrastructure. I am handling it on this PR by bounding the concurrency the test itself creates rather than relying on runner size.

Two things I also said that need withdrawing:

The test raced 16 background clickhouse-client processes. The flaky check runs
nproc-1 copies of a changed test at once, so on a 16 vCPU runner that is 8 x 16 =
128 concurrent sanitizer-instrumented clients. The kernel's task dump for the OOM
kill on this test counted exactly 128 clickhouse-client at 48.5 GiB of a 64 GiB
memory cgroup, against 11.3 GiB for the server; the server was picked as the
victim only because the runner biases oom_score_adj toward it, which is why the
job reported Server died with no test results at all.

clickhouse-benchmark drives --concurrency independent pooled connections from a
single process, so the concurrent resolution of one table name is unchanged while
the peak driver process count per copy goes 16 -> 1. Measured under the same 8-job
shape the flaky check uses: peak concurrent clients 121 -> 8.

The oracle keeps all three properties the per-client loop asserted, and each is
still able to fail on its own:

  - liveness, as the Queries executed line, which benchmark prints only after
    every query has finished, so a wedged database has no such line;
  - the per-execution count, moved server-side into throwIf so that all 16
    executions are checked rather than one survivor, since benchmark reads result
    blocks only for its statistics and discards the values;
  - the quiescent state, unchanged.

Verified on this test with the DatabaseFilesystem fix reverted: it still fails,
the runner killing it on its own timeout with 15 queries parked and is_cancelled =
0, SHOW TABLES on that database hanging while unrelated queries answer normally.

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

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 cold gate rounds, adjudicated; one wording correction applied)

An independent model reviewed this change cold four times, and I reviewed it separately each round before reading the implementation notes. Findings are answered with measurements, not prose. No code defect survived. The last two rounds were text-only: git diff between them is empty, so the source verdict carries forward.

❌ 04653-race-oracle (major, raised cold in three separate rounds) - AGREED, and closed by measurement. The claim: 16 concurrent benchmark workers may not actually overlap, so the test could pass with the deadlock still present.

An earlier round of mine argued this was structurally impossible and that was wrong, so I want to record the correction rather than bury it. The reasoning was that a glob entry is invalidated on every lookup, since tryGetTableFromCache erases whenever fs::exists fails on the table path and that path is the literal **/*.csv. All true, and the conclusion is inverted: the erase makes the sequential case collision-free. Query A inserts and inserted is true, so no throw. Query B then probes, finds A's entry, erases it, rebuilds, and emplaces into a just-emptied map, so inserted is true again and there is still no throw. The duplicate emplace needs genuine overlap, which makes it probabilistic. The finding was right and I was not.

So it is closed the way the finding itself asked, with a rate rather than an argument. Pre-fix DatabaseFilesystem.cpp restored from the merge-base, shipped test file unchanged in both arms, --test-runs 20 -t 60:

arm reddened per-run
pre-fix addTable 20 of 20, every one Reason: Timeout! 60 s cap
fix (control, same N and cap) 0 of 20 1.18 to 1.59 s

Each server's buildId() was asserted equal to its binary's ELF Build ID before every verdict, and the two differ. Build ID alone only proves two different builds, so the arms were also discriminated by content: the fix deletes the LOGICAL_ERROR message, and strings -a counts it once in the pre-fix binary and zero times in the fixed one.

The accumulation confound was measured rather than assumed, since each wedged run leaks 16 queries onto the mutex forever and a later run could redden from saturation instead of the deadlock. A 1 Hz sampler recorded the stuck pile at 1 immediately before run 1 and 292 after run 20, so run 1 reddened with the pile empty: the pile is the consequence of the reds, not their cause. It never approached max_concurrent_queries (292 of 1000).

The remedy the finding preferred, a barrier or failpoint between the cache probe and the insert, stays declined: it is a source change to already-reviewed code, and a failpoint is server-global. Its own stated alternative is what was done.

⚠️ A false count in this description - found in my own final review, corrected before publishing. The description previously said a sweep of "all 118 lock_guard(mutex) scopes" in src/Databases/ found these two sites. That number does not reproduce. Across a matrix of lock-token, mutex-token and file-scope predicates at four refs, exactly one cell yields 118, and it is a raw line grep in which four matches are comments, two of them comments this pull request itself added. The same predicate returns 116 before the change, so the figure was inflated by the change's own prose. Counting lock declarations with comments stripped gives 117 including headers and 112 in .cpp alone, identical before and after.

A second, smaller one in the same sweep: the validation comment posted alongside this description gave the fixed binary's per-run time as "1.03 to 1.64 sec" over the 20-run arm. Neither endpoint is from that arm (its true range is 1.18 to 1.59 s over 20 runs); the two digits come from a 50-run arm and a 25-run parallel arm respectively. Corrected. Every other figure in that row re-derives exactly, including the two that carry the argument: 20 of 20 reddened against 0 of 20, and the 121 to 8 driver-process drop.

The sentence now names the predicate instead of a digit, and the claim it makes is the one that was actually checked and is stronger: exactly four IDatabase methods lock the non-recursive base mutex (getDatabaseName, getCreateDatabaseQuery, getDatabaseComment, setDatabaseComment), and scoping every mutex region in src/Databases/ for calls to any of them gives 2 hits before the change (DatabaseFilesystem.cpp:79 and DatabaseHDFS.cpp:77, both the deleted throw) and 0 after. That sweep is the whole argument for the DatabaseHDFS half, which has no test of its own, so it needed to be a claim a reviewer can re-run.

💡 Notes, none blocking. DatabaseS3 is the third glob-database sibling and is deliberately untouched: it keeps no table cache at all, so it has no addTable to fix. The newly possible case of two queries sharing one StoragePtr at the same instant is safe, since StorageFile already carries a reader lock and an atomic reader counter and was already shared by every later cache hit, while the loser's discarded storage has no shutdown obligation. On comment density the src/ text is 10 comment lines against 8 code lines, which is over budget by the letter; it is left as is because the content is the local invariant that makes the change correct, and all of it belongs to the earlier commit rather than this one.

Session id: cron:clickhouse-review-slot-51:20260805-083700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i) for the test-shape change

This covers the 04653 change pushed on top of the deadlock fix, which replaces the test's 16 background clickhouse-client processes with one clickhouse-benchmark driver. Every measurement below was taken on one Debug build, Build ID 0fd2e527cb049682b73d4a1917f45d7fa635f4a8, with SELECT lower(buildId()) asserted equal to the binary's ELF Build ID before each verdict.

# Question Answer
a Deterministic repro? Yes, in both senses. The resource shape is deterministic, not probabilistic: every copy of the test spawned 16 clients, and under the flaky check's own --jobs 8 shape I measured 121 concurrent clients. The test's bug detection is measured, not asserted: with the fix reverted it reddens 20 of 20 runs, against 20 of 20 green on the fixed binary at the same repeat count.
b Root cause explained? Yes. A client per racing query, multiplied by the flaky check's nproc-1 workers, exhausts the runner's memory cgroup. The kernel's task dump for the kill counted 128 clickhouse-client at 48.5 GiB against 11.3 GiB for the server; the server was the victim only because the runner biases oom_score_adj toward it, which is why the job reported Server died with no test results.
c Fix matches root cause? Yes. The defect is the process count, and the change collapses 16 processes into 1 while keeping 16 concurrent connections. No tag, no reduced dataset, no reduced attempt count, no CI-side lever.
d Test intent preserved? Yes, and this was the round's main risk. All three properties survive and each was proven able to fail independently: liveness and the per-execution count by the mutation in (e), deadlock detection by the reverted-fix arm. Total attempts stay 16. Coverage is sharper on one axis: throwIf checks the count on all 16 executions server-side, where the previous sort -u proved it only for the lines that were written.
e Demonstrated in both directions? Yes, three arms. Deadlock: pre-fix DatabaseFilesystem (restored from the merge-base, md5-verified) with the new test reddens 20 of 20 runs, every one Reason: Timeout!; the fixed binary is 20 of 20 green at the same repeat count, in 1.18 to 1.59 sec. After those 20 runs the pre-fix server held 291 queries parked with is_cancelled = 0, spanning exactly 20 wedged databases, one per run, with SHOW TABLES on such a database hanging while SELECT 1 answers. The first run reddened with no queries parked yet, so the pile is the consequence and not the cause. The two binaries differ (0a4bf9f7… vs 0fd2e527…), and only the pre-fix one still contains the deleted LOGICAL_ERROR message. Value oracle: mutating != 4 to != 5 on the fixed binary flips exceptions: 0 to 1 and removes the Queries executed line, i.e. the two oracle lines fail on independent mechanisms. Process count: peak drivers 16 -> 1 per copy, and 121 -> 8 under --test-runs 25 --jobs 8.
f General across code paths? The invariant is that a stateless test must bound the client processes it spawns, since the flaky check multiplies them by nproc-1. 03915_exchange_tables_race.sh is already compliant at 2 per copy and its own comment documents this same OOM. No other test in this PR's diff spawns background clients. A tree-wide sweep is deliberately out of scope here.
g General across inputs? Not a type or settings surface; this is a shell test's process shape. The randomized-settings axis is exercised: 50 randomized runs plus 25 more under 8 parallel jobs, all green.
h Backward compatible? N/A, and verified so: no src/ change in this commit, no settings, no SettingsChangesHistory entry, no serialization format, no feature gate.
i Invariants and contracts preserved? The contract under test is concurrent resolution of one table name by independent connections. Preserved by construction, since --concurrency uses independent pooled connections, and confirmed by measurement: system.query_log shows exactly 16 executions per run overlapping 11.4 to 14.7-way inside a 7 to 33 ms window, so the queries are not serialized. The reverted-fix arm still deadlocking is the end-to-end confirmation. Cleanup is unchanged; the temporary log is removed on the normal path exactly as the previous output file was.

/// `emplace` keeps the existing entry if the key is already there, so `first->second` is the storage
/// a concurrent call for the same name inserted first. Nothing that locks `mutex` again may be called
/// here: it is the non-recursive base `IDatabase::mutex`, shared with `getDatabaseName`.
return loaded_tables.emplace(table_name, table_storage).first->second;

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.

The PR contract says the HDFS database deadlock is fixed too, but the new regression only exercises DatabaseFilesystem. Without any executable coverage for DatabaseHDFS's duplicate-addTable path, this half of the fix still rests only on source similarity, so a later drift between the siblings could silently reintroduce the deadlock on HDFS.

Can we either add an HDFS-backed regression for concurrent resolution of one table name, or narrow the PR scope/description to Filesystem until that proof exists?

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.

I checked this rather than answering from source similarity, because "the two files are
near-identical" is exactly the argument the finding rejects. The gap is real. Both remedies
you offer turn out to be the wrong ones, so I am leaving the change as it is and giving the
measurement instead.

The fix does change the HDFS site. git diff --name-only <merge-base>..HEAD includes
src/Databases/DatabaseHDFS.cpp and src/Databases/DatabaseHDFS.h, and the two addTable
bodies are byte-identical modulo the class name. So narrowing the description to Filesystem
would understate what the diff does.

An HDFS-backed regression is not constructible in this repository. The HDFS integration
fixture was removed on purpose and the removal is on master: #74295 "CI: Remove hdfs from
Integration tests", reverted by #74405, re-landed as #74413 (4f822c643831e28, an ancestor of
origin/master). At master today tests/integration/helpers/hdfs_api.py and
tests/integration/compose/docker_compose_hdfs.yml are both gone, while helpers/cluster.py
and compose/docker_compose_minio.yml are present, so those absences are real rather than a
bad path. with_hdfs appears 0 times in helpers/cluster.py (with_minio 12, with_kafka
20), and with_hdfs=True appears in 0 files under tests/integration/. Neither the stateless
nor the stress image provides a namenode (0 hdfs matches in either Dockerfile, against 17
minio matches in the stateless one). CREATE DATABASE ... HDFS appears 0 times anywhere
under tests/, against 13 for Filesystem and 12 for S3; the two stateless files that build
an HDFS engine or call hdfs() do so in five statements, every one of which asserts an argument
or format error without contacting a server. use-hdfs
is carried by one test and its only runner effect is NOT_SUPPORTED_IN_CLOUD
(tests/clickhouse-test:2752); it provisions nothing. Adding the arm therefore means
re-landing infrastructure that was deliberately deleted twice, which is well outside a
two-line deadlock fix.

That is also unavoidable on the SQL path rather than incidental: getTableImpl reaches
addTable only after table_function->execute(...) has run schema inference against the URL,
so with no namenode the table function throws before addTable is entered.

On the drift risk, which I think is the substantive half of your point. I re-derived the
sweep the description relies on, over every lock_guard, unique_lock and scoped_lock on
mutex in src/Databases/, checking for calls to the four IDatabase methods that relock it
(getDatabaseName IDatabase.h:452, getCreateDatabaseQuery :434, getDatabaseComment
:440, setDatabaseComment :445): 126 scopes at every ref, with 2 offending scopes pre-fix
(DatabaseFilesystem.cpp:79 and DatabaseHDFS.cpp:77, both the deleted throw) and 0 at this
head. loaded_tables exists in exactly four files, all DatabaseFilesystem.* and
DatabaseHDFS.*, and DatabaseS3 holds no table cache at all, so those two are the complete
carrier set.

One point worth stating because it bears on what a regression would even prove: the defect is
not a property of HDFS I/O. I reproduced the pre-fix shape standalone, in a single thread, with
a non-recursive mutex, an emplace collision, and a throw whose argument list calls a relocking
accessor: it hangs before reaching the throw. Concurrency is only what produces the collision;
the hang itself is plain re-entry, and that re-entry is what this change deletes. An HDFS arm
would confirm the collision is reachable over HDFS, not that the fix works.

The description already carries this boundary explicitly ("DatabaseHDFS has no test coverage,
so its identical fix rests on that sweep"), so I would rather leave the honest caveat standing
than narrow a claim that is true.

One difference I noticed and am not addressing here: DatabaseHDFS never erases from
loaded_tables, whereas DatabaseFilesystem::tryGetTableFromCache does at line 127, so an
HDFS cache entry is never invalidated. I cannot pair that with a runnable input and an observed
result without a namenode, so I am recording it rather than acting on it.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 21e3353

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks build_profile_hook.py fails closed after its build-profile telemetry INSERT INTO build_time_trace is rejected by the shared CI logs cluster with LogCluster query failed with code 500. The build itself is green: the enclosing check-run concludes success, and inside the job report every step (Checkout Submodules, Cmake configuration, Build ClickHouse, Build Packages, the sibling build_master_head_hook.py) is OK. Only the telemetry upload fails, so nothing about this PR's code was left unbuilt or untested. Fleet-wide, not specific to this PR or head: 1084 rows across 520 distinct pull requests plus 136 on master over the last 3 days #113409 (external, open) - "Retry the build-profile telemetry INSERT through the CI logs cluster memory-pressure spikes". Causal link verified rather than assumed by area: it edits LogCluster.do_query, the exact transport that emitted this row, raises the three profile INSERTs from a single attempt to retries=8 on a growing backoff, and keeps the fail-close assert so a genuinely lost upload still reddens

Gates: 174 check-runs, 0 queued or in progress; Config Workflow and Finish Workflow both
completed successfully; 57 minutes since the last check completed, so CIDB ingestion has settled.

The failure set was enumerated twice, because the two predicates do not see the same rows: this one
is invisible to a check-runs census (the hook is non-gating, so the enclosing Build (arm_release)
check-run reports success and only the per-test row is FAIL). A per-test query
(test_status IN ('FAIL','ERROR')) plus a job-level one (check_status IN ('failure','error')) over
this commit return exactly the one row above, and the recursive job report agrees: 174 leaves, 156 OK,
18 skipped, 0 other.

Not PR-caused. This PR fixes the DatabaseFilesystem / DatabaseHDFS self-deadlock on a same-name
concurrent cache insertion; it touches no CI hook, no telemetry transport and no build script, and
the failing step never runs a test of this PR at all.

Session id: cron:our-pr-ci-monitor:20260805-150000

@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit c8cea90 Aug 7, 2026
180 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 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 groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default 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