Skip to content

Fix Iceberg INSERT server abort on stale schema field id mismatch - #107279

Merged
SmitaRKulkarni merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-insert-stale-schema-field-id-107268
Jun 16, 2026
Merged

SmitaRKulkarni merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/iceberg-insert-stale-schema-field-id-107268

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #107268

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 server abort (std::out_of_range logical error) when inserting into an Iceberg table whose write block column names do not match the field ids of the latest schema (for example after a concurrent writer renames a column within the iceberg_metadata_staleness_ms window). The insert now fails with a clean query error instead of crashing the server.

Description

Parquet::prepareColumnRecursive looked up a leaf column's field id with column_field_ids->at(name). unordered_map::at throws std::out_of_range, which is not a DB::Exception, so a missing name escalated to a fatal abort. Every composite path (tuple/array/map) already guarded the same lookup with find() and tolerated a missing id; only the primitive leaf used at().

The names disagree because the two metadata reads can resolve different schemas: the INSERT analysis path uses force_fetch_latest_metadata=false (honoring iceberg_metadata_staleness_ms, so a cached/stale schema is allowed), while the write sink reads with force=true and builds the field-id map from the latest current-schema-id. A concurrent writer renaming a column within the staleness window leaves the block carrying an old name that is absent from the sink's latest field-id map.

Fix:

  • Make the leaf field-id lookup tolerant (find()), consistent with the composite paths.
  • Reject a missing top-level field id with a clean INCORRECT_DATA error rather than aborting. A silently omitted top-level field id would write a data file whose footer disagrees with its manifest (the manifest maps field ids positionally from the fresh schema), so a hard error is the safe behavior here.

A note on the deeper cause: the stale-vs-latest metadata disagreement between the INSERT analysis path and the sink is a separate metadata-consistency question; this PR fixes the crash and prevents silent corruption, and leaves the broader reconciliation for follow-up.

Reproduction (from the issue, run against a server with a warm metadata cache):

  • Seed IcebergLocal table {c0, c1}, warm the cache, publish a newer metadata version renaming c0 -> c9, then INSERT (c0, c1).
  • Before: 100% server abort with the stack from the issue.
  • After: clean Code: 117 ... (INCORRECT_DATA), server stays alive.

Regression test 04329_iceberg_insert_stale_schema_field_id_107268 reproduces the exact scenario. It is server-based because the bug requires a persistent (warm) metadata cache that disagrees with the on-disk metadata, which a fresh clickhouse local process cannot create.

Version info

  • Merged into: 26.6.1.847

Inserting into an Iceberg table could abort the server with a
std::out_of_range logical error when the INSERT block column names did
not match the field-id map the write sink resolved.

Parquet::prepareColumnRecursive looked up a leaf column's field id with
column_field_ids->at(name). unordered_map::at throws std::out_of_range,
which is not a DB::Exception, so a missing name escalated to a fatal
abort. Every composite path (tuple/array/map) already guarded the same
lookup with find() and tolerated a missing id; only the primitive leaf
used at().

The names disagree because the INSERT analysis path resolves columns
from a possibly cached (stale) schema (force_fetch_latest_metadata=false,
honoring iceberg_metadata_staleness_ms) while the sink builds the
field-id map from the force-fetched latest current-schema-id. A
concurrent writer renaming/replacing a column within the staleness
window leaves the block carrying an old name absent from the latest map.

Make the leaf lookup tolerant like the composite paths, and reject a
missing top-level field id with a clean INCORRECT_DATA query error
instead of aborting (a silently omitted top-level field id would
mismatch the data file footer against its manifest, which maps field
ids positionally from the fresh schema).

Closes ClickHouse#107268

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate:

# Check Result
a Deterministic repro? Yes. The issue's script (using INSERT ... SELECT against a running server): seed IcebergLocal {c0,c1} → warm the metadata cache → publish v3 renaming c0->c9 → INSERT (c0, c1). Pre-fix: 100% server SIGABRT; fatal log std::out_of_range, unordered_map::at: key not found in prepareColumnRecursive -> prepareColumnForWrite:836.
b Root cause explained? Yes. INSERT analysis resolves columns with force_fetch_latest_metadata=false (honors iceberg_metadata_staleness_ms, may return a stale {c0,c1} schema); the sink reads force=true and builds the field-id map from the latest current-schema-id ({c9,c1}). The block carries c0, absent from the latest map, so the leaf column_field_ids->at("c0") throws std::out_of_range (not a DB::Exception) and aborts.
c Fix matches root cause? Yes. Replaces the leaf at() with a tolerant find() (matching the composite tuple/array/map paths) and rejects a missing top-level field id with a clean INCORRECT_DATA error.
d Test intent preserved / new test added? New regression test 04329_iceberg_insert_stale_schema_field_id_107268 added; asserts the clean INCORRECT_DATA error and that the server stays alive. No existing test weakened.
e Demonstrated in both directions? Yes. Pre-fix binary: test output Connection refused / server DEAD = mismatch (catches the bug). Post-fix binary: INCORRECT_DATA + 1 / server ALIVE = match. Also verified normal Iceberg writes (primitives + Tuple + Array + Map roundtrip), generic non-Iceberg Parquet writes, and existing tests 04214 and 04033 all pass.
f Fix is general, not a narrow patch? Yes. Both at() sites fixed (LowCardinality leaf + default primitive leaf); composite paths already used find(). The top-level guard covers the whole class of name/field-id disagreement, not just the one reproduced rename. The leaf find() is the convention-consistent fix; the top-level error is required to prevent a silent footer/manifest mismatch (data corruption), not merely a symptom guard. The deeper stale-vs-latest metadata-consistency reconciliation is a separate design question left for follow-up.

Session: cron:clickhouse-worker-slot-5:20260611-202200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @scanhex12 — could you review this? It fixes the Iceberg INSERT server abort from #107268: the Parquet write path's primitive-leaf field-id lookup used unordered_map::at() (the tuple/array/map paths already used find()), so a block column name absent from the sink's latest field-id map threw std::out_of_range and aborted. The leaf now uses find(), and a missing top-level field id raises a clean INCORRECT_DATA error instead of risking a footer/manifest mismatch.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [084f624]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) FAIL
04329_iceberg_insert_stale_schema_field_id_107268 ERROR cidb IGNORED
Server died FAIL cidb, issue ISSUE EXISTS

AI Review

Summary
  • The PR fixes Iceberg INSERT into Parquet data files when the analysis schema is stale but the sink resolves a newer schema: primitive leaf field-id lookup no longer throws std::out_of_range, and convertSchema now rejects missing Iceberg field ids before writing a footer inconsistent with the manifest. I verified the prior nested-field concern against the current code; recursive validation now covers Tuple, Array, and Map logical paths, and the regression test covers both top-level and nested rename cases. I did not find remaining correctness issues that warrant inline comments.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
The previous fix only checked top-level block column names against the
sink's force-fetched field-id map. A rename inside a stable top-level
field (e.g. cached t Tuple(a Int32) vs latest t Tuple(b Int32), with t
keeping its field id) slipped past the top-level contains() check:
buildSubFieldIds() then handed the leaf mapper {b -> id} to
prepareColumnRecursive and lookupLeafFieldId(..., "a") returned nullopt,
so the renamed nested field was written with no Iceberg field id. The
data file footer then mismatched the latest schema (reads expect b, the
file has a with no id), committing a file inconsistent with its manifest.

Replace the top-level-only guard with validateIcebergFieldIds(), which
walks the block column types and reconstructs the same dotted logical
paths used by the field-id map and buildSubFieldIds (t, t.a, arr.element,
m.key, m.value), rejecting any missing path with the same clean
INCORRECT_DATA error. Nullable/LowCardinality are stripped (transparent
in Iceberg field naming, mirroring prepareColumnNullable and the
LowCardinality branch). Nested leaf lookups during writing keep the
tolerant find() since the top-level validation has already rejected stale
schemas, and partial sub-maps remain legal there.

Extends the regression test with a nested Tuple rename case.

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

Copy link
Copy Markdown
Collaborator Author

Good catch, confirmed and fixed in a550ac7.

I reproduced the nested-rename hole exactly as you described, against the prior commit (top-level guard + tolerant leaf find()): created IcebergLocal (c0 Int32, t Tuple(a Int32)), warmed the staleness cache, published a v3 metadata renaming the nested field t.a -> t.b (top-level t keeps its field id), then ran a stale-schema INSERT (c0, t). It silently succeeded (RC 0, server alive) and wrote a data file whose leaf path is t.a with no field id, while the latest schema has t.b (id 3) - the inconsistent footer you predicted.

Fix: replaced the top-level-only contains(c.name) check with a recursive validateIcebergFieldIds() that walks the block column types and reconstructs the same dotted logical paths the field-id map and buildSubFieldIds() use (t, t.a, arr.element, m.key, m.value), rejecting any missing path with the same clean INCORRECT_DATA error. Nullable/LowCardinality are stripped since they are transparent in Iceberg field naming (mirroring prepareColumnNullable and the LowCardinality branch of prepareColumnRecursive). The map produced by traverseSchema/traverseComplexType is complete for the current schema (every composite node and leaf), so a complete-tree check is sound. The nested leaf lookup during writing keeps the tolerant find(), because the top-level recursive validation has already rejected stale schemas and partial sub-maps remain legal there.

Verified both directions on a debug build:

  • nested rename (t.a -> t.b), top-level rename (c0 -> c9), and a rename inside Array(Tuple(...)) element: all now rejected with INCORRECT_DATA, server stays alive.
  • normal Iceberg writes with Tuple/Array/Map and deeply nested Tuple(Tuple) across multiple inserts: still succeed and round-trip.
  • generic non-Iceberg Parquet writes (no field-id map): unaffected.

Added a nested Tuple rename case to the regression test 04329_iceberg_insert_stale_schema_field_id_107268.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (recursive nested validation, commit a550ac7)

# Question Answer
a Deterministic repro? Yes. IcebergLocal (c0 Int32, t Tuple(a Int32)), warm the staleness cache, publish a v3 metadata renaming nested t.a -> t.b (top-level t keeps its id), then INSERT (c0, t) with --iceberg_metadata_staleness_ms=600000 --async_insert=0. On the prior commit this silently succeeded and wrote a footer with leaf t.a and no field id.
b Root cause explained? Yes. The field-id map (traverseSchema/traverseComplexType) is keyed by full dotted logical paths and is complete for the latest schema. The prior guard only checked top-level names, so a rename inside a stable top-level field passed contains("t"); buildSubFieldIds then passed {b -> id} down and lookupLeafFieldId(..., "a") returned nullopt, writing the renamed leaf without a field id and producing a footer inconsistent with the manifest.
c Fix matches root cause? Yes. validateIcebergFieldIds() walks the block column types, reconstructs the same dotted paths the map uses (t, t.a, arr.element, m.key, m.value), and rejects any missing path with the clean INCORRECT_DATA error before any data file is written.
d Test intent preserved / new tests added? Yes. Extended 04329_iceberg_insert_stale_schema_field_id_107268 with a nested Tuple rename scenario (top-level case retained). Reference asserts two INCORRECT_DATA lines plus server-alive.
e Both directions demonstrated? Yes. Prior commit: nested-rename INSERT silently succeeds (RC 0, data file written). Fixed commit: same INSERT rejected with INCORRECT_DATA, server alive. Verified for nested Tuple, top-level, and Array(Tuple)-element renames.
f Fix is general, not a narrow patch? Yes. Validation is recursive over every logical field path (Tuple/Array/Map, through Nullable/LowCardinality), not a one-off guard for the reproduced case. Normal nested writes (incl. Tuple(Tuple) across multiple inserts) and generic non-Iceberg Parquet writes are unaffected.

Session id: cron:clickhouse-worker-slot-2:20260611-221500

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary for HEAD a550ac7860e5: all gating checks green (Finish Workflow, Mergeable Check, Bugfix validation functional tests all passed). A 04329_iceberg_insert_stale_schema_field_id_107268 server died row shows up in CIDB from a Bugfix-validation run, but the validation job itself passed (the abort bug reproduces on master and is fixed on this PR, which is exactly what Bugfix validation checks). Only non-green context is external CH Inc sync. No PR-caused failures. Ready for review.

Session: cron:our-pr-ci-monitor:20260612-033000

@SmitaRKulkarni SmitaRKulkarni self-assigned this Jun 15, 2026
The repro relies on a warmed entry in the server-global Iceberg metadata
files cache persisting between the warm-up SELECT and the INSERT, so that
INSERT analysis serves a stale schema while the sink force-reads the latest
one. A concurrent SYSTEM DROP ICEBERG METADATA CACHE, or LRU eviction under
parallel cache pressure, would drop that entry and silence the regression.
Unique table names isolate values but not the shared cache, so no-parallel
is required.

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

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.30% 92.40% +0.10%
Branches 77.30% 77.40% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 46/50 (92.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on HEAD 084f6248 (Finish Workflow SUCCESS). No PR-caused failures.

The red Bugfix validation (functional tests) is the by-design master-side reproduction: the regression test 04329_iceberg_insert_stale_schema_field_id_107268 deliberately aborts the unfixed server on master HEAD (that is exactly what bugfix validation asserts), so the job records Server died. On the actual PR side the test passes on every stateless variant (amd_asan_ubsan, amd_debug, amd_msan, amd_tsan, arm_asan_ubsan, arm_binary, llvm_coverage all OK), confirming the fix holds.

Session: cron:our-pr-ci-monitor:20260615-160000

@SmitaRKulkarni SmitaRKulkarni left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@SmitaRKulkarni
SmitaRKulkarni added this pull request to the merge queue Jun 16, 2026
Merged via the queue into ClickHouse:master with commit c4cad2b Jun 16, 2026
164 of 166 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix Iceberg INSERT server abort on stale schema field id mismatch

ClickGap verified: reproduced it with the script below on 26.5; tested 4 version(s) — 1 affected, 3 clean (see Affects).

Reproduction

Server-based; the bug needs a WARM metadata cache that disagrees with on-disk metadata (a fresh clickhouse-local can't diverge the two reads). Steps:
1) CREATE TABLE t (c0 Int32, c1 String) ENGINE=IcebergLocal('/path/');
2) INSERT INTO t VALUES (1,'a');   -- SETTINGS allow_insert_into_iceberg=1, iceberg_metadata_staleness_ms=600000
3) SELECT count() FROM t;          -- warm the latest-schema cache {c0,c1}
4) Externally publish a newer metadata version that renames c0 -> c9 (new current-schema-id) while still within iceberg_metadata_staleness_ms;
5) INSERT INTO t (c0, c1) VALUES (2,'b');
Observed (buggy): server aborts with "Code: 1001. DB::Exception: std::out_of_range: unordered_map::at: key not found. (STD_EXCEPTION)" in DB::Parquet::prepareColumnRecursive.
Fixed: clean "Code: 117 ... (INCORRECT_DATA)", server stays alive.

Bisect

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5
  • Does NOT reproduce on: master, 26.4, 26.3
  • Could not test (binary unavailable): 26.2, 26.1
  • Backport needed: 26.5

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-datalake
Severity: P2

cc fix PR author: @groeneai
cc fix PR reviewer: @SmitaRKulkarni


ClickGap · Finding: phase_d_pr107279

Triage metadata

  • Primary component: comp-datalake
  • Secondary components: comp-testing
  • Component owners (comp-datalake): @scanhex12 @divanik

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

Development

Successfully merging this pull request may close these issues.

Iceberg insert: std::out_of_range in Parquet

5 participants