Skip to content

Fix Iceberg DELETE/UPDATE deleting wrong rows after ADD COLUMN under PREWHERE - #111693

Merged
PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-prewhere-mixed-schema-delete-111664
Jul 30, 2026
Merged

PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-iceberg-prewhere-mixed-schema-delete-111664

Conversation

@groeneai

@groeneai groeneai commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111664

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):

Fix DELETE/UPDATE on an Iceberg table silently removing the wrong rows (or throwing NOT_FOUND_COLUMN_IN_BLOCK) when the table contains data files written both before and after ALTER TABLE ... ADD COLUMN and optimize_move_to_prewhere is enabled.

Description

Root cause: an Iceberg DELETE/UPDATE reads the matching rows together with the _row_number virtual column and records (data_file, row_number) into a positional-delete file. _row_number is recovered from ChunkInfoRowNumbers (row_num_offset + applied_filter) attached by the Parquet reader. For a file that predates the ADD COLUMN, the read goes through the schema-changed path where PREWHERE is stripped from the reader and replayed as a fallback FilterTransform. FilterTransform dropped rows without composing its filter into applied_filter, so _row_number became the compacted post-filter index (0,1,2,...) instead of the physical position, and the positional-delete targeted the wrong rows. This is the invariant ChunkInfoRowNumbers documents ("a step that uses this info must not run after a step that breaks it").

Fix: FilterTransform can now compose the mask it applies into ChunkInfoRowNumbers.applied_filter (like DeletionVectorTransform / IcebergStreamingPositionDeleteTransform), but only when explicitly asked via a new opt-in flag. The data lake read fallback filters and the Iceberg equality-delete filter enable it, since they run right after the format reader where the info still describes the chunk. Every other FilterTransform caller keeps its previous behavior, which matters because some callers (e.g. FilterSortedStreamByRange, or a LimitTransform upstream) hand FilterTransform a chunk whose retained ChunkInfoRowNumbers no longer matches the columns; the composition also guards against such stale info.

Setting optimize_move_to_prewhere = 0 was a workaround; it is no longer needed.

Version info

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

groeneai and others added 2 commits July 23, 2026 19:33
…PREWHERE

An Iceberg DELETE/UPDATE reads matching rows plus the _row_number virtual
column and records (data_file, row_number) into a positional-delete file.
_row_number is recovered from ChunkInfoRowNumbers (row_num_offset +
applied_filter) attached by the Parquet reader. For a data file predating an
ALTER TABLE ADD COLUMN, the read goes through the schema-changed path where
PREWHERE is stripped from the reader and replayed as a fallback FilterTransform.

FilterTransform dropped rows without composing its filter into
ChunkInfoRowNumbers.applied_filter, so _row_number became the compacted
post-filter index instead of the physical row position, and the positional
delete targeted the wrong rows. DELETE removed the wrong rows; UPDATE left
duplicates and missing rows.

FilterTransform can now compose the applied filter into ChunkInfoRowNumbers,
but only when explicitly asked to via a new update_row_numbers_info flag
(default off). The data lake read fallback filters and the Iceberg
equality-delete filter in StorageObjectStorageSource/IcebergMetadata enable it:
they run right after the format reader (only row-count-preserving-or-tracking
transforms in between), so the info still describes the chunk. Every other
FilterTransform caller keeps its previous behavior, which matters because some
callers (e.g. FilterSortedStreamByRange, or a LimitTransform upstream) hand
FilterTransform a chunk whose retained ChunkInfoRowNumbers no longer matches
the columns. The composition also guards against such stale info (set-bit
count must equal the pre-filter row count).

Closes: ClickHouse#111664

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. DELETE FROM t WHERE number % 3 = 0 on a mixed pre/post-ADD COLUMN IcebergLocal(Parquet) table fails every run with default settings; SELECT number, _row_number ... PREWHERE number % 3 = 0 shows the wrong (compacted) row numbers deterministically.
b Root cause explained? Yes. The mutation reads _row_number (recovered from ChunkInfoRowNumbers.applied_filter) to build a positional-delete file. Pre-ADD COLUMN files take the schema-changed path where PREWHERE is stripped to a fallback FilterTransform; that transform dropped rows without composing its mask into applied_filter, so _row_number became the compacted index (0,1,2,...) not the physical position → positional delete hits the wrong rows.
c Fix matches root cause? Yes. FilterTransform composes its applied mask into ChunkInfoRowNumbers.applied_filter (opt-in), at the exact transforms that broke the invariant.
d Test intent preserved / new tests added? New test 04615_iceberg_prewhere_mixed_schema_delete_update.sh (4 cases: _row_number under PREWHERE, DELETE, UPDATE, two sequential DELETEs). No existing test weakened.
e Both directions demonstrated? Yes. Pristine ecd631bc: test FAILS (wrong _row_number, wrong DELETE survivors, UPDATE dups+missing). Fixed: PASSES, 50/50 with randomization.
f Fix is general across code paths? Yes. Applied at the generic FilterTransform (opt-in flag), so BOTH fallback filters (row-level filter + PREWHERE) and the Iceberg equality-delete filter are covered — not just the one DELETE case. Sibling consumers (DeletionVectorTransform, IcebergStreamingPositionDeleteTransform) already composed correctly.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The dense mask is built via FilterDescription::preprocessFilterColumn (handles const/sparse/nullable/LowCardinality/wide filter columns); DELETE and ALTER UPDATE both covered; two pre-ADD COLUMN files with different offsets verified; the existing-mask branch is exercised by two sequential DELETEs.
h Backward compatible? Yes. No setting/format/protocol/on-disk change. Pure correctness fix; behavior changes only for the previously-corrupt path. No SettingsChangesHistory.cpp entry needed.
i Invariants and contracts preserved? Yes. Restores the documented ChunkInfoRowNumbers invariant (set-bit count == surviving rows). Composition is opt-in so other FilterTransform callers are byte-identical, and it guards against stale info (count mismatch → no-op) so it cannot misindex or crash when an upstream transform (e.g. LimitTransform, FilterSortedStreamByRange probe) left the info inconsistent.

Session id: cron:clickhouse-author-slot-2:20260723-192800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 review rounds as the fix was re-architected; final round: 0 findings).

# Sev Finding Verdict Evidence / action
1 ❌ Composing into ChunkInfoRowNumbers in the generic FilterTransform can OOB-read filter when an upstream row-changing transform (LimitTransform) left the info stale (PREWHERE→LIMIT→WHERE) AGREE — fixed Reproduced a real server abort locally. Re-architected to an opt-in update_row_numbers_info flag (default off) + a staleness guard (set-bit count must equal filter.size(), else no-op).
2 ⚠️ Test used WHERE without pinning prewhere; runner disables it ~5% → test could pass on buggy code AGREE — fixed Pinned optimize_move_to_prewhere=1 + query_plan_optimize_prewhere=1, and switched the _row_number probe to explicit PREWHERE.
3 ❌ FilterSortedStreamByRange runs a 2-row probe through FilterTransform while retaining chunk infos → could corrupt row numbers AGREE — fixed The opt-in flag resolves this: only the data lake fallback filters opt in; FilterSortedStreamByRange (default off) never composes.
4 💡 ChunkInfoRowNumbers doc comment still named FilterTransform as not updating the info AGREE — fixed Updated the comment (FilterTransform updates it only via the opt-in flag; LimitTransform named as the example).
5 ❌ Iceberg equality-delete FilterTransform runs before the fallback filters with the flag off → row numbers stale for equality-delete + schema-evolution files AGREE — fixed Enabled the flag on the equality-delete filter too (it runs right after the format reader).
6 ⚠️ Explicit-PREWHERE still did not prove the mutation queries reach the fallback path AGREE — fixed Both-directions proof at the test level: the test (explicit PREWHERE + pinned settings) FAILS on pristine ecd631bc and PASSES with the fix.
7 ⚠️ Test never exercised composition into an EXISTING applied_filter (the complex branch) AGREE — fixed Added case 4: two sequential DELETEs — the 2nd reads through the 1st's positional-delete mask + fallback PREWHERE.
8 💡 Suggested Critical Bug Fix category + present tense PARTIAL Present tense applied. Category kept Bug Fix: I do not proactively pick Critical Bug Fix — a maintainer can request it.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE/PARTIAL verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-author-slot-2:20260723-192800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @arsenmuk @SmitaRKulkarni — could you review this? It fixes silent wrong-row DELETE/UPDATE on Iceberg tables with data files spanning an ALTER TABLE ... ADD COLUMN: the schema-changed read strips PREWHERE to a fallback FilterTransform that dropped rows without updating ChunkInfoRowNumbers, so _row_number (used to build positional deletes) pointed at the wrong physical rows. The composition is now opt-in on the data lake fallback / equality-delete filters only.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4959bcd]

Summary: ✅


AI Review

Summary

This PR fixes wrong _row_number propagation in the Iceberg mixed-schema mutation path by making the affected fallback and equality-delete FilterTransform call sites compose their masks into ChunkInfoRowNumbers, and it now adds focused stateless coverage for both the mixed-schema PREWHERE mutation case and the equality-delete path. I did not find remaining correctness, compatibility, or evidence gaps in the current head.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 005d71e

Every failure below has an owner. The only real failure is a chronic, PR-independent amd_tsan job timeout (server froze mid-suite; 0 per-test results); the aggregate checks just reflect it.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) non-deterministic TSAN server stall / job-level timeout (2h30m, empty results; 16 errors across 14 unrelated PRs / 0 master in 30d; our own new 04615 passed all 4 flaky-checks) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Finish Workflow / Mergeable Check / PR aggregate of the above same as above

The Iceberg fix and its new test (04615, _row_number/DELETE/UPDATE across mixed pre/post-ADD-COLUMN files) passed; the only red is the amd_tsan-parallel job timeout, which is unrelated to this diff.

Session id: cron:our-pr-ci-monitor:20260724-030000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Following up on the CI finish ledger above: the Stateless tests (amd_tsan, parallel) line's fix task has produced #112269.

To be precise about what it does and does not cover, since the ledger line described the failure as a non-deterministic stall: it fixes the pid-identification defect on that same abort path (clickhouse-test matched clickhouse-server as a substring of the whole ps command line, so the shell=True launcher wrapper was selected and the lldb dump labelled a dash as the "main server"). It does not resolve the stall itself, and my reading of the 14 errored job logs no longer supports the "false positive" framing in that ledger line: the probe genuinely exhausts its full budget and no test completes inside the window, so the verdict is true. The stall is server-side, and the probe's scheduling is a separate change; both are tracked apart from #112269.

groeneai and others added 5 commits July 28, 2026 13:53
The fix in this PR makes three FilterTransform call sites compose their
applied filter into ChunkInfoRowNumbers. Only the two stripped-PREWHERE
fallback filters were covered by 04615; the Iceberg equality-delete
notIn filter was not, so the equality-delete half of the contract was
unproven.

Reverting only the equality-delete call site to the old behaviour makes
the new test fail, and pristine master fails it too: on a table that
carries equality delete files the _row_number column is built from a
stale mask, which either aborts with a column length mismatch
("Expected the argument ClickHouse#2 ('__table1._row_number' of type Int64) to
have 423 rows, but it has 470") or silently yields compacted post-filter
indices instead of physical row positions. Those indices are what the
mutation path writes into positional delete files, so a wrong value
deletes the wrong rows.

The test uses the existing committed fixtures: deletes_db/eq_deletes_table
(equality plus position deletes, also read under PREWHERE so the fallback
filter stacks on top of the notIn filter) and
deletes_db/eq_deletes_required_table (equality deletes only, where the
exact physical row numbers are asserted). The per-file offset assertion is
independent of the engine path: it is checked against the raw Parquet data
files read directly through s3().

Co-Authored-By: Claude Fable 5 <[email protected]>
The equality-delete call site does not run right after the format reader:
a position-delete transform, and an earlier equality-delete filter, can
precede it. What actually holds is that each of those maintains
ChunkInfoRowNumbers, so the info still describes the chunk.

Also say what happens when the composition declines a stale mask: the
info is unrecoverable at that point and is left untouched, and a consumer
of a stale mask fails loudly on the resulting column length mismatch
rather than silently producing wrong row numbers.

Co-Authored-By: Claude Fable 5 <[email protected]>
A declined stale mask does not necessarily fail downstream: the row
numbers are built one per set bit, so a mask with N set bits on a chunk
that the filter reduces to N rows yields N row numbers and no length
mismatch. State only what holds: the info cannot be repaired at that
point, and the opt-in callers are those whose upstream transforms
maintain it.

The header carried the same "right after the format reader" inaccuracy
that the equality-delete call site had.

Co-Authored-By: Claude Fable 5 <[email protected]>
Asserting only that id - _row_number is constant per data file is weaker
than it looks: a mask that replaced rather than composed would keep it
constant while shifting it. Assert the exact offset per file instead. The
expected values are the ones the raw Parquet data files carry, so they do
not depend on the read path. With this, reverting the composition branch
produces scattered offsets rather than a single shifted value.

The second case is also mislabelled: this fixture is same-schema Parquet,
so PREWHERE is not stripped into a fallback filter; it stays in the reader
and its mask is composed with the equality-delete mask.

Co-Authored-By: Claude Fable 5 <[email protected]>
The tag comment named the fallback filter path, which this fixture never
takes: eq_deletes_table is same-schema Parquet, so the reader keeps PREWHERE
(the same fact the second case's own comment states). The real reason is that
StorageObjectStorageCluster does not override IStorage::supportsPrewhere, so
the explicit PREWHERE throws ILLEGAL_PREWHERE once the cluster wrapper is
used. Verified against the running server: with enable_parallel_replicas = 1,
a cluster_for_parallel_replicas set and parallel_replicas_for_cluster_engines
= 1, the second query returns Code 182 ILLEGAL_PREWHERE "Storage IcebergS3
does not support PREWHERE"; with parallel_replicas_for_cluster_engines = 0 it
returns 125 rows. Points at the same explanation 04071 and 04615 already use.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 54/56 (96.43%) · Uncovered code

Full report · Diff report

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 28, 2026
…line

`Stateless tests` jobs have been failing with a job-level `error` that burns the
full wall-clock budget and reports no per-test results at all: `check_status`
is `error` and `results` is empty, so the failure is invisible to every
test-name-based query. Over the last 30 days this happened 16 times across 14
unrelated pull requests and 0 times on master.

In CI the runner heads a shell pipeline,
`clickhouse-test | ts | tee -a <file>` (`ci/jobs/functional_tests.py`). A
per-test wrapper is spawned with `start_new_session=True` and inherited stdio,
so it holds the pipeline's write end and lives in its own session. When the
runner aborts and exits, a wrapper that outlives it keeps that descriptor open,
`ts` and `tee` never see EOF, and the pipeline never finishes. The job-level
wall-clock timeout then replaces the runner's real exit status, which is why
the underlying `Server died` report is never produced and no per-test rows are
written.

The wrapper does not need the runner's streams: the command already redirects
the test's own output to the per-test `{stdout}`/`{stderr}` files that
`process_result_impl` reads back, so the inherited descriptors carried nothing.
Its stdout is now `DEVNULL` and its stderr is appended to the per-test stderr
file, which removes the coupling without reaping anything. The parallel workers
and the bookkeeping manager keep the runner's stdout by design, since they
report results through it; fd 0 is likewise still inherited.

Also fixed here, found while validating the above:

- The per-test stderr file is truncated before each attempt, so a retried
  attempt no longer inherits the previous one's diagnostics, and the wrapper
  appends rather than overwrites, since the command's own `2> {stderr}` holds a
  second descriptor on that path with its own offset.
- A `preexec_fn` that dies before `exec` is now reported as the test's failure
  with its numeric exit status, instead of being lost.

Documented in `tests/clickhouse-test-process-management.md`.

Verified in the job's own image with a live server: the pipeline finishes with
the runner's status while the orphan is deliberately left running, and
reverting the redirect reproduces the wedge.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111693&sha=005d71edc8389539f2661acd34f2bd165de3b108&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112265&sha=afd4ae8bc5b3cbfa78cad8f1bf5e0a5a66c33b54&name_0=PR&name_1=CI%20Tests
Related: ClickHouse#111693
Related: ClickHouse#112265

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4959bcd

Every failure below has an owner: a fixing PR (ours 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
Stateless tests (arm_binary, parallel) / 04367_distributed_plan_merge_scatter_multishard real hang, unbounded condition-variable wait at max_threads = 1 (139/139 same-settings reruns passed, so not randomization) #111762 (external, open)

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

@PedroTadim

Copy link
Copy Markdown
Member

LGTM! @scanhex12 can you give a quick look?

@PedroTadim PedroTadim self-assigned this Jul 30, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 4a989ab Jul 30, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

The fixing PR for the ledger line on this PR is now open: #112265.

The Stateless tests (amd_tsan, parallel) row here was a job-level error that burned the full
wall-clock budget and reported no per-test results, so it was invisible to every test-name query.
Root cause turned out not to be a TSAN server stall: the test wrapper shell inherited the runner's
stdout, which is the write end of the pipe into ts, so after the runner decided to stop, an
orphaned test process kept that pipe open and the job sat until praktika's watchdog killed it. The
run on this branch, 005d71edc8389539f2661acd34f2bd165de3b108, is one of the runs analysed there.

Deciding to stop took 0.2 to 7.7 minutes across the affected runs; the wait between that decision
and the kill was 71.8 to 142.4 minutes, which is essentially all of the wasted budget.

Correcting the reason I gave in that ledger: I described this as a non-deterministic TSAN server
stall. It is neither TSAN-specific nor a server stall.

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

4 participants