Skip to content

Fix a crash in INSERT ... RETURNING whose query reads the inserted table through merge - #127919

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-insert-returning-merge-shared-snapshot
Nov 4, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-insert-returning-merge-shared-snapshot

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #76867 (comment)
Related: #126476

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Fix a crash in INSERT ... RETURNING when the RETURNING query reads the inserted table through the merge table function, a Merge table or remote.

Description

Segmentation fault (STID: 2830-4b5d) in KeyCondition under the AST fuzzer: #76867 Stress test (arm_tsan), #127090 Stress test (amd_tsan), and through remote in #128707 Stateless tests (amd_tsan, s3 storage, targeted). Deterministic on master:

CREATE TABLE t (id UInt64, s String) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, 'a');
INSERT INTO t RETURNING (SELECT (SELECT count() FROM merge(currentDatabase(), '^t$') WHERE s = 'a')) VALUES (2, 'a');

The RETURNING query is analyzed with the inserted block (a StorageValues without keys) as the view source. Resolving t keeps the catalog storage but took its storage snapshot with the view source's metadata, and with enable_shared_storage_snapshot_in_query that snapshot is cached per storage for the whole query. A merge or local remote read of t then got the key-less snapshot and KeyCondition dereferenced a null primary key expression.

The snapshot is now taken with the table's own metadata, and only the resolved table node gets a copy with the view source's metadata (same parts). Using getStorageSnapshotWithoutData there, as in #126589, also stops the crash, but leaves that node without parts: a materialized view whose query reads its source table through merge with a Distributed sibling then reads 0 rows instead of 12 (measured).

INSERT ... RETURNING is only on master (#126476), so no changelog entry; a materialized view with the same merge scalar does not crash.

Validation: each of the test's four cases crashes master with the cache on and passes with the fix; 80/80 runs (random and fixed settings) and the insert_returning, shared-snapshot and MV-source tests pass.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1367-master (included in 26.11 and later)

…ble through merge

The RETURNING query is analyzed with the inserted block (a StorageValues
without keys) as the view source. Resolving the inserted table kept the
catalog storage but took its storage snapshot with the view source's
metadata, and with enable_shared_storage_snapshot_in_query that snapshot
is cached per storage for the whole query. A merge() or Merge read of the
same table in a RETURNING subquery then got the key-less snapshot, and
KeyCondition dereferenced a null primary key expression
(STID 2830-4b5d, found by the AST fuzzer in Stress tests).

Take the snapshot with the table's own metadata, which is the one the
shared cache may hand to every read of the table, and give only the
resolved table node a copy with the view source's metadata and the same
data. getStorageSnapshotWithoutData would also keep the cache clean, but
leaves the node without parts, so a materialized view that reads its
source table through merge with a Distributed sibling (the node is then
read without the view source swap) would read no rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test would also pass with getStorageSnapshotWithoutData; add the materialized-view merge + Distributed read with its row count DISAGREE That read returns 12 on master and with this fix alike, so the arm would not check the fix; every shape of the test crashes master and passes here. No change.
2 💡 The substituted node now always carries the view source's metadata, also when the table's snapshot was cached first AGREE, noted A read that a nested interpreter plans without the view-source swap then gets the key-less metadata, as it already does in materialized views; that path is #125990's. Not blocking.
3 💡 Substituted resolutions of an experimental UNIQUE KEY table now also take its delete-bitmap snapshot, as every read of it does AGREE, noted No change.

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

Session id: cron:clickhouse-review-slot-8:20261027-072300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Three statements in clickhouse-local on a master debug build (6b579ca20d3): SIGSEGV every run at KeyCondition.cpp:1689. Needs at least one part and enable_shared_storage_snapshot_in_query = 1 (the default).
b Root cause explained? Yes. IdentifierResolver::tryResolveTableIdentifier took the catalog table's snapshot with the view source's (key-less StorageValues) metadata, the per-query cache stored it, and the merge child read of the same table got it.
c Fix matches root cause? Yes. The snapshot is taken with the table's own metadata and only the resolved node gets a copy with the view source's metadata, so the shared cache never holds another storage's metadata. No guard at the crash site, no setting change.
d Test intent preserved / new tests added? New 05453_insert_returning_merge_shared_snapshot: RETURNING through merge(), a Merge table, and a key predicate with force_primary_key = 1, with the cache pinned on.
e Both directions demonstrated? Yes. Master crashes on each of the three statements with the cache on and passes with it off; with the fix the test passes and its output is byte-identical to master with the cache off.
f Fix is general across code paths? Yes. The substitution was the only getStorageSnapshot caller pairing a storage with another storage's metadata.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked merge(), merge(''), Merge engine, a key predicate and the fuzzed INSERT ... SELECT; 50/50 random + 50/50 fixed settings pass.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change.
i Invariants and contracts preserved? Yes. A snapshot cached under a storage now always carries that storage's metadata; clone keeps the data and the storage holder.

Session id: cron:clickhouse-impl-slot-5:20261027-064600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir, could you review this and add the can be tested label so CI runs? When the INSERT ... RETURNING query resolves the inserted table, it took the storage snapshot of that table with the key-less metadata of the inserted block, and the per-query shared snapshot cache passed it to a merge() read of the same table, so KeyCondition dereferenced a null key expression. Now the snapshot keeps the table's own metadata and only the resolved table node gets a copy with the view source metadata.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ac7d6d]

Summary: ✅


AI Review

Summary

The PR fixes a segmentation fault in INSERT ... RETURNING by keeping the table's own metadata in the shared storage snapshot and applying the inserted block's metadata only to a cloned snapshot for the resolved table node. No actionable findings at head 2ac7d6de7c530109bd91ec809e2b3d60bf193ff9.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4c055b0

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
Build profile diff infra, not from this PR: every readiness probe got No connection to LogCluster, so the job ended with LogClusterNotReady: the endpoint never became ready in has_pr_data before comparing anything. 291 of 295 runs since 2026-10-26 22:00 UTC are red, on 237 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

The first runs of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-213006

@PedroTadim PedroTadim self-assigned this Nov 4, 2026
@PedroTadim

Copy link
Copy Markdown
Member

🕵️ @groeneai The same crash (STID 2830-4b5d) also happens through remote(). The server AST fuzzer hit it in Stateless tests (amd_tsan, s3 storage, targeted) on #128707 with INSERT INTO t_04344 RETURNING ((SELECT * FROM remote('127.0.0.1', currentDatabase(), 't_04344')) EXCEPT (SELECT * FROM t_04344 ...)) SELECT ....

A shorter version, with enable_shared_storage_snapshot_in_query = 1:

CREATE TABLE t (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t VALUES (1);
INSERT INTO t RETURNING ((SELECT * FROM remote('127.0.0.1', currentDatabase(), 't')) EXCEPT (SELECT * FROM t)) SELECT 4;

On the CI release binaries:

  • Master 9a348d8c282, the base of this PR: the query gives Segmentation fault at address 0x48 in KeyCondition.cpp:1689, the same as the merge case.
  • This PR, 4c055b0a0e9: it returns the rows the table already had.

remote() alone does not crash. The bare t in the same query is needed, because that is the read that resolves the table with the view source's metadata and caches the key-less snapshot.

Since the fix already covers it, could you add this query to 05453_insert_returning_merge_shared_snapshot as a third case?

PedroTadim and others added 2 commits November 4, 2026 11:46
The same crash happens when the RETURNING query reads the inserted table
through remote() on the local shard while the bare table name in the same
query resolves to the inserted block (found by the AST fuzzer in
Stateless tests (amd_tsan, s3 storage, targeted) on ClickHouse#128707).

prefer_localhost_replica is pinned to 1: with 0, remote() sends a separate
query over TCP and the read does not share the snapshot, so the case would
not reach the defect.

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

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Added in 2ac7d6de7c5, with prefer_localhost_replica pinned to 1 by a Random settings limits line: the runner draws 0 half of the time, and then remote sends a separate query over TCP and master does not crash.

On master 4f752f7e6fc the new case crashes on its own (same KeyCondition stack, reached from buildPrimaryKeyCondition without StorageMerge), and with this PR the test passed 80/80 runs. The #128707 report is now linked in the description.

@PedroTadim
PedroTadim enabled auto-merge November 4, 2026 13:10
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2ac7d6de7 with master c8383042c (stripped binary size, per-symbol sizes and ThinLTO time; 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.

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

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit c0c9282 Nov 4, 2026
185 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-not-for-changelog This PR should not be mentioned in the changelog 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.

5 participants