Skip to content

Fix LOGICAL_ERROR on system.detached_tables WHERE uuid filter - #104979

Merged
azat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-issue-102705-detached-tables-uuid-filter
May 18, 2026
Merged

azat merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-issue-102705-detached-tables-uuid-filter

Conversation

@groeneai

@groeneai groeneai commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #102705.

What is the bug

Filtering system.detached_tables by uuid raises a LOGICAL_ERROR and aborts in debug builds:

CREATE TABLE t (key Int) ENGINE = MergeTree ORDER BY key;
DETACH TABLE t;

SELECT count() FROM system.detached_tables
WHERE database = currentDatabase() AND uuid = '<some-uuid>';
-- Code: 49. DB::Exception: Expected the argument №1 ('uuid' of type UUID)
-- to have 1 rows, but it has 0: while executing 'FUNCTION equals(...)'.
-- (LOGICAL_ERROR)

Root cause

detail::getFilteredTables is shared between system.tables and system.detached_tables. When the WHERE clause references the uuid column, the function creates a uuid_column to feed the filter expression. The non-detached branch fills uuid_column from table->getStorageID().uuid, but the is_detached branch only filled table_column. After the loop, both columns are inserted into the same Block:

table_column : N rows
uuid_column  : 0 rows

VirtualColumnUtils::filterBlockWithExpression then executes equals(uuid, '<literal>'), and checkFunctionArgumentSizes raises LOGICAL_ERROR because the columns have mismatched lengths.

Fix

Populate uuid_column from the detached iterator's uuid() so the columns stay in lockstep. DatabaseDetachedTablesSnapshotIterator already exposes uuid() (it is used elsewhere in StorageSystemDetachedTables.cpp).

engine_column cannot currently be created on the detached path — system.detached_tables has no engine column, so the predicate cannot reference it — but a defensive engine_column->insertDefault() is added so the loop stays correct if that schema is ever extended.

Reproduction

The query above crashed the local debug build before this change; with the fix it returns the expected count and the server stays up. The new regression test exercises three failing query shapes (lookup by uuid via subquery, by direct uuid comparison after detach, and uuid-only filter).

Documentation entry for user-facing changes

  • Documentation entry: not required (bug fix in a system table; no user-facing API change).

Information about CI checks

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 LOGICAL_ERROR thrown when filtering system.detached_tables by uuid (e.g. SELECT count() FROM system.detached_tables WHERE uuid = '...'). The query now returns the expected result instead of aborting the server.

Version info

  • Merged into: 26.5.1.749

Filtering `system.detached_tables` by `uuid` raised:

  Code: 49. DB::Exception: Expected the argument №1 ('uuid' of type UUID)
  to have 1 rows, but it has 0: while executing 'FUNCTION equals(uuid, ...)'

`getFilteredTables` builds an empty `uuid_column` when the WHERE clause
references `uuid`, but the `is_detached` branch only filled `table_column`.
`filterBlockWithExpression` then saw mismatched column lengths and threw.

Populate `uuid_column` from the detached iterator's `uuid()` to keep the
columns in lockstep. Also insert a default value for `engine_column`
defensively — `system.detached_tables` has no `engine` column today so
`filter_by_engine` cannot be true on that path, but this keeps the code
robust against future schema changes.

Adds regression test 04240_detached_tables_uuid_filter_102705.

Closes ClickHouse#102705
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

a. Deterministic repro? Yes. CREATE TABLE t (key Int) ENGINE = MergeTree ORDER BY key; DETACH TABLE t; SELECT count() FROM system.detached_tables WHERE database = currentDatabase() AND uuid = '<uuid>'; raises a LOGICAL_ERROR every time on master (debug build aborts).

b. Root cause explained? Yes. getFilteredTables constructs an empty uuid_column whenever the WHERE predicate references uuid. The is_detached branch (src/Storages/System/StorageSystemTables.cpp:112-119) only pushed rows into table_column. After the loop, both columns are inserted into the same Block (lines 153-156), so table_column had N rows and uuid_column had 0. VirtualColumnUtils::filterBlockWithExpression then evaluates equals(uuid, '<literal>') and checkFunctionArgumentSizes throws.

c. Fix matches root cause? Yes. Populate uuid_column from table_it->uuid() in the detached branch — mirroring the non-detached branch — so the columns stay in lockstep. The defensive engine_column->insertDefault() is a future-proof guard: today system.detached_tables has no engine column, so filter_by_engine cannot be true on the detached path, but the loop now stays correct if the schema is extended.

d. Test intent preserved / new test added? New regression test 04240_detached_tables_uuid_filter_102705.sql exercises three failing query shapes: lookup-by-uuid via subquery, direct uuid comparison after detach, and uuid-only filter. No existing tests were weakened.

e. Both directions demonstrated? Yes. Original repro crashed my local debug build with the exact stack trace from the issue (getFilteredTables → filterBlockWithExpression → checkFunctionArgumentSizes). After applying the fix and rebuilding, the same queries return correct results and the test passes 20/20 with full randomization.

f. Fix is general, not a narrow patch? Yes. The patch fixes the column-mismatch invariant at its source by always populating uuid_column whenever it exists, not by silencing the assertion. The same bug pattern does not appear in sibling code paths: the non-detached branch (lines 119-138) already populates both engine_column and uuid_column correctly, and no other caller produces a Block that mixes filled and empty columns before filterBlockWithExpression.

Session: cron:clickhouse-ci-task-worker:20260514-194500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @alexey-milovidov — could you review? Trivial fix for #102705 (system.detached_tables WHERE uuid = ... raised LOGICAL_ERROR because getFilteredTables left uuid_column empty on the detached path). Two-line code change + regression test.

@azat azat self-assigned this May 15, 2026
@azat azat added the can be tested Allows running workflows for external contributors label May 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d17571c]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL

AI Review

Summary

This PR fixes system.detached_tables filtering by uuid by keeping uuid_column populated in the detached iterator path and adds a focused regression test that reproduces the previous LOGICAL_ERROR behavior safely via clickhouse local. I found no remaining correctness, safety, performance, or metadata issues in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 15, 2026
/// `system.detached_tables` has no `engine` column, so `filter_by_engine`
/// is never true for the detached path in practice. Insert a default value
/// defensively so the columns stay aligned if that ever changes.
if (engine_column)

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.

Shouldn't we just not create engine_column above in case of is_detached?
Also it does not make sense to write comments for such a simple fix

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 6e10f2f — engine_column is now never created on the detached path (guarded by !is_detached), and the comments are dropped. filter_by_engine && is_detached is logically unreachable anyway since system.detached_tables has no engine column and the analyzer rejects the predicate with UNKNOWN_IDENTIFIER before reaching getFilteredTables.

…ents

- Guard engine_column creation with !is_detached so it's never allocated
  on the detached path. system.detached_tables has no engine column, so
  filter_by_engine cannot be true when is_detached (UNKNOWN_IDENTIFIER
  is raised at the analyzer level).
- Remove the defensive engine_column->insertDefault() call which is no
  longer necessary.
- Trim explanatory comments per reviewer feedback.
…ailure

The reproducer for issue ClickHouse#102705 runs `SELECT ... FROM system.detached_tables
WHERE uuid = ...` against a table that has already been detached. Without
the fix, the planner creates `uuid_column` (because the predicate filters
on `uuid`) but the detached branch of `getFilteredTables` leaves it empty
while `table_column` has one row. The mismatched column lengths trigger
a `LOGICAL_ERROR` which fires `chassert` in debug / sanitizer builds and
aborts the process.

When run via `clickhouse-client` against the long-running test server,
that abort lands inside the server. The runner's hung-check then
terminates the test before any result is recorded, so the `Bugfix
validation` framework cannot invert the result to `OK` and the check
fails on the PR (as observed on PR ClickHouse#104979). The original `.sql` form
of `04240_detached_tables_uuid_filter_102705` had this issue.

Switching the test to `.sh` and running the reproducer in `clickhouse
local` contains the `SIGABRT` to a short-lived subprocess: stdout is
truncated before reaching `SELECT 'ok'`, the runner sees the diff
against the `.reference`, and reports a normal `FAIL`. Bugfix validation
can then invert it to `OK` on the PR branch.

The `.sh` uses the same pattern as `04238_kill_mutation_subquery_multi_block.sh`
(PR ClickHouse#104927) and `01600_detach_permanently.sh` (Atomic database under
`--path` + `${CLICKHOUSE_TEST_UNIQUE_NAME}` working folder).

Verified locally on the rebuilt debug binary:
- with the fix → `1\nok` → matches reference (30 / 30 deterministic).
- without the fix (line 118-119 reverted, rebuilt) → `Aborted (core dumped)`
  with empty stdout → does not match reference → `FAIL`.

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

Copy link
Copy Markdown
Collaborator Author

Pushed d17571c4afb to address the Bugfix validation (functional tests) failure.

Diagnosis: The regression test in its previous .sql form fired the chassert inside the long-running test server, the runner's hung-check tore everything down before any [ FAIL ] was recorded, and the inversion loop in Bugfix validation therefore could not see the master-side failure.

Fix: Converted the test to .sh and run the reproducer inside clickhouse local with an Atomic database under a per-test --path. The SIGABRT is now contained to a short-lived subprocess: the runner observes truncated stdout, the diff against the .reference fails, and Bugfix validation can correctly invert that to OK on the PR branch. Same pattern as 04238_kill_mutation_subquery_multi_block.sh (#104927).

Local verification (debug build):

  • With this PR's source-side fix → output 1\nok matches reference, 30 / 30 deterministic.
  • After reverting only line 118–119 of StorageSystemTables.cpp and rebuilding → Aborted (core dumped) with truncated stdout, diff mismatches reference, runner reports FAIL — exactly the shape Bugfix validation needs to see.

The other red check, Unit tests (tsan, function_prop_fuzzer) on FunctionsStress.stress (1900-01-01 datetime), is the chronic FunctionsStress family tracked under issue #104877 — unrelated to this PR. Cross-PR CIDB confirms it hits master and many unrelated PRs.

Session: cron:clickhouse-ci-task-worker:20260515-174500

@azat
azat enabled auto-merge May 15, 2026 20:33
@azat
azat disabled auto-merge May 15, 2026 20:34
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.10% -0.10%
Functions 90.80% 90.80% +0.00%
Branches 76.60% 76.50% -0.10%

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

Full report · Diff report

@azat
azat enabled auto-merge May 18, 2026 12:34
@azat
azat added this pull request to the merge queue May 18, 2026
Merged via the queue into ClickHouse:master with commit 532614c May 18, 2026
165 of 167 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @azat — the changelog category for this PR might need a look.

Current: Bug Fix
Suggested: Critical Bug Fix (crash, data loss, RBAC) or LOGICAL_ERROR

Why: LOGICAL_ERROR exceptions are internal assertion failures (chassert in debug builds) that indicate contract violations. This category applies when the server detects an internal inconsistency. The PR description confirms this is Code 49 LOGICAL_ERROR.

Could you verify this is correct? Ignore if the current category is intentional.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS), 26.2, 25.8 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: detail::getFilteredTables in src/Storages/System/StorageSystemTables.cpp — detached tables branch (lines 112-121) — core code present in all supported branches.

Why this might apply: The bug was introduced in commit 51d293b (2024-06-28) when getFilteredTables was refactored to share logic between system.tables and system.detached_tables. This predates all supported release branches. The fix is safe (adds missing column population) and affects a user-visible system table query path.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 18, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 29, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 29, 2026
@watson-ch watson-ch Bot added v26.6-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Oct 15, 2026
@watson-ch

watson-ch Bot commented Oct 15, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2077

Labels added:

  • v26.6-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 15, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 15, 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 v26.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

getFilteredTables detached path omits uuid_column population, causing LOGICAL_ERROR on system.detached_tables WHERE uuid = ...

8 participants