Skip to content

Rework enable_named_columns_in_function_tuple and add constraint settings - #71030

Open
amosbird wants to merge 107 commits into
ClickHouse:masterfrom
amosbird:fix-70830
Open

amosbird wants to merge 107 commits into
ClickHouse:masterfrom
amosbird:fix-70830

Conversation

@amosbird

@amosbird amosbird commented Oct 24, 2024 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Backward Incompatible Change

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

INSERT into named Tuple columns now rejects by-name tuple conversions that would drop source fields by default. Set allow_named_tuple_conversion_with_extra_source_fields_on_insert = 1 to keep the previous permissive INSERT behavior, or allow_named_tuple_conversion_with_extra_source_fields = 0 to reject such conversions for every query, not only for INSERT. Named tuples whose element names are fully disjoint from the destination are converted positionally and are unaffected. This helps #70830 and implements #70853 (comment).

Example:

-- Rejected on INSERT by default, and everywhere with allow_named_tuple_conversion_with_extra_source_fields = 0
SELECT (1 AS a, 2 AS b2)::Tuple(a Int32, b Int32)

This PR also introduces explicit named-tuple syntax in the tuple function:

tuple('x', 'y')(1, 2)

It works regardless of the analyzer, and it fixes incorrect reuse of named tuple metadata in distributed queries: when the same tuple expression is used with different logical names, AST-level reuse must be prevented, otherwise element names can be mixed up. In non-initial (distributed) queries aliases are not preserved, so names cannot be reliably reconstructed later.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

CI Settings (Only check the boxes if you know what you are doing):

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64, release, debug

  • Run only fuzzers related jobs (libFuzzer fuzzers, AST fuzzers, etc.)
  • Exclude: AST fuzzers

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

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

@robot-ch-test-poll robot-ch-test-poll added the pr-backward-incompatible Pull request with backwards incompatible changes label Oct 24, 2024
@divanik divanik assigned divanik and unassigned divanik Oct 25, 2024
@amosbird
amosbird force-pushed the fix-70830 branch 2 times, most recently from 76b3e98 to dfec54b Compare October 28, 2024 03:17
@Algunenano Algunenano self-assigned this Oct 29, 2024
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
Comment thread src/Functions/FunctionsConversion.cpp Resolved
This setting helps prevent silent data loss during named tuple
conversions. When enabled, it throws an exception if any fields would be
dropped during the conversion process. This makes it easier to catch
potential data loss issues, especially in INSERT-SELECT operations.

Example:
```sql
(1 as a2, 2 as b2)::Tuple(a int, b int) -- Would fail with setting enabled
```
@Algunenano

Copy link
Copy Markdown
Member

I haven't forgotten about this issue, no need to rebase or anything, but I need to think about different approaches to solve the problem.

@clickhouse-gh

clickhouse-gh Bot commented Dec 10, 2024

Copy link
Copy Markdown
Contributor

Dear @Algunenano, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@Algunenano Algunenano self-assigned this Dec 10, 2024
@clickhouse-gh

clickhouse-gh Bot commented Jan 14, 2025

Copy link
Copy Markdown
Contributor

Dear @Algunenano, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (clean merge, the incremental build passes, and the PR's named-tuple tests pass locally in clickhouse local). The red checks on the previous head are unrelated to this PR:

@groeneai, thanks for #123699 (the DNS cache race in test_reverse_dns_profile_events).

The three open review threads are unchanged. Each needs a maintainer decision on compatibility: the insert guard for named tuples nested in containers in VALUES, the null-context schema-alignment casts, and rolling-upgrade compatibility of the explicit-alias tuple syntax on distributed queries.

Comment thread src/Functions/FunctionsConversion.h Resolved
alexey-milovidov pushed a commit to ygxio/ClickHouse that referenced this pull request Oct 13, 2026
…che update

`DNSResolver::dropCache` cleared `cache_host` and `cache_address` before
taking `update_mutex`. The periodic `updateCache` holds `update_mutex` while
it refreshes every known host and address, and `updateHost`/`updateAddress`
end with an unconditional `CacheBase::set`, so a drop that landed during an
update had its cleared entries put back; it then waited for the update,
cleared only `known_*`/`new_*`, and returned with a non-empty cache.

This made `test_host_regexp_multiple_ptr_records::test_reverse_dns_profile_events`
flaky (`assert 7 > 7` on `DNSReverseRequests`): `SYSTEM CLEAR DNS CACHE`
ran inside an update cycle, the PTR answer for the client was re-inserted
before the statement returned, and the following access check was a
cache hit.

Clear both caches inside the existing `scoped_lock(update_mutex, drop_mutex)`.
The drop already waited on `update_mutex`, so its latency is unchanged.

The new gtest runs `updateCache` in a single updater thread (the server has
exactly one, `DNSCacheUpdater`; two concurrent `updateCache` callers would
race on `known_hosts`), waits until the updater has refreshed the entry, then
drops the cache and checks it is empty. Without the fix it fails in every
repetition.

Requested in ClickHouse#71030 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 19, 2026 20:26
Conflicts:
- `resolveFunction.cpp`: keep master's `ARRAY[x]` rewrite before the PR's named `tuple` rewrite.
- `tuple.h`: keep master's documentation-only `getSignatureString` and route both
  `getReturnTypeImpl` overloads to the PR's parameter-aware implementation.
- `InterpreterInsertQuery.cpp`: keep the PR's insert guard and master's `getEffectiveMaxThreads`.
- `KeyCondition.cpp`: apply the PR's `recursiveRemoveTupleElementNames` to master's `mapping.key_expr_type`.
…fields` in `FunctionConvertSettings::updateHash`

A strict and a permissive cast of the same types must not share a hash, as it feeds
`ActionsDAG` and other cache keys.

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

Copy link
Copy Markdown
Member

🕵 Merged master (conflicts in resolveFunction.cpp, tuple.h, InterpreterInsertQuery.cpp, KeyCondition.cpp; resolved keeping both sides — notably tuple.h keeps master's documentation-only getSignatureString and routes both getReturnTypeImpl overloads to the parameter-aware implementation). Addressed the new review thread: FunctionConvertSettings::updateHash now includes allow_named_tuple_conversion_with_extra_source_fields. The binary builds and the PR's tests plus the tuple-related stateless tests (429) pass locally.

The only red on the previous head was 05317_local_read_throttler_filesystem_cache (flaky, fixed on master by #124920 and follow-ups, pulled in by this merge).

The three other open threads (strict insert semantics for nested containers in VALUES, propagating the insert guard through null-context schema casts, and the distributed rolling-upgrade policy for the parametric tuple syntax) remain policy decisions for a maintainer, as stated in their replies.

alexey-milovidov and others added 4 commits October 21, 2026 19:25
…m master

The branch rewrote the queries of this test to request the full tuple
structure. For `array_tuple_column` and `map_tuple_column`, the element
`c` is stored in the file as `Nullable(Int64)`, but the queries asked for
`c Tuple(i UInt32, j UInt32)`, so both the reference and the patched
server failed with `CAST AS Tuple can only be performed between tuple types
or from String`. The original queries that read only the `a` subfield work
with this branch, so there is no reason to diverge from master.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=71030&sha=70428270d2033297b1fd7dad08e2c6426b3a5a0e&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%204%2F6%29
ClickHouse#71030

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

Copy link
Copy Markdown
Member

🕵 Fixed the red Performance Comparison (arm_release, master_head, 4/6) (report). The cause was in this PR, not in master.

  • This branch had rewritten the queries of tests/performance/parquet_read_with_index.xml (commit 2f9a964 from 2024). Queries 4 and 5 asked for c Tuple(i UInt32, j UInt32) inside array_tuple_column and map_tuple_column, but the file stores c as Nullable(Int64). Both servers, the reference c6e4b71cfa2 and the patched one, failed with CAST AS Tuple can only be performed between tuple types or from String.
  • aa5e903 restores master's version of the test, which reads only the a subfield. I checked all six queries locally against a build of this branch, and they pass.

The three open review threads and the change request from 2024 still need a maintainer's decision on strict insert semantics:

  • nested containers in VALUES
  • casts with no context in Native, Arrow/ORC, and ConstantExpressionTemplate
  • parametric tuple syntax in mixed-version distributed queries

I made no code change for those.

alexey-milovidov and others added 2 commits October 25, 2026 17:44
# Conflicts:
#	tests/queries/0_stateless/00309_formats.sql
#	tests/queries/0_stateless/04338_tuple_inside_nullable_null_carrying_elements.sql
Master removed `enable_analyzer` from tests in 71b0310 because the old
query analysis is gone and the setting is frozen at `1`. Drop it from the
tests touched by this PR as well.

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

Copy link
Copy Markdown
Member

🕵 Merged master (2327ae0). Conflicts were in 00309_formats.sql and 04338_tuple_inside_nullable_null_carrying_elements.sql, where master had removed enable_analyzer from tests (71b0310). I kept this PR's changes and dropped the setting. 66ba9de also removes the obsolete SET enable_analyzer = 1 from the other tests this PR touches. The binary builds, and all 24 .sql and 3 .sh tests changed by the PR pass locally.

The three open review threads still need a maintainer decision, as explained in the earlier replies: strict insert semantics for named tuples nested in containers, enforcing the insert guard in null-context schema casts (Native, Arrow/ORC, ConstantExpressionTemplate), and the parametric tuple syntax in distributed queries during a rolling upgrade.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (441ea2e, clean merge). The binary builds, and the PR's changed .sql tests pass locally in clickhouse local (the two that need the test clusters were skipped locally).

The only red on the previous head is 05218_text_index_substreams_opened_lazily in Stateless tests (arm_binary, sequential). It is not related to this PR: the CI diagnosis pins it to the randomized use_columns_cache = 1, and the fix is in progress in #127781.

The three open review threads still need a maintainer decision, as explained in the replies there: strict insert semantics for named tuples nested in containers, enforcing the insert guard in null-context schema casts (Native, Arrow/ORC, ConstantExpressionTemplate), and the parametric tuple syntax in distributed queries during a rolling upgrade.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (2f84496, clean merge) because the branch was more than a week behind. The binary builds, and the 21 changed .sql tests that run without test clusters pass locally in clickhouse local. CI on the previous head was green.

The three open review threads still need a maintainer decision, as explained in the replies there:

  • strict insert semantics for named tuples nested in Array/Map/Nullable/LowCardinality in VALUES;
  • whether to enforce the insert guard in null-context schema casts (Native, Arrow/ORC, ConstantExpressionTemplate);
  • how to handle the explicit named-tuple syntax in distributed queries during rolling upgrades.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 3 commits November 11, 2026 22:23
…ansforms

`convertColumnForDeterministicDag` cast set elements and constants to the
still-named `dag.input_type`, so a `Tuple(b, a)` element was reordered by name
before `sipHash64(v)` was applied, while `IN` and `equals` compare tuple
elements positionally. The index then pruned rows that satisfy the predicate,
for `PARTITION BY sipHash64(v)` and `ORDER BY sipHash64(v)` alike.

Cast to the name-less input type and relabel the result with the type the DAG
was built against (the column layout is identical).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The style check now rejects plain `std::unordered_map` and `std::vector`
in `src/Processors`. Replace them with `UnorderedMapWithMemoryTracking`
and `VectorWithMemoryTracking` in the named tuple reordering helpers.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=71030&sha=34b6ca75fd7f7cb31c83db630822d4b8b7e5deab&name_0=PR&name_1=Style%20check
ClickHouse#71030

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

Copy link
Copy Markdown
Member

🕵 Fixed the red Style check (report) in 40527c2: the new memory-tracking style rule rejected plain std::unordered_map / std::vector in ValuesBlockInputFormat.cpp, so they are now UnorderedMapWithMemoryTracking / VectorWithMemoryTracking. The translation unit passes a -fsyntax-only compile locally. Because the style check failed, the rest of CI did not run on the previous head, so it runs on this one.

The KeyCondition thread is fixed by 34b6ca7 (with the regression test 05621_named_tuple_in_set_key_transform_positional) and is now resolved. The three remaining open threads still need a maintainer decision, as explained in the replies there:

  • strict insert semantics for named tuples nested in Array / Map / Nullable / LowCardinality in VALUES
  • enforcing the insert guard in null-context schema casts (Native, Arrow/ORC, ConstantExpressionTemplate)
  • distributed compatibility of the explicit-alias parametric tuple syntax with older shards

# Conflicts:
#	src/Interpreters/InterpreterInsertQuery.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (977af8e). There was one conflict, in InterpreterInsertQuery.cpp: master switched to getEffectiveMaxThreads(*getContext()) / limitThreadsByFreeMemory. I kept the PR's allow_named_tuple_conversion_with_extra_source_fields_on_insert override and took master's new thread-limit calls. The binary builds, and the 22 changed .sql tests that run without test clusters pass locally in clickhouse local.

The only red check on the previous head was the gate for unresolved review threads in Finish Workflow. The three open threads still need a maintainer decision, as explained in the replies there:

  • strict insert semantics for named tuples nested in Array / Map / Nullable / LowCardinality in VALUES;
  • enforcing the insert guard in null-context schema casts (Native, Arrow/ORC, ConstantExpressionTemplate);
  • a rolling-upgrade policy for the parametric tuple syntax in distributed queries.

alexey-milovidov and others added 3 commits November 23, 2026 19:50
Conflicts resolved:
- `src/Analyzer/Resolve/resolveFunction.cpp`: keep the rewrite of `tuple(x AS a, ...)` into the parametric form before the new `__compose` and `groupConcat` handling from master.
- `src/Functions/FunctionsConversion.cpp`: master moved the tuple element mapping into `getTupleCastElementPositions`; the `allow_named_tuple_conversion_with_extra_source_fields` guard is re-applied on top of that mapping.
- `src/Functions/tuple.h`: keep the parametric `FunctionTuple`, with the `[[nodiscard]]` attributes from master.
- `src/Interpreters/InterpreterInsertQuery.cpp`: keep the two named-tuple settings, drop the settings master no longer uses there.
- `src/Interpreters/Set.cpp`: master moved the key cast into `Set::castToKeyType`; the positional (name-agnostic) tuple cast is re-applied there.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The `26.11` release branch has been created, so the settings history entries of `enable_named_columns_in_function_tuple`, `allow_named_tuple_conversion_with_extra_source_fields` and `allow_named_tuple_conversion_with_extra_source_fields_on_insert` must refer to `26.12`, the version where they will appear.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…eted `VALUES` path

The interpreted `VALUES` path (`input_format_values_deduce_templates_of_expressions = 0`, or an expression the template cannot handle) reordered a named tuple only when the source and the destination had exactly the same set of names. With partially overlapping names it fell back to the positional `convertFieldToType`, so with `allow_named_tuple_conversion_with_extra_source_fields_on_insert = 1` the value `tuple('b2', 'a')(1, 2)` inserted into `Tuple(a Int32, b Int32)` was stored as `(1, 2)`, while the expression template path and `INSERT ... SELECT` store `(2, 0)`. A non-lossy schema expansion (`Tuple(b, a)` into `Tuple(a, b, c)`) was rejected, and named tuples inside `Array`, `Map` and `Nullable` were converted positionally and bypassed the insert guard.

Now the value is brought to the destination layout with the same mapping as `CAST` (`tryGetTupleCastElementPositions`): matched by name when both sides are named and have a name in common, dropping unmatched source elements and filling unmatched destination elements with defaults, and by position otherwise. The conversion and the guard descend into tuples, `Array`, `Map` and `Nullable`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch has not been deployed

No deployments
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-data-types Type system & core datatypes used across query planning/execution. external Author is not a member of the ClickHouse organization pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants