Skip to content

Lazy materialization for reading local Parquet files (file / File) - #114262

Merged
alexey-milovidov merged 33 commits into
masterfrom
ch-file-lazy-mat
Aug 22, 2026
Merged

alexey-milovidov merged 33 commits into
masterfrom
ch-file-lazy-mat

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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 — the file table function and the File table engine.

For ORDER BY ... LIMIT n queries, the columns that are not needed for sorting and filtering are read only for the n rows that survive the LIMIT. The format side (row-selective Parquet reads via FormatFilterInfo::rows_to_read) and the plan split (JoinLazyColumnsStep, LazyMaterializingTransform) from #110970 are reused as-is; this PR adds the StorageFile counterpart of the two branches:

  • 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 a per-file set of rows to read and parquet.preserve_order.
  • The storage-agnostic column-split logic of ReadFromObjectStorageStep::keepOnlyRequiredColumnsAndCreateLazyReadStep (which columns can be deferred: DEFAULT expression dependencies, PREWHERE inputs, hive partition and virtual columns) is extracted into the shared splitLazilyReadColumnsFromFormatInfo and reused by both storages.

Generation safety. POSIX has no conditional read, so the reread cannot be pinned the way If-Match pins it on S3. Instead 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 from 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, no distributed_processing, no --rename_files_after_processing, uncompressed files only. Controlled by the new setting query_plan_optimize_lazy_materialization_for_file (enabled by default), on top of query_plan_optimize_lazy_materialization.

Bug fix for #110970 shared via the helper: deferring a requested subcolumn (e.g. of a JSON column) left the lazy branch's format header empty and the query failed with Not 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 5 runs 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):

  • Performance Improvement

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

Lazy materialization for ORDER BY ... LIMIT n queries (#110970) now also applies to local Parquet files read with the file table function and the File table engine: the columns that are not needed for sorting and filtering are read only for the n rows that survive the LIMIT. The second read of a surviving file fails close with the new FILE_CHANGED_DURING_READ error if the file was modified between the two passes. Controlled by the new setting query_plan_optimize_lazy_materialization_for_file (enabled by default). Also fixes lazy materialization for object storage failing with Not found column or subcolumn ... in block when a requested subcolumn (e.g. of a JSON column) is deferred.


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

Version info

  • Merged into: 26.8.1.1895 (included in 26.8 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3bc0f39]

Summary: ✅


AI Review

Summary

This PR extends lazy materialization to local Parquet reads through the file table function and the File table engine, and it also hardens the shared split logic around DEFAULT expressions, row policies, and subcolumns. Most of the earlier correctness holes look fixed in the current head, but I still see one storage-side fail-close gap that was dismissed in-thread, plus a new test-race bug in the final follow-up commit.

Findings

❌ Blockers

  • [src/Storages/StorageFile.cpp:1723-1746, 1970-1982, 2452-2504] [dismissed by author -- https://github.com/Lazy materialization for reading local Parquet files (file / File) #114262#discussion_r3790882678] The lazy File path still allows a two-pass reread when the local generation token is explicitly known to be unsettled. In that state computeFileCacheVersionToken is too weak to distinguish a same-size in-place rewrite inside one filesystem timestamp tick, yet the main pass still registers the file for lazy reread and the lazy pass treats the unchanged token as proof that it reopened the same generation. A rewrite that lands after the main pass but before the lazy pass can therefore still splice sort/filter columns from one generation with deferred columns from another, even though a single-pass read would not reopen the file at all. Suggested fix: keep the existing master behavior for ordinary reads, but disable lazy materialization (or fail closed before registering the file) whenever any participating local file has an unsettled version token.

⚠️ Majors

  • [tests/queries/0_stateless/05019_parquet_lazy_materialization_file_change.sh:56] The new race fix still identifies the “main pass has opened the file” state only by inode number. Inodes are unique only within a filesystem, so any unrelated FD on another mount with the same inode value can satisfy the condition and let the rename happen before data.parquet is actually open, which makes the test flaky again. Suggested fix: compare device + inode together, or otherwise validate both the FD target path and its inode.
Final Verdict

Request changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 516/572 (90.21%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 11, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🏋 ClickBench on local Parquet (the clickhouse-parquet variant: ENGINE = File(Parquet, 'hits.parquet'), one fresh clickhouse-local process per run, as in the ClickBench query runner). Binary built from this PR, 96-core aarch64 box, single 14.78 GB hits.parquet (99,997,497 rows) on EBS (~110 MB/s effective read throughput).

Same shape as the datalake result on #110970: an EXPLAIN diff over all 43 queries with query_plan_optimize_lazy_materialization_for_file on and off shows exactly one affected query — Q23, SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10; the other 42 plans are byte-identical. The split defers 103 of the 105 columns: the main pass reads only URL (PREWHERE input) and EventTime (sort key) plus the row index.

Q23, interleaved on/off runs:

cache state lazy materialization wall time data read from disk
cold (file evicted per run via posix_fadvise) off 135.1 / 132.6 s 14.45 GB
cold on 32.9 / 33.9 s 3.5–3.7 GB
warm (file in page cache) off 4.58 / 4.62 s 0
warm on 0.70 / 1.03 s 0

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 URL, one of the largest columns), and ~4.6x faster warm, where the gain is pure decompress/decode saving — consistent with the ~3.9x warm result on the object-storage variant of #110970. Disk bytes are /proc/self/io read_bytes of the query process; the off side reading the full 14.45 GB also proves every cold run was really cold.

Correctness: with a deterministic tie-break appended to the sort key (plain Q23 has ties in EventTime), the full result is sha256-identical with the optimization on and off, for both LIMIT 10 and LIMIT 1000. These numbers are an on/off comparison on this box, not comparable to the published leaderboard.

alexey-milovidov and others added 2 commits August 11, 2026 18:15
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Fixed the only CI failure on 21d0cf64 — Build (arm_tidy) failed with readability-ambiguous-smartptr-reset-call on pipeline.reset() in StorageFile.cpp (the pointee QueryPipeline also has a reset method); replaced with pipeline = nullptr as the check suggests. Also merged current master (clean, no conflicts). Incremental build: 0 errors, 0 warnings; smoke-verified that EXPLAIN still shows JoinLazyColumnsStep + LazilyReadFromFile for file(...) ORDER BY ... LIMIT with correct results.

@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3bc0f3932 with master 590a91de6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 577afb433; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.54 MiB 701.55 MiB -2.99 MiB (-0.43%)

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 sizes

49 object files changed (+447.45 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/LazilyReadFromFile.cpp.o new 212.31 KiB +212.31 KiB
src/CMakeFiles/dbms.dir/Processors/Sources/LazyReadFromFileSource.cpp.o new 127.16 KiB +127.16 KiB
src/CMakeFiles/dbms.dir/Storages/prepareReadingFromFormat.cpp.o 204.51 KiB 285.05 KiB +80.54 KiB (+39.38%)
src/CMakeFiles/dbms.dir/Storages/StorageFile.cpp.o 1008.48 KiB 1.05 MiB +68.21 KiB (+6.76%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromObjectStorageStep.cpp.o 425.48 KiB 369.18 KiB -56.30 KiB (-13.23%)

737 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

227 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.
The matched translation units cost -83.6 s (-4%) in total before that adjustment.

Job report

alexey-milovidov and others added 2 commits August 12, 2026 13:52
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review blocker and refreshed the branch:

  • Fix: the default-dependency analysis in splitLazilyReadColumnsFromFormatInfo now runs on storage-level names (a1c4f28) — a subcolumn of a defaulted parent seeds and pins through getNameInStorage, 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 deferred as well.
  • Regression test: 04869_parquet_lazy_materialization_file_default_subcolumn — j JSON DEFAULT ...(a) with the Parquet file lacking j; covers the input-in-sort-key pin, the defer-together case, and sorting by the subcolumn itself; results identical with the optimization on and off.
  • Merged current master (clean) — this pulls in the Revert the PromQL topk/limitk streaming plan and its shared-subquery materialization #114326 revert that fixes the fleet-wide Hung check failed, possible deadlock found storm behind all three stress-test reds on the previous run (unrelated to this PR).
  • Incremental build: 0 errors, 0 warnings; 04838_parquet_lazy_materialization_file still passes.

…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review blocker and refreshed the branch:

  • Merged master (clean, 718 commits) — the previous CI run on a1c4f28f was green.
  • Fix 1 (641ef29): a bare row policy (no PREWHERE) is now visible to the lazy-materialization split — its input columns are pinned to the main pass at the split site in ReadFromFile::keepOnlyRequiredColumnsAndCreateLazyReadStep (plus a defensive mirror in ReadFromObjectStorageStep). Deliberately not done by propagating the filter into ReadFromFormatInfo: that prunes the filter's inputs from the format header and regresses DEFAULT columns computed from them (a shape that works on master); details in the thread reply.
  • Fix 2 (908a3e3): row policy + WHERE moved to PREWHERE + lazy materialization no longer throws Unknown identifier (LOGICAL_ERROR) — mapInputsToHeaderPositions now tolerates a dangling unused DAG input left by optimizePrewhere, erroring only if the input is actually required.
  • Regression test (841c7d0): 04891_parquet_lazy_materialization_file_row_policy — policy-input pinning (EXPLAIN shows only s lazy), WHERE→PREWHERE under a policy, a DEFAULT column computed from the policy input, and aggregates; the whole battery must match with the optimization on and off.

Out of scope, verified pre-existing on current master (fails identically with lazy materialization off): a row policy referencing a DEFAULT column that is missing from the data file throws UNKNOWN_IDENTIFIER (official 26.7 returned silently wrong results instead, so master is already fail-safe here).

04838 and 04869 re-verified locally on the rebuilt binary; a subset of MergeTree lazy-materialization tests (02813, 03381, 03761, 04327, 04365, 04652, 04654) passes unchanged.

Comment thread src/Storages/StorageFile.cpp Resolved
Comment thread src/Storages/StorageFile.cpp Resolved
Comment thread src/Storages/StorageFile.cpp Resolved
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).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review blocker and the only CI red, and refreshed the branch (head 66b0b841c150).

  • Merged master (clean, 512 commits; FILE_CHANGED_DURING_READ still 1014, no error-code collision).
  • Blocker (9b1ddb0): the two passes now use one and the same format metadata cache contract — but by making the lazy pass follow the main pass, not the other way round. The main pass is master behaviour (it builds RelativePathWithMetadata for every plain local file unconditionally, and 04207_parquet_metadata_cache_local_file on master pins the footer-cache hit right after a write), so gating it on the settle window — the previous attempts — changed pre-existing behaviour for all local Parquet reads and got reverted each time. StorageFileLazyRowsSource now builds the same metadata unconditionally, so both passes key the footer cache by the same path and the same token and JoinLazyColumnsStep cannot combine two interpretations of the file. Details in the thread reply. LazyFileRegistry::FileEntry::version_settled is now unused and removed; current_file_version_settled still gates the Query Condition Cache as on master.
  • CI red (66b0b84): 05019_parquet_lazy_materialization_file_change failed on amd_msan (twice), amd_msan (flaky check) and amd_tsan (s3) with the query returning new_0 instead of throwing — the fixed sleep 1 elapsed while the sanitizer build was still starting up, so the replacement landed before the main pass ever opened the file and the query legitimately read the replacement as its only generation. The test now waits until the file actually shows up among the query process's open descriptors before replacing it, and reads with a single thread so the sleepEachRow pause 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). Ran it 4× locally on the rebuilt binary: stable at ~2.6 s each.
  • Incremental build: 0 errors. 04838, 04869, 04891 and 05019 all pass locally against the merged binary.

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

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.

%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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: 99f2ea96-1904-487e-b899-817f5740f440
  • MIRAI run: c91ffd60-9521-4f0a-930e-1cad4dd2ce1c
  • PR check IDs:
    • clickbench_29567_1787352726
    • clickbench_29578_1787352726
    • tpch_adapted_1_official_29598_1787352726
    • tpch_adapted_1_official_29615_1787352726
    • tpch_adapted_1_official_29638_1787352726

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not bad.

@alexey-milovidov alexey-milovidov self-assigned this Aug 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 22, 2026
Merged via the queue into master with commit f4b987c Aug 22, 2026
349 of 350 checks passed
@alexey-milovidov
alexey-milovidov deleted the ch-file-lazy-mat branch August 22, 2026 03:05
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 22, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants