Repository navigation
Lazy materialization for reading local Parquet files (file / File) - #114262
Conversation
Follow-up to #110970 for plain local files, as discussed in #110970 (comment) For `ORDER BY ... LIMIT n` queries over local Parquet files read through `StorageFile` (the `file` table function and the `File` table engine), the columns that are not needed for sorting and filtering are now read only for the `n` rows that survive the `LIMIT`. - The storage-agnostic column-split logic of `ReadFromObjectStorageStep::keepOnlyRequiredColumnsAndCreateLazyReadStep` is extracted into the shared `splitLazilyReadColumnsFromFormatInfo` (`prepareReadingFromFormat`) and reused by the new `ReadFromFile::keepOnlyRequiredColumnsAndCreateLazyReadStep`. - The main pass appends a `__global_row_index` column (file index in a per-query `LazyFileRegistry` + physical row numbers from `ChunkInfoRowNumbers`) in `StorageFileSource::generate`. - The lazy branch (`LazilyReadFromFile` -> `LazyReadFromFileSource` -> `StorageFileLazyRowsSource`) reopens only the surviving files (at most `LIMIT n` of them) with per-file `FormatFilterInfo::rows_to_read` and `parquet.preserve_order`. - Generation safety: POSIX has no conditional read, so the reread fails close with the new `FILE_CHANGED_DURING_READ` error when the file's generation token - sub-second mtime + inode + size, reusing `computeFileCacheVersionToken` - no longer matches the one captured when the main pass opened the file. The token is validated at registration time in the main pass, and both before and right after the reopen in the lazy pass. Replace-by-rename (the common atomic-update pattern) is always caught; an in-place rewrite is caught up to the filesystem timestamp tick. - Gates (`ReadFromFile::canUseLazyMaterialization`): Parquet format only, no file descriptor reads (stdin cannot be reopened), no archives, no `distributed_processing`, no `rename_files_after_processing`, uncompressed files only. New setting `query_plan_optimize_lazy_materialization_for_file` (default true). - Fixes a latent bug shared with the object storage path (via the shared helper): deferring a requested subcolumn (e.g. of `JSON`) left the lazy branch's format header empty and the query failed with `Not found column or subcolumn ... in block`, because `format_header` contains the parent column of a requested subcolumn. The split now maps requested columns to their storage-level names, and keeps the parent on the main branch as well when a sort key still needs another subcolumn of it. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Workflow [PR], commit [3bc0f39] Summary: ✅
AI ReviewSummaryThis PR extends lazy materialization to local Findings❌ Blockers
Final VerdictRequest changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 516/572 (90.21%) · Uncovered code |
|
🏋 ClickBench on local Parquet (the Same shape as the datalake result on #110970: an Q23, interleaved on/off runs:
So ~4.0x faster and ~4x less disk IO cold (both sides are disk-bound at the same ~110 MB/s, so the speedup tracks the byte reduction — the remaining 3.6 GB is dominated by Correctness: with a deterministic tie-break appended to the sort key (plain Q23 has ties in |
…line pointer The arm_tidy build failed with readability-ambiguous-smartptr-reset-call: pipeline is a std::unique_ptr<QueryPipeline> and QueryPipeline also has a reset method, so pipeline.reset() is flagged as ambiguous. Use pipeline = nullptr instead, as suggested by the check. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114262&sha=21d0cf64b99f564cfd3a00ea10fa277262724b45&name_0=PR&name_1=Build%20%28arm_tidy%29 #114262 Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Fixed the only CI failure on |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Object file sizes49 object files changed (+447.45 KiB total), 2 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units227 translation units recompiled, 2019 s compile time in total, 225 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
A subcolumn of a defaulted column (`j.user.name` of `j JSON DEFAULT ...`) was matched against `column_defaults` by its query-level name, which never matches the storage-level key (`j`), so the default-dependency fixpoint never saw the parent's expression: the subcolumn could be deferred while an input of the expression (`a`) stayed on the main branch, and `AddingDefaultsTransform` in the lazy branch then computed `j` from type defaults instead of the row's real values. Normalize names to their storage parents for the analysis: a subcolumn seeds and pins through its parent, a pinned parent keeps all of its subcolumns on the main branch, and an expression input counts as deferred only when it is a whole requested column that is deferred as well. Addresses the review finding on the PR. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Addressed the AI review blocker and refreshed the branch:
|
…alization The planner pushes a row policy into the reading step via `query_info.row_level_filter` for any storage that supports `PREWHERE`, independently of whether the query has a `PREWHERE`. `StorageFile::read` propagates it into `ReadFromFormatInfo` only together with `query_info.prewhere_info`, so the lazy-materialization split could not see a bare row policy and deferred its input columns to the lazy branch, while the source still evaluates the filter in the main pass via `FormatFilterInfo`. Routing the bare filter through `updateFormatPrewhereInfo` instead would prune the filter's input columns from the format header and break `DEFAULT` expressions computed from them in the source (a shape that works on master), so the inputs are pinned at the split site. Addresses the AI review blocker on `prepareReadingFromFormat.cpp`.
…izer `optimizePrewhere` can leave the remaining `ExpressionStep` with a DAG input that no longer exists in the reading step's shrunken output header when a row-level filter is applied inside the step (its input column is consumed there). Execution tolerates such a dangling input because `ExpressionActions` only requires inputs its outputs depend on, but `mapInputsToHeaderPositions` treated it as a logical error, so a row policy combined with a `WHERE` moved to `PREWHERE` failed with `Unknown identifier` (LOGICAL_ERROR) once lazy materialization for `file` was enabled. Map such inputs to a sentinel and only raise the exception if the input turns out to be required.
…licy Covers: the policy's input column is pinned to the main pass (only `s` is lazily read), a `WHERE` moved to `PREWHERE` on top of the policy, a `DEFAULT` column computed from the policy's input column, and aggregates over the policy-filtered table. The whole battery runs with `query_plan_optimize_lazy_materialization_for_file` enabled and disabled; the results must match.
|
🕵 Addressed the AI review blocker and refreshed the branch:
Out of scope, verified pre-existing on current master (fails identically with lazy materialization off): a row policy referencing a
|
# Conflicts: # src/Common/ErrorCodes.cpp
The main pass of a local `Parquet` read builds a synthetic `RelativePathWithMetadata` for every plain local file, so the format metadata cache (the `Parquet` footer cache) is reachable - this is what `master` does and is not changed by lazy materialization. The lazy pass, however, only built that metadata when the file version token was outside the filesystem timestamp settle window, so the two passes of one query could read the same file under two different cache contracts: the main pass could interpret it through a cached footer while the lazy pass reparsed the current bytes. Build the metadata unconditionally in `StorageFileLazyRowsSource` as well. Both passes now key the footer cache by the same path and the same version token, so whatever footer the main pass chose the row numbers with is the footer the deferred columns are read with, and `JoinLazyColumnsStep` cannot combine interpretations of two generations. How strong the token itself is (sub-second mtime + inode + size) is a property of every local `Parquet` read on `master`, single-pass ones included. `LazyFileRegistry::FileEntry::version_settled` becomes unused and is removed; `current_file_version_settled` still gates the Query Condition Cache exactly as on `master`.
`05019_parquet_lazy_materialization_file_change` replaced the file after a fixed one-second delay, assuming the query had reached the file by then. Under a sanitizer build the process can still be starting up at that point, so the replacement lands before the main pass ever opens the file; the query then reads the replacement as the only generation it ever saw and returns a normal result instead of `FILE_CHANGED_DURING_READ` (seen on `amd_msan` and `amd_tsan`). Wait for the file to actually appear among the query process's open descriptors before replacing it, and read with a single thread so the `sleepEachRow` pause of the main pass is serial (with the default thread count the row groups sleep in parallel and the main pass is over in a fraction of the time).
|
🕵 Addressed the AI review blocker and the only CI red, and refreshed the branch (head
|
In the tsan and msan flaky checks the test observed `new_0` instead of `FILE_CHANGED_DURING_READ`: the wait loop latched onto the short-lived schema inference fd, so the replacement was installed before the main pass opened the file at all, and the query legitimately read the replacement as the only generation it ever saw. Spell out the structure in the query (so schema inference never opens the file) and wait for an fd whose target is the pre-swap inode, which proves the main pass holds the original generation open before the replacement is installed. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114262&sha=66b0b841c150d2ccc0e937ac1106621ada39452d&name_0=PR&name_1=Stateless%20tests%20(amd_tsan,%20flaky%20check) Co-Authored-By: Claude Fable 5 <[email protected]>
| # the inode proves the fd is not already a reopen of some later generation. | ||
| for _ in {1..1200}; do | ||
| for fd in "/proc/${query_pid}/fd"/*; do | ||
| if [ "$(stat -Lc %i "${fd}" 2>/dev/null)" = "${orig_inode}" ]; then |
There was a problem hiding this comment.
%i alone is still too weak to prove that this FD is the original data.parquet. Inodes are only unique within one filesystem, so an unrelated FD on another mount can satisfy this comparison and let the mv happen before the main pass has actually opened the file, which reintroduces the race this commit is trying to close. Comparing both device and inode (for example stat -Lc '%D:%i') would make the wait condition match the opened file generation rather than any coincidental inode value.
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds lazy materialization for ORDER BY ... LIMIT queries over local Parquet files (the file table function and File engine), gated behind the new default-on query_plan_optimize_lazy_materialization_for_file setting, plus a shared fix so the optimizer tolerates dangling DAG inputs. ClickBench Q30 is a GROUP BY aggregation over a MergeTree table and never touches the new file-reading path, so its -13.1% (199 vs 229 ms) is run-to-run variance well inside master's current band (112-338 ms). The deterministic no-change verdict is correct; no real regression or improvement is attributable to this change. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Related: #110970
Follow-up to the lazy materialization for object storage (#110970), as discussed in #110970 (comment): implement it for plain local Parquet files read through
StorageFile— thefiletable function and theFiletable engine.For
ORDER BY ... LIMIT nqueries, the columns that are not needed for sorting and filtering are read only for thenrows that survive theLIMIT. The format side (row-selective Parquet reads viaFormatFilterInfo::rows_to_read) and the plan split (JoinLazyColumnsStep,LazyMaterializingTransform) from #110970 are reused as-is; this PR adds theStorageFilecounterpart of the two branches:__global_row_indexcolumn (file index in a per-queryLazyFileRegistry+ physical row numbers fromChunkInfoRowNumbers) inStorageFileSource::generate.LazilyReadFromFile→LazyReadFromFileSource→StorageFileLazyRowsSource) reopens only the surviving files (at mostLIMIT nof them) with a per-file set of rows to read andparquet.preserve_order.ReadFromObjectStorageStep::keepOnlyRequiredColumnsAndCreateLazyReadStep(which columns can be deferred:DEFAULTexpression dependencies, PREWHERE inputs, hive partition and virtual columns) is extracted into the sharedsplitLazilyReadColumnsFromFormatInfoand reused by both storages.Generation safety. POSIX has no conditional read, so the reread cannot be pinned the way
If-Matchpins it on S3. Instead the reread fails close with the newFILE_CHANGED_DURING_READerror when the file's generation token — sub-second mtime + inode + size, reusingcomputeFileCacheVersionTokenfrom the query condition cache integration — no longer matches the one captured when the main pass opened the file. The token is validated at file registration time in the main pass, and both before and right after the reopen in the lazy pass. Replace-by-rename (the common atomic-update pattern) is always caught since it changes the inode; an in-place rewrite is caught up to the filesystem timestamp tick (and already tears a single-pass read today).Gates (
ReadFromFile::canUseLazyMaterialization): Parquet format only, no file descriptor reads (stdin cannot be reopened), no archive entries, nodistributed_processing, no--rename_files_after_processing, uncompressed files only. Controlled by the new settingquery_plan_optimize_lazy_materialization_for_file(enabled by default), on top ofquery_plan_optimize_lazy_materialization.Bug fix for #110970 shared via the helper: deferring a requested subcolumn (e.g. of a
JSONcolumn) left the lazy branch's format header empty and the query failed withNot found column or subcolumn ... in block, because the format header contains the parent column of a requested subcolumn while the split filtered it by subcolumn names. The split now maps requested columns to their storage-level names — the parent of a deferred subcolumn moves to the lazy branch, and stays in the main branch as well when a sort key still needs another subcolumn of it. Covered for both storages by the new tests.On a 1 GB local Parquet file (2M rows × 105 columns equivalent shape: two 300-byte strings),
SELECT * ... ORDER BY k DESC LIMIT 5runs 3× faster (0.15 s vs 0.45 s, page-cache warm), with results verified identical with the optimization on and off.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Lazy materialization for
ORDER BY ... LIMIT nqueries (#110970) now also applies to local Parquet files read with thefiletable function and theFiletable engine: the columns that are not needed for sorting and filtering are read only for thenrows that survive theLIMIT. The second read of a surviving file fails close with the newFILE_CHANGED_DURING_READerror if the file was modified between the two passes. Controlled by the new settingquery_plan_optimize_lazy_materialization_for_file(enabled by default). Also fixes lazy materialization for object storage failing withNot found column or subcolumn ... in blockwhen a requested subcolumn (e.g. of aJSONcolumn) is deferred.Workflow [PR]
Sync PR [sync-upstream/pr/114262]
Version info
26.8.1.1895(included in26.8and later)