Skip to content

Fix LOGICAL_ERROR crash in IcebergMetadata::iterate when datalake_table_state is missing - #102033

Merged
alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/iceberg-iterate-missing-datalake-state
Jul 2, 2026
Merged

alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:fix/iceberg-iterate-missing-datalake-state

Conversation

@groeneai

@groeneai groeneai commented Apr 8, 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 to CHANGELOG.md):

Fix LOGICAL_ERROR exceptions when reading Iceberg or DeltaLake data lake tables through paths that can reach the read pipeline without a pinned datalake_table_state, such as concurrent Iceberg metadata updates or merge reads over DeltaLake tables.

What this PR does

Problem: IcebergMetadata::iterate and isDataSortedBySortingKey throw a LOGICAL_ERROR (Can't extract iceberg table state from storage snapshot) when datalake_table_state is not set in the storage metadata snapshot. The same family of failures hits DeltaLake (No version found in table state snapshot). This raises an exception (and, in stress tests, a server abort under abort_on_logical_error) — tracked as STID 2606-4a47, a chronic failure with master and PR hits across many sanitizer/build variants over the last 30 days.

PR #101577 fixed one such path (materialized views accessing Iceberg target tables), but the failure continued on master because other code paths can reach the read pipeline without datalake_table_state:

  • Concurrent metadata updates create a TOCTOU race between updateExternalDynamicMetadataIfExists setting the state (via setInMemoryMetadata) and the next getInMemoryMetadataPtr reading it.
  • Cluster table functions and other paths that bypass the analyzer/interpreter reach read/iterate without having had the state pinned.
  • merge reads over DeltaLake tables reach the read step with a snapshot that lacks the pinned state.

Fix: Pin a single, internally consistent data lake snapshot at the source instead of papering over the missing state deep inside the callees. This follows the reviewer's guidance to fix all the places to create the table state snapshot instead of ad-hoc fallbacks in the callees:

  • StorageObjectStorage::read pins one coherent datalake_table_state before prepareReadingFromFormat, so the requested columns, the field-id mapping used to list/read files, and the read-in-order sorting key all come from the same data lake snapshot. For cluster table functions it first calls lazyInitializeIfNeeded, otherwise update, so getTableStateSnapshot does not hit an uninitialized-metadata assertion. When shouldReloadSchemaForConsistency is set, columns and sorting key are rebuilt from the same state via buildStorageMetadataFromState so they cannot diverge.
  • StorageObjectStorageSource::createFileIterator repopulates datalake_table_state from getTableStateSnapshot before iterate, as a safety net for the remaining callers.
  • ReadFromObjectStorageStep::getDataOrder reads the sorting key from the pinned storage_snapshot->metadata rather than re-deriving it.

The LOGICAL_ERROR assertions inside iterate and isDataSortedBySortingKey are preserved untouched as safety nets — they should now be unreachable on the fixed paths.

A test-only failpoint datalake_simulate_missing_table_state strips the pinned state from the snapshot right before the read step, so the regression test reproduces the missing-state condition deterministically.

Tests

  • 04305_iceberg_missing_table_state.sh — deterministic reproducer using the datalake_simulate_missing_table_state failpoint; a non-trivial read (sum) and an ORDER BY query exercise both the iterate and isDataSortedBySortingKey sites.
  • 04306_delta_lake_merge_missing_table_state.sh — merge read over a DeltaLake table, the DeltaLake variant of the same bug.
  • 04141_iceberg_concurrent_no_logical_error.sh — concurrent readers and a writer producing fresh snapshots, exercising the TOCTOU race in the regular planner path.

Closes: #102037
Closes: #107334
Related: #93278

Version info

  • Merged into: 26.7.1.448 (included in 26.7 and later)
  • Backported to: 26.6.3.41, 26.5.7.46, 26.3.18.32

@groeneai

groeneai commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session: cron:clickhouse-ci-task-worker:20260408-084500)

a) Deterministic repro?
This is a race condition in stress tests — not deterministically reproducible from a single query. The crash is deterministic when datalake_table_state is missing from the metadata, but the condition that causes it to be missing is timing-dependent. Code analysis identifies multiple paths where this can happen (cluster functions passing nullptr, concurrent metadata updates creating TOCTOU races).

b) Root cause explained?
IcebergMetadata::iterate() requires datalake_table_state in the storage metadata snapshot. This is normally set by updateExternalDynamicMetadataIfExists() called by the analyzer. However, several code paths reach iterate() without this state: (1) StorageObjectStorageCluster::getPathSample() passes nullptr as storage_metadata (line 45); (2) Concurrent queries can race between setInMemoryMetadata() in updateExternalDynamicMetadataIfExists() and the subsequent getInMemoryMetadataPtr() in IdentifierResolver; (3) updateStorageSchemaIfNeeded() passes nullptr (line 96). When the state is missing, extractIcebergSnapshotIdFromMetadataObject() returns nullptr and the code throws LOGICAL_ERROR.

c) Fix matches root cause?
Yes. Instead of crashing when the state is absent, we fall back to getRelevantState() which fetches the current state directly from the Iceberg metadata files. This is the exact pattern already used in getColumnMapperForCurrentSchema() (line ~1260 of the same file) for the same reason ("temporary cludge for cluster functions because the state on replicas is not synchronized").

d) New tests added?
No new test — the crash path is triggered by timing-dependent races in stress tests. The existing test from PR #101577 (04077_iceberg_mv_select_crash) covers the materialized view path. The defense-in-depth fix covers all remaining paths without behavior change for the normal case.

e) Demonstrated in both directions?
Cannot demonstrate both directions for a race condition. Verified: code compiles, links, and basic clickhouse-local functionality works. The fix is structurally identical to the existing working fallback in getColumnMapperForCurrentSchema(). CI stress tests will validate the fix — the STID should stop appearing.

f) Fix is general, not a narrow patch?
Yes. Both iterate() AND isDataSortedBySortingKey() are fixed (the two throw sites). The fix pattern matches getColumnMapperForCurrentSchema() which handles the same edge case for the same reason. This covers all code paths that reach these functions without the datalake state, not just the specific path that was most recently observed.

@groeneai

groeneai commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @divanik — could you review this? It adds defense-in-depth fallback to IcebergMetadata::iterate() and isDataSortedBySortingKey() so they don't crash with LOGICAL_ERROR when datalake_table_state is missing from the storage snapshot — instead falling back to getRelevantState(), matching the existing pattern in getColumnMapperForCurrentSchema(). Fixes STID 2606-4a47 (22 hits in 30 days, 3 on master).

@groeneai
groeneai force-pushed the fix/iceberg-iterate-missing-datalake-state branch from c745e76 to c16eefb Compare April 8, 2026 18:06
@groeneai

groeneai commented Apr 8, 2026

Copy link
Copy Markdown
Collaborator Author

@alesapin Reworked per your feedback. The approach is now:

What changed: Instead of adding fallback hacks inside iterate() and isDataSortedBySortingKey(), the fix ensures datalake_table_state is properly created at the call sites before these functions are reached:

  1. createFileIterator() (StorageObjectStorageSource.cpp) — the funnel for all iterate() calls. When the metadata lacks datalake_table_state, it obtains the state from the configuration and creates a patched metadata copy before calling iterate().

  2. requestReadingInOrder() (ReadFromObjectStorageStep.cpp) — the entry point for isDataSortedBySortingKey(). Same approach.

What's preserved: The LOGICAL_ERROR assertions inside iterate() and isDataSortedBySortingKey() are kept as-is — they serve as safety nets for any unknown future code paths that might reach these functions without the state.

No changes to IcebergMetadata.cpp — the fix is entirely at the caller level.

The root cause is a TOCTOU race: updateExternalDynamicMetadataIfExists() sets datalake_table_state via setInMemoryMetadata(), but concurrent queries can capture a stale metadata snapshot (via getInMemoryMetadataPtr()) before the state is written. The call-site fix covers this by obtaining the state directly from the configuration when it's missing.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [45cb6bd]

Summary: ✅


AI Review

Summary

This PR moves the data-lake snapshot pin into StorageObjectStorage::read, adds deterministic failpoint coverage for the missing-datalake_table_state path, and keeps a concurrent Iceberg smoke test around the original race. The Iceberg side now looks coherent, but the DeltaLake regression proof is still weaker than the contract the code claims to fix.

Tests
  • ⚠️ [tests/queries/0_stateless/04306_delta_lake_merge_missing_table_state.sh:32-42] This test no longer exercises the merge() / first-access path from issue #107334, and it does not prove that the new pin in StorageObjectStorage::read is required. With storage_snapshot->metadata stripped, DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat falls back to the session setting when no version is pinned (src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp:500-512), and StorageObjectStorageSource::createFileIterator re-fetches datalake_table_state before iterate (src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:390-399). A plain SELECT c1.id FROM ${TABLE} ORDER BY c1.id can therefore still go green even if the new read()-time pin is removed. Please keep at least one focused reproducer that actually enters through merge() or otherwise proves that prepareReadingFromFormat and iterate share the same pinned snapshot.
Final Verdict

⚠️ Needs changes before approval: the DeltaLake regression test does not currently prove the read() / first-access contract that this PR adds.

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

Copy link
Copy Markdown
Collaborator Author

@alesapin @Michicosun @scanhex12 @alexey-milovidov — re-review request

Following @alexey-milovidov's directive 4 hours ago on #100277:

"@groeneai, please fix the defects in Iceberg, reflected by the finding Logical error: Can't extract iceberg table state from storage snapshot for table location A (STID: 2606-4a47) and send a PR. Ask for review from "Iceberg guys", notably, @Michicosun, @scanhex12. Also, mention @alesapin as much as possible as he is the Iceberg manager. Make sure @alesapin will receive notifications even if it is annoying for him (be ruthless). We don't tolerate low-quality code."

This PR is that fix. It has been awaiting re-review for 18 days (since 2026-04-08).

PR status

  • State: OPEN, MERGEABLE, mergeStateStatus=BLOCKED (only because the 2026-04-08 CHANGES_REQUESTED hasn't been dismissed)
  • CI on rework HEAD c16eefb7: 142 SUCCESS, 0 real failures (the 1 listed FAILURE is the trivial "Finish Workflow" infra wrap-up)
  • Latest review: @alesapin's CHANGES_REQUESTED from 2026-04-08 11:20 UTC. We reworked + force-pushed c16eefb7 the same day at 18:05 UTC and posted a writeup. No reviewer activity since.

Reviewer feedback already addressed

@alesapin's inline comment was: "Let's fix all the places to create table_state_snapshot instead of this adhoc hacks".

We complied: removed the in-callee fallbacks and moved the fix to the call sites so datalake_table_state is guaranteed to be present before iterate() / isDataSortedBySortingKey() are reached:

  • createFileIterator() in StorageObjectStorageSource.cpp — funnel for all iterate() calls
  • requestReadingInOrder() in ReadFromObjectStorageStep.cpp — entry point for isDataSortedBySortingKey()

The LOGICAL_ERROR assertions inside IcebergMetadata.cpp are preserved untouched as safety nets. Root cause: the state is normally set by updateExternalDynamicMetadataIfExists() during query analysis, but can be missing due to TOCTOU between concurrent queries (setInMemoryMetadata vs getInMemoryMetadataPtr), or when called from code paths that bypass the analyzer (schema inference, cluster functions).

Active trunk impact — CIDB last 30 days

Window Master Distinct PRs Total
Last 30 days 11 44 55
Last 7 days 3 master + 6 PR — 9
Last 24h 0 1 (#103490) 1 (today, 06:32 UTC)

13 affected check variants: amd_msan, arm_tsan, arm_msan, amd_tsan, arm_ubsan, arm_asan_ubsan (+s3), amd_asan_ubsan, arm_release, amd_debug, arm_debug, experimental serverfuzz (azure amd_tsan, arm_tsan).

The bug is still triggering today. Fix has been ready and CI-green for 18 days.

Asks

  • @alesapin — re-review the caller-side rework. Per @alexey-milovidov's directive this is P0 with a 24-hour escalation deadline (2026-04-27 23:59 UTC).
  • @Michicosun / @scanhex12 — Iceberg experts, your eyes welcome on the call-site approach in createFileIterator() and requestReadingInOrder().
  • @alexey-milovidov — cc per directive.

If anything in the rework needs further changes, please flag it explicitly so I can address it today.

@groeneai

Copy link
Copy Markdown
Collaborator Author

24h follow-up ping — @alesapin @Michicosun @scanhex12 @alexey-milovidov

24h have elapsed since the previous ping and there is still no response from any reviewer. Per @alexey-milovidov's directive on #100277 ("we should be ruthless about pinging him on Iceberg defects"), I am being ruthless.

Fresh hit since the previous ping (last 24h):

30-day chronic pattern (refreshed now):

  • 11 master + 45 PR hits across 45 distinct PRs over 21 distinct days
  • Master hits as recently as 2026-04-24 (amd_tsan, sha 5656e213) and 2026-04-23 (arm_tsan, sha 2cfc72ed)
  • 7-day daily breakdown: hits on every single day of the past week (master or PR)

PR state, unchanged since 2026-04-08:

  • HEAD c16eefb7 reworked exactly per @alesapin's CHANGES_REQUESTED feedback ("Let's fix all the places to create table_state_snapshot instead of this adhoc hacks") — moved the fix from inside iterate() / isDataSortedBySortingKey() to their two real call sites: createFileIterator() in StorageObjectStorageSource.cpp and requestReadingInOrder() in ReadFromObjectStorageStep.cpp. LOGICAL_ERROR assertions preserved as safety nets.
  • mergeable=MERGEABLE, conflict-free against current master
  • Blocker is purely the un-dismissed CHANGES_REQUESTED from 2026-04-08

Asks:

  • @alesapin (Iceberg manager): please re-review or dismiss the stale CHANGES_REQUESTED — the rework directly addresses your feedback.
  • @Michicosun, @scanhex12 (Iceberg experts): an additional review would unblock this if @alesapin is unavailable.
  • @alexey-milovidov: this directive thread.

This is a chronic P0 LOGICAL_ERROR landing on master twice this week alone. Each day it sits is another set of stress runs hitting the same crash.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, "Bug Fix" category requires new tests that reproduce the issue.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov thanks for the direct feedback. You're right that "Bug Fix" requires a regression test. I just pushed a972e9bff8a which adds 04141_iceberg_concurrent_no_logical_error.sh.

What the test does

It exercises both call sites the fix protects (createFileIterator → iterate and requestReadingInOrder → isDataSortedBySortingKey) by running many parallel readers against an IcebergLocal table with ORDER BY c0 while a writer thread produces fresh snapshots. The runtime invariant the test asserts is that Can't extract iceberg table state from storage snapshot never appears in any client's stderr — without the fix, the TOCTOU between setInMemoryMetadata and getInMemoryMetadataPtr will surface that LOGICAL_ERROR; with the fix, the missing datalake_table_state is repopulated from the configuration on the fly.

Why concurrent rather than fully deterministic

The bug is a TOCTOU race between two clients (InterpreterSelectQuery.cpp:612 calls updateExternalDynamicMetadataIfExists → setInMemoryMetadata; the same call on a sibling client can land between the first client's analyzer finishing and its planner running). The deterministic single-threaded path that hit the same LOGICAL_ERROR was the materialized-view-target path, which PR #101577 already covered with 04077_iceberg_mv_select_crash.sh by adding the explicit updateExternalDynamicMetadataIfExists call inside StorageMaterializedView::read. This PR fills the remaining race-condition window in the regular planner / cluster planner paths, so the natural shape of a regression test for it is concurrent.

The 30-day CIDB stress evidence in the PR description (11 master + 44 PR hits across 13 sanitizer/build variants) is exactly that kind of concurrent reproducer — the test mirrors that shape in a single stateless test file.

Other shapes I considered and rejected

  • icebergLocalCluster(...) table function passing nullptr storage_metadata — getPathSample in both StorageObjectStorage and StorageObjectStorageCluster is gated on !isDataLakeConfiguration(), so this code path is unreachable for Iceberg in master and would not catch a regression of this fix.
  • A schema-inference-only test — updateExternalDynamicMetadataIfExists is invoked unconditionally on the outer storage by all schema-inference call sites I could trace.
  • Reverting the fix in a unit test — the fix is in createFileIterator / requestReadingInOrder, both of which need a real storage and a real Configuration instance, so the unit-test scaffolding would need most of the integration test machinery anyway.

If you'd prefer a different test shape (e.g. extending 04077 with ORDER BY c0 to add requestReadingInOrder coverage on the MV path, or a unit test against IcebergMetadata::iterate with a hand-built StorageMetadataPtr lacking datalake_table_state) please let me know and I'll add that instead of / on top of this one.

cc @alesapin @Michicosun @scanhex12 — @alesapin's CHANGES_REQUESTED is still listed but was addressed in c16eefb7 (rework moved the fix from the assertion sites to the two caller sites per his guidance). Re-review or dismiss would unblock the merge.

groeneai added 2 commits May 18, 2026 14:49
… isDataSortedBySortingKey()

Instead of adding fallback hacks inside IcebergMetadata::iterate() and
IcebergMetadata::isDataSortedBySortingKey(), fix the callers to ensure
datalake_table_state is present in the storage metadata before calling
these functions.

The state is normally set by updateExternalDynamicMetadataIfExists()
during query analysis, but can be missing due to race conditions between
concurrent queries (TOCTOU between setInMemoryMetadata and
getInMemoryMetadataPtr), or when called from code paths that bypass
the analyzer/interpreter (schema inference, cluster functions).

Two call sites fixed:
- createFileIterator(): the funnel for all iterate() calls — when the
  metadata lacks datalake_table_state, obtain it from the configuration
  and create a patched metadata copy before calling iterate().
- requestReadingInOrder(): entry point for isDataSortedBySortingKey() —
  same approach.

This preserves the LOGICAL_ERROR assertions inside iterate() and
isDataSortedBySortingKey() as safety nets for any unknown future code
paths, while fixing the actual root cause at the call sites.

Fixes STID 2606-4a47 (43 hits in 30 days, 3 on master).
Issue ClickHouse#93278 (reopened): `IcebergMetadata::iterate` and
`IcebergMetadata::isDataSortedBySortingKey` throw `LOGICAL_ERROR`
"Can't extract iceberg table state from storage snapshot" when
`datalake_table_state` is missing from the storage metadata snapshot
(STID 2606-4a47, 11 master + 45 PR hits over 30 days).

The PR's fix in `StorageObjectStorageSource::createFileIterator` and
`ReadFromObjectStorageStep::requestReadingInOrder` re-fetches the
snapshot from the configuration when it is missing. PR ClickHouse#101577 already
covered the materialized-view-target path
(`04077_iceberg_mv_select_crash`); this new test exercises the
concurrent-normal-SELECT path that the same fix has to keep stable.

The test runs many parallel `SELECT`s (both plain and `ORDER BY c0`)
against an `IcebergLocal` table while a writer thread produces new
snapshots, then asserts that the
"Can't extract iceberg table state" `LOGICAL_ERROR` never appears in
captured stderr and that the table remains readable.
@groeneai
groeneai force-pushed the fix/iceberg-iterate-missing-datalake-state branch from a972e9b to e0fc016 Compare May 18, 2026 14:50
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master (was 8714 commits behind, last activity 2026-04-28). Two-commit fix is unchanged:

  1. Ensure datalake_table_state is created at call sites of iterate() and isDataSortedBySortingKey() — patches ReadFromObjectStorageStep::requestReadingInOrder() and StorageObjectStorageSource::createFileIterator() to materialize datalake_table_state from configuration->getTableStateSnapshot(...) when the storage metadata snapshot is missing it, before the call into iterate / isDataSortedBySortingKey.
  2. Add regression test for Iceberg LOGICAL_ERROR under metadata churn — 04141_iceberg_concurrent_no_logical_error.sh exercises the concurrent-query/TOCTOU path.

Why this matters now: STID 2606-44c0 just hit @alexey-milovidov's unrelated PR #105087 (Stress test arm_release). That STID is the same chronic family as 2606-4a47 — identical error message ("Can't extract iceberg table state from storage snapshot for table location A"), same call into IcebergMetadata::iterate(). CIDB last 30d: 17 hits / 5 master / 13 distinct PRs on 2606-4a47, +1 new hit on 2606-44c0.

cc @alesapin @Michicosun @scanhex12 @kssenii — could one of you take another look? @alesapin dismissed the original review on the day this opened (2026-04-08), but no comments were left, so the action item never came back to me. The fix is at the call sites (4 files / 143 lines / 1 deletion), preserves the LOGICAL_ERROR assertions inside iterate() and isDataSortedBySortingKey() as safety nets, and matches the same approach already used elsewhere for the same metadata snapshot.

— @groeneai (session cron:clickhouse-ci-task-worker:20260518-144500)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Re-engagement ping from @PedroTadim on the parent issue today: #102037 (comment-4519163992).

@alesapin @Michicosun @scanhex12 @alexey-milovidov could one of you take a review pass?

Status snapshot on HEAD e0fc0164 (rebased onto current master 2026-05-18):

  • 143/166 CI checks SUCCESS; MergeStateStatus=BLOCKED on no approving review (12+ days)
  • @alesapin's 2026-04-08 CHANGES_REQUESTED already DISMISSED; HEAD already addresses that feedback (call-site fix in createFileIterator + requestReadingInOrder, no changes inside iterate() / isDataSortedBySortingKey())
  • 2 CI FAILURES, neither blocking on the fix:
    • Bugfix validation (functional tests) on our regression test 04141_iceberg_concurrent_no_logical_error. STID 2606-4a47's master rate dropped from a 5/week peak to 0/week now (last master hit 2026-05-08), so the probabilistic concurrent-reader test no longer reproduces deterministically on master HEAD baseline.
    • Stateless tests (amd_debug, flaky check): unrelated noise (STID 2508-36b2 file_offset_of_buffer_end <= getFileSize() + "Server died"), not 2606-4a47.

CIDB still shows STID 2606-4a47 firing sporadically in PR stress runs (last hit PR #105172 arm_asan_ubsan 2026-05-21 18:42). The defense-in-depth call-site fix prevents the LOGICAL_ERROR on both reaching paths.

Question on the issue thread is whether to keep 04141 (tighten it to push failure rate back up on stale-master) or drop it (rely on deterministic 04077_iceberg_mv_select_crash from PR #101577). Happy to do either.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai merge with master

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim merged master into the branch and pushed. New HEAD 96922aeb12ae.

Fix scope unchanged (4 files): call-site fix for the TOCTOU race in IcebergMetadata::iterate() / isDataSortedBySortingKey() plus the 04141_iceberg_concurrent_no_logical_error regression test. No conflicts on the merge; CI will re-run on the new HEAD.

Ready for re-review.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Please apply v26.3-must-backport to this PR, @alexey-milovidov.

This fix is on master and present on 26.7, but 26.6, 26.5 and 26.3 still take the pre-fix path while the throw site exists on all three. It surfaced on 26.6 on 2026-08-02 as a logical error reaching abortOnFailedAssertion, that is, a server abort in debug and sanitizer builds: Stress test (amd_tsan) at sha 54b7f7f5, CI report. It is unrelated to the carrier PR's own diff.

v26.3-must-backport expands to 26.3, 26.5, 26.6 and 26.7 per select_backport_branches, and the 26.7 leg is an empty-diff skip because this merge commit is already an ancestor of its tip. I am deliberately not asking for pr-must-backport: that also targets 25.8, where neither the throw site nor the five helpers this fix calls exist, so the port there would be meaningless.

I simulated the cherry-pick the way tests/ci/cherry_pick.py performs it (the merge commit against its first parent, merge.renameLimit=999999). It resolves cleanly on all three tips, each yielding exactly the 11 files of this PR (+278/-3), and I grepped the resolved trees to confirm the read-time pin, the failpoint registration, the source-side materialization and the sorting-key hunk all land, so no branch would get a half port. I have not compiled or run those trees.

The same port also carries the DeltaLake half of this class (issue #107334). This PR is labelled pr-bugfix ("Pull request with bugfix, not backported by default"), so the missing label looks like an oversight rather than a decision.

Measurements (branch tips of 2026-08-03, re-measured through 12:40 UTC)

Per-branch presence, read from the contents API at each tip:

marker master 26.7 26.6 26.5 26.3 25.8
datalake_simulate_missing_table_state in StorageObjectStorage.cpp 2 2 0 0 0 0
read-time pin comment 1 1 0 0 0 0
StorageObjectStorageSource.cpp materialization 1 1 0 0 0 0
failpoint registration in FailPoint.cpp 1 1 0 0 0 0
storage_snapshot->metadata->getSortingKey in ReadFromObjectStorageStep.cpp 1 1 0 0 0 0
throw message in IcebergMetadata.cpp 2 2 2 2 2 0
getTableStateSnapshot / setDataLakeTableState 4 / 3 4 / 3 2 / 2 2 / 2 2 / 2 0 / 0

The message occurs twice per affected branch (iterate and isDataSortedBySortingKey); this PR covers both call sites. 25.8 has neither the message nor any of the helpers, hence its exclusion.

Cherry-pick simulation, reducing create_cherrypick's merge -s ours form to one command (MC = merge commit cff54e151b69):

git -c merge.renameLimit=999999 merge-tree --write-tree --merge-base=$MC^1 origin/<branch> $MC

On 26.6, 26.5 and 26.3 this resolves cleanly and the resolved tree differs from the branch tip by exactly the 11 files of this PR (+278/-3), with no collateral. I re-ran it as those three tips advanced during the day (three generations each) and the result was identical every time, so it is not a property of one tip.

The naive --merge-base=<PR base> form is not a valid simulation here: it reports 45 conflicts across .github/workflows, .gitmodules and ci/defs, because it diffs the whole branch history rather than the cherry-pick.

CIDB, 45 days, keyed on the message: 8 rows. Seven are on master and all predate the merge (latest 2026-06-30); the only later row is the 26.6 sighting above.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)

This request carries no code change: the fix is already merged on master as this PR, and the ask is a backport label. The gate is answered against that deliverable.

# Question Answer
a Deterministic repro? Satisfied by the reproducer this PR already shipped: 04305_iceberg_missing_table_state.sh with the datalake_simulate_missing_table_state failpoint. I confirmed it is present in each simulated backport tree, and absent at the failing 26.6 sha (contents API returns 404 there, resolves on master).
b Root cause explained? Yes. updateExternalDynamicMetadataIfExists pins datalake_table_state during analysis; a concurrent commit in the window between setInMemoryMetadata and the next getInMemoryMetadataPtr leaves the snapshot reaching the read pipeline with no pinned state, and IcebergMetadata::iterate then throws. The second layer is why it is still live: this PR is labelled pr-bugfix ("Pull request with bugfix, not backported by default") and carries no v*-must-backport.
c Fix matches root cause? Yes. The remedy is to ship the reviewed, merged fix to the three branches that lack it. No new code, no guard, no band-aid.
d Test intent preserved / new tests added? Preserved. Each simulated port carries 04141, 04305 and 04306 verbatim, with 04306 keeping no-msan and 04141 keeping long. No test weakened or removed.
e Both directions demonstrated? Yes, as presence and absence. Fix markers count 0 on 26.6, 26.5 and 26.3 and non-zero on master and 26.7; CIDB over 45 days has 7 master rows all predating the merge and 1 post-merge row, on unfixed 26.6.
f Fix is general across code paths? Yes. The message has two throw sites per branch, iterate and isDataSortedBySortingKey; this PR covers both, the latter through the ReadFromObjectStorageStep.cpp sorting-key hunk, which is present in all three resolved trees. The pin sits in the shared read path, so DeltaLake is covered as well (issue #107334).
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A, no new logic. The relevant axis is branches and labels, and it is enumerated exhaustively: all five active release branches classified, 25.8 excluded because neither the throw site nor any of the five helpers this PR calls exists there, and all four candidate label expansions computed with select_backport_branches.
h Backward compatible? Yes. No settings, no serialization, no SettingsChangesHistory.cpp entry. The ported code is identical to what already ships on master and 26.7, and the only new runtime surface is a test-only failpoint, inert unless enabled.
i Invariants and contracts preserved? Yes, and one is restored: every active release branch containing the throw site should also contain the pin, which currently fails on three branches. Each simulated port resolves to exactly the 11 files of this PR (+278/-3) with no collateral, so no branch-local invariant is disturbed.

Session id: cron:clickhouse-review-slot-49:20260803-115800

@SmitaRKulkarni SmitaRKulkarni added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 11, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 11, 2026
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
Resolve conflict in src/Common/FailPoint.cpp: keep the 26.6 failpoint list
and add the new `datalake_simulate_missing_table_state` failpoint from #102033.

Related: #114386
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
Resolve conflict in `src/Common/FailPoint.cpp`: both branches added a
failpoint at the same place; keep both `datalake_get_tables_throw` (from
26.5) and `datalake_simulate_missing_table_state` (from #102033).
robot-ch-test-poll added a commit that referenced this pull request Aug 12, 2026
Cherry pick #102033 to 26.5: Fix LOGICAL_ERROR crash in IcebergMetadata::iterate when datalake_table_state is missing
robot-clickhouse added a commit that referenced this pull request Aug 12, 2026
…:iterate when datalake_table_state is missing
robot-ch-test-poll added a commit that referenced this pull request Aug 12, 2026
Cherry pick #102033 to 26.6: Fix LOGICAL_ERROR crash in IcebergMetadata::iterate when datalake_table_state is missing
robot-clickhouse added a commit that referenced this pull request Aug 12, 2026
…:iterate when datalake_table_state is missing
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 12, 2026
alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
Backport #102033 to 26.5: Fix LOGICAL_ERROR crash in IcebergMetadata::iterate when datalake_table_state is missing
alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
…on 26.3

`04306_delta_lake_merge_missing_table_state` failed in CI with
`Unknown table expression identifier`: the branch has no
`tests/queries/0_stateless/data_delta_lake/struct_column_mapping`
dataset (it was added to `master` by a later pull request), so the
`cp -r` copied nothing and `CREATE TABLE ... ENGINE = DeltaLakeLocal`
failed before the read.

The files are copied verbatim from `master`; they are identical to the
state at the merge commit of the original pull request #102033.
Verified with the 26.3 build of this pull request: the failpoint-guarded
read returns the expected `1` / `2`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114383&sha=0925d7c93148d0914652ed32e40cf3b18bdf669b&name_0=BackportPR
Pull request: #114383
alexey-milovidov added a commit that referenced this pull request Aug 15, 2026
Backport #102033 to 26.6: Fix LOGICAL_ERROR crash in IcebergMetadata::iterate when datalake_table_state is missing
alexey-milovidov added a commit that referenced this pull request Aug 15, 2026
Backport #102033 to 26.3: Fix LOGICAL_ERROR crash in IcebergMetadata::iterate when datalake_table_state is missing
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…gMetadata::iterate when datalake_table_state is missing
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The fallback added in 7612950 calls `getTableStateSnapshot` early in
`StorageObjectStorage::read`, but on cluster table function workers and
other paths that bypass the analyzer the underlying datalake configuration
has never had `update`/`updateExternalDynamicMetadataIfExists` run on it
yet. `getTableStateSnapshot` then hits `assertInitialized` and throws
`Metadata is not initialized` instead of the expected
`PATH_ACCESS_DENIED` (or normal read result), regressing
`test_local_table_safety`, `test_cluster_table_function*`, and stateless
flaky-check / bugfix-validation runs on PR ClickHouse#102033 head 2d39c85
(STID 2377-2862).

Initialize the configuration the same way the surrounding analyzer paths
do (`lazyInitializeIfNeeded` for table functions, `update` for ENGINE
tables) before invoking `getTableStateSnapshot`, so the fallback works
for all callers and any underlying error such as `PATH_ACCESS_DENIED`
keeps propagating with its original code.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The flaky-check (50x) on amd_debug/amd_msan/amd_tsan caught
`Code: 117 INCORRECT_DATA: JSON object/array should start with corresponding opening bracket`
from a `SELECT c0 FROM ... ORDER BY c0 LIMIT 5` race against a concurrent
INSERT-side iceberg manifest write. That is a separate (manifest-read mid-write)
race, not the `LOGICAL_ERROR: Can't extract iceberg table state` class this
test exists to gate. The previous `grep -iE "error|exception"` final guard
plus the `status=0` exit-on-any-non-zero check folded both classes together
and turned this test into a generic flake detector.

This test only exists to catch the specific LOGICAL_ERROR thrown by
`IcebergMetadata::iterate()` and `isDataSortedBySortingKey()` when
`datalake_table_state` is missing under concurrent commits. The
deterministic counterpart `04305_iceberg_missing_table_state.sh` already
covers the LOGICAL_ERROR path via `datalake_simulate_missing_table_state`
failpoint; 04141 is the noisy concurrent-workload counterpart that should
only fail when the LOGICAL_ERROR resurfaces.

Tighten the LOG_FILE check to a literal `Can't extract iceberg table state`
match. Stop exiting on any non-zero background-PID status; transient
non-LOGICAL_ERROR failures (e.g. INCORRECT_DATA on manifest reads,
randomized-setting validation errors) are not in scope.

PedroTadim directive on PR ClickHouse#102033 2026-06-09:
ClickHouse#102033 (comment)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test exceeded the 180s test-runtime limit in the sync branch on a debug
build with randomized settings and --max_threads 1 (reported by PedroTadim on
PR ClickHouse#102033).

Root cause: the test spawned a fresh clickhouse-client process per query
(12 readers x 10 iterations x 2 queries + 24 writer inserts = ~264 spawns).
On a contended debug runner each spawn re-parses ~200 randomized settings,
which dominated the runtime.

Fix: each reader/writer now runs its whole loop inside a single client
connection (7 spawns total instead of ~264). Every statement still
re-resolves the Iceberg table-state snapshot independently, so the
concurrent-commit TOCTOU race the test exists to detect is fully preserved
(verified: a later SELECT in the same connection sees rows the writer
committed after an earlier SELECT, and a live run shows reader ORDER BY
queries overlapping with writer commits). Reader/writer counts were also
right-sized (6 readers x 15 read-pairs, 20 writer commits) so the workload
keeps the readers active across the writer's commit window without the
hundreds of expensive read-in-order queries that each trigger a full Iceberg
manifest re-parse via totalRows().

Also redirect stdin from /dev/null on the client invocations: a backgrounded
clickhouse-client running INSERT ... VALUES reads stdin for trailing insert
data, so an inherited non-EOF stdin would block the insert.

The LOGICAL_ERROR guard string is unchanged, so the test still fails on the
specific "Can't extract iceberg table state" error and ignores unrelated
transient errors. Deterministic coverage stays in 04305_iceberg_missing_table_state.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…e-missing-datalake-state

Fix LOGICAL_ERROR crash in IcebergMetadata::iterate when datalake_table_state is missing
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

6 participants