Skip to content

Do not skip Iceberg position deletes on inverted reference bounds - #118181

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai-iceberg-inverted-delete-bounds
Sep 7, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai-iceberg-inverted-delete-bounds

Conversation

@groeneai

@groeneai groeneai commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a query over an Iceberg table returning rows that had been deleted, when a position-delete manifest declares a lower bound above the upper bound for the reserved file_path column. Such a pair describes an empty range, so the delete file was skipped for every data file it covers; those bounds are now ignored instead. Closes #118113.

Description

Closes: #118113
Related: #116604

A position-delete manifest entry can declare the range of data file paths its delete file references, and nothing checks that pair. When referenced_data_file is absent, the deserializer takes lower_bounds and upper_bounds for the reserved file_path column independently, and the reader then keeps the delete file for a data file only when lower <= path && upper >= path. Inverted, that conjunction is false for every path, so the delete file is skipped everywhere and the rows it deletes come back. The query succeeds with wrong rows; only a LOG_TEST line and IcebergMinMaxPrunedDeleteFiles record it, and no setting gates the check.

That branch is the one ClickHouse itself takes: it never writes referenced_data_file, so every merge-on-read delete it produces carries these bounds.

I check the pair where it is built and, when inverted, drop both bounds and warn, which leaves the entry as one that declares no bounds. I did not swap or clamp them, because a swapped pair would go on skipping delete files, over a range the manifest never asserted.

Dropping the bounds cannot lose deletes. The path is re-checked downstream: PositionDeleteTransform pushes WHERE file_path = '<data file>' into the delete-file read, then filters every delete row by exact path match against the current data file. So the cost is at most reading a delete file that filters to zero rows, which is already what happens for a delete file that declares no bounds.

Not addressed here: getMaterializedRowLineageRange reads its reserved-field ranges just as unchecked. That is a separate site and a separate pull request.

Validation

It is an integration test because it rewrites an Avro manifest out of band. The fixture is written entirely by ClickHouse: two inserts make two data files, and one ALTER TABLE ... DELETE over both makes one delete file whose file_path bounds are those two paths. Both arms rewrite field id 2147483546 alone, which selects the delete manifest by construction: a data file entry keys its bounds by the table's own column ids.

Two data files are needed: the bounds are the extremes of the delete file's own file_path column, so one would make them equal. The first arm exchanges the two real extrema, the reported shape; it asserts they differ, and that an entry was rewritten, so it cannot pass unfixed. The second installs a pair derived from the real maximum that sorts above every path, so reordering rather than ignoring it would leave a range holding no data file and the delete file skipped everywhere. That pins dropping these bounds over sorting them.

binary bounds rows profile events
before as written [1,3,..,19] NonPrunedDeleteFiles=2
before inverted [0,1,2,..,19] PrunedDeleteFiles=2
after as written [1,3,..,19] NonPrunedDeleteFiles=2
after inverted [1,3,..,19] NonPrunedDeleteFiles=2

Rows 1 and 3 are the control: on a well-formed pair the two binaries agree on rows and counters, so the check fires only on inversion and good-pair pruning is unchanged. The test passes with the fix and fails without it, on the first fault arm, its control still passing.

Also green: test_position_deletes.py, all 17 functions, incl. three test_position_deletes_bounds_logging parametrizations, which pin the logged bounds against the manifest bounds, so the check never fires on Spark's well-formed pairs; the whole test_storage_iceberg_no_spark module, 63 functions; five repeats of the new test; 85 Iceberg stateless tests; 85 Iceberg unit tests.


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

Version info

  • Merged into: 26.9.1.893 (included in 26.9 and later)

A position-delete manifest entry may declare the range of data file paths
its delete file references. When `referenced_data_file` is absent,
`AvroForIcebergDeserializer` took `lower_bounds` and `upper_bounds` for the
reserved `file_path` column independently, with no ordering check, and
`IcebergIterator` then kept the delete file for a data file only when
`lower <= path && upper >= path`. An inverted pair makes that conjunction
false for every path, so the delete file was skipped for every data file it
covers and the rows it deletes were returned. The query succeeded with wrong
rows; only a `LOG_TEST` line and `IcebergMinMaxPrunedDeleteFiles` recorded it,
and no setting gated the check.

That branch is the one ClickHouse itself takes: it never writes
`referenced_data_file`, so every merge-on-read delete it produces carries
these bounds.

The pair is now checked where it is built. When inverted, both bounds are
dropped and a warning is logged, which leaves the entry as one that declares
no bounds. Swapping or clamping was rejected: a swapped pair would go on
skipping delete files, over a range the manifest never asserted.

Dropping the bounds cannot lose deletes, because the path is re-checked
downstream. `PositionDeleteTransform` pushes `WHERE file_path = '<data file>'`
into the delete-file read and then filters every delete row by exact path
match against the current data file. The cost is at most reading a delete file
that filters to zero rows, which is already what happens for a delete file
that declares no bounds.

The regression test is an integration test because it rewrites an Avro
manifest out of band. Its fixture is written entirely by ClickHouse, and it
needs two data files under one delete file: the bounds are the extremes of the
delete file's own `file_path` column, so a single data file gives
`lower == upper` and exchanging them would be a no-op.
The regression test built its inverted pair by exchanging the two real
extrema, so an implementation that reordered the pair rather than dropping it
restored the original well-formed range and satisfied the test. Drop and
reorder were observationally identical there, and no assertion on rows or
profile events could separate them, because one delete file covering both data
files is never skipped on a well-formed pair.

Reordering is not an equivalent implementation: it prunes on a range the
manifest never asserted, so where the two declared values are not the real
extrema the sorted range can exclude every data file path and the delete file
goes on being skipped. A second fault arm pins that. Its pair is derived from
the real maximum and sorts above every data file path, so the sorted form
contains no data file at all, and only dropping the bounds keeps the delete
file. Measured on the built binaries: that pair returns the surviving rows
with the fix and every row without it, while its sorted form returns every row
even with the fix.

The rewrite loop now takes the mutation as a parameter so both arms share it,
and the assertion that the two bounds differ moves into the exchanging arm,
the only arm it constrains.

Two smaller corrections. The control arm's comment claimed a discrimination it
does not provide, an implementation ignoring these bounds outright satisfying
the control as well; it now states what the control does pin, which is the
fixture the fault arms need. And the warning names the manifest file that
declares the malformed pair, as the data file bounds guard it mirrors does,
since that is the file an operator has to find to repair it.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 4, 2026
@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two rounds against the change. Round 1 raised one major, which I fixed; round 2 raised none.

Major, test liveness (agreed, fixed). The regression test built its inverted pair by exchanging the two real extrema, so an implementation that reordered the pair instead of dropping it restored the original well-formed range and satisfied the test. Drop and reorder were observationally identical there, and no assertion on rows or profile events could separate them. A second fault arm now installs a pair derived from the real maximum that sorts above every data file path: reordering that pair leaves a range holding no data file, so only dropping the bounds keeps the delete file. Measured on both binaries across all four bound states.

Two smaller corrections in the same round: the control arm's comment claimed a discrimination it does not provide, and the new warning now names the manifest file that declares the malformed pair, as the data file bounds guard it mirrors does.

Noticed nearby, not part of this change and not reproduced, so I am not raising it: IcebergPositionDeleteTransform::getSchemaFields sets the file_path field's f_name, f_required and f_type on the positions field object instead of its own, which also overwrites the positions field's declared name and type. DataFileStatistics reads only f_id, so I observed no consequence.

@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cc417d2]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
04035_alp_rd_codec_special_values FAIL cidb IGNORED

AI Review

Summary

This PR hardens Iceberg position-delete manifest parsing by treating inverted file_path bounds as untrustworthy and clearing them before delete-file pruning. I traced the new bounds through their only consumer and checked the updated regression test, and I did not find a remaining correctness gap in the touched contract.

Final Verdict

✅ No new blockers or majors found.

LLVM Coverage Report

Measured on commit cc417d2.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cc417d231 with master e4c374202 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of bcaec2e05; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

8 object files changed (+16.66 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/Common/AvroForIcebergDeserializer.cpp.o 412.31 KiB 428.57 KiB +16.25 KiB (+3.94%)

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

7 translation units recompiled, 12 s compile time in total, 7 of them have a recent master baseline.

Job report

@zlareb1

zlareb1 commented Sep 5, 2026

Copy link
Copy Markdown
Member

TL;DR: the fix looks complete for the delete-file bounds (single build site, single consumer, and the check uses the identical operator<=> on the identical post-deserialize values the consumer uses — no desync possible). Could the acknowledged sibling get a tracking issue or the follow-up PR number linked here, so it doesn't evaporate with the PR body?

The residual named in the description — getMaterializedRowLineageRange (ManifestFileIterator.cpp:153-176) — is one step worse than the shape fixed here: it builds DB::Range(*left, true, *right, true) from the raw reserved-field bounds with no inversion check, and addRowLineageHyperrectangles feeds that into pruning. An inverted _row_id / _last_updated_sequence_number pair produces an empty Range, so a data file is silently pruned for queries filtering on those virtual columns — silent missing rows rather than a delete file wrongly skipped, with no downstream exact-match re-check to soften it the way PositionDeleteTransform does for position deletes.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

The follow-up is a separate pull request, tracked on my side; I will post the number in this thread when it opens, so the link does not depend on this description.

The remedy transfers without a new mechanism: at master caea94f9121c, when getMaterializedRowLineageRange returns nullopt the caller falls through to DB::Range(0, true, inherited_upper_bound, true) at ManifestFileIterator.cpp:219, whose lower bound is 0 rather than the inherited one, so it cannot prune a file the inherited range would keep. Ignoring an inverted pair there is then the same detect, warn and drop shape as #116604.

@zlareb1

zlareb1 commented Sep 5, 2026

Copy link
Copy Markdown
Member

One correction on where the follow-up guard has to live, because the :219 fallthrough argument does not reach the residual case.

The Range(0, true, inherited_upper_bound, true) fallthrough at ManifestFileIterator.cpp:219 is only taken when getMaterializedRowLineageRange returns nullopt. For an inverted-but-present pair it does not return nullopt: with value_bounds containing the field and nulls_count == 0, it reaches the tail and returns a non-null DB::Range(*left, true, *right, true) at :175 with *left > *right. The caller then takes the else if (auto range = getMaterializedRowLineageRange(...)) branch at :213, does hyperrectangles.emplace(field_id, *range) and continue at :215-216 — so :219 is never reached and the empty range is what gets fed to pruning. canBePruned sees has_no_nulls == true (only reset on the non-lineage branch) and an empty range, and drops the data file.

So a follow-up that only ignores an inverted pair "at :219" would not change this path. The guard has to go inside getMaterializedRowLineageRange itself — return nullopt when *right < *left before building the Range — which then falls through to the permissive :219 range. That is the same detect/warn/drop shape as the regular-column bounds guard 20 lines below at :672: if (accurateLess(*declared_right, *declared_left)) { LOG_WARNING(...); continue; }, whose comment already states an inverted declared pair means the statistics are untrustworthy and no range derived from them is safe to prune on. The lineage subpath is the one place that guard is missing.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

You are right, and the ambiguity was mine: "there" attached to :219, which is not where the guard goes. It returns nullopt from inside getMaterializedRowLineageRange, before the Range is built, and that is what makes the :219 fallthrough reachable at all. The regular-column guard you point at is the precedent I am mirroring, down to the accurateLess spelling.

One route a guard there does not reach, so it needs its own early return rather than the fallthrough: first_row_id is read with safeGet<Int64>() into an optional<UInt64> and never checked for sign, at AvroForIcebergDeserializer.cpp:206 and StatelessMetadataFileGetter.cpp:250. A declared negative value wraps, so *first_row_id + record_count - 1 at ManifestFileIterator.cpp:193 can land below *first_row_id, and when the reserved field carries no column stats :209 emplaces that inverted inherited range without calling getMaterializedRowLineageRange at all. inherited_upper_bound is the wrapped value on that route, so :219 is not permissive there either. That one is a code reading at master cdc26e3bd497; I have not reproduced it yet.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8b8f6f3

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Docker server image / clickhouse-server:head-arm64, clickhouse-server:head-distroless-arm64 (2 of 10 legs, both arm64) arm64 ports mirror outage mutated into a package-resolution error: Err:1 http://us-east-1.ec2.ports.ubuntu.com/ubuntu-ports jammy InRelease then 503 Service Unavailable [IP: 100.26.142.62 80], after which apt-get update only WARNS, the build continues, and apt-get install dies E: Package 'ca-certificates' has no installation candidate. Because the 503 surfaces as a package error rather than an index-fetch failure, the apt mirror fallback never fires #118023 (mine, open)

Session id: cron:our-pr-ci-monitor:20260905-043000

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

@zlareb1 The follow-up is #118299, as promised in this thread. It carries the placement you prescribed: the ordering check returns nullopt from inside getMaterializedRowLineageRange, which is what makes the fallthrough to the permissive range reachable at all.

The second route I described in this thread is reproduced now, so it is no longer a code reading: patching the manifest list's first_row_id to -1 aborts on the same assertion once the overflow check is removed. That also confirms what I said about the fallback, since the wrapped value is the fallback's own upper bound, so this route installs no row lineage range rather than falling through to one.

@PedroTadim PedroTadim self-assigned this Sep 5, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit 8396165 Sep 7, 2026
173 of 175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 9, 2026
A filter on `_row_id` or `_last_updated_sequence_number` over a format-version 3
table is answered from the manifest, by handing `KeyCondition` the range of row
lineage values a data file can hold. Two writer-declared inputs can make that
range start above where it ends, and neither was checked:

- `getMaterializedRowLineageRange` built `DB::Range` straight from the
  `value_bounds` pair declared for the reserved field id, so a manifest that
  declares a lower bound above the upper bound produced an empty range.
- `addRowLineageHyperrectangles` derived a file's inherited block as
  `first_row_id + record_count - 1`. `first_row_id` is a signed long on the wire
  and unsigned in the reader, so a negative value made the sum wrap and the
  block end below its own start.

An empty range prunes the data file away, so a filtered read silently loses
every row it holds, and the `chassert` in `KeyCondition::checkInRange` aborts the
server in debug and sanitizer builds.

Both cases now drop the untrustworthy bounds. A pair inverted as declared means
the manifest's statistics do not describe the file, so no range derived from them
may be pruned on; swapping or clamping the pair would instead prune on a range
the manifest never asserted, which is the same reasoning the guard for ordinary
columns already uses. The declared-pair case returns no range and lands on the
existing conservative fallback, `[0, last inherited row id]`, which holds for
both reserved ids: a materialized value always comes from an earlier write, so it
is below this file's own block. The wrapped-block case cannot use that fallback,
because the wrapped value IS the fallback's upper bound, so it installs no row
lineage range at all.

Re-reading the bounds with rounding compensation, as the ordinary-column path
does, is not needed here: the type is `DataTypeUInt64`, which takes the
non-decimal branch of `deserializeFieldFromBinaryRepr` where that flag is unused,
so the deserialized values are the declared ones.

Tested by two integration arms that patch a Spark-written v3 table's avro
metadata: one declares an inverted `_row_id` pair, the other a negative
`first_row_id`. Each arm reddens when its own check is removed.

Reported by @ zlareb1 on pull request ClickHouse#116604, which fixed the same defect class
for ordinary columns, and again on ClickHouse#118181, which fixes it for position delete
file paths.

Related: ClickHouse#116499
Related: ClickHouse#116604
@clickhouse-gh clickhouse-gh Bot added the comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... label Nov 22, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

Iceberg position-delete files with inverted file_path bounds are silently skipped — deleted rows resurface

4 participants