Skip to content

Fix crash when selecting subcolumns from Buffer table - #102470

Merged
Michicosun merged 8 commits into
ClickHouse:masterfrom
groeneai:fix/buffer-subcolumn-crash
Apr 28, 2026
Merged

Michicosun merged 8 commits into
ClickHouse:masterfrom
groeneai:fix/buffer-subcolumn-crash

Conversation

@groeneai

@groeneai groeneai commented Apr 11, 2026 •

Copy link
Copy Markdown
Collaborator

Linked issues

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

Fixed a crash (LOGICAL_ERROR: Unknown virtual column) when selecting subcolumns (like .null for Nullable, .size0 for Array, tuple elements, or map keys/values) from a Buffer table engine.

What changed and why:

When selecting subcolumns from a Buffer table, the server crashed with:

Logical error: 'Unknown virtual column: 'c0.null''

Root cause: BufferSource::generate() iterates over the output header columns and checks buffer.data.has(name) to decide whether to read from the in-memory buffer or fill a virtual column. For subcolumn accesses like c0.null, the name is the full qualified subcolumn name (e.g., "c0.null"), but the buffer's data block only stores parent columns (e.g., "c0"). So has() returned false, and the code fell through to fillVirtualColumn(), which only handles the _table virtual column and threw a LOGICAL_ERROR.

Fix: Resolve column names through the storage metadata (ColumnsDescription::tryGetColumnOrSubcolumn), which properly identifies subcolumns and returns a NameAndTypePair with the correct parent column name and subcolumn extraction info. This allows the existing getColumnFromBlock() function to find the parent column in the buffer data and extract the subcolumn correctly.

This is the same approach used by ReadFromMemoryStorageStep, which correctly handles subcolumns from in-memory data blocks.

Reproduction (from #102104):

CREATE TABLE t0 (c0 Nullable(Int)) ENGINE = MergeTree() ORDER BY tuple();
CREATE TABLE t1 ENGINE = Buffer(default, t0, 60, 816, 532, 50, 191, 494, 766);
SET optimize_trivial_insert_select = 1, min_insert_block_size_rows = 1025;
INSERT INTO TABLE t1 (c0) SELECT number FROM numbers(1026);
SELECT c0.null FROM t1; -- crashes without fix

Closes #102104

Version info

  • Merged into: 26.5.1.146 (included in 26.5 and later)
  • Backported to: 26.4.5.98

When selecting subcolumns (like `.null` for Nullable, `.size0` for Array,
tuple elements, or map keys/values) from a Buffer table, the server
crashed with:

    Logical error: Unknown virtual column: 'c0.null'

The issue was in BufferSource::generate(). It checked
`buffer.data.has(name)` using the full subcolumn name (e.g., "c0.null"),
but the in-memory buffer block only stores parent columns (e.g., "c0").
When the column wasn't found, it fell through to fillVirtualColumn()
which only handles the "_table" virtual column and threw a LOGICAL_ERROR.

The fix resolves column names through the storage metadata's
ColumnsDescription, which properly identifies subcolumns and provides the
parent column name. This allows getColumnFromBlock() to find the parent
column in the buffer data and extract the subcolumn.

Closes ClickHouse#102104
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (session: cron:clickhouse-ci-task-worker:20260411-174500)

a) Deterministic repro? ✅ Yes — SELECT c0.null FROM <buffer_table> crashes 100% of the time on current master.

b) Root cause explained? ✅ BufferSource::generate() checks buffer.data.has(name) using the full subcolumn name ("c0.null"), but the buffer's in-memory data block only stores parent columns ("c0"). has() returns false → falls to fillVirtualColumn() → only handles _table → throws LOGICAL_ERROR: Unknown virtual column.

c) Fix matches root cause? ✅ The fix resolves column names through ColumnsDescription::tryGetColumnOrSubcolumn() to get a proper NameAndTypePair with subcolumn delimiter info, allowing getColumnFromBlock() to find the parent column and extract the subcolumn. Same pattern as ReadFromMemoryStorageStep.

d) New test added? ✅ 04097_buffer_subcolumn_virtual_column_crash — tests .null, .size0, tuple elements, and map keys/values through Buffer tables.

e) Both directions demonstrated? ✅ Without fix: crashes with LOGICAL_ERROR. With fix: returns correct results. 50/50 passes with full randomization.

f) Fix is general? ✅ Covers ALL subcolumn types via metadata resolution — not hardcoded to specific subcolumn names. Preserves existing behavior for regular columns and virtual columns. Other storages (StorageLog, StorageStripeLog) use different read patterns (file-based serialization) and are not affected.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @azat — could you review this? It fixes a LOGICAL_ERROR crash when selecting subcolumns (.null, .size0, tuple/map accessors) from a Buffer table — the BufferSource didn't resolve subcolumn names through storage metadata, so it tried to treat them as virtual columns.

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

clickhouse-gh Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6d8e6a5]

Summary: ✅


AI Review

Summary

This PR fixes Buffer reads for subcolumns by resolving requested names through storage metadata before reading in-memory buffered blocks, and adds a stateless regression test that covers Nullable, Array, Tuple, Map, and _table access. I found no correctness, safety, or performance issues in the final diff.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 15, 2026
@@ -0,0 +1,42 @@
-- Tags: no-parallel

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

-- Tags: no-parallel looks unnecessary for this stateless regression test and will reduce parallel test coverage/perf in CI. The test only creates/drops local tables and does not rely on global state, so it should be safe to run in parallel.

Please remove the no-parallel tag unless there is a specific known race/isolation issue that requires serialization.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in 0bce791 — thanks for the catch.

The test only creates/drops two local tables in the current database (t_buf_sub, t_buf_sub_dst) and does not touch any shared/global state, so it is safe to run in parallel. The no-parallel tag was an unneeded carryover.

…n-crash

Resolve conflict in src/Storages/StorageBuffer.cpp:
- Master refactored the virtuals API (storage_snapshot->virtual_columns
  was removed, virtuals now live in metadata->virtuals).
- The unused 'virtual_columns' member I introduced in PR ClickHouse#102470 was
  dead code; drop it.
- Keep the 'metadata' member — used in generate() via
  columns_desc = metadata->getColumns() to resolve subcolumn names.

Pulls in trunk fix ClickHouse#103489 (yakov-olkhovskiy) for the unrelated
Unit tests (msan, function_prop_fuzzer) failures.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master at commit 496f4b2 to clear the DIRTY state (which accumulated since 2026-04-21) and to pick up the trunk fix #103489 (merged today, 2026-04-24 11:48 UTC) — this resolves the previous spurious Unit tests (msan, function_prop_fuzzer) failure which was a chronic trunk bug, not caused by this PR.

Conflict resolution

The only merge conflict was in src/Storages/StorageBuffer.cpp:

Master refactored the virtuals API (#102304, move virtuals into in-memory metadata):

  • storage_snapshot->virtual_columns was removed; virtuals now live under metadata->virtuals.
  • setVirtuals(createVirtuals()) moved before setInMemoryMetadata(...).

My original fix added two members to BufferSource:

  • virtual_columns(storage_snapshot->virtual_columns) — never used in generate(); removed (it was dead code, and master's API change would have made it fail to compile).
  • metadata(storage_snapshot->metadata) — used in generate() via columns_desc = metadata->getColumns() to resolve subcolumn names through tryGetColumnOrSubcolumn; kept.

Verification

  • The fix logic (subcolumn-resolving lookup in generate()) is unchanged.
  • StorageSnapshot::metadata and ColumnsDescription::tryGetColumnOrSubcolumn both still exist in master — no other API breakage.
  • Branch has exactly 2 commits ahead of master: the original fix 88a9b67cf13b and this merge commit 496f4b27c159.

cc @novikd @azat — could you take another look? CI will re-run on the rebased HEAD.

Address review feedback from `clickhouse-gh[bot]` on PR ClickHouse#102470:
the test only creates and drops local tables in the current database
and does not depend on global state, so it can run in parallel safely.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Michicosun — could you please review this PR?

This fixes the chronic BuzzHouse trunk bug STID 3381-2a5e — Logical error: Unknown virtual column (tracking issue: #102104, ~9 occurrences across master + 7 PRs in 90 days, including PR #100949 which surfaced it as Unknown virtual column: 'עברית0.size0'). The bug was introduced in commit aac90df (support common virtuals for buffer table, 2026-04-01) which you authored.

Root cause: BufferSource::generate() checks buffer.data.has(name) for the full subcolumn name (e.g. arr.size0, c0.null), but the buffer's in-memory data block only stores parent columns, so subcolumns fall through to fillVirtualColumn() which only handles _table and throws LOGICAL_ERROR.

Fix: Resolve names through metadata->getColumns().tryGetColumnOrSubcolumn(...) to obtain a proper NameAndTypePair with subcolumn delimiter info, then let getColumnFromBlock() extract the subcolumn via tryGetSubcolumn(). Same pattern as ReadFromMemoryStorageStep.

CI is clean on the rebased HEAD (0bce791c):

  • Style check ✅, Fast test ✅, Code Review ✅ (AI Review verdict: Approve)
  • The two reported failures are unrelated chronic flaky tests tracked separately:
    • 04103_user_network_bandwidth_throttler — known P2 flaky (5–7 master failures/day across all PRs)
    • Unit tests (asan_ubsan, function_prop_fuzzer) — 0 master failures in last 14 days, very rare flake

Regression test (04097_buffer_subcolumn_virtual_column_crash.sql) covers .null, .size0, tuple elements, and map keys/values through Buffer tables — the exact subcolumn shapes BuzzHouse keeps rediscovering.

Per @alexey-milovidov's directive on #100949 (2026-04-25): this is the separate fix he asked for. cc @alexey-milovidov @azat @novikd

Session: cron:clickhouse-ci-task-worker:20260427-151500

Comment thread src/Storages/StorageBuffer.cpp Outdated
Comment on lines +252 to +259
/// Resolve the column through metadata to get proper subcolumn info
/// (e.g., "c0.null" for Nullable, "arr.size0" for Array).
/// The header's NameAndTypePair lacks subcolumn_delimiter_position,
/// so getNameInStorage() would return the full name instead of the parent.
auto resolved = columns_desc.tryGetColumnOrSubcolumn(GetColumnsOptions::All, name);
if (resolved && buffer.data.has(resolved->getNameInStorage()))
columns.emplace_back(getColumnFromBlock(buffer.data, *resolved));
else if (buffer.data.has(name))

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.

@groeneai

Remove this comment completely.

change logic to the following:

  1. Use the metadata isVirtualColumn method to check if the column is virtual
  2. If it is virtual, use fillVirtualColumns
  3. If it is not virtual, use tryGetColumnFromBlock
  4. If the column is not found, throw a logical error

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 2cbf5702041 — refactored to the 4-step shape you specified:

if (metadata->isVirtualColumn(name))
{
    columns.emplace_back(fillVirtualColumn(name, type, buffer.data.rows()));
    continue;
}

auto resolved = columns_desc.tryGetColumnOrSubcolumn(GetColumnsOptions::All, name);
auto col = resolved ? tryGetColumnFromBlock(buffer.data, *resolved) : nullptr;

if (!col)
    throw Exception(ErrorCodes::LOGICAL_ERROR,
        "Column or subcolumn '{}' not found in Buffer table", name);

columns.emplace_back(std::move(col));

Notes:

  • The intermediate tryGetColumnOrSubcolumn lookup is needed because the header pair from getPort().getHeader().getNamesAndTypes() is built via the default NameAndTypePair(name, type) constructor, which leaves subcolumn_delimiter_position unset. tryGetColumnFromBlock relies on requested_column.isSubcolumn() to extract subcolumns, so without resolving against metadata->getColumns() first it would treat c0.null as a top-level column and fail. Same pattern as ReadFromMemoryStorageStep::fillPhysicalColumns.
  • fillVirtualColumn (singular) — kept the name unchanged, since this helper returns one column per call.
  • Explanatory comment removed as requested.

Verified locally on debug build:

  • 04097_buffer_subcolumn_virtual_column_crash — 50/50 PASS with full randomization
  • Manual repro from issue Logical error: Unknown virtual column: 'A (STID: 3381-2a5e) #102104 (SELECT c0.null FROM buffer_table) returns correct values, no LOGICAL_ERROR
  • _table virtual column still works
  • Adjacent Buffer/virtual-column tests (00126, 00158, 00168, 02890, 03094) all pass

PR HEAD: 2cbf5702041 on fork:fix/buffer-subcolumn-crash.

…ispatch

Per review feedback on ClickHouse#102470,
restructure the per-column dispatch in `BufferSource::generate` into a clear
4-step shape:

1. `metadata->isVirtualColumn(name)` — check whether the column is virtual
2. If virtual, use `fillVirtualColumn`
3. Otherwise, resolve the name through `tryGetColumnOrSubcolumn` and fetch
   via `tryGetColumnFromBlock`, which natively handles subcolumn extraction
4. If the column is not found, throw a `LOGICAL_ERROR`

This removes the awkward fall-through chain that conflated "subcolumn lookup
failed" with "column might be virtual" and the dead-code path that called
`fillVirtualColumn` for non-virtual misses (which was the original crash vector
fixed by ClickHouse#102104). The explicit
`isVirtualColumn` check makes the dispatch obvious and keeps the unknown-column
case as a pure invariant guard.

Behaviour:
- `_table` (virtual) → `fillVirtualColumn` returns the constant column
- `c0`, `c0.null`, `arr.size0`, `tup.a`, `m.keys`, ... → `tryGetColumnFromBlock`
  via the resolved `NameAndTypePair` extracts the parent column from the
  buffer's in-memory block and returns the requested subcolumn
- Anything else (must not happen — `getSampleBlockForColumns` validates the
  column list upstream) → `LOGICAL_ERROR`

The existing regression test
`tests/queries/0_stateless/04097_buffer_subcolumn_virtual_column_crash.sql`
covers all the subcolumn shapes (`.null`, `.size0`, tuple elements, map
keys/values) plus the `_table` virtual column path. It passes 50/50 with full
randomization on this commit.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Refactor pushed in 2cbf5702041. cc @Michicosun

Applied @Michicosun's 4-step refactor request:

  1. metadata->isVirtualColumn(name) check
  2. Virtual → fillVirtualColumn
  3. Otherwise → tryGetColumnOrSubcolumn to resolve subcolumn delimiter, then tryGetColumnFromBlock
  4. Not found → LOGICAL_ERROR

The intermediate tryGetColumnOrSubcolumn is necessary because the header pair from getPort().getHeader().getNamesAndTypes() doesn't carry subcolumn info — same pattern as ReadFromMemoryStorageStep::fillPhysicalColumns. Explanatory comment removed.

Verified on debug build: 50/50 PASS for 04097_buffer_subcolumn_virtual_column_crash with full randomization, plus manual issue #102104 repro and adjacent Buffer/virtual-column tests (00126, 00158, 00168, 02890, 03094) all green.

Inline reply: #102470 (comment)

Comment thread src/Storages/StorageBuffer.cpp Resolved
Comment thread src/Storages/StorageBuffer.cpp Resolved
Comment thread src/Storages/StorageBuffer.cpp Resolved
Comment thread src/Storages/StorageBuffer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 100.00% (12/12) · Uncovered code

Full report · Diff report

@Michicosun
Michicosun added this pull request to the merge queue Apr 28, 2026
Merged via the queue into ClickHouse:master with commit d4414d4 Apr 28, 2026
165 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 28, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @Michicosun — this PR fixes a LOGICAL_ERROR (code 49), which according to the changelog rules should be categorized as Critical Bug Fix (crash, data loss, RBAC) or LOGICAL_ERROR rather than Bug Fix.

I verified this by running the test queries which produce: Code: 49. DB::Exception ... Unknown virtual column: 'c0.null' ... (LOGICAL_ERROR)

Could you update the changelog category? Feel free to ignore if there's a specific reason for the current categorization.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, 25.8 (LTS), but no backport label was found.

Affected code: BufferSource::generate in src/Storages/StorageBuffer.cpp — core code present in all supported branches.

Why: StorageBuffer.cpp and BufferSource predate all supported branches (file is ancient — git log --diff-filter=A shows no recent add). The bug — LOGICAL_ERROR when selecting any subcolumn through a Buffer table — is reproducible on the running master binary and affects any user reading subcolumns of Nullable, Array, Tuple, Map, etc. through a Buffer. Each currently supported branch (25.8 lts, 26.1, 26.2, 26.3 lts) contains the buggy code path.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

@fm4v fm4v self-assigned this Jul 2, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 2, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 2, 2026
fm4v added a commit that referenced this pull request Jul 2, 2026
Backport #102470 to 26.4: Fix crash when selecting subcolumns from Buffer table
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 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 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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Unknown virtual column: 'A (STID: 3381-2a5e)

8 participants