Skip to content

Fix LOGICAL_ERROR in flattenTuple for inputs with no scalar leaves - #104989

Merged
antonio2368 merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flatten-tuple-empty-result-100272
May 18, 2026
Merged

antonio2368 merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flatten-tuple-empty-result-100272

Conversation

@groeneai

@groeneai groeneai commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

flattenTuple recursively expands nested tuples and arrays into the
underlying scalar columns. When the input type tree contained only
empty Tuple() leaves (directly, or wrapped in any combination of
Tuple / Array), the recursion produced zero scalar columns, the
result reached ColumnTuple::create with an empty column list, and the
defensive LOGICAL_ERROR guard in ColumnTuple::create aborted the
server in debug builds.

The check at the top of FunctionFlattenTuple::getReturnTypeImpl
already rejects an empty top-level tuple, but it does not catch inputs
whose flatten result happens to be empty, e.g.
Tuple(c0 Array(Tuple())), Tuple(c0 Tuple()),
Tuple(c0 Tuple(c00 Tuple())), or Tuple(c0 Array(Array(Tuple()))),
including the same shapes wrapped in Nullable.

After this change, getReturnTypeImpl runs the flatten on the input
type and validates that the result has at least one element; otherwise
it throws ILLEGAL_TYPE_OF_ARGUMENT with a user-readable message that
names the offending input type. Reachable shapes that already have at
least one scalar leaf (e.g. Tuple(c0 Int32, c1 Array(Tuple()))) are
unchanged.

Routed by @alexey-milovidov from the CI thread of
#100272 as a
function_prop_fuzzer finding. Same class as previously-fixed empty
tuple constructions in reverse (#89137) and arrayIntersect
(#72578), but for the flattenTuple code path which had no equivalent
guard.

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

flattenTuple no longer raises a LOGICAL_ERROR when called on a tuple whose nested structure contains only empty Tuple() leaves (e.g. Tuple(c0 Array(Tuple())) or Tuple(c0 Tuple())). Such inputs now produce a user-facing ILLEGAL_TYPE_OF_ARGUMENT exception explaining that the flatten result would be an empty tuple.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.5.1.755

`flattenTuple` recursively expands nested tuples and arrays into scalar
columns. When the input type tree contained only empty `Tuple()` leaves
(directly, or wrapped in any combination of `Tuple` / `Array`), the
recursion produced zero scalar columns. The result then reached
`ColumnTuple::create` with an empty column list, which is guarded by a
`LOGICAL_ERROR` and aborts the server in debug builds.

The check that already rejects an empty top-level tuple does not catch
inputs whose flatten result happens to be empty (for example
`Tuple(c0 Array(Tuple()))` or `Tuple(c0 Tuple(c00 Tuple()))`).

Detect the empty-flatten case in `getReturnTypeImpl` and throw
`ILLEGAL_TYPE_OF_ARGUMENT` with a user-readable message that names the
offending input type.

Reproduced as a `function_prop_fuzzer` finding routed by
@alexey-milovidov via the CI thread of
ClickHouse#100272.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation self-assessment (TASK.md Phase 4 Step 9)

(a) Deterministic repro? Yes. SELECT flattenTuple(CAST((tuple([])) AS Tuple(c0 Array(Tuple())))); deterministically aborts the server with Logical error: 'This function cannot be used to construct empty tuple. It is a bug'. on master (verified locally; debug build, SIGABRT, stack ends at ColumnTuple::create called from flattenTuple in src/DataTypes/flattenTuple.cpp:99).

(b) Root cause explained? Yes. flattenTuple walks the input type tree expanding nested tuples and arrays into the scalar leaves. When the input tree contains only empty Tuple() leaves, the recursion completes with zero scalar columns. ColumnPtr flattenTuple(...) then calls ColumnTuple::create({}), which throws LOGICAL_ERROR because the defensive guard rejects empty tuple construction. The existing top-level check rejects Tuple() directly but not inputs whose flatten result happens to be empty.

(c) Fix matches root cause? Yes. getReturnTypeImpl now runs the flatten on the input type and validates the result has at least one element, throwing ILLEGAL_TYPE_OF_ARGUMENT upstream of the column-flattening path that would otherwise hit the LOGICAL_ERROR. The fix targets the real mechanism — the empty flatten result — rather than masking the symptom. The bad state (empty result) is detected at the exact boundary where the function rejects malformed input types; this is the same place the existing top-level emptiness check already lives.

(d) Test intent preserved? / New test added? New regression test 04240_flatten_tuple_empty_result_104877.sql covers every reproduced crash variant:

  • Tuple() direct (covered by the existing check)
  • Tuple(c0 Array(Tuple())) (original fuzzer-reduced case)
  • Tuple(c0 Tuple())
  • Tuple(c0 Tuple(c00 Tuple()))
  • Tuple(c0 Array(Array(Tuple())))
  • The same shapes wrapped in Nullable (with allow_experimental_nullable_tuple_type = 1)

It also re-asserts that valid usage still flattens: Tuple(c0 Int32), the doc example Tuple(a UInt32, b Tuple(c String, d UInt32)), and the mixed case Tuple(c0 Int32, c1 Array(Tuple())) (which has one scalar leaf, so the flatten succeeds and the empty-tuple branch contributes nothing). No existing test has been weakened.

(e) Demonstrated in both directions? Yes.

  • Without the fix (master flattenTuple.cpp, stashed locally then rebuilt + restarted): the test triggers Fatal: 'This function cannot be used to construct empty tuple. It is a bug', the server aborts, and clickhouse-test returns SIGTERM (exit 143). Stack confirmed in tmp/ch-server/log/error.log.
  • With the fix: clickhouse-test 04240_flatten_tuple_empty_result_104877 --test-runs 5 → 5/5 passes. Existing tests (00897_flatten, 02246_flatten_tuple, 02906_flatten_only_true_nested) also pass.

(f) Fix is general, not a narrow patch?

  • "Does the same bug pattern exist elsewhere?" The flattenTuple C++ function has only one caller — FunctionFlattenTuple (grep confirmed). The sibling empty-tuple bugs that existed historically (reverse Logical error: 'This function cannot be used to construct empty tuple. It is a bug' #89137, arrayIntersect This function cannot be used to construct empty tuple. It is a bug #72578, the transform cast wrapper) were each fixed in their own caller; this PR closes the equivalent gap for flattenTuple at its only caller.
  • "Am I fixing the root cause or just guarding a symptom?" The bad state (flattened_columns.empty()) arises because the user-provided input type tree has no scalar leaves. This is a legitimate user-input case — the type tree is constructed from user SQL — so surfacing it as ILLEGAL_TYPE_OF_ARGUMENT (and not as LOGICAL_ERROR) is the correct semantics, not a defensive workaround.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @rschu1ze — could you review? Closes the function_prop_fuzzer finding you routed via the CI thread of #100272. Adds a user-facing ILLEGAL_TYPE_OF_ARGUMENT for inputs whose flatten result would be an empty tuple, instead of the current LOGICAL_ERROR. Regression test attached.

@antonio2368 antonio2368 self-assigned this May 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8445673]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, sequential) FAIL
Server died FAIL cidb, issue
02503_cache_on_write_with_small_segment_size UNKNOWN cidb
02501_deep_recusion_schema_inference UNKNOWN cidb
Logical error: Attempt to release query context that does not exist (query_id: A) (STID: 4192-71db) FAIL cidb

AI Review

Summary

This PR adds a guard in FunctionFlattenTuple::getReturnTypeImpl to reject inputs whose flattened result would be an empty tuple, converting a LOGICAL_ERROR path into a user-facing ILLEGAL_TYPE_OF_ARGUMENT exception, and adds focused regression coverage for representative empty-leaf shapes (including Nullable variants). The contract is met by the current code and tests, and I did not find unresolved correctness, safety, or compatibility issues in the changed surface.

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
@antonio2368 antonio2368 added the can be tested Allows running workflows for external contributors label May 15, 2026
The previous `.sql` form relied on `{ serverError ILLEGAL_TYPE_OF_ARGUMENT }`
directives, but on master HEAD (without the fix) the bug-triggering
queries reach the `LOGICAL_ERROR` guard in `ColumnTuple::create` and
abort the server under `abort_on_logical_error = true` (the default
in CI test environments). The bugfix-validation framework saw the
parent server crash as `ERROR` / `SERVER_DIED` and reported "Failed
to reproduce the bug" because that result is not invertible.

This commit wraps the bug-triggering queries in a `.sh` script that
runs each query inside a `clickhouse-local` subprocess. The abort
on master HEAD now stays contained: `clickhouse-local` returns a
non-43 exit code, the script prints `BUG`, the output diff fails,
and the bugfix-validation framework can invert that `FAIL` into a
"bug reproduced" signal. On the PR branch the queries return
`ILLEGAL_TYPE_OF_ARGUMENT` (Code 43) cleanly and the script prints
`OK`.

See PR ClickHouse#104861 for an earlier example of this `.sh` wrapper pattern
for a contained-abort regression test.

Session: cron:clickhouse-ci-task-worker:20260516-114500
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed ebc756f to address the Bugfix validation (functional tests) failure ("Failed to reproduce the bug").

Root cause. The previous .sql form used { serverError ILLEGAL_TYPE_OF_ARGUMENT } directives. On master HEAD (without the fix), the bug-triggering queries reach the LOGICAL_ERROR guard in ColumnTuple::create and abort the server under abort_on_logical_error = true (the default in CI test environments — see tests/config/config.d/abort_on_logical_error.yaml). The bugfix-validation framework saw the parent server crash as ERROR / SERVER_DIED and reported "Failed to reproduce the bug" because that result is not invertible (see ci/jobs/functional_tests.py:750-767 — only Status.FAIL flips to OK and counts toward has_failure).

Fix. Convert the test to a .sh script that runs each bug-triggering query inside a clickhouse-local subprocess. The abort on master HEAD now stays contained: clickhouse-local returns a non-43 exit code, the script prints BUG, the output diff fails, and the bugfix-validation framework can invert that FAIL into a "bug reproduced" signal.

  • On the PR branch the queries return Code: 43 (ILLEGAL_TYPE_OF_ARGUMENT) cleanly via getReturnTypeImpl and the script prints OK × 6.
  • On master HEAD the queries cause SIGABRT (rc=134) and the script prints BUG × 6.

Verified locally against the master binary: 6 BUG outputs as expected.

$ PATH=build/programs:$PATH tests/queries/0_stateless/04240_flatten_tuple_empty_result_104877.sh
BUG
BUG
BUG
BUG
BUG
BUG

This mirrors the wrapper pattern used in PR #104861 for the partition-pruner Bad cast regression test, where the same SERVER_DIED-vs-FAIL classification problem applies to any abort-class crash.

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@antonio2368

Copy link
Copy Markdown
Member

@groeneai please merge with master

@groeneai

Copy link
Copy Markdown
Collaborator Author

@antonio2368 Done — merged master into the branch and pushed.

  • Merge commit: 8445673eb1a4 (no conflicts)
  • Branch advanced 202 commits to incorporate latest master
  • Fix commits 04a50116e2d5 + ebc756f14d50 intact
  • PR state: OPEN, MERGEABLE
  • CI re-running against the merged HEAD

Ready to merge once the new CI run is green. Thanks for the review!

— Session: cron:clickhouse-ci-task-worker:20260518-110000

@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: 83.33% (10/12) · Uncovered code

Full report · Diff report

@antonio2368
antonio2368 added this pull request to the merge queue May 18, 2026
Merged via the queue into ClickHouse:master with commit 8bd43ac May 18, 2026
164 of 166 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 18, 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-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.

4 participants