Skip to content

TopN Parquet read caches a reduced row count; later count() is wrong #123716

Open

Description

@clickgapai

Describe what's wrong

  • After a TopN read skips Parquet row groups, count() over the same files answers from a wrong cached row count.
  • Trigger: ORDER BY k LIMIT 3 over two files where the TopN filter skips every row group of part2.parquet, then count() per _file.
  • Expected 10000 rows for part2.parquet; actual result has no row for it, while use_cache_for_count_from_files = 0 returns 10000.
  • All involved settings default to on, and the wrong value stays in the server-wide schema cache until the file changes.

Root cause: StorageFileSource::generate writes total_rows_in_file to the count cache when !format_filter_info->hasFilter() (StorageFile.cpp:2248), but FormatFilterInfo::hasFilter checks only filter_actions_dag and ignores top_k_filter. So a TopN read without WHERE is treated as unfiltered and the rows left after pruning are cached as the file's row count.

Analysis details (evidence, affected locations, impact)

Why we believe this is a bug: ReadFromFile::initializePipeline attaches top_k_filter to the shared FormatFilterInfo ([src/Storages/StorageFile.cpp:2609](https://github.com/ClickHouse/ClickHouse/blob/1e69f4756841/src/Storages/StorageFile.cpp#L2609)). When a file is exhausted, StorageFileSource::generate stores total_rows_in_file in the count cache if !format_filter_info->hasFilter() (StorageFile.cpp:2248). FormatFilterInfo::hasFilter only checks filter_actions_dag ([src/Formats/FormatFilterInfo.cpp:99-102](https://github.com/ClickHouse/ClickHouse/blob/1e69f4756841/src/Formats/FormatFilterInfo.cpp#L99-L102)), so a TopN read without WHERE counts as unfiltered and the rows that survived pruning get cached as the file's row count. The query-condition-cache write a few lines below already excludes TopN reads (!format_filter_info->top_k_filter, StorageFile.cpp:2274); the row-count cache write does not.

Affected locations:

Impact: Wrong count() (an undercount, down to 0 for a whole file) on file()/File Parquet reads that follow an ORDER BY col LIMIT n query on the same files. All the settings involved default to on (use_top_k_dynamic_filtering, optimize_count_from_files, use_cache_for_count_from_files). The wrong value stays in the server-wide schema cache until the file changes. It reproduces deterministically with max_threads = 1, where files are read one after another. With default settings it depends on timing.

Does it reproduce on most recent release?

Confirmed on master; not checked on a release.

How to reproduce

Deterministic with max_threads = 1 and file mtimes set an hour back; with default settings it depends on timing.

# - no-fasttest: writes and reads Parquet files

DIR=$(mktemp -d "${CLICKHOUSE_TMP}/05320_parquet_topk_count_cache_XXXXXX")
trap 'rm -rf "${DIR}"' EXIT

# An ORDER BY ... LIMIT read that skips row groups must not leave a reduced row count in the cache
# that count() answers from. part1 is read first and sets the threshold, so every row group of part2 is skipped.
LOCAL=(clickhouse-local
    --use_top_k_dynamic_filtering=1
    --query_plan_max_limit_for_top_k_optimization=1000
    --input_format_parquet_use_native_reader_v3=1
    --input_format_parquet_filter_push_down=1
    --query_plan_optimize_lazy_materialization_for_file=0
    --optimize_count_from_files=1
    --use_cache_for_count_from_files=1
    --max_threads=1 --max_parsing_threads=1)

"${LOCAL[@]}" --query "
    INSERT INTO FUNCTION file('${DIR}/part1.parquet', Parquet) SELECT number AS k FROM numbers(10000)
    SETTINGS output_format_parquet_row_group_size = 1000000, engine_file_truncate_on_insert = 1;
    INSERT INTO FUNCTION file('${DIR}/part2.parquet', Parquet) SELECT 10000 + number AS k FROM numbers(10000)
    SETTINGS output_format_parquet_row_group_size = 1000, engine_file_truncate_on_insert = 1;
"

# A cached row count is used only for a file modified before the second it was cached in.
touch -d '1 hour ago' "${DIR}/part1.parquet" "${DIR}/part2.parquet"

"${LOCAL[@]}" --query "
    SELECT k FROM file('${DIR}/part{1,2}.parquet', Parquet) ORDER BY k LIMIT 3;
    SELECT _file, count() FROM file('${DIR}/part{1,2}.parquet', Parquet) GROUP BY _file ORDER BY _file;
    SELECT _file, count() FROM file('${DIR}/part{1,2}.parquet', Parquet) GROUP BY _file ORDER BY _file SETTINGS use_cache_for_count_from_files = 0;
"

Note: an automated re-run of this exact block on current master (4127c65654d0) did not show the failure; the analyst's run did (outputs below). Environment or ordering may matter.

Expected behavior

count() per file returns 10000 for both part1.parquet and part2.parquet.

Expected output of the reproducer above:

0
1
2
part1.parquet	10000
part2.parquet	10000
part1.parquet	10000
part2.parquet	10000

Error message and/or stacktrace

count() reports nothing for part2.parquet (0 rows instead of 10000) when served from the row-count cache.

Actual output of the reproducer above:

0
1
2
part1.parquet	10000
part1.parquet	10000
part2.parquet	10000
Suggested fix

Gate the count-cache write in StorageFileSource::generate on !format_filter_info->top_k_filter (as the condition-cache write already does), or make hasFilter report top_k_filter too. Open PR #122835 extends hasFilter to PREWHERE and row policies but not to TopN. Trade-off: going through hasFilter also disables the cache for every other hasFilter consumer of a TopN read, which is the safe direction.

Additional context

Same pattern as #122746 (found by: vector, fix_path; vector: cosine distance 0.27).

Open risks:

  • Could not verify: the lazy-materialization second pass (FormatFilterInfo::rows_to_read, StorageFile.cpp:2738) also leaves filter_actions_dag null, so the same write may store the number of re-read rows. One lazy plus TopN run cached 4000 of 10000, and that run does not separate the two passes.
  • TopN for object storage (TopN dynamic filtering for Parquet reads from object storage and data lakes #122109, open) would hit the same pattern if StorageObjectStorageSource keeps gating its count-cache write on the filter DAG alone.

Found during automated review of PR #123381; whether that PR introduced it could not be established, so nobody is tagged. Severity P1 · Finding h_pr123381_101

Activity

  1. added
    comp-table-functions
    on Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ai_p2comp-table-functions

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions