Skip to content

Merge table function filesystem. Originally #42039. Originally #50208. - #53610

Merged
alexey-milovidov merged 154 commits into
masterfrom
qoega-table-function-filesystem
May 6, 2026
Merged

alexey-milovidov merged 154 commits into
masterfrom
qoega-table-function-filesystem

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 20, 2023 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

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

  • Merged into: 26.5.1.361

alexey-milovidov and others added 2 commits May 4, 2026 05:09
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]>
Comment thread src/Storages/StorageFilesystem.cpp Outdated
: canonical_user_files_path.string();

return std::make_shared<StorageFilesystem>(
args.table_id, args.columns, args.constraints, args.comment, local_mode, path,

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.

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:

  1. CREATE TABLE t (x UInt8) ENGINE = Filesystem('/var/lib/clickhouse/user_files');
  2. 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.

alexey-milovidov and others added 2 commits May 4, 2026 16:56
…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"; }

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.

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

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.

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

alexey-milovidov and others added 4 commits May 5, 2026 02:51
…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);

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.

user_files_path is canonicalized here, but later checks use fileOrSymlinkPathStartsWith(file_path, user_files_absolute_path_string) (lexical, non-canonical).

Concrete trace:

  1. Server config: user_files_path=/srv/ch_user_files (symlink to /mnt/storage/user_files).
  2. Query: SELECT count() FROM filesystem('/srv/ch_user_files/subdir').
  3. user_files_absolute_path_string becomes /mnt/storage/user_files (canonical).
  4. file_path becomes /srv/ch_user_files/subdir (absolute + lexically normalized).
  5. fileOrSymlinkPathStartsWith('/srv/ch_user_files/subdir', '/mnt/storage/user_files') is false, so we throw DATABASE_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"])

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.

/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.
@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 86.14% (317/368) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this May 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 6, 2026
Merged via the queue into master with commit db00f4b May 6, 2026
324 of 326 checks passed
@alexey-milovidov
alexey-milovidov deleted the qoega-table-function-filesystem branch May 6, 2026 22:26
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 6, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Should we add a setting to enable this function? There could be security concerns on this?

Comment on lines +310 to +311
LOG_DEBUG(getLogger("StorageFilesystem"), "Path {} is not inside user_files {}",
child_path.string(), path_info->user_files_absolute_path_string);

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.

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

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

Labels

pr-feature Pull request with new product feature 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.

7 participants