Skip to content

Remove Field from constant-expression evaluation (table functions + column-native coercion) - #110945

Merged
yakov-olkhovskiy merged 19 commits into
masterfrom
cursor/field-convert-column-to-type
Jul 27, 2026
Merged

yakov-olkhovskiy merged 19 commits into
masterfrom
cursor/field-convert-column-to-type

Conversation

@yakov-olkhovskiy

@yakov-olkhovskiy yakov-olkhovskiy commented Jul 18, 2026 •

Copy link
Copy Markdown
Member

Part of a larger effort to eliminate DB::Field

Ongoing effort to remove DB::Field from the ClickHouse server, replacing it with type-consistent, copy-free representations. Field's type tags don't map to ClickHouse SQL types (NearestFieldType collapses UInt8→UInt64, Float32→Float64, DateTime64→Decimal, ...), and it forces copies of data that already lives in columns.

This PR takes one self-contained flow — constant-expression evaluation for numeric table-function arguments — all the way from Field to column-native, and provides the two reusable pieces the rest of the effort needs.

What's here

1. Producer — evaluate a constant as a column (evaluateConstantExpression.{h,cpp})
evaluateConstantExpression already builds a size-1 ColumnConst internally, then discards it via (*result_column)[0] as a Field (which also collapses the exact type). New evaluateConstantExpressionAsColumn / tryEvaluateConstantExpressionAsColumn return {ColumnPtr /*size 1*/, DataTypePtr} instead; the Field-returning functions become thin shims, so un-migrated callers are unaffected.

2. Coercion — column-native convertFieldToType (convertColumnToType.{h,cpp})
convertColumnToTypeOrNull / try… / …OrThrow convert a single value (row 0 of a size-1 column) into a target type, returning a size-1 column (or ColumnPtr{} when not representable; a valid NULL result is a column holding NULL). Plain numeric→numeric in the default mode is done column-natively via castColumnAccurateOrNull (same accurate::convertNumeric as convertFieldToType); other cases delegate to convertFieldToType for now. Pinned by a differential test (gtest_convert_column_to_type) against convertFieldToType across numerics/float-modes/Bool/Decimal/String↔number/Date/Nullable/LowCardinality/Array/Tuple/ColumnConst, incl. the NULL-vs-not-representable distinction.

3. Actual Field removal — table functions
numbers, primes, generateSeries argument evaluation, and the String arguments of prometheusQuery/prometheusQueryRange/timeSeriesSelector, now read their constant as a column and coerce column-natively instead of materializing a Field and calling safeGet. The happy path no longer builds a Field (a Field is only formatted on the error path).

No user-facing behavior change (smoke-tested: numbers/primes/generate_series results and error messages preserved; Nullable/LowCardinality string args and NULL handling preserved).

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

Internal refactor to reduce DB::Field usage in constant-expression evaluation. No user-facing change.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.8.1.210 (included in 26.8 and later)

yakov-olkhovskiy and others added 2 commits July 18, 2026 15:36
`evaluateConstantExpression` already builds a size-1 `ColumnConst` internally,
then discards it by returning `(*result_column)[0]` as a `Field` — which both
allocates and collapses the exact SQL type through `Field`'s `NearestFieldType`
mapping (`UInt8`->`UInt64`, `Float32`->`Float64`, `DateTime64`->`Decimal`, ...).

Add `evaluateConstantExpressionAsColumn` (and `tryEvaluateConstantExpressionAsColumn`)
returning the value as `{ColumnPtr /*size 1*/, DataTypePtr}`, preserving the exact
type and avoiding the `Field`. The existing `Field`-returning functions become thin
shims over it, so behavior is unchanged for callers not yet migrated.

Migrate the plain `String` literal arguments of `prometheusQuery`/`prometheusQueryRange`
(`StoragePrometheusQuery`) and `timeSeriesSelector` (`StorageTimeSeriesSelector`) to the
new API, reading the value with `IColumn::getDataAt` instead of materializing a `Field`
and calling `safeGet<String>`.

This is the first step of reducing `DB::Field` usage; no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…egation)

Introduce `convertColumnToTypeOrNull` / `tryConvertColumnToTypeOrNull` /
`convertColumnToTypeOrThrow`, the column-native counterpart of `convertFieldToType`:
convert a single value (row 0 of a size-1 column of type `from`) into type `to`,
returning a size-1 column of `to`, or a null `ColumnPtr{}` when the value is not
representable (the twin of a Null `Field`).

The goal is to coerce constants without materializing a `Field`. This first step
implements the facility by delegating to `convertFieldToType` (so behavior is exactly
preserved); `gtest_convert_column_to_type` pins the result against `convertFieldToType`
across numerics, float modes, Bool, Decimal, String<->number, Date/DateTime, Nullable,
LowCardinality, Array and Tuple. Column-native fast paths (numeric, ...) that actually
avoid the `Field` will replace the delegation incrementally in the same effort, guarded
by that test.

Part of the effort to remove `DB::Field`. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [211a606]

Summary: ✅


AI Review

Summary

This PR moves the reviewed constant-expression paths from Field materialization to the new column-based helpers, keeps the previously raised compatibility fixes in the current head, and adds focused regressions for the Bool literal bridge and the TimeSeries string-argument wrappers. I did not find any remaining correctness, compatibility, or evidence gaps in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 18, 2026
yakov-olkhovskiy and others added 2 commits July 18, 2026 17:41
The style check rejects a bare catch(...) that swallows exceptions; use the
project's `// Ok: ...` suppression idiom (as tryConvertFieldToType does), since
this is an intentional try-pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses automated review on #110944: the exact-type column API narrowed the
accepted argument types. The previous `Field`-based code read the value via
`operator[]`, which flattens wrappers, so a non-NULL `Nullable(String)` /
`LowCardinality(String)` constant passed the `Field::Types::String` check.

Unwrap via `removeLowCardinalityAndNullable` before the String kind check to keep
those accepted, and add an explicit `isNullAt` check so a NULL value is still
rejected as before.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
yakov-olkhovskiy and others added 4 commits July 20, 2026 06:09
…(review fix)

Addresses automated review on #110945: convertFieldToType returns a Null Field
both for a legitimate NULL result (NULL input into a nullable-capable type) and for
"not representable". The first version collapsed both into ColumnPtr{}, so
`NULL :: Nullable(Int32) -> Nullable(Int64)` could not be represented, and
convertColumnToTypeOrThrow diverged from convertFieldToTypeOrThrow (threw on a valid
NULL, and threw the wrong exception for NULL -> non-nullable).

Now a valid NULL result becomes a size-1 column holding NULL, while ColumnPtr{} means
only "not representable". convertColumnToTypeOrThrow mirrors convertFieldToTypeOrThrow:
TYPE_MISMATCH for NULL into a non-nullable target, ARGUMENT_OUT_OF_BOUND for a non-NULL
value that does not fit. Extends the differential test with the nullable/NULL cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add the first Field-free fast path: plain numeric-to-numeric in the default mode now
converts via castColumnAccurateOrNull instead of materializing a Field. It uses the
same accurate numeric conversion (accurate::convertNumeric, strict) as
convertFieldToType's default path, so out-of-range / inexact-narrowing still yield
'not representable'. Excluded (still delegate to convertFieldToType): strict /
convert_inexact_floats modes, Bool (clamp semantics), and anything non-native-numeric
(Decimal/Date/Enum/String/wrappers/composite).

The API now takes 'from'/'to' as DataTypePtr (needed for castColumn; no external
callers yet). The differential test against convertFieldToType (numeric widening/
narrowing/overflow, float modes, ...) stays green, pinning equivalence.

Part of removing DB::Field. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Migrate the numeric argument evaluation of the numbers, primes and generateSeries
table functions off Field end-to-end: evaluateConstantExpressionAsColumn +
convertColumnToTypeOrNull + IColumn::getUInt/getInt, instead of
evaluateConstantExpression + convertFieldToType + Field::safeGet. The happy path no
longer materializes a Field (a Field is only built on the error path, to format the
offending value).

Also make convertColumnToTypeOrNull robust to ColumnConst input (what
evaluateConstantExpressionAsColumn returns) by operating on the full column, and cover
ColumnConst input in the differential test.

Part of removing DB::Field. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@yakov-olkhovskiy yakov-olkhovskiy changed the title Add convertColumnToType: column-native constant coercion (Field removal) Remove Field from constant-expression evaluation (table functions + column-native coercion) Jul 20, 2026
yakov-olkhovskiy and others added 3 commits July 20, 2026 06:49
Belt-and-suspenders for the automated review on #110945: even though callers already
unwrap the input before the numeric fast path (so castColumnAccurateOrNull gets a full
column and returns a non-const result), unwrap the cast result too, so the
assert_cast<ColumnNullable> is locally correct regardless of the argument's constness
(ExecutableFunctionCast wraps const results). The ColumnConst regression test already
covers this input shape.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Migrate LIMIT/OFFSET/LIMIT BY value evaluation off Field on both the analyzer and the
legacy paths:
- Planner::getLimitOffsetValue now takes the ConstantNode and reads its column
  (getColumn) + convertColumnToTypeOrNull, instead of ConstantNode::getValue() (a Field)
  + convertFieldToType.
- InterpreterSelectQuery::getLimitOffsetValue uses evaluateConstantExpressionAsColumn +
  convertColumnToTypeOrNull + IColumn typed getters.
- QueryAnalyzer::convertLimitOffsetExpression converts the constant column-natively and
  rebuilds the ConstantNode from the resulting column (via ConstantValue), avoiding both
  the getValue() Field and the ConstantNode(Field) re-conversion.

The UInt64 -> Int64 -> Float64 order and the negative/fractional-limit handling are
unchanged; a Field is only materialized on the error path (to format the bad value).
Smoke-tested LIMIT/OFFSET/LIMIT BY, positive/negative/fractional, analyzer + legacy.

Part of removing DB::Field. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Migrate the remaining LIMIT/OFFSET ConstantNode reads off Field:
- PlannerJoinTree: the 'is the limit/offset a non-negative UInt64' checks used for
  limit pushdown now read the ConstantNode's column (getColumn) + convertColumnToTypeOrNull
  instead of getValue() + convertFieldToType, and take the value from the converted column.
- OptimizeTrivialGroupByLimitPass::tryGetNonNegativeUInt64 now takes the ConstantNode and
  converts column-natively.

Same non-negative-UInt64 semantics (negative/fractional -> skip optimization); no Field on
the happy path. Smoke-tested limit pushdown and the group-by-limit optimization.

Part of removing DB::Field. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A review flagged that the `Field`-returning `evaluateConstantExpression` can return
nested `Field` tags collapsed (e.g. `Bool` elements of a literal `array(...)` /
`tuple(...)` come back as `UInt64`), because the value is produced as a size-1 column
and read back with `operator[]`, which re-canonicalizes tags through the column
implementation.

This is not a user-reachable bug: strict `Bool` consumers read via
`evaluateConstantExpressionAsLiteral` (which returns literal nodes verbatim, bypassing
this path) or via `Array(Variant)` (which is per-element type-aware), and tolerant
consumers pass the value through `convertFieldToType`. It is inherent to the `Field`
representation and is one of the reasons `Field` is being removed. Rather than add a
backward-compatibility path that materializes a `Field` for literals (which would move
against removing `Field`), the behavior is left as is and pinned by a gtest, alongside
a test showing the column API (`evaluateConstantExpressionAsColumn`) keeps the exact
SQL type (`Array(Bool)`) - the type-faithful replacement callers should migrate to.

Part of removing DB::Field.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A review noted that `convertColumnToTypeOrNull` is documented as a generic column twin
of `convertFieldToType`, but the delegation path is not faithful for every type: it does
`IColumn::get(0, field)` to reconstruct a `Field`, and `get` canonicalizes tags. For a
`DataTypeBool` source (backed by `ColumnUInt8`) the reconstructed `Field` is `UInt64`, so
`Bool -> String` yields `'1'`/`'0'` instead of `convertFieldToType`'s `'true'`/`'false'`
(same for nested `Array(Bool)` / `Tuple(Bool)`).

This does not affect any current caller: they all convert to numeric types, and a
`Bool`-source into a numeric `to` is value-preserving (verified by the differential test).
Rather than reintroduce a `Field` into the API (against the goal of removing `Field`) or
enumerate every tag-sensitive type in the fallback, narrow the documented contract to the
faithful scope and record the `Bool`-to-textual gap explicitly in `convertColumnToType.h`.
The gap disappears as the `convertFieldToType` delegation is replaced by column-native
paths. Adjust `gtest_convert_column_to_type` to cover `Bool`-source into numeric targets
(faithful) and document why `Bool -> String` is not asserted.

Part of removing DB::Field. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
yakov-olkhovskiy and others added 2 commits July 23, 2026 15:48
…ression

Phase B reimplemented `evaluateConstantExpression` on top of a size-1 column. For a
literal node the `Field`-returning API then produced its `Field` by reading the value
back with `operator[]`, which canonicalizes nested/scalar `Field` tags through the
column implementation (`Bool` -> `UInt64`, since a `DataTypeBool` column is a plain
`ColumnUInt8`). Callers that still convert the returned `Field` observed a real change:
`values('x String', true)` returned `'1'` instead of `'true'` (verified). This is a
user-facing regression introduced within this effort.

Restore the pre-Phase-B behavior: the `Field`-returning entry points take a
tag-preserving fast path for literal nodes (return `convertFieldToType(literal->value,
type)` directly) instead of round-tripping through the column. The non-literal path is
unchanged - it still returns `(*result_column)[0]`, so its long-standing behavior (a
computed `Array(Bool)` yields `UInt64` elements) is preserved.

This fast path re-adds a `Field` materialization, which is a temporary compatibility
bridge, not the end state: it is removed together with the `Field`-returning
`evaluateConstantExpression` once its callers migrate to the column API (tracked as
bridge B1 in the project notes). The `array(...)` / `tuple(...)` literal case is
unaffected here because the analyzer wraps those as `_CAST(...)` (a non-literal), which
behaves as on master.

Covered by a stateless test (`values(...)` with `Bool` into `String`/`Nullable(String)`,
plus a numeric sanity case) and a gtest asserting the `Field` API preserves nested `Bool`
tags for literal `array`/`tuple`, while the column API keeps the exact `Array(Bool)` type.

Part of removing DB::Field.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/StoragePrometheusQuery.cpp Resolved
…ppers

`prometheusQuery` / `timeSeriesSelector` read their String arguments via
`evaluateConstantExpressionAsColumn` (no `Field`). A review noted the compatibility
contract - accept a non-NULL `Nullable(String)` / `LowCardinality(String)` constant
(the previous `Field`-based code unwrapped these), still reject `NULL` - was only
asserted by a comment. Add a stateless test on both public entry points covering
`CAST('ts', 'Nullable(String)')`, `toLowCardinality('ts')`, a `Nullable(String)`
promql/selector, and `CAST(NULL, 'Nullable(String)')` (rejected with `BAD_ARGUMENTS`).

Part of removing DB::Field.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
yakov-olkhovskiy and others added 2 commits July 24, 2026 14:27
The literal fast path (bridge B1) only preserved `Field` tags when the original node was already an
`ASTLiteral`. But `evaluateConstantExpressionAsColumnImpl` has a second literal site: the non-analyzer
path where `TreeRewriter::analyze` folds a non-literal into an `ASTLiteral` (e.g. a SQL UDF returning a
literal). That site still went through `getColumnAndDataTypeFromLiteral` + `materializeToField`, so the
legacy `Field` API re-canonicalized `Bool` back to `UInt64` and `values('x String', udf_returning_true())`
returned `'1'` instead of `'true'`.

Handle both literal sites with one mechanism: a `from_literal` helper plus a `literal_out` out-param.
When the `Field`-returning API is calling, a literal (original or rewrite-folded) is returned through
`literal_out` as its tag-preserving `Field` and no column is built; when the column API is calling, the
size-1 column is built as before. This also removes the earlier duplicated literal short-circuit in the
entry points.

Verified the fix is load-bearing (temporarily gating it off makes the cases return `'1'`). Extended the
regression test with a SQL UDF folded to a `Bool` literal, checked with `enable_analyzer` = 1 and 0.

Part of removing DB::Field. Transitional bridge B1 (removed with the `Field` API).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The rewrite-to-literal case in this test creates a SQL UDF (a global object). The CI flaky check runs
the changed test many times concurrently against one server, so a fixed function name collided
(`DROP`/`CREATE` racing) and every run failed. Mark the test `no-parallel` so its copies run serially;
the function name stays unique in time. Only the tag changed - the reference is unaffected because the
tag line precedes `-- { echo }`.

CI: #110945

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A review noted the code/test comments referenced `.cursor/projects/valueref-pilot/BRIDGES.md` and a
`bridge B1` label, but that ledger file is intentionally git-excluded (local project notes), so the
reference was dead in-tree and the removal condition undocumented for readers of the branch. Rewrite
the comments to be self-contained: describe the shim and its removal condition inline (delete together
with the `Field`-returning `evaluateConstantExpression` once callers move to `evaluateConstantExpressionAsColumn`),
and cross-reference the sibling function instead of an external path. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 353/373 (94.64%) · Uncovered code

Full report · Diff report

@yakov-olkhovskiy
yakov-olkhovskiy marked this pull request as ready for review July 25, 2026 08:01
@yakov-olkhovskiy
yakov-olkhovskiy added this pull request to the merge queue Jul 27, 2026
Merged via the queue into master with commit 83ced69 Jul 27, 2026
695 of 701 checks passed
@yakov-olkhovskiy
yakov-olkhovskiy deleted the cursor/field-convert-column-to-type branch July 27, 2026 14:45
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
…(review fix)

Addresses automated review on ClickHouse#110945: convertFieldToType returns a Null Field
both for a legitimate NULL result (NULL input into a nullable-capable type) and for
"not representable". The first version collapsed both into ColumnPtr{}, so
`NULL :: Nullable(Int32) -> Nullable(Int64)` could not be represented, and
convertColumnToTypeOrThrow diverged from convertFieldToTypeOrThrow (threw on a valid
NULL, and threw the wrong exception for NULL -> non-nullable).

Now a valid NULL result becomes a size-1 column holding NULL, while ColumnPtr{} means
only "not representable". convertColumnToTypeOrThrow mirrors convertFieldToTypeOrThrow:
TYPE_MISMATCH for NULL into a non-nullable target, ARGUMENT_OUT_OF_BOUND for a non-NULL
value that does not fit. Extends the differential test with the nullable/NULL cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
Belt-and-suspenders for the automated review on ClickHouse#110945: even though callers already
unwrap the input before the numeric fast path (so castColumnAccurateOrNull gets a full
column and returns a non-const result), unwrap the cast result too, so the
assert_cast<ColumnNullable> is locally correct regardless of the argument's constness
(ExecutableFunctionCast wraps const results). The ColumnConst regression test already
covers this input shape.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
The rewrite-to-literal case in this test creates a SQL UDF (a global object). The CI flaky check runs
the changed test many times concurrently against one server, so a fixed function name collided
(`DROP`/`CREATE` racing) and every run failed. Mark the test `no-parallel` so its copies run serially;
the function name stays unique in time. Only the tag changed - the reference is unaffected because the
tag line precedes `-- { echo }`.

CI: ClickHouse#110945

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants