Skip to content

Add the mergeTreeParts table function - #115722

Open
alexey-milovidov wants to merge 79 commits into
masterfrom
merge-tree-parts-table-function
Open

alexey-milovidov wants to merge 79 commits into
masterfrom
merge-tree-parts-table-function

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Brings the mergeTreeParts table function over from the private repository, where it is used to read
MergeTree data parts on a server that has no table and no table metadata for them. Everything a
MergeTree table would normally take from its own metadata — the list of parts, the mark ranges, the
column structure and the index granularity — is written out in the query instead:

SELECT count()
FROM mergeTreeParts(
    structure('dt Date, id Int64, data String'),
    parts(Wide(path = 'store/707/70794cd7-9505-4011-9400-fde425bb25d1/20000101_1_1_0/',
               marks_count = 1954,
               ranges = [(0, 1953)],
               has_lightweight_delete = 0)),
    disk(type = s3, endpoint = 'https://mybucket.s3.amazonaws.com/data/',
         access_key_id = '...', secret_access_key = '...'),
    table_settings(index_granularity_bytes = 10485760))

table_settings carries the settings of the source table that the parts do not describe themselves:
index_granularity_bytes (required), index_granularity (the granule size of a part with
non-adaptive marks), share_nested_offsets (which decides the names of the offsets streams of a
Nested column) and format_version (0 for a table created with the deprecated
MergeTree(date, ...) syntax, whose part names have a layout of their own). A part path must be relative and must stay inside the root of the disk.

It is a low-level introspection and recovery tool: passing values that do not match what is on the disk
gives an error or garbage. PREWHERE is supported and pushed down to the part readers, and a
materialized lightweight-delete mask is applied.

What is ported

StorageMergeTreeParts and the MergeTreeReadPoolStatelessParts read pool behind it,
BorrowedMergeTreeDataPartInfoForReader (an IMergeTreeDataPartInfoForReader for a part built on the
fly rather than loaded by a table), and the table function itself. The pool derives from
MergeTreeReadPool, so the parts are read with the ordinary machinery: work is spread by marks rather
than by parts, threads steal from each other's queues, and slow reads lower the number of active
threads through the inherited backoff.

Three small changes to the shared pool classes make the subclass possible, and are the same ones the
private repository made: the members of MergeTreeReadPool become protected, the per-part task size
becomes a virtual getMinMarksPerTask (a pool that builds its task infos lazily has no
per_part_infos to read it from), and buildAnnouncementDescriptions becomes virtual — a borrowed
part has no RangesInDataPart to announce.

The private repository also ships per-part metadata from a coordinator to its workers, so they can skip
reading it from object storage. None of that is here; the parts are described only by their location,
and the reader is built from columns.txt, serialization.json, columns_substreams.txt, the marks
and the checksums of the part itself.

Differences from the private version

The disk argument did not work there. The disk was created with the disk name as the configuration
prefix while the configuration built from the arguments is rooted at the disk itself, so nothing under
disk(...) was ever read and type fell back to its local default — every invocation produced an
empty local disk under the server path. The disk now goes through DiskFromAST::createCustomDisk, the
same path as SETTINGS disk = disk(...) of a table definition, so the restrictions on dynamically
configured disks apply as well: a local disk must live under custom_local_disks_base_directory, and
an S3 disk cannot resolve the server's own credentials. read_only and skip_access_check are forced
on.

Two arguments are dropped. metadata = [...] of a part only set an in_memory_metadata flag on the
disk configuration, which no disk implementation has read since the metadata storages were reworked, so
it was silently ignored. disk(config_path = '...') copied a disk definition out of the server
configuration file, which would let any user read the raw parts of tables stored on a server-configured
disk without that disk's credentials and without table-level grants.

Reading requires the READ grant on the source that matches the kind of the disk — FILE, S3,
AZURE, HDFS or URL — and the function is not allowed in readonly mode. A filtered grant is
matched against the literal endpoint of the disk; a local disk and an Azure disk need the unfiltered
grant (a filtered AZURE grant is matched against a blob name, while the disk reads any blob of its container). The disk type must be a literal, include is rejected, and the keys that decide the source
or its location cannot be repeated, so the access check always looks at the source the disk is created
for; the disk itself is created only after the check, and is not registered on the server.

Testing

05024_merge_tree_parts_table_function writes a MergeTree table to one disk and reads its parts back
through a second disk that knows nothing but where they are, checking the result against the table
itself. It covers all four combinations of Wide/Compact parts and full/packed part storage, PREWHERE,
a materialized lightweight-delete mask, a read that forces each part's mark ranges to be split across
threads, and an empty part list. 05025_merge_tree_parts_bad_arguments covers the argument errors, including part paths that leave the
root of the disk. 05029_merge_tree_parts_table_settings reads back a table written with
index_granularity_bytes = 0 and one with a Nested column written with share_nested_offsets = 0.

The same tests, with the same reference file, were run against the private repository, where the fixes
above are applied in a separate change.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added the mergeTreeParts table function, which reads a set of MergeTree data parts that the query describes explicitly - by path, part type, mark ranges, column structure and index granularity - from a disk that the query also describes. It needs neither a table nor any table metadata on the server running the query, so it can read the parts of a table that lives elsewhere as long as the disk is reachable. PREWHERE is supported. It configures a disk from its arguments, so it is not allowed in readonly mode and requires the READ grant on the source matching the kind of the disk.


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

robot-clickhouse and others added 2 commits August 20, 2026 22:14
Port the `mergeTreeParts` table function and the `StorageMergeTreeParts`
storage behind it from the private repository. They read a set of MergeTree
data parts that the query describes explicitly - by path, part type, mark
ranges and column structure - from a disk that the query also describes, so
neither a table nor any table metadata is needed on the server that runs the
query.

Ported along with them:

- `BorrowedMergeTreeDataPartInfoForReader`, the `IMergeTreeDataPartInfoForReader`
  implementation for a part that is built on the fly instead of being loaded by
  a `MergeTree` table. `IMergeTreeReader::fillVirtualColumns` returns early for
  such a part instead of throwing, as it does in the private repository.
- A `MergeTreeIndexGranularityInfo` constructor that takes the granularity
  explicitly, for a part read without the settings of the table that owns it.

Differences from the private version, all in the handling of the `disk`
argument, whose original form did not work:

- The disk was created with the disk name as the configuration prefix, while
  the configuration built from the arguments is rooted at the disk itself, so
  none of the passed settings were read and every disk came out as a `local`
  disk under the server path. The disk is now created through
  `DiskFromAST::createCustomDisk`, the same path as `SETTINGS disk = disk(...)`
  of a table definition, which also applies the restrictions on dynamically
  configured disks - the base directory of custom local disks and the
  server-managed S3 credential check. `read_only` and `skip_access_check` are
  forced on.
- The `metadata = [...]` argument of a part is dropped. It only set an
  `in_memory_metadata` flag on the disk configuration, which no disk
  implementation reads anymore, so the argument was silently ignored.
- The `disk(config_path = '...')` form is dropped. It copied a disk definition
  out of the server configuration file, which would let any user read the raw
  parts of tables stored on a server-configured disk, without the credentials
  of that disk and without table-level grants.

The function is not allowed in readonly mode, and reading requires the `READ`
grant on the source that corresponds to the kind of the disk (`FILE`, `S3`,
`AZURE`, `HDFS` or `URL`).

The arguments are functions rather than expressions, so they are excluded from
query analysis through `skipAnalysisForArguments`; without it the analyzer
failed to resolve `structure(...)`.

The private integration test `test_table_function_merge_tree_parts` is not
ported: it is in the private skip list, and it depends on the `metadata = [...]`
argument. Its coverage is replaced by a stateless test that reads the parts of a
`MergeTree` table back through a second disk, for all four combinations of
Wide/Compact parts and full/packed part storage, with `PREWHERE` and with a
materialized lightweight delete mask.

Co-Authored-By: Claude Fable 5 <[email protected]>
Re-port `StorageMergeTreeParts` from the revision of the private repository that
maintains it. The first port was taken from a checkout that was ten days behind,
and in the meantime the bespoke source that read one part per stream was replaced
by `MergeTreeReadPoolStatelessParts`, a `MergeTreeReadPool` subclass. The storage
shrinks to assembling the pool and the sources; the reader construction moves into
the pool.

What this buys over the hand-rolled source:

- Work is spread by marks rather than by parts, so a query over a single large
  part fans out across threads instead of running on one; threads steal from each
  other's queues when their own run dry, and slow reads lower the number of active
  threads through the inherited backoff.
- The per-part read task info is a `MergeTreeReadTaskInfo`, so the lightweight
  delete step is owned for as long as the readers chain that points at it. The
  hand-rolled source built that step in a local, which the chain then referenced
  after it was destroyed - a use-after-free on any part with a materialized delete
  mask.
- The reading side is the standard `MergeTreeSelectProcessor` / `MergeTreeSource`,
  rather than a second implementation of chunk assembly and progress reporting.

Only the parts of the private version that the table function can populate are
taken. The coordinator of the distributed-query work also ships per-part metadata
(the part's columns, serialization infos, granularity, substreams, column sizes
and the auxiliary info of packed parts) so its workers can skip reading it from
object storage; none of that is ported, and neither is the `buildReaderInfoFromMetadata`
path that consumes it. What remains is `buildReaderInfoFromDisk`, which reads
`columns.txt`, `serialization.json`, `columns_substreams.txt`, the marks and the
checksums from the part itself - the path the table function uses.

Three small changes to the shared read-pool classes make the subclass possible,
identical to the private ones: the members of `MergeTreeReadPool` become protected,
the per-part task size becomes a virtual `getMinMarksPerTask` (a pool that builds
its task infos lazily has no `per_part_infos` to read it from), and
`buildAnnouncementDescriptions` becomes virtual (borrowed parts have no
`RangesInDataPart` to announce).

The stateless test is extended with a read that forces each part's mark ranges to
be split across threads, and with an empty part list. Its reference is unchanged
otherwise: the pool returns exactly what the previous implementation returned, for
all four combinations of Wide/Compact parts and full/packed part storage, with
`PREWHERE` and with a materialized lightweight delete mask. The same test and
reference now run against the private repository too.

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

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2c7781c]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
Server died FAIL cidb
UndefinedBehaviorSanitizer: undefined behavior (STID: 3791-45ea) FAIL cidb
Stateless tests (amd_asan_ubsan, flaky check) FAIL
Server died FAIL cidb
UndefinedBehaviorSanitizer: undefined behavior (STID: 3791-45ea) FAIL cidb
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
Server died FAIL cidb
UndefinedBehaviorSanitizer: undefined behavior (STID: 3791-45ea) FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (wasm64) DROPPED
Build (arm_fuzzers) DROPPED
Integration tests (arm_binary, distributed plan, targeted) DROPPED
Integration tests (amd_tsan, targeted) DROPPED

AI Review

Summary

Adds mergeTreeParts to read explicitly described MergeTree parts without their owning table, using a query-local disk and the existing read machinery. Block: three source-traced issues remain in read-only enforcement, filtered source authorization, and malformed compact-part handling. Previously fixed findings are dropped; the author's decision to defer general disk-factory dry-run validation is accepted.

Findings

❌ Blockers

  1. A read can replay destructive metadata maintenance. TableFunctionMergeTreeParts.cpp:572: read_only adds a ReadOnlyDiskWrapper, but startup still reaches MetadataStorageFromDisk::startup and BlobKillerThread. With metadata_type = local and persistent_removal_log = 1, an existing .metadata/blobs_to_remove.log is replayed and queued objects are deleted directly through the underlying object storage. A SELECT authorized only for READ can therefore delete data. Prevent query-local disk startup/maintenance from mutating the source, including replay of removal queues.

  2. Local metadata bypasses filtered S3 prefixes. TableFunctionMergeTreeParts.cpp:586: authorization checks only the literal endpoint, although accepted local metadata can contain version 5 object keys outside that endpoint's prefix. DiskObjectStorage::prepareRead forwards them to S3ObjectStorage::readObject unchanged. A grant covering https://host/bucket/allowed/.* can thus authorize reads of other/... when the provided credentials can access both. Require an unfiltered grant for unconstrained metadata modes, or check effective object locations before access.

  3. Malformed compact metadata reaches an empty-list access. MergeTreeReadPoolStatelessParts.cpp:316: columns_substreams is not validated against the physical columns. A compact .mrk4 part with zero columns in columns.txt and one substream in columns_substreams.txt passes the nonzero marks-per-granule check. Matching marks and readable checksums then let getReadTaskColumns reach BorrowedMergeTreeDataPartInfoForReader::getColumnNameWithMinimumCompressedSize with an empty list, causing undefined behavior at available_columns.front. Reject empty physical columns and validate the substream-column correspondence before constructing the reader.

Tests

The current-head Fast test report has 16 passing and 7 skipped merge_tree_parts tests; the S3/Azure grant tests are skipped there. The remaining CI suite is pending. No local tests were run: this CI job has no ClickHouse binary, and nested Praktika execution is prohibited. The findings above are based on source traces, without runtime reproductions.

  • ⚠️ Add a non-empty read proving that a persisted removal queue and its objects remain untouched.
  • ⚠️ Add an RBAC regression reading real parts through local metadata whose object keys lie outside the granted S3 prefix.
  • ⚠️ Add a malformed compact-part regression proving that inconsistent empty columns produce a regular exception.
Final Verdict

Status: ❌ Block

Prevent destructive maintenance on the read path, enforce source grants on effective object locations, and reject invalid compact-part metadata before unchecked column access. Cover each fix with its focused regression.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 21, 2026
…are_nested_offsets`

Three gaps in what the query has to describe, and the `clang-tidy` failure.

`path` of a part is joined onto the root of the disk when the part is read, and `std::filesystem`
drops the left-hand side of the join for an absolute right-hand side and keeps `..` components, so
`path = '/var/lib/clickhouse/store/...'` or `path = '../../store/...'` stepped outside the disk and
past the `custom_local_disks_base_directory` confinement that `createCustomDisk` applies to the disk
itself. Absolute and escaping part paths are now rejected.

`table_settings` only carried `index_granularity_bytes`, so a part with non-adaptive marks was read
with a granule size of zero: `buildReaderInfoFromDisk` turns adaptivity off for such a part while
`fixed_index_granularity` stayed at `0`, and `MergeTreeDataPartWide::loadIndexGranularityImpl` then
built a `MergeTreeIndexGranularityConstant(0, 0, ...)`. It takes `index_granularity` now, `8192` by
default.

The borrowed parts were reconstructed with a default-constructed `MergeTreeSettings`, so they were
always read as if `share_nested_offsets = 1`, which is both the names of the offsets streams of a
`Nested` column and whether dotted `Array` columns are collected into one. `table_settings` takes
`share_nested_offsets` as well.

`fillPerThreadInfoForBorrowedParts` runs from the constructor, so it must not reach the size of a task
through the virtual `getMinMarksPerTask` - the override returns `min_marks_per_task` for every part
anyway. This is what `clang-analyzer-optin.cplusplus.VirtualCall` reported in `Build (arm_tidy)`.

`05029_merge_tree_parts_table_settings` reads back a table written with `index_granularity_bytes = 0`
and one written with `share_nested_offsets = 0`, and `05025_merge_tree_parts_bad_arguments` covers the
rejected part paths.
Comment thread src/Storages/StorageMergeTreeParts.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2c7781cb2 with master cb694c085 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

71 object files changed (+1.26 MiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReadPoolStatelessParts.cpp.o new 465.00 KiB +465.00 KiB
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionMergeTreeParts.cpp.o new 391.15 KiB +391.15 KiB
src/CMakeFiles/dbms.dir/Storages/StorageMergeTreeParts.cpp.o new 338.91 KiB +338.91 KiB
src/CMakeFiles/dbms.dir/Disks/DiskFromAST.cpp.o 248.74 KiB 269.11 KiB +20.37 KiB (+8.19%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

408 translation units recompiled, 2958 s compile time in total, 405 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Storages/StorageMergeTreeParts.cpp: 7.3 s
  • src/Storages/MergeTree/MergeTreeReadPoolStatelessParts.cpp: 7.2 s

Job report

@shankar-iyer shankar-iyer self-assigned this Aug 24, 2026
…le settings

- `ranges` of `mergeTreeParts` are now validated during argument parsing: negative
  bounds, `begin >= end`, ends beyond `marks_count`, and unsorted or overlapping
  ranges are rejected as `BAD_ARGUMENTS`. `MarkRange` checks `begin <= end` only
  with an assertion that release builds compile out, so a bad range would underflow
  the mark arithmetic and drive the read scheduler off bogus mark counts. Found by
  the AST fuzzer: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115722&sha=403afa8f7760bd87d5b5e7598bbd925a9feebb0a&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

- `StorageMergeTreeParts::read` sized `min_marks_for_concurrent_read` from a
  default-constructed `MergeTreeSettings` instead of the granularity carried in
  `table_settings(...)`. The settings construction is now shared with the read pool
  as `ReadFromPartsInfo::buildStorageSettings`, and a new test pins the stream
  count for both a rows-based and a bytes-based concurrent-read threshold.

- `getDiskConfigurationFromASTImpl` indexed the value of a `key=value` pair after
  only checking that the argument list is non-empty, so an `equals` with a single
  child, e.g. `disk(equals(type))`, read past the end of the list. Found by the
  AST fuzzer: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115722&sha=403afa8f7760bd87d5b5e7598bbd925a9feebb0a&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

- `05024_merge_tree_parts_table_function` ran longer than the 180 seconds the flaky
  check allows: the parts description is now computed once per state instead of once
  per read, the row count is smaller, and the synchronous lightweight-delete mutation
  runs once per part type instead of once per combination.

PR: #115722
Master added a pure virtual `getPartition` to `IMergeTreeDataPartInfoForReader`
for folding partition predicates into skip-index conditions. The partition value
is not loaded for a borrowed part, and skip indexes are never read through one,
so it throws `NOT_IMPLEMENTED` like `getIndexPtr`.
… query

`mergeTreeParts` used to create its disk in `parseArguments`, which runs before
`ITableFunction::checkSourceAccess` and the readonly gate of `ITableFunction::execute`, and it
registered the disk in the `DiskSelector` of the context, so a rejected `SELECT` could still start
a disk (a local disk creates its directory on startup) and every unique `disk(...)` value grew the
global disk map until restart.

Now `parseArguments` only keeps the sanitized disk description, the source to check access for is
derived from the literal `type` of that description (a substitution, a wrapper disk, or a missing
`type` is rejected before anything is resolved), and the disk is created in `executeImpl`, after
the access and readonly checks, through the new `DiskFromAST::createTransientDisk`, which applies
the same validation as `DiskFromAST::createCustomDisk` but never registers the disk anywhere: it
lives only as long as the storage of the query.

#115722 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
…eParts`

The access check for `mergeTreeParts` derives the required source from the
literal `type` of the disk description, and it runs before the disk is created.
`include` pulls part of the description out of the server configuration, so with
`dynamic_disk_allow_include = 1` a query could pass a non-S3 `type` through
`checkSourceAccess` and then have `DiskFromAST::createTransientDisk` resolve and
start a disk with a completely different backend. The comment above the loop
already claimed that `include` was rejected there; now it actually is.

Test `05044_merge_tree_parts_disk_include`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115722&sha=5b48129244a21391556d7989b12045318076eedd&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 — Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-348f), aborting in DistinctSortedStreamTransform::transform via ColumnVector<int>::getEqualRangeEndAssumeSorted. It is unrelated to this PR (which only adds the mergeTreeParts table function) and matches the open issue #115455, which has no fix yet. Please provide a fix in a separate PR, or link it here if one is already in progress.

The other red, 04312_client_chime_on_slow_query_92718 in Stateless tests (amd_debug, parallel), is a known timing flake already being fixed by #116033.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #113242 "Do not push sorting into Merge children across an order-breaking cast".

I resolved the carrier out of the run you linked rather than matching on the STID, since 2508-348f pools more than one mechanism. fatal.log gives query_id 2f89c951-c1ec-492a-a9bb-c26d8dc64242, and query_log gives log_comment 04870_distinct_merge_over_distributed.sql plus the fuzzer-minted fixture

CREATE TABLE merge_distinct__fuzz_3 (`s` Time) ENGINE = Merge(currentDatabase(), '^dist_distinct$')

whose only child dist_distinct is Distributed(..., t_distinct) over t_distinct (s String). So the child conversion is String to Time, DataTypeTime is a DataTypeNumberBase<Int32>, and that is the ColumnVector<int> in your frame. ReadFromMerge still delegated the sort to the child, the conversion reordered the values, and DistinctSortedStreamTransform then met equal keys that are not adjacent. The fuzzer's only contribution is the retyping: the shape aborts with no fuzzer and no WITH TIES.

Measured on master b6f3fe1a, debug, one build directory, the two arms differing only by that PR's 92 lines in StorageMerge.cpp:

child declared Time child declared String (control)
master, build id 8C166615 aborts, your stack, client rc 32 21, plan keeps DistinctSortedStreamTransform
with #113242, build id 3A8E07BC 21, rc 0 21

The control is what makes that non-vacuous: an identity conversion keeps both the result and the transform, so the gate withdraws the delegation only for the order-breaking pair. Time is not in that PR's regression test, but conversionPreservesOrder is fail-closed and refuses every pair it does not recognise, so this one is covered by construction. The patch still applies cleanly to today's master, and the abort reproduces the same way on a pristine-master build (9adeb11c, build id 1AA0CC11).

#113242 is blocked rather than unfinished. Its only test-level red is Fast test / 00717_merge_and_distributed, which CIDB shows twice in 30 days, both times on that PR and never on master or on any other PR; the Finish Workflow / Post Hooks red is downstream of it. #113735 fixes that test and is sitting at CHANGES_REQUESTED, and while Fast test is red the Mergeable Check drops the other 148 checks, so the PR has never had a full CI run.

One adjacent point, since this family is landing on a lot of PRs: the stress runner feeds 04870, a shard test, to the AST fuzzer, and the whole assertion family went from 28 rows in the 19 days before 2026-08-17 to 169 in the 11 days since, which is when that test merged. #115839 pins ast_fuzzer_runs = 0 on it, +7/-0, open and unreviewed since 08-21. That would take the noise out independently of the engine fix.

Comment thread src/Disks/DiskFromAST.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 65f39b50-d923-446e-8705-25a730d919b9
  • MIRAI run: 1c1e4b94-8e22-4f35-9aca-4a99f41c6ed1
  • PR check IDs:
    • clickbench_899341_1791739132
    • clickbench_899347_1791739132
    • clickbench_899353_1791739132
    • tpch_adapted_1_official_899364_1791739132
    • tpch_adapted_1_official_899375_1791739132
    • tpch_adapted_1_official_899411_1791739132

…it is created

`DiskFromAST::createTransientDisk` checked `custom_local_disks_base_directory` on the disk that came
out of `DiskFactory::create`, which is too late: creating a disk starts it, `DiskLocal::setup` creates
the directory right there, and a local object storage creates it in the constructor of
`LocalObjectStorage` - for which `isRemote` is also true, so the post-check never looked at it. A
`mergeTreeParts` query with only `READ ON FILE` could therefore create a directory anywhere on the
server before being rejected.

The local paths the resolved configuration can carry (`path` of a `local`, `local_blob_storage`,
`local_plain`, `local_plain_rewritable` backend, and `metadata_path`) are now checked before the disk
is created; the post-creation check is kept as well.

Test `05059_merge_tree_parts_disk_confinement` pins that no directory appears outside the base
directory for any of these shapes, and that every local backend inside it is readable.

#115722 (comment)
…names for `mergeTreeParts`

- `getFunctionURI` now returns the literal `endpoint` of an object storage disk description, so a
  filtered grant such as `GRANT READ ON S3('http://host/bucket/export/.*')` is matched against it
  instead of falling back to the unfiltered grant on the source. Only a plain literal is used (no
  substitution, no macro, no `endpoint_subpath`, and a repeated `endpoint` is rejected), so the disk
  that is created reads exactly where the check looked. A local disk has no URI, as `file` has none.
- The allowlist of disk types covers every name `DiskFactory` and `ObjectStorageFactory` register:
  `local_blob_storage`, `local_plain`, `local_plain_rewritable`, `azure_plain`,
  `azure_plain_rewritable`, and the `s3_*` compatibility names.
- The backend of a description is picked the same way `ObjectStorageFactory::create` picks it:
  `object_storage_type` when it is given (for any type but `local`), the `type` itself otherwise. Before,
  `type = s3, object_storage_type = local` was checked as S3 and then hit the `LOGICAL_ERROR` consistency check.

Test `05060_merge_tree_parts_source_grants` covers the RBAC matrix: `SELECT`, `DESCRIBE` and
`CREATE TABLE ... AS` denied without the grant, allowed with `READ ON FILE`, a filtered `READ ON S3`
that allows one endpoint and denies another (and an `endpoint_subpath`), and the unfiltered grant.

#115722 (comment)
#115722 (comment)
#115722 (comment)
@clickhouse-gh clickhouse-gh Bot added the comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). label Sep 4, 2026
alexey-milovidov and others added 2 commits September 9, 2026 13:54
…t, and let `object_storage_type` decide the backend

`IMergeTreeReader::fillVirtualColumns` returned early for a part that is read without its table
(`BorrowedMergeTreeDataPartInfoForReader`), so `SELECT _row_exists FROM mergeTreeParts(...)` on a part
that does not store the column physically fell through to `fillMissingColumns`, which default-filled
`UInt8(0)` for every row instead of the constant `1`. The same happened to `_block_number` on a part
where it is not materialized or is invalidated. The reader now materializes those two from the part
name, through the new `getFieldForConstVirtualColumnOfBorrowedPart`, and still refuses the virtual
columns a borrowed part genuinely cannot know.

The S3-credential classifier in `getDiskConfigurationFromAST` did not follow the backend rule the rest
of the change advertises. `disk(type = s3, object_storage_type = local, ...)` is a local disk for
`DiskFromAST` and for `ObjectStorageFactory::create`, and the table function checks `READ ON FILE` for
it, but the classifier still saw `maybe_s3_disk` and rejected it with `ACCESS_DENIED` under the default
`s3_allow_server_credentials_in_user_queries = 0`. The classifier now picks the backend the same way:
`type = local` is a disk of its own, otherwise a literal `object_storage_type` is authoritative, for a
compatibility alias as well as for the `object_storage` wrapper.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and adapted the branch to it:

  • MergeTreeSelectProcessor no longer takes a ColumnsDescription, and IMergeTreeDataPartInfoForReader gained getMinMaxIndex and getSecondaryIndexColumnTypes. BorrowedMergeTreeDataPartInfoForReader now returns nullptr and an empty record for these (138d848).
  • Match filtered source grants only against the location that is actually accessed #129899 changed how filtered AZURE grants are matched: against a blob name as written, with any subject that contains // refused. The <storage_account_url>/<container>/ subject could never match a filter after that, and 05270_merge_tree_parts_azure_source_grants failed on the merged tree. A blob-name filter cannot describe a disk that reads any blob of its container, so an Azure disk now needs the unfiltered READ ON AZURE grant, as a local disk needs the unfiltered READ ON FILE. Updated the test, the function documentation and the PR description to match (247c5b2).

All 22 merge_tree_parts stateless tests pass locally against the merged build.

Address review: the part type, `marks_count` and `has_lightweight_delete` of a
part description were trusted as given, although the part on disk already tells
them. A wrong part type drove the part through the wrong granularity loading
path, a wrong `marks_count` failed deep in the readers, and a wrong
`has_lightweight_delete = 0` returned rows that were deleted. Now each of them
is compared with what was read from the part, and a mismatch is rejected with
`BAD_ARGUMENTS`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the three review threads in 7be4bde: mergeTreeParts now checks the part type, marks_count and has_lightweight_delete of each part description against the part on disk, and rejects a mismatch with BAD_ARGUMENTS. New test: 05569_merge_tree_parts_descriptor_mismatch.

CH Inc sync failed because the incremental sync could not merge 247c5b2 into the sync branch: private master had changed getDiskConfigurationFromAST.cpp, MergeTreeReadPoolStatelessParts.cpp and StorageMergeTreeParts.cpp since the last sync. I merged private master and then 7be4bde into sync-upstream/pr/115722 (1fe33c2605d5) and resolved the conflicts. I also dropped the copies of getMinMaxIndex and getSecondaryIndexColumnTypes that private master already had. A cloud-mode -fsyntax-only check of every changed .cpp file passes. The sync PR is MERGEABLE now, and its CI is running.

Comment thread src/Disks/DiskFromAST.cpp
if (config->has("name"))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "The description of a query-local disk cannot have a `name`");

checkTransientDiskLocalPaths(*config, context);

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.

[Major] validateTransientDisk is still only doing the query-local path / credential checks and then returning the resolved config. mergeTreeParts now relies on this path for DESCRIBE and for zero-mark reads as if it were the same validation as a real read, but it never goes through the DiskFactory / ObjectStorageFactory checks that creation would run. So descriptions like disk(type = local, path = '<base>/x/', object_storage_type = s3) (unknown key for a local disk) or disk(type = web, endpoint = 'https://host/no-slash') pass here even though createTransientDisk rejects them immediately. That leaves the non-instantiating path accepting disk definitions the function cannot actually use.

Please factor a side-effect-free validation entrypoint out of disk creation — at least the unknown-key check and the pre-client backend checks — and call it from validateTransientDisk, so DESCRIBE / empty reads enforce the same contract as the real read path.

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.

🕵 Not changing this in this PR. The unknown-key check of DiskFactory::create is not a static list: it is computed by ConfigurationWithUsageTracking from the keys the disk creator actually reads while it creates the disk (object storage client, metadata storage, local directories). A side-effect-free version would need a dry-run mode in every disk and object storage creator, which is a refactoring of the disk factory on its own and not specific to mergeTreeParts.

What validateTransientDisk guarantees now is the security-relevant part: the dynamic_disk_allow_* gates, the server credentials restriction, the confinement of every local path to custom_local_disks_base_directory, the local disk config checks, and the required metadata_path. A definition that passes it but is malformed for its type cannot do anything on the DESCRIBE / zero-mark path, because nothing is read from the disk there; any read that touches data creates the disk and gets the full check. Leaving it open for a human decision on whether the dry-run refactoring is worth doing as a follow-up.

alexey-milovidov and others added 4 commits November 11, 2026 00:17
Resolve the conflict in `DiskFromAST`: `master` reworked `getOrCreateCustomDisk`
(several serializations of a definition, the server credentials flag of a custom disk).
The resolution and validation of the resolved configuration is factored into
`getValidatedDiskConfig` again, now returning also `uses_server_credentials` and
`restriction_exempt`, and is shared by `getOrCreateCustomDisk` and the query-local
disk of `mergeTreeParts` (`createTransientDisk` / `validateTransientDisk`), which
passes `uses_server_credentials` to the two-argument `markDiskAsCustom`.
…in tests

The expected results are taken from the source table first, then the table is
detached and only then read with `mergeTreeParts`, so a fallback to the metadata
of the live `MergeTree` table (or to its settings, for `index_granularity` and
`share_nested_offsets`) cannot go unnoticed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in the private repository

The private repository already has the same constructor with the parameter named
`index_granularity_`, and a test there calls it with `/*index_granularity_=*/`, which
`bugprone-argument-comment` rejects in the "CH Inc sync" build (`arm_tidy`) against
`fixed_index_granularity_`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_repeated_key_s3_credentials`

The private build rejects a key repeated in a dynamic disk description altogether
(`The key ... is specified more than once`), which refuses the disk as well; the test
failed in every stateless job of the "CH Inc sync" run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 12, 2026 09:03
…against the root of the disk

Only the part directory was canonicalized, so a part directory inside the root of a local disk
could contain symlinked `columns.txt`, marks and data files leading outside of it, which `DiskLocal`
follows when reading. Now every entry of the part directory (recursively, including projections)
is checked to resolve inside the root of the disk before anything is read from the part.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115722&sha=6474792bdc858e3ed3d621c4cf90eea03b22f1a2&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_debug%29 (Inconsistent AST formatting for CREATE TABLE ... ENGINE = TimeSeries with ViewTargets, not related to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here. This may be #128897.

The Stress test (arm_release) failure ("Cannot start clickhouse-server", broken from_zk disks left by 05496_dynamic_disk_wrapper_of_server_credentials_disk) is fixed on master by #130670, which has now been merged into this branch.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, there was an outage, so this request may have been missed. Please take a look at #115722 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator

This one is fixed by #130698 (merged 2026-11-11), not #128897.

The failing statement (line 273 of fuzzerout.sql) ends in RECENT SAMPLES INNER UUID '00000000-0000-0000-0000-000000000000'. A <target> INNER UUID with the Nil UUID parsed into an empty ViewTargets node that formats to nothing, so the parsed-back AST has no ViewTargets child at all. #130698 rejects a Nil INNER UUID with BAD_ARGUMENTS, as TO INNER UUID already did. The current head of this branch contains it, and on today's master debug build the statement returns Code: 36. DB::Exception: RECENT SAMPLES INNER UUID cannot use a Nil UUID. (BAD_ARGUMENTS).

#128897 is a different TimeSeries shape (INNER ENGINE written before INNER COLUMNS, where ViewTargets survives the round trip with its children reordered) and stays open separately.

alexey-milovidov and others added 2 commits November 14, 2026 08:31
…with `clickhouse-local`

The style check `server_data_manipulation_in_stateless_tests` rejected the test, because it
fetched the path of a server part from `system.parts` and then ran `mkdir`/`cp`/`ln` in the
same script. The test does not need a server table: the source part outside the root of the
disk is now written by `clickhouse-local` into a directory of the test itself, and the server
only reads it through `mergeTreeParts`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115722&sha=8c2ca2d65d86b3095977ae7a7cf175487edcfacc&name_0=PR&name_1=Style%20check
#115722

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, confirmed: #130698 is on master and in this branch.

Changes in c19679b (after merging master in 29cdc89):

  • Style check (server_data_manipulation_in_stateless_tests) rejected 05620_merge_tree_parts_file_symlinks because it read a server part path from system.parts and then ran mkdir/cp/ln. The out-of-root source part is now written by clickhouse-local into the test's own directory, so the test no longer touches any server table; the server only reads it through mergeTreeParts. The test passes locally.
  • Build (arm_tidy, 4/4) failed in gtest_s3_object_storage_explicit_settings.cpp on a createClientConfiguration signature mismatch that came from master and is already fixed there; the master merge pulls in the fix.

The thread on validateTransientDisk stays open for a human decision on whether a dry-run validation mode of the disk factory is worth a follow-up.

alexey-milovidov and others added 6 commits November 18, 2026 08:53
# Conflicts:
#	src/Disks/getDiskConfigurationFromAST.cpp
…_file_symlinks`

The style check requires queries to `system.parts` in tests to have a `database` condition.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng master

Master added the `stored_definition` argument of `getDiskConfigurationFromASTImpl` while this branch moved its
call into `getValidatedDiskConfig`. A query-local disk of `mergeTreeParts` is never a stored definition.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ble-function

Conflict in `src/Disks/DiskFromAST.cpp`: keep the transient disk functions of this branch next to
the `check_remote_hosts` argument that `ensureDiskIsAllowed` got on master.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ionURI`

After merging master, `ITableFunction::getFunctionURI` returns `std::string_view`, so the override
returning `const String &` no longer compiles.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
m7kss1 pushed a commit to m7kss1/ClickHouse that referenced this pull request Nov 22, 2026
…able

When the file iterator is exhausted, `StorageObjectStorageStableTaskDistributor::getAnyUnprocessedFile`
waits on `replica_seen_cv` until `cluster_function_wait_for_replica_ms` passes for a replica that has not
asked for tasks yet. The wait runs inside the read-task callback, on an initiator pipeline thread that
holds `RemoteQueryExecutor::was_cancelled_mutex`, and nothing checked the query or notified the cv on
cancellation: `QueryStatus::cancelQuery` blocks in `RemoteQueryExecutor::cancel` on that same mutex.
So `KILL QUERY` and `max_execution_time` waited for the whole interval, and since the deadline saturates
for huge values (ClickHouse#130812) such a query never ended. This hung the Stress test (arm_release) on PR ClickHouse#115722
for a fuzzed `icebergLocalCluster('test_cluster_two_shards', ...)` query with `max_threads = 1`.

The wait now polls `QueryStatus::checkTimeLimit()` every 100 ms, as the other waits on a query's behalf
do (ZooKeeperWaitLimit, DatabaseReplicated, the worker side ReadTaskIterator::next). `cancelQuery` sets
`is_killed` before cancelling the executors, so the waiter sees it while the canceller is blocked, throws,
and the unwinding releases `was_cancelled_mutex`. With `timeout_overflow_mode = 'break'` the replica gets
an empty task. The query status comes from `getProcessListElementSafe()` of the query context; the
gtests construct the distributor without one and keep their behaviour.

With fewer initiator threads than replicas the owner's request can still sit behind the wait, so the
query can still wait until `cluster_function_wait_for_replica_ms`, but that wait now ends on
`KILL QUERY` and at `max_execution_time`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 24, 2026 10:38
…file_symlinks`

On a case-insensitive filesystem (macOS) `replaceFileNameToHashIfNeeded` replaces the names of the
files of a part with their hashes, so the data file of the column is not `id.bin` there. The test
removed and symlinked `id.bin`, which left a dangling symlink next to the real data file, and the
read succeeded instead of being rejected. Take the name of the only `.bin` file of the part instead.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115722&sha=4518871c0a8fce3a70dd5db094d54a0a045cc2c4&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
#115722

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for 4518871:

  • Fast test (arm_darwin), 05620_merge_tree_parts_file_symlinks — caused by the test of this PR. On a case-insensitive filesystem replaceFileNameToHashIfNeeded replaces the names of the files of a part with their hashes, so there is no id.bin on macOS; the test left a dangling symlink next to the real data file and the read succeeded. Fixed in 2af07f5 by taking the name of the only .bin file of the part.
  • Stress test (arm_release), hung icebergLocalCluster query with cluster_function_wait_for_replica_ms — unrelated, fixed on master by Make the owner wait of cluster_function_wait_for_replica_ms cancellable #133412.
  • La Casa Del Dolor (amd_tsan), Directory '...' is virtual exception from SetOrJoinSink::onFinish on a plain_rewritable disk — unrelated, fixed on master by Fix INSERT into a Set or Join table on a plain_rewritable disk #132449.

Merged master (no conflicts) to pull both fixes in.

getName(), object_storage_type.empty() ? type : type + ", object_storage_type = " + object_storage_type));

if (type != "local")
disk_function_to_create->arguments->children.push_back(make_setting("read_only", 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.

[Blocker] Keep metadata maintenance from deleting objects during a read

Forcing read_only = 1 only adds a ReadOnlyDiskWrapper; its startupImpl still delegates to DiskObjectStorage::startupImpl. With the accepted configuration metadata_type = local, metadata_path = '<base>/meta/', persistent_removal_log = 1, MetadataStorageFromDisk::startup loads <metadata_path>/.metadata/blobs_to_remove.log, and disk startup then starts BlobKillerThread. That thread calls the underlying object storage's removeObjectsIfExist directly, bypassing both the wrapper and any WRITE source-grant check.

Consequently, a SELECT through this recovery function can replay a persisted removal queue and delete source objects even though the caller was authorized only for READ. The local object-storage backend is affected too: it reads readonly, so the forced read_only does not make that backend read-only.

Please prevent maintenance/recovery mutations before starting a query-local disk, including replay of this queue, and add a focused regression proving that a non-empty read leaves a persisted deletion queue and its objects untouched.

&& !source_args.contains("endpoint_subpath")
&& source_args.contains("endpoint"))
{
function_uri = get_source_arg("endpoint");

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.

[Blocker] Do not authorize unconstrained metadata keys using only the endpoint

The disk is not guaranteed to read under endpoint when it uses local metadata. For example, disk(type = s3, endpoint = 'https://host/bucket/allowed/', metadata_type = local, metadata_path = '<base>/meta/', access_key_id = '...', secret_access_key = '...') passes a grant filtered to https://host/bucket/allowed/.*, but version-5 DiskObjectStorageMetadata::deserialize takes each stored object key verbatim. Metadata for the requested part can therefore name other/columns.txt, other/data.bin, etc. DiskObjectStorage::prepareRead forwards these objects, and S3ObjectStorage::readObject uses their keys without prepending uri.key or checking the source grant again.

This lets the query read a part outside its granted prefix when the supplied credentials can access both prefixes. Checking endpoint_subpath does not cover this metadata-driven relocation.

Please require an unfiltered grant for metadata modes whose object keys are not confined to the checked endpoint, or check each effective object location before accessing it. Cover this with a non-empty part read whose metadata points outside the granted prefix; the current source-grant test uses only parts().

/// Compact parts need getTotalSubstreams() (below) when mark_type.with_substreams is true.
ColumnsSubstreams columns_substreams;
if (auto buf = data_part_storage->readFileIfExists("columns_substreams.txt", metadata_read_settings, {}))
columns_substreams.readText(*buf);

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.

[Blocker] Validate compact-part columns before constructing the borrowed reader

Unlike IMergeTreeDataPart::loadColumnsSubstreams, this path never validates the loaded substream columns against serialization_columns. A compact .mrk4 part can have columns.txt containing columns format version: 1\n0 columns:\n, while columns_substreams.txt still describes one column with one substream. The compact branch obtains a nonzero marks_per_granule from that second file, so matching marks and a readable checksums.txt let the empty physical column list reach the borrowed reader.

Then buildTaskInfoForPart calls getReadTaskColumns -> injectRequiredColumns: no physical column is found, and BorrowedMergeTreeDataPartInfoForReader::getColumnNameWithMinimumCompressedSize calls available_columns.front on an empty list. This is undefined behavior reachable from the part files, rather than a corruption exception.

Please reject an empty physical column list for both part types and validate columns_substreams against it before loading compact marks, as the normal part loader does. Add a small malformed-part regression that gets a regular exception.

This branch has not been deployed

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

Labels

comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants