Repository navigation
Fix deadlock on concurrent resolution of one Filesystem or HDFS table - #112495
Conversation
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]>
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 Round 1 (commit ❌
❌ The 💡 The sweep denominator was wrong: it read 95 scopes, which is not reproducible under any 💡 Literal names in the new test's comments were not in code blocks, against Round 2 (commit The second model returned no findings. My own read re-verified every claim in the new comment Reviewer never edited source: the fix in Session id: cron:clickhouse-review-slot-10:20260729-220800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-41:20260729-214300 |
|
cc @tuanpach @tavplubix, could you review this? |
|
Workflow [PR], commit [21e3353] Summary: ✅
AI ReviewSummaryThis PR removes the self-deadlock in Findings
Final VerdictLLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 7/13 (53.85%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 7/13 (53.85%) · Uncovered code |
CI finish ledger - 8ee8963Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Gates: 174 check-runs, 0 queued or in progress; Neither failure is PR-caused. This PR fixes the Session id: cron:our-pr-ci-monitor:20260803-180000 |
|
Fixing PR for the It fixes both contributors to that host OOM: it propagates the build type into Verified by CIDB: This PR's head Note the |
|
Correction to my previous comment. I re-measured the dmesg from that run and got the attribution wrong: the OOM on this PR's The kernel's own task list at the kill shows where the memory went:
Total 61.3 GiB in a The arithmetic is specific to the test this PR adds: 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]>
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: ❌ 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 So it is closed the way the finding itself asked, with a rate rather than an argument. Pre-fix
Each server's 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 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 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 💡 Notes, none blocking. Session id: cron:clickhouse-review-slot-51:20260805-083700 |
Pre-PR validation gate (a-i) for the test-shape changeThis covers the
|
| /// `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; |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
CI finish ledger - 21e3353Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Gates: 174 check-runs, 0 queued or in progress; The failure set was enumerated twice, because the two predicates do not see the same rows: this one Not PR-caused. This PR fixes the Session id: cron:our-pr-ci-monitor:20260805-150000 |
Related: #107941
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a deadlock that permanently wedges a
FilesystemorHDFSdatabase 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::getTableImplprobes 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 athrowinaddTablewhose message callsIDatabase::getDatabaseName, which locks the non-recursiveIDatabase::mutexaddTablealready holds, so the thread parks forever holding it.Every later access blocks in
tryGetTableFromCache, and astd::mutexwait has no cancellation point, so neitherKILL QUERYnor the hung-check breaks it.DatabaseHDFShas a byte-identicaladdTable.One mechanical change per engine:
addTablereturnsloaded_tables.emplace(...).first->secondandgetTableImplreturns 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
addTablemakes it hang in 20 of 20 runs, against 20 of 20 green with the fix. 50 randomized runs pass. Sweeping everymutexscope insrc/Databases/for calls to the fourIDatabaseaccessors that relock it finds these two.It drives those 16 resolutions from one
clickhouse-benchmarkprocess, not 16 background clients: the flaky check runsnproc-1copies at once, so a client per racing query exhausted the runner's memory cgroup, reportingServer diedwith no results. Peak clients go 121 to 8;--concurrencyconnections are independent, so the race is unchanged andthrowIfchecks all 16.Coverage boundary: the oracle is the deadlock, not which storage a loser gets, since a
Filesystemdatabase exposes no table cache to SQL.DatabaseHDFShas no test coverage, so its identical fix rests on that sweep.