Repository navigation
Add the mergeTreeParts table function - #115722
alexey-milovidov wants to merge 79 commits into
Conversation
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]>
|
Workflow [PR], commit [2c7781c] Summary: ❌
AI ReviewSummaryAdds Findings❌ Blockers
TestsThe current-head Fast test report has 16 passing and 7 skipped
Final VerdictStatus: ❌ 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. |
…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.
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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 ssrc/Storages/MergeTree/MergeTreeReadPoolStatelessParts.cpp: 7.2 s
…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`.
|
🕵 @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 — The other red, |
|
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. CREATE TABLE merge_distinct__fuzz_3 (`s` Time) ENGINE = Merge(currentDatabase(), '^dist_distinct$')whose only child Measured on master
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. #113242 is blocked rather than unfinished. Its only test-level red is One adjacent point, since this family is landing on a lot of PRs: the stress runner feeds |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
…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)
…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]>
|
🕵 Merged
All 22 |
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]>
|
🕵 Addressed the three review threads in 7be4bde:
|
| if (config->has("name")) | ||
| throw Exception(ErrorCodes::BAD_ARGUMENTS, "The description of a query-local disk cannot have a `name`"); | ||
|
|
||
| checkTransientDiskLocalPaths(*config, context); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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.
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]>
…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]>
|
🕵 @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 ( The |
|
@groeneai, there was an outage, so this request may have been missed. Please take a look at #115722 (comment) |
|
This one is fixed by #130698 (merged 2026-11-11), not #128897. The failing statement (line 273 of #128897 is a different TimeSeries shape ( |
…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]>
|
🕵 Thanks @groeneai, confirmed: #130698 is on master and in this branch. Changes in c19679b (after merging
The thread on |
# 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]>
The `arm_tidy` builds fail with `modernize-use-nodiscard` on it. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115722&sha=7c89c83eec98656ca6cffb2f635cc41c89862ff5&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #115722 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…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]>
…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]>
|
🕵 CI triage for 4518871:
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)); |
There was a problem hiding this comment.
[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"); |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
[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.
Brings the
mergeTreePartstable function over from the private repository, where it is used to readMergeTree data parts on a server that has no table and no table metadata for them. Everything a
MergeTreetable would normally take from its own metadata — the list of parts, the mark ranges, thecolumn structure and the index granularity — is written out in the query instead:
table_settingscarries 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 withnon-adaptive marks),
share_nested_offsets(which decides the names of the offsets streams of aNestedcolumn) andformat_version(0for a table created with the deprecatedMergeTree(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.
PREWHEREis supported and pushed down to the part readers, and amaterialized lightweight-delete mask is applied.
What is ported
StorageMergeTreePartsand theMergeTreeReadPoolStatelessPartsread pool behind it,BorrowedMergeTreeDataPartInfoForReader(anIMergeTreeDataPartInfoForReaderfor a part built on thefly 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 ratherthan 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
MergeTreeReadPoolbecome protected, the per-part task sizebecomes a virtual
getMinMarksPerTask(a pool that builds its task infos lazily has noper_part_infosto read it from), andbuildAnnouncementDescriptionsbecomes virtual — a borrowedpart has no
RangesInDataPartto 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 marksand the checksums of the part itself.
Differences from the private version
The
diskargument did not work there. The disk was created with the disk name as the configurationprefix while the configuration built from the arguments is rooted at the disk itself, so nothing under
disk(...)was ever read andtypefell back to itslocaldefault — every invocation produced anempty local disk under the server path. The disk now goes through
DiskFromAST::createCustomDisk, thesame path as
SETTINGS disk = disk(...)of a table definition, so the restrictions on dynamicallyconfigured disks apply as well: a local disk must live under
custom_local_disks_base_directory, andan S3 disk cannot resolve the server's own credentials.
read_onlyandskip_access_checkare forcedon.
Two arguments are dropped.
metadata = [...]of a part only set anin_memory_metadataflag on thedisk 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 serverconfiguration 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
READgrant on the source that matches the kind of the disk —FILE,S3,AZURE,HDFSorURL— and the function is not allowed in readonly mode. A filtered grant ismatched against the literal
endpointof the disk; a local disk and an Azure disk need the unfilteredgrant (a filtered
AZUREgrant is matched against a blob name, while the disk reads any blob of its container). The disktypemust be a literal,includeis rejected, and the keys that decide the sourceor 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_functionwrites aMergeTreetable to one disk and reads its parts backthrough 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_argumentscovers the argument errors, including part paths that leave theroot of the disk.
05029_merge_tree_parts_table_settingsreads back a table written withindex_granularity_bytes = 0and one with aNestedcolumn written withshare_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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the
mergeTreePartstable 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.PREWHEREis supported. It configures a disk from its arguments, so it is not allowed in readonly mode and requires theREADgrant on the source matching the kind of the disk.Workflow [PR]
Sync PR [sync-upstream/pr/115722]