Skip to content

Load a Filesystem database whose directory is gone instead of refusing to start - #118684

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/database-filesystem-tolerate-missing-path-on-load
Sep 12, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/database-filesystem-tolerate-missing-path-on-load

Conversation

@groeneai

@groeneai groeneai commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118377
Related: #117895

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

Fixed a server that refused to start after the directory backing a Filesystem database had been removed. Such a database is now loaded without tables and can be inspected and dropped, while a CREATE DATABASE or ATTACH DATABASE issued by a user is still rejected when the path does not exist.

Description

Stress test (arm_tsan) on #118377 could not start the server at all: all 11 start attempts died with Code: 36 ... Path does not exist: /var/lib/clickhouse/user_files/05057_..., thrown while loading database fsdb_05057_.... Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/34118002382/job/101749188450

Root cause. DatabaseFilesystem's constructor validated the existence of its backing directory unconditionally. Startup rebuilds every database by replaying its stored ATTACH DATABASE statement, and loadMetadata aborts on the first exception. One removed directory therefore made the server unstartable, recoverable only by hand-editing metadata/. Any user who creates ENGINE = Filesystem(<dir>) and later removes <dir> reaches it.

Change. The check is skipped, and a warning logged instead, only while the server replays its own stored metadata on start. The loader answers that directly: InterpreterCreateQuery::setIsMetadataReplay is called only from executeCreateQuery in loadMetadata.cpp, and no SQL can reach it. Neither substitute works here: not internal, because PARALLEL WITH and EXECUTE AS run a user's children as internal queries, and not isLoadingFromExistingMetadata, because a database replay runs at plain ATTACH (loadDatabase passes create = true, so setForceAttach is never reached). A user CREATE/ATTACH DATABASE over a missing path is unchanged and still fails BAD_ARGUMENTS, and the user_files containment check stays fail-closed even on replay. A tolerated database exposes no tables, since every table resolves its file on access, and drops normally.

Validation. New 05136_database_filesystem_missing_path_on_load removes the directory between two clickhouse local --path invocations over one store: it fails on master, passes here, and asserts the database returns on the next start while a hand-issued replay is still refused. 02921_database_filesystem_path_check gains four arms for the user-supplied and wrapper-wrapped forms. Both directions of the guard are mutation-covered.

Not fixed here: the same startup-only relaxations in the PostgreSQL and DataLake database engines still key on internal; #116260 converts those three sites.

Reproduced first-party CI failure, and the deterministic local repro

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118377&sha=58f7c10d1c3a06e4661e9b38aa3d45dc6b268a96&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

SELECT check_start_time, check_name, test_name, pull_request_number,
       substring(test_context_raw, 1, 160) AS ctx
FROM default.checks
WHERE test_name = 'Cannot start clickhouse-server'
  AND check_start_time > now() - INTERVAL 30 DAY
  AND (test_context_raw LIKE '%fsdb_05057%' OR test_context_raw LIKE '%05057_file_rename%')
ORDER BY check_start_time DESC
2026-09-07 12:53:35   Stress test (arm_tsan)   Cannot start clickhouse-server   118377
Cannot start clickhouse-server: server process is not running after 11 start attempts
<Error> Application: Caught exception while loading metadata: Code: 36. DB::Exception:
Path does not exist: /var/lib/clickhouse/user_files/05057_file_rename_after_processing_write_grant_...

A stress-test SIGKILL landing between a test's DROP DATABASE and its rm -rf of the
directory leaves the metadata file behind, so no test-side cleanup can prevent it.

$ clickhouse local --path=$D/store -q "CREATE DATABASE fsdb ENGINE = Filesystem('$D/files')"
$ rm -rf $D/files
$ clickhouse local --path=$D/store -q "SELECT name FROM system.databases WHERE name='fsdb'"
Code: 36. DB::Exception: Path does not exist: .../files: while loading database `fsdb`
from file metadata/fsdb.sql. (BAD_ARGUMENTS)

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

Version info

  • Merged into: 26.9.1.1315 (included in 26.9 and later)
  • Backported to: 26.8.3.102, 26.7.8.5, 26.6.6.3, 26.3.33.71

groeneai and others added 4 commits September 7, 2026 16:52
…g to start

`DatabaseFilesystem`'s constructor validated the existence of its backing
directory unconditionally. Server startup rebuilds every database by replaying
its stored `ATTACH DATABASE` statement (`loadDatabase` -> `executeCreateQuery`
-> `InterpreterCreateQuery` -> `DatabaseFactory::get` -> that constructor),
`loadMetadata` aborts on the first exception, and nothing catches around the
factory call. A directory removed after the database was created therefore made
the server refuse to start, recoverable only by hand-editing `metadata/`, with
no SQL escape hatch because the server never accepts a connection.

Skip the existence check only for an internal metadata replay,
`args.internal && args.mode >= LoadingStrictnessLevel::ATTACH`. This is the
predicate `DatabaseDataLake`, `DatabasePostgreSQL` and
`DatabaseMaterializedPostgreSQL` already use for the same requirement.
`isLoadingFromExistingMetadata` is the trap here: it matches only
`FORCE_ATTACH`/`FORCE_RESTORE`, and a database replay uses plain `ATTACH`
because `loadDatabase` passes `create = true`, so `setForceAttach(true)` is
never reached. A regression arm covers that distinction, and building the fix
with the narrower helper leaves the original failure in place.

Deferring the check into `beforeLoadingMetadata` (as `DatabaseBackup` and
`DatabaseReplicated` do) is unavailable: `supportsLoadingInTopologicalOrder()`
is false for this engine, so `TablesLoader` takes the `loadStoredObjects`
branch and never calls it. Deleting the check outright was rejected because it
would silently accept `Filesystem('/nonexistent')` from a user and break
`02722_database_filesystem`.

A tolerated database exposes no tables, since every table resolves its file on
access, and it can still be inspected and dropped. `DatabaseFilesystem` was the
only path-backed database engine that hard-failed on an unreachable location:
`DatabaseS3` does no validation, `DatabaseHDFS` checks URL syntax only, and
`DatabaseURL` checks only that a scheme is present. The `user_files`
containment check is deliberately left fail-closed on replay, because it is a
security boundary and `checkTableFilePath` re-checks containment per table
regardless of `throw_on_error`.

The failure was first observed as `Cannot start clickhouse-server` in a
`Stress test (arm_tsan)` job, where a SIGKILL landing between a test's
`DROP DATABASE` and its `rm -rf` of the directory leaves the metadata file
behind. No test is changed to accommodate this; the removal is required for
that test's re-runnability.

Co-Authored-By: Claude Opus 5 <[email protected]>
…the comment

`05136_database_filesystem_missing_path_on_load` sent the second
`clickhouse local` invocation's stderr to `/dev/null`, which discarded the only
text that identifies the defect: without it a base-build failure is a bare
missing-lines stdout diff, on the sole regression test for a "server cannot
start" fix. The redirect suppressed nothing that a green run emits. A bare
`clickhouse local` sets `logger.level` to `fatal` unless one of
`logger.console`, `logger.level`, `log-level` or `logger.log` is given, so the
tolerated path's `LOG_WARNING` never reaches stderr; `shell_config.sh` builds
`--send_logs_level` into `CLICKHOUSE_CLIENT` only, never into
`CLICKHOUSE_LOCAL`; and the first invocation in the same test already ran
unredirected. Measured after removing it: stderr is empty on the fix build and
50 randomized runs stay green, while the base build now reports
`Code: 36 ... Path does not exist: ... while loading database ... from file
metadata/fsdb.sql. (BAD_ARGUMENTS)`.

Also reword the second sentence of the `is_internal_metadata_replay` comment.
It justified the exclusion by who supplies the path, which is false for the
short `ATTACH DATABASE db` form: that reads `metadata/<db>.sql`, replays the
stored definition and supplies no path of its own, yet still throws, because
`args.internal` is false. Name the discriminator that actually decides it.
`RESTORE` is internal too and is excluded by the mode term instead, so the
wording claims only what the guard does.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118377&sha=58f7c10d1c3a06e4661e9b38aa3d45dc6b268a96&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#118377

Co-Authored-By: Claude Opus 5 <[email protected]>
…ssing path

The previous commit's guard was `args.internal && args.mode >= ATTACH`, on the
assumption that `internal` means the server generated the statement. It does
not. `InterpreterParallelWithQuery::executeSubquery` runs every `PARALLEL WITH`
child through `executeQuery(..., QueryFlags{ .internal = true })`, and
`InterpreterExecuteAsQuery::execute` does the same for `EXECUTE AS`, so a
statement a user writes arrives at `DatabaseFactory` with `internal` set.
`PARALLEL WITH` is gated by no setting and DDL children are its canonical use.

Measured on a server: `ATTACH DATABASE d ENGINE = Filesystem('<missing>')` is
rejected with `Code: 36`, while the same statement followed by
`PARALLEL WITH DROP TABLE IF EXISTS <absent>` was accepted, wrote
`metadata/d.sql`, and survived a restart. Both plain forms already threw, so
only the wrapped form reached the tolerant branch.

Add a third conjunct, `args.replays_stored_definition`, computed by the
interpreter one line above the factory call as `create.attach &&
!need_write_metadata`. That expression already means "the definition being
attached is the one stored in `metadata/`", so this reuses the interpreter's own
answer instead of inventing a second notion of replay. A definition supplied
with the query is never a stored one, wrapper or not. The change moves in one
direction only: strictly fewer statements reach the tolerant branch, and a
genuine startup replay still evaluates all three terms true, which
`05136_database_filesystem_missing_path_on_load` continues to assert.

`02921_database_filesystem_path_check` gains the wrapped `ATTACH` arm. Its
sibling is `DROP TABLE IF EXISTS`, whose pipeline is empty, so the assertion
does not depend on the order the children run in or on what `max_threads`
randomizes to. Dropping the new conjunct while keeping the plumbing reddens
that arm with `The query succeeded but the server error '36' was expected`.

The sibling engines that share the two-term predicate are left alone: the same
laundering reaches them, but that belongs with the wrapper rather than with each
engine.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118377&sha=58f7c10d1c3a06e4661e9b38aa3d45dc6b268a96&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#118377

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit's third conjunct was `create.attach && !need_write_metadata`,
which it described as "the definition being attached is the one stored in
`metadata/`". It does not test that. `need_write_metadata` is
`!create.attach || !existsFile(metadata/<name>.sql)`, so the conjunct only tests
whether the NAME already has a stored definition; whether the definition being
executed came from that file is never checked. The file is read solely in the
short-syntax branch (`!create.storage && create.attach`), which a long-syntax
`ATTACH DATABASE ... ENGINE = ...` skips. `DETACH DATABASE` leaves the metadata
file in place (`DatabaseCatalog` removes it only when dropping, and
`DatabaseFilesystem::shouldBeEmptyOnDetach()` is false), so two ordinary
statements arrange the precondition.

Measured on a server, twice, with `buildId()` asserted against the binary:

    CREATE DATABASE d;
    DETACH DATABASE d;
    ATTACH DATABASE d ENGINE = Filesystem('<missing>')
      PARALLEL WITH DROP TABLE IF EXISTS <absent>;

was accepted, and `system.databases` then reported `d` with engine `Filesystem`
over a path that does not exist, while `metadata/d.sql` still held the original
`ENGINE = Atomic` definition. The same shape via short syntax, after removing
the directory of a real `Filesystem` database, was likewise accepted. Both plain
forms threw `Code: 36`, so `internal`, laundered by the wrapper, was again the
term being defeated.

Feed the decision from the loader instead of deriving it from the statement.
`InterpreterCreateQuery` gains `setIsMetadataReplay`, called only from
`executeCreateQuery` in `loadMetadata.cpp`, beside the `setInternal(true)` that
startup metadata replay already performs. Nothing else can reach it: `QueryFlags`
has no route to an interpreter member, so no SQL sets it. A dedicated flag rather
than the adjacent `setLoadDatabaseWithoutTables` because that one means "defer
table loading", not "this is a replay".

With the loader answering directly, `args.internal` leaves the predicate: the
same call site sets both, so it decided nothing. `args.mode >= ATTACH` is kept as
the idiom the sibling engines use; it is not independently provable by mutation
here, because a replayed `Filesystem` definition is always an `ATTACH DATABASE`
statement and therefore always that mode.

`isLoadingFromExistingMetadata` remains unusable for this: a database is replayed
under plain `ATTACH`, unlike tables, which use `FORCE_ATTACH`, so the helper never
matches a database load.

`02921_database_filesystem_path_check` gains the name-aliasing arm in pure SQL,
and re-attaches before dropping, since a database left detached keeps a metadata
file that every later start replays. `05136_database_filesystem_missing_path_on_load`
gains the sharper arm: the definition a start has just replayed is refused to a
user who replays it by hand, plainly and wrapped, and the start after each
rejection attaches the database again. Restoring the previous predicate reddens
both arms, the wrapped `05136` line flipping while its plain line stays green,
which is exactly the statement class that was reachable before.

The sibling engines that share the two-term predicate are still left alone: the
laundering reaches them too, and belongs with the wrapper rather than with each
engine.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118377&sha=58f7c10d1c3a06e4661e9b38aa3d45dc6b268a96&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#118377

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added 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 labels Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 2 blockers found and fixed over 3 rounds; 1 note on overlap with #116260 (click to expand)

An independent model reviewed the resulting code cold, without the implementation notes, and a
separate gate re-reviewed the diff on each round. Every finding below is either fixed here or
answered with evidence.

# Finding Verdict
❌ 1 The first version skipped the check for args.internal && args.mode >= ATTACH, on the assumption that internal means the server generated the statement. It does not: InterpreterParallelWithQuery.cpp:125 runs every PARALLEL WITH child through executeQuery(..., QueryFlags{ .internal = true }), and EXECUTE AS does the same, so a user's own ATTACH DATABASE arrived with internal set and reached the tolerant branch. Measured on a server: the plain statement threw Code: 36, the wrapped one was accepted and survived a restart. AGREE, fixed
❌ 2 The second version's remedy narrowed that without closing it. Its extra conjunct create.attach && !need_write_metadata reduces to create.attach && existsFile(metadata/<name>.sql), which tests whether the NAME has a stored definition, never whether the definition being executed came from it. CREATE DATABASE d; DETACH DATABASE d; then a wrapped ATTACH ... ENGINE = Filesystem(<missing>) was still accepted, and system.databases reported d as Filesystem while metadata/d.sql still held ENGINE = Atomic. AGREE, fixed
💡 3 The new flag is documented as true "only when the server replays a definition it stored itself", but executeCreateQuery sets it before distinguishing the query source, so it is also true when loadDatabase synthesizes CREATE DATABASE on first start, where nothing was stored. Harmless at the only consumer, which additionally requires mode >= ATTACH, but the doc promises more than the setter establishes. AGREE, noted, not blocking

The remedy for 1 and 2 is what the diff now does: the tolerance is keyed on a flag the loader sets
(setIsMetadataReplay, called only from executeCreateQuery in loadMetadata.cpp), not derived from
any property of the statement, so no SQL can reach it. 02921 gains the name-aliasing arm and 05136
the sharper one - the definition a start has just replayed is refused to a user who replays it by hand,
plainly and wrapped - and restoring either previous predicate reddens them.

Note for merge sequencing. My open #116260 threads an equivalent loader-set flag through the same
DatabaseFactory::get/getImpl signatures and Arguments struct under a different name, so whichever
of the two merges first, the other should reuse the merged flag rather than add a second one. This PR
uses a dedicated setter rather than reusing the adjacent setLoadDatabaseWithoutTables, because that
one means "defer table loading" rather than "this is a replay".

Known residual, disclosed rather than fixed: the user_files containment throw at
DatabaseFilesystem.cpp:57-61 stays fail-closed even on replay. It is a security boundary, no failure
has been observed on it, and it is not the enforcement point anyway, since checkTableFilePath
re-checks containment per table regardless of throw_on_error.

@clickhouse-gh clickhouse-gh Bot closed this Sep 8, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand: clickhouse local --path=$D/store -q "CREATE DATABASE fsdb ENGINE = Filesystem('$D/files')", then rm -rf $D/files, then a second clickhouse local --path=$D/store invocation. On master the second one exits 36 with Path does not exist: ... while loading database 'fsdb' from file metadata/fsdb.sql. (BAD_ARGUMENTS), the same message shape as the CI job. Shipped as 05136_database_filesystem_missing_path_on_load.
b Root cause explained? DatabaseFilesystem's constructor validated the existence of its backing directory unconditionally. Startup replays every stored ATTACH DATABASE statement (loadDatabase -> executeCreateQuery -> InterpreterCreateQuery -> DatabaseFactory::get -> that constructor), loadMetadata aborts on the first exception, and there is no try/catch around the factory call, so one removed directory made the server unstartable.
c Fix matches root cause? Yes. The eager check is skipped only when the server itself replays a definition it stored, during startup metadata loading, decided at the point that performs the replay. It is not a widened bound, a no-* tag, a size reduction, or a guard at the failure site: the check is preserved verbatim for every statement a user runs, including one wrapped in a clause that executes its children as internal queries, and including a user's own hand-replay of the very definition startup tolerates.
d Test intent preserved / new tests added? 05057_file_rename_after_processing_write_grant is not touched: its rm -rf is load-bearing for the 50x flaky check, since a passing arm renames granted_write.csv to processed_granted_write.csv and a re-run recreates the original, so without cleanup file_state reports unexpected. New coverage: 05136_... (the P1 regression test) plus, in 02921_database_filesystem_path_check, a user-supplied ATTACH, the wrapped form, and the name-aliasing form where the name already has a stored definition. 02921 re-attaches before dropping, because a database left detached keeps a metadata file that every later start replays.
e Both directions demonstrated? Yes, through clickhouse-test against A/B servers whose buildId() was asserted equal to readelf -n before each verdict. Base fd1a1efd: 05136 FAIL with a 574-byte stderr naming Code: 36 ... while loading database 'fsdb' from file metadata/fsdb.sql. (BAD_ARGUMENTS). Fix fce2f1fc: 05136 and 02921 both OK, stderr empty. The base failure is what the oracle catches.
f Fix is general across code paths? Fixed at the source (the constructor), not at the startup call site. Re-verified by grep at this head: exactly one DatabaseFilesystem construction site, so its constructor parameter is non-defaulted; exactly one caller of DatabaseFactory::instance().get (InterpreterCreateQuery.cpp), so its defaulted parameter cannot be silently taken by another site; and exactly one call to setIsMetadataReplay, in loadMetadata.cpp. Sibling path-backed engines need no change and were not touched: DatabaseS3 does no validation, DatabaseHDFS checks URL syntax only, DatabaseURL checks the scheme only. Other database engines that still key on the older two-term internal && mode >= ATTACH idiom are out of scope here and are not touched. My open #116260 converts those sites to a loader-set flag of the same shape, so whichever of the two lands first, the other should reuse the merged flag rather than keep a second one.
g Fix generalizes across inputs (params/datatypes/wrappers)? The predicate has two terms, args.is_metadata_replay and args.mode >= ATTACH. The first is set by the loader and by nothing else: QueryFlags has no route to an interpreter member, so no SQL can set it, which is what makes the guard insensitive to statement shape. Every route was measured, twice each, on a server: plain CREATE, plain long-syntax ATTACH, short-syntax ATTACH, each of those wrapped so it runs as an internal query, and the name-aliasing case where a detached database left its metadata file behind. All are rejected with Code: 36 and attach nothing. In honesty about the second term: it is not independently provable by mutation here, because a replayed Filesystem definition is always an ATTACH DATABASE statement and therefore always that mode; it is kept as the idiom the sibling engines use, not because a test distinguishes it. No column data on this path, so type wrappers and numeric boundaries do not apply.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format, no on-disk change, hence no SettingsChangesHistory.cpp entry and no versioning. Strictly more permissive on exactly one path, the server's own startup replay, and byte-identical for every statement a user runs, wrapped or not.
i Invariants and contracts preserved? Yes, and verified in the repro: after a tolerated load, system.tables for the database is 0 and DROP DATABASE succeeds; 05136 additionally shows the database still reachable through a later start and dropping cleanly, leaving no metadata file behind. Every downstream path already handled a missing directory: cache eviction on a vanished file, isTableExist false, getTableImpl {}/FILE_DOESNT_EXIST, getTable UNKNOWN_TABLE, SHOW CREATE DATABASE formats the stored string with no filesystem access, empty tables iterator. Containment stays enforced independently: checkTableFilePath throws PATH_ACCESS_DENIED regardless of throw_on_error.

Mutation testing (the guard was mutated, never deleted), each leg rebuilt and its buildId() asserted:
restoring the previous predicate (7a5ae547) reddens both new arms, the wrapped 05136 line flipping
from 1 to 0 while its plain line stays 1, and 02921 naming the exact statement with
The query succeeded but the server error '36' was expected. A strictly weaker variant (0a84dfff)
flips both 05136 lines. Restoring produced a diff -q-identical source and the original build id
(fce2f1fc) with both tests green, so the arms are live rather than decorative.

--test-runs 50 on both changed tests: 100/100 passed. Style: check_cpp.sh and various_checks.sh
produce no output, and the full check_style.py reports no finding against any changed file.

Noticed while reading nearby code, not addressed here and not otherwise raised:
DatabaseHDFS::getEngineName() returns "S3".

Session id: cron:clickhouse-impl-slot-4:20260907-221300

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach @tavplubix, could you review this? Startup replays every stored ATTACH DATABASE and loadMetadata aborts on the first exception, so a directory removed after CREATE DATABASE ... ENGINE = Filesystem(...) made the constructor refuse the whole server start. The check is now skipped only for the loader's own replay, keyed on a flag set in loadMetadata.cpp that no SQL can reach, rather than on internal, which a PARALLEL WITH child carries.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a46be7a]

Summary: ✅


AI Review

Summary

This PR fixes the original Filesystem startup regression by distinguishing the server's own metadata replay from user-authored ATTACH DATABASE statements, and the new regression tests cover that path well. I do not think it is ready to merge yet, because the new is_metadata_replay contract is only applied to Filesystem while the same wrapper-laundered internal path still bypasses startup-only validation in sibling external database engines.

Findings

❌ Blockers

  • [src/Databases/DatabaseFactory.h:51] The new is_metadata_replay flag correctly captures the Filesystem case, but DatabasePostgreSQL.cpp:715, DatabaseMaterializedPostgreSQL.cpp:786 / 818, and DatabaseDataLake.cpp:1688 still treat args.internal && args.mode >= LoadingStrictnessLevel::ATTACH as if it meant "startup metadata replay". That is still user-reachable through InterpreterParallelWithQuery.cpp:125 and InterpreterExecuteAsQuery.cpp:129, which rerun a user's ATTACH DATABASE with QueryFlags{ .internal = true } while is_metadata_replay remains false. The PostgreSQL engines therefore still let a wrapped ATTACH DATABASE bypass remote_url_allow_hosts, and MaterializedPostgreSQL also skips its single-address validation. Suggested fix: migrate the remaining consumers of the old predicate to args.is_metadata_replay (or move the distinction to a shared path wrappers cannot forge) in the same change.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Replace the remaining startup-only args.internal && args.mode >= LoadingStrictnessLevel::ATTACH checks in the affected external database engines with args.is_metadata_replay, or otherwise make that distinction unforgeable for wrapper-executed user queries.

LLVM Coverage Report

Measured on commit a46be7a.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 40/42 (95.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. labels Sep 8, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 765654b

Every failure below has an owner: a fixing PR (mine 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_tidy) / Build ClickHouse trunk regression: master 2be1edf87853 left a duplicate #include <DataTypes/DataTypeLowCardinality.h> in src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:36, and readability-duplicate-include is -Werror #118680 (external, open); same one-line fix in #118661
Finish Workflow / new_tests_check.py cascade of the same gate: Bugfix validation reports DROPPED (Dropped due to previous failure [Build (arm_tidy)]) #118680 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260908-013052

/// True when the database is created by the server itself (e.g. loading metadata on startup) rather
/// than by a user query. Lets an engine distinguish an internal reload from a user `ATTACH DATABASE`.
bool internal = false;
/// True only when the server replays a definition it stored itself, during startup metadata loading.

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.

Filesystem now gets the right discriminator, but the shared invariant is still broken for the other external database engines that use the same startup-only exception. InterpreterParallelWithQuery::executeSubquery and InterpreterExecuteAsQuery::execute both rerun a user-authored ATTACH DATABASE with QueryFlags{ .internal = true }, and InterpreterCreateQuery::createDatabase forwards that bit here while is_metadata_replay stays false. DatabasePostgreSQL.cpp:715, DatabaseMaterializedPostgreSQL.cpp:786 / 818, and DatabaseDataLake.cpp:1688 still key their relaxed path on args.internal && args.mode >= LoadingStrictnessLevel::ATTACH, so the same wrapped ATTACH DATABASE ... PARALLEL WITH ... / EXECUTE AS ... shape still bypasses their startup-only checks even though it is not a metadata replay. For the PostgreSQL engines that means a user can persist a database pointing at a host that remote_url_allow_hosts should reject, and MaterializedPostgreSQL also skips its single-address validation. I think those consumers need to switch to args.is_metadata_replay in the same change, otherwise this PR only closes the laundering hole for Filesystem.

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.

Agreed, and verified against the source here: InterpreterParallelWithQuery.cpp:125 and InterpreterExecuteAsQuery.cpp:129 both re-run a user-authored statement with QueryFlags{ .internal = true }, so args.internal && args.mode >= LoadingStrictnessLevel::ATTACH does not mean "the server is replaying its own metadata". That is precisely why this PR stopped keying on it: is_metadata_replay is written in exactly one place, by the loader (loadMetadata.cpp:86), so no statement, wrapped or not, can set it.

On the three sibling engines, the disagreement is only about which PR carries the conversion, not about whether it is owed. It is already written: #116260 converts DatabasePostgreSQL.cpp:715, DatabaseMaterializedPostgreSQL.cpp:786/818 and DatabaseDataLake.cpp:1688, and threads the same marker through the same DatabaseFactory::get/getImpl signatures, under the name loading_stored_metadata. Repeating those hunks here would put the same three files in both PRs and turn a clean rebase into a conflict for whichever merges second.

Sequencing, so it does not need chasing: whichever of the two merges first keeps its flag name, the other rebases onto it and drops its own, so the tree ends with one marker rather than two. If #116260 stalls, or if reviewers would rather the siblings move with this fix, I will bring those hunks here and drop them from #116260 instead. I have added the residual to this PR's description so it is visible at merge time and not only in this thread.

This PR changes no sibling behaviour: all three predicates are byte-identical to master.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a46be7ae0 with master 55c256363 (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

49 translation units recompiled, 369 s compile time in total, 49 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 +28.3 s (+8%) in total before that adjustment.

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Very minor, and maybe an overkill. Still passable.

@PedroTadim

Copy link
Copy Markdown
Member

Need to backport this to fix CI in release branches

@groeneai

Copy link
Copy Markdown
Collaborator Author

The three older backports of this PR cannot be built or applied as the robot produced them. I measured all four arms:

Backport Target Git state Build
#119691 26.8 mergeable green
#119690 26.7 mergeable 6 of 6 build flavours fail
#119689 26.6 mergeable 6 of 6 build flavours fail
#119688 26.3 conflicting not built (do not test)

Cause on 26.6 and 26.7: this PR gave DatabaseFilesystem a fourth constructor parameter with no default value. On master the only construction site is the engine factory, which this PR updated in the same diff. Those two branches have a second, direct construction site that master no longer has, because master registers DatabaseURL there instead: programs/local/LocalServer.cpp:473 on 26.6 and :484 on 26.7 still build it with three arguments. So the cherry-pick applies textually clean and then fails with no matching constructor for initialization of 'DB::DatabaseFilesystem', one error in one file, on every flavour.

The remedy is one line on each of those branches:

-    overlay->registerNextDatabase(std::make_shared<DatabaseFilesystem>(name_, "", context));
+    overlay->registerNextDatabase(std::make_shared<DatabaseFilesystem>(name_, "", context, /*is_internal_metadata_replay=*/false));

false is what the factory's own derivation produces for that site: args.is_metadata_replay is written only by loadMetadata, and createClickHouseLocalDatabaseOverlay builds its database directly, outside the factory and outside metadata loading. It also keeps those branches behaving exactly as they did before this PR, because the path there resolves to the process working directory and its absence still has to throw. The smaller alternative is to give the parameter a default value in the header on the backport branch, but that moves the header away from master's bytes and undoes the reason the parameter has no default.

26.3 is a different problem. Its DatabaseFactory::get, getImpl and Arguments have no internal member at all, and this PR appends is_metadata_replay after internal, so that hunk has no pre-image and #119688 conflicts structurally rather than textually. Its InterpreterCreateQuery does already carry internal and loadMetadata already sets it, so threading is_metadata_replay alone through the factory and dropping the internal positional would work; whether that is preferable to also backporting the internal prerequisite is a maintainer's call, not mine.

I am not hand-authoring backport content: @ pufit's standing rule keeps that with the maintainers, and a fix pushed to the backport/* branch is also what CI actually tests, since a pull request based on that branch matches no workflow. If it is useful I will build and verify any of these on the branch and report the result.

@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer

Shell reproducer — set BIN to a ClickHouse binary path and run with bash; requires the referenced test fixtures from the repo.

#!/bin/bash
BIN="${BIN:-./clickhouse}"  # path to the ClickHouse binary under test
# PR #118684 — a `Filesystem` database whose backing directory was removed makes the
# startup metadata replay throw BAD_ARGUMENTS, so the server/clickhouse-local refuses
set -uo pipefail

D=$(mktemp -d /tmp/repro_118684_XXXXXX)
trap 'rm -rf "$D"' EXIT
mkdir -p "$D/files"

out1=$(timeout 60 "$BIN" local --path "$D/store" -q "CREATE DATABASE fsdb ENGINE = Filesystem('$D/files'); SELECT name FROM system.databases WHERE name = 'fsdb'" 2>&1)
rc1=$?
echo "== run 1: create over an existing directory (rc=$rc1) =="
echo "$out1"
[ "$rc1" = "124" ] && { echo "TIMEOUT on run 1"; exit 2; }
if [ "$rc1" != "0" ] || ! echo "$out1" | grep -q "^fsdb$"; then
    echo "INCONCLUSIVE: this build cannot create ENGINE = Filesystem over --path metadata"
    exit 2
fi

rm -rf "$D/files"

out2=$(timeout 60 "$BIN" local --path "$D/store" -q "SELECT name FROM system.databases WHERE name = 'fsdb'" 2>&1)
rc2=$?
echo "== run 2: same store, directory removed (rc=$rc2) =="
echo "$out2"
[ "$rc2" = "124" ] && { echo "TIMEOUT on run 2"; exit 2; }

if echo "$out2" | grep -q "Path does not exist"; then
    echo "BUG: metadata replay of the stored ATTACH DATABASE throws, nothing starts"
    exit 1
fi
if echo "$out2" | grep -q "^fsdb$"; then
    echo "CLEAN: database loaded without its directory"
    exit 0
fi
echo "INCONCLUSIVE: unexpected run-2 output"
exit 2

Results:

Backport the fix to 26.3.

CC component owner: @alexey-milovidov @scanhex12

Analysis metadata

comp-database-engines · Severity P2 · Finding phase_d_pr118684

  • Verified against master build 044e813459c6 (aarch64)
Introducing change: not identified
  • No clean release baseline found and no lower bound established — source-build bisect is required to pin the introducing PR (not yet performed).
  • Walked 6 release(s) below the supported window: still reproduces down to 25.8.
  • Secondary components: comp-testing

PedroTadim added a commit that referenced this pull request Sep 13, 2026
#118684 gave `DatabaseFilesystem`'s constructor a fourth parameter with no default
value. On master the factory in `DatabaseFilesystem.cpp` is the only place that
constructs one, so the change compiles there. This branch still has a second call
site that master no longer has: `createClickHouseLocalDatabaseOverlay` in
`programs/local/LocalServer.cpp`, which master rewrote to register a `DatabaseURL`
over `file://` instead, in a change that was never backported. Every build job
failed on it, each with a single error:

    programs/local/LocalServer.cpp: note: in instantiation of function template
    specialization 'std::make_shared<DB::DatabaseFilesystem, const std::string &,
    const char (&)[1], std::shared_ptr<const DB::Context> &, 0>' requested here
    allocator_traits.h:302:5: error: no matching function for call to '__construct_at'

Pass `false`, which keeps the behaviour this call site had. The flag only suppresses
the `Path does not exist` refusal while the server replays its own stored metadata,
and this overlay is registered fresh on every `clickhouse-local` start over an empty
path, which resolves to the current directory.

Adding a default argument to the declaration would also build, but it would leave the
header differing from master's and would hand the permissive value to any call site
added later. Naming the argument here keeps every ported file identical to master and
states the choice at the one place that has to make it.

26.8 needs none of this: it already carries the `DatabaseURL` rewrite, which is why
its backport merged green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 13, 2026
#118684 gave `DatabaseFilesystem`'s constructor a fourth parameter with no default
value. On master the factory in `DatabaseFilesystem.cpp` is the only place that
constructs one, so the change compiles there. This branch still has a second call
site that master no longer has: `createClickHouseLocalDatabaseOverlay` in
`programs/local/LocalServer.cpp`, which master rewrote to register a `DatabaseURL`
over `file://` instead, in a change that was never backported. Every build job
failed on it, each with a single error:

    programs/local/LocalServer.cpp: note: in instantiation of function template
    specialization 'std::make_shared<DB::DatabaseFilesystem, const std::string &,
    const char (&)[1], std::shared_ptr<const DB::Context> &, 0>' requested here
    allocator_traits.h:302:5: error: no matching function for call to '__construct_at'

Pass `false`, which keeps the behaviour this call site had. The flag only suppresses
the `Path does not exist` refusal while the server replays its own stored metadata,
and this overlay is registered fresh on every `clickhouse-local` start over an empty
path, which resolves to the current directory.

Adding a default argument to the declaration would also build, but it would leave the
header differing from master's and would hand the permissive value to any call site
added later. Naming the argument here keeps every ported file identical to master and
states the choice at the one place that has to make it.

26.8 needs none of this: it already carries the `DatabaseURL` rewrite, which is why
its backport merged green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 13, 2026
…tory is gone

Resolved four conflicts. Three of them are the same divergence: master threads an
`internal` flag through `DatabaseFactory::get`, `getImpl` and `Arguments`, which this
branch does not have, and #118684 adds `is_metadata_replay` alongside it. Only
`is_metadata_replay` belongs to this backport, so it is threaded on its own here and
the signatures keep their existing shape:

    get(create, metadata_path, context, mode, is_metadata_replay)
    getImpl(create, metadata_path, context, mode, is_metadata_replay)

The incoming hunk around `getImpl` also carried `isDatabaseExternal`, a master-only
function this branch never had; it is not part of #118684 and is left out. Nothing
references it. The `Arguments` comment is reworded for the same reason, since the
`internal` field it contrasts against does not exist in this struct here. The
`internal` concept itself does still exist on `InterpreterCreateQuery`, so the comment
in `DatabaseFilesystem.cpp` is master's, unchanged.

The fourth conflict is `02921_database_filesystem_path_check.sql`, where master had
renamed the fixed database name to `{CLICKHOUSE_DATABASE_1:Identifier}` before adding
this PR's four arms. Taking master's file whole: both that substitution and
`PARALLEL WITH` already work on this branch, so the arms run as written and the file
stays identical to master. The reference file is unchanged.

`clickhouse-local` here reaches `loadMetadata` exactly as master does, so the premise
of the new `05136_database_filesystem_missing_path_on_load` holds.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 13, 2026
#118684 gave `DatabaseFilesystem`'s constructor a fourth parameter with no default
value. On master the factory in `DatabaseFilesystem.cpp` is the only place that
constructs one, so the change compiles there. This branch still has a second call
site that master no longer has: `createClickHouseLocalDatabaseOverlay` in
`programs/local/LocalServer.cpp`, which master rewrote to register a `DatabaseURL`
over `file://` instead, in a change that was never backported. Every build job
failed on it, each with a single error:

    programs/local/LocalServer.cpp: note: in instantiation of function template
    specialization 'std::make_shared<DB::DatabaseFilesystem, const std::string &,
    const char (&)[1], std::shared_ptr<const DB::Context> &, 0>' requested here
    allocator_traits.h:302:5: error: no matching function for call to '__construct_at'

Pass `false`, which keeps the behaviour this call site had. The flag only suppresses
the `Path does not exist` refusal while the server replays its own stored metadata,
and this overlay is registered fresh on every `clickhouse-local` start over an empty
path, which resolves to the current directory.

Adding a default argument to the declaration would also build, but it would leave the
header differing from master's and would hand the permissive value to any call site
added later. Naming the argument here keeps every ported file identical to master and
states the choice at the one place that has to make it.

26.8 needs none of this: it already carries the `DatabaseURL` rewrite, which is why
its backport merged green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-clickhouse added a commit that referenced this pull request Sep 13, 2026
…y is gone instead of refusing to start
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #118684 to 26.6: Load a `Filesystem` database whose directory is gone instead of refusing to start
clickhouse-gh Bot added a commit that referenced this pull request Sep 13, 2026
Backport #118684 to 26.7: Load a `Filesystem` database whose directory is gone instead of refusing to start
alexey-milovidov added a commit that referenced this pull request Sep 13, 2026
Backport #118684 to 26.3: Load a `Filesystem` database whose directory is gone instead of refusing to start
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…e directory is gone instead of refusing to start
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…e directory is gone instead of refusing to start
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…e directory is gone instead of refusing to start
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Oct 21, 2026
…e accessed

The DatabaseFilesystem constructor probed its path with the throwing
fs::exists and, on a server, with pathStartsWith (fs::relative, which
canonicalizes). libc++ maps only ENOENT/ENOTDIR to "not found", so any
other stat error (ELOOP, EACCES, ESTALE, EIO, ENAMETOOLONG) escaped as
Code: 1001 STD_EXCEPTION before the startup-replay guard of ClickHouse#118684.
loadMetadata stops at the first exception, so a server or a
clickhouse-local --path store holding such a database refused to start,
and the database could not be dropped.

Probe once with fs::exists(path, ec). When stat works, containment keeps
the canonical pathStartsWith check. When it fails, the path cannot be
canonicalized, so containment is checked lexically with
fileOrSymlinkPathStartsWith, the check every table resolution already
uses, and a path outside user_files is still refused on replay. An
unreachable path is then handled like a missing one: the replay logs the
errno and attaches the database with no tables, and a user statement
gets BAD_ARGUMENTS with the errno instead of STD_EXCEPTION. Missing and
existing paths behave exactly as before.

05136 gains a symlink-loop restart sequence for clickhouse-local and two
server arms with a component over NAME_MAX, inside and outside
user_files.

Closes ClickHouse#121705

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants