Repository navigation
Merge table function filesystem. Originally #42039. Originally #50208. - #53610
Conversation
- Synchronized with master - Bug fixes
- Synchronized with master - Bug fixes
The `Docs check` CI job timed out at 300 seconds running this script, because `clickhouse-local` was hanging in shutdown for several minutes when launched with a config containing many `*_log` table entries. Stack trace at the time of hang (debug build): ``` DB::SystemLogQueue<DB::FilesystemCacheLogElement>::~SystemLogQueue -> __pthread_cond_destroy (futex_wait, expected=12) DB::SystemLogs::~SystemLogs DB::ContextSharedPart::~ContextSharedPart DB::SharedContextHolder::~SharedContextHolder DB::ClientBase::~ClientBase DB::LocalServer::~LocalServer mainEntryClickHouseLocal ``` The config (`utils/generate-system-tables-docs-config.xml`) attempted to enable `query_log`, `trace_log`, etc. for the script's introspection queries, but `clickhouse-local` does not actually create those tables (initialization requires full server infrastructure), so the config provided no benefit. It only triggered the shutdown-hang path scaling super-linearly with the number of configured logs: | logs | startup | |------|---------| | 2 | 0.16 s | | 5 | 0.23 s | | 8 | 1.30 s | | 10 | 8.77 s | | 30 | ~280 s | Drop the default config and remove the file. The `--config` flag remains available for explicit opt-in. The full script now runs in under one second. Failing CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=53610&sha=1130968a24bf9e680aa286b2549357660f79e92b&name_0=PR&name_1=Docs%20check PR: #53610 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…T claim Two small adjustments based on bot review feedback on PR #53610: 1. `ReadFromFilesystem::applyFilters` previously assumed `storage_snapshot->metadata` always contained every entry from `cheap_column_names` (`path`, `name`, `depth`, `type`, `is_symlink`), and called `getByName` directly. Because `ENGINE = Filesystem` is exposed via the storage factory, a user can `CREATE TABLE` with a reduced column subset, and any query with a filter would then fail at runtime with `getByName` throwing. Skip cheap columns that the table's schema does not expose, so filter pushdown gracefully degrades to whichever cheap columns are present. 2. The "Early LIMIT" optimization claim in the table function description overstated the guarantee. `expandDirectory` enumerates each visited directory in full before returning, so `LIMIT 1` over a single very large directory still pays the full enumeration cost. Reword as "Streaming LIMIT" with an explicit note about per-directory eager enumeration, so the docs match observable behavior. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| : canonical_user_files_path.string(); | ||
|
|
||
| return std::make_shared<StorageFilesystem>( | ||
| args.table_id, args.columns, args.constraints, args.comment, local_mode, path, |
There was a problem hiding this comment.
ENGINE = Filesystem currently accepts any user-defined column list (args.columns), but FilesystemSource::fillEntryColumns only fills a fixed set of known names (path, name, depth, type, is_symlink, size, modification_time, content, and permissions).
Concrete repro:
CREATE TABLE t (x UInt8) ENGINE = Filesystem('/var/lib/clickhouse/user_files');SELECT * FROM t;
generate increments total_rows for each entry, while column x remains empty. That produces a chunk with mismatched row counts and fails at runtime.
Please either validate args.columns at creation time (reject unknown columns / enforce exact schema), or remove direct ENGINE = Filesystem registration and keep only filesystem table function.
…ation The `Filesystem` storage is an implementation detail of the `filesystem` table function. Allowing direct `CREATE TABLE ... ENGINE = Filesystem(...)` was unsafe because `args.columns` was accepted as-is, while `FilesystemSource::fillEntryColumns` only fills a fixed set of column names. A user-declared schema with unknown columns (e.g. `CREATE TABLE t (x UInt8) ENGINE = Filesystem(...)`) produced chunks with mismatched row counts and failed at runtime. Drop the storage-engine registration entirely; the table function constructs `StorageFilesystem` directly with the canonical schema. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| ColumnsDescription getActualTableStructure(ContextPtr /* context */, bool /* is_insert_query */) const override; | ||
|
|
||
| private: | ||
| const char * getStorageEngineName() const override { return "Filesystem"; } |
There was a problem hiding this comment.
TableFunctionFilesystem::getStorageEngineName currently returns "Filesystem", but no storage engine with this name is registered in StorageFactory.
ITableFunction::checkSourceAccess calls StorageFactory::getSourceAccessObject(getStorageEngineName()), and for unknown engine names that throws UNKNOWN_STORAGE. Existing table functions that use custom storages avoid this by returning an empty engine name (for example numbers), while file-backed functions return "File" to enforce FILE source access.
Please change this to a registered engine name (most likely "File" if you want FILE source access checks) or otherwise override source-access resolution, otherwise filesystem can fail at execution time before executeImpl.
| } | ||
| } | ||
|
|
||
| path_info->in_flight.fetch_add(1); |
There was a problem hiding this comment.
in_flight is incremented before enqueue (fetch_add), including entries that spill into local_overflow, but those counts are decremented only when an entry is later popped and processed.
If a FilesystemSource instance is cancelled/destroyed while its thread-local local_overflow still has entries, those entries are dropped without decrementing in_flight. Then in_flight can stay permanently positive, queue.finish() is never reached, and sibling streams can keep polling an empty queue until cancellation instead of completing naturally.
Could you make in_flight accounting symmetric for overflowed-but-never-processed entries (for example by decrementing leftovers in FilesystemSource destructor, or by draining local_overflow before returning on cancellation)?
…access The previous commit removed the `Filesystem` storage-engine registration, but `TableFunctionFilesystem::getStorageEngineName` still returned `"Filesystem"`. At runtime, `ITableFunction::checkSourceAccess` calls `StorageFactory::getSourceAccessObject(getStorageEngineName())`, which throws `UNKNOWN_STORAGE` (`Code: 56. Unknown table engine Filesystem.`) when the engine is not registered. This caused `04041_filesystem_table_function` and `04201_filesystem_symlink_cycle` to fail in CI. Override `getSourceAccessObject` directly to return `AccessTypeObjects::Source::FILE`, bypassing the `StorageFactory` lookup. Make `getStorageEngineName` return an empty string since the storage is constructed directly by `executeImpl`, not via `StorageFactory`. CI: #53610 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When a `FilesystemSource` is destroyed with non-empty `local_overflow` (e.g. on cancellation from a sibling stream completing or `LIMIT` short-circuit), the corresponding `in_flight` increments would never be decremented. Sibling streams could then keep polling the shared queue indefinitely because `in_flight > 0` blocks the `queue.finish()` transition. Decrement `in_flight` for any leftover overflow entries in the destructor and call `queue.finish()` if that brings the counter to zero, so sibling streams complete naturally instead of having to wait for cancellation to propagate. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| /// `user_files_path` may not exist, so fall back to a lexically-normalized absolute path. | ||
| fs::path user_files_path(context->getUserFilesPath()); | ||
| std::error_code ec; | ||
| auto canonical_user_files_path = fs::canonical(user_files_path, ec); |
There was a problem hiding this comment.
user_files_path is canonicalized here, but later checks use fileOrSymlinkPathStartsWith(file_path, user_files_absolute_path_string) (lexical, non-canonical).
Concrete trace:
- Server config:
user_files_path=/srv/ch_user_files(symlink to/mnt/storage/user_files). - Query:
SELECT count() FROM filesystem('/srv/ch_user_files/subdir'). user_files_absolute_path_stringbecomes/mnt/storage/user_files(canonical).file_pathbecomes/srv/ch_user_files/subdir(absolute + lexically normalized).fileOrSymlinkPathStartsWith('/srv/ch_user_files/subdir', '/mnt/storage/user_files')is false, so we throwDATABASE_ACCESS_DENIED.
So an absolute path under the configured user_files_path is rejected whenever user_files_path itself is a symlink. Please keep the prefix used for this check in the same lexical namespace as user input (use context->getUserFilesPath() for prefix checks, and reserve canonicalization only for cycle/visited tracking if needed).
`fileOrSymlinkPathStartsWith` compares lexically-normalized absolute paths, so canonicalizing the prefix put it in a different namespace than user input whenever `user_files_path` was a symlink. Concretely, with `user_files_path=/srv/ch_user_files` symlinked to `/mnt/storage/user_files`, an absolute path `/srv/ch_user_files/subdir` was rejected with `DATABASE_ACCESS_DENIED` because it did not start with the canonical `/mnt/storage/user_files`. Switch to a lexically-normalized absolute path for the prefix. This also drops the requirement that `user_files_path` exist on disk, which is a common case in `clickhouse-local`.
|
|
||
| # Create a controlled directory outside user_files for symlink testing. | ||
| # Using /var/log/clickhouse-server/ would include an unpredictable number of log files. | ||
| node.exec_in_container(["mkdir", "-p", "/tmp/link_target"]) |
There was a problem hiding this comment.
/tmp/link_target is created with mkdir -p, but the test later asserts exact row counts (23 and 1) that assume this directory contains only test.log. If that path already exists in the container (for example from a previous run in a reused environment), extra files will make this test flaky.
Can we make the fixture deterministic by resetting the directory first, e.g. rm -rf /tmp/link_target && mkdir -p /tmp/link_target before creating test.log?
Avoid flaky exact row counts in `test_filesystem` if the container reuses a directory that already contains entries from a previous run.
LLVM Coverage Report
Changed lines: 86.14% (317/368) · Uncovered code |
|
Should we add a setting to enable this function? There could be security concerns on this? |
| LOG_DEBUG(getLogger("StorageFilesystem"), "Path {} is not inside user_files {}", | ||
| child_path.string(), path_info->user_files_absolute_path_string); |
There was a problem hiding this comment.
This is for the case when some children contains a symlink outside of the user_files_path?
Shouldn't we throw in this case?
Also make sense to add a test
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Add table function
filesystem. It allows to represent directory structure as a table, to query files' metadata and contents with SQL. Originally #42039 by @perst20. See #42039. See #50208.Version info
26.5.1.361