Skip to content

Introduce NumberLiteral Field type for precision-preserving numeric literals - #102646

Closed
Algunenano wants to merge 98 commits into
ClickHouse:masterfrom
Algunenano:number-literal-type
Closed

Algunenano wants to merge 98 commits into
ClickHouse:masterfrom
Algunenano:number-literal-type

Conversation

@Algunenano

@Algunenano Algunenano commented Apr 14, 2026 •

Copy link
Copy Markdown
Member

Numeric literals that overflow Int64/UInt64 (e.g. 100000000000000000000000) were silently parsed as Float64, losing precision. Decimal-point literals like 3.14 also went through Float64, preventing exact comparisons with Decimal columns.

The NumberLiteral Field type from #121554 stores the original text of such a literal. This PR makes the parser produce it and defers parsing to a concrete type until the context is known. The spelling of a literal decides its value; the arguments it is used with decide its type:

  • A decimal integer literal that overflows Int64/UInt64 resolves to the smallest fitting wide integer (UInt128/Int128/UInt256/Int256), falling back to Float64 only beyond Int256/UInt256. Overflowing hexadecimal (0x) literals stay Float64 for compatibility; overflowing binary (0b) literals are a syntax error, as before.
  • In a comparison with a Decimal argument, the literal is parsed from its text into a wide Decimal, so the comparison is exact. This covers =, < and friends, IN sets, and literals nested in tuples, arrays and maps.
  • In any other function with a Decimal argument, such as arithmetic, the literal stays a Float64, as before: price * 1.1 with price Decimal64(2) is still a Float64, toDecimal64(1, 2) / 3.0 is still 0.3333333333333333, and / 0.0 is still inf. So the expressions stored in tables (DEFAULT, MATERIALIZED and ALIAS columns, keys, skip indices, projections, TTL, mutations and materialized views) compute the same values as before. Keys, skip indices and projections are built by the old analyzer, which also types these literals as Float64, so they keep matching the same expression in a query.
  • Next to floating-point arguments a literal is a Float64, including an integer literal too large for UInt64 (toFloat64(x) + 100000000000000000000000 keeps working), and so is such an integer next to a Decimal. Next to Float32 arguments a literal that is exact in Float32 is a Float32 (greatest(toFloat32(x), 1.5) is Float32, while 1.1 stays Float64). Next to integer arguments an integer literal takes their type when it fits.
  • With several numeric arguments the reference is their least common supertype, so the result does not depend on argument order.
  • A standalone literal resolves through a single NumberLiteral::toFloat64 (readFloatTextPrecise, deterministic and locale-independent; strtod only for hex floats).

The Analyzer's resolveFunction re-types NumberLiteral constants from the sibling arguments before function resolution. Table functions that analyze their own arguments (view, viewIfPermitted, and viewExplain behind SELECT * FROM (EXPLAIN ...)) receive the literal text, so they type literals the same way as the query. Paths that take a literal as a plain value (settings, aggregate function parameters, index and codec arguments, dictionary layout parameters, SYSTEM INSTRUMENT) call Field::resolveNumberLiteral, and convertFieldToType does the same for anything else.

A wide integer that ends up as a setting or config value is now written without quotes (FieldVisitorToSettingValueString): a setting value is not a SQL literal, and the quoted form re-parsed as a String.

The clickhouse_json dialect carries the literal text verbatim and only accepts text that ParserNumber reads as one deferred literal.

A literal that takes a wide integer type inherits the limits of that type, exactly as an explicit constant would: 100000000000000000000000 OR 0 fails like toUInt128(1) OR 0. Fixing those limits belongs to the types themselves, not to the literals.

In existing tables, a comparison with a Decimal column in a stored expression (a materialized view WHERE, a DEFAULT price > 0.1) becomes exact after the upgrade, so its result changes only where Float64 used to round. A key or skip index built on such a comparison is not used by queries, as before.

The new behavior is controlled by the setting enable_context_typed_number_literals, enabled by default. Disabling it (or compatibility below 26.10) resolves every literal that is not a plain Int64/UInt64 to Float64, as before. It applies to the queries of the session (SELECT, INSERT including the DEFAULT and MATERIALIZED expressions it computes, EXPLAIN), to stored views and other definitions when the session reads them, to the Values input format, and to formatQuery, parseQueryToJSON and clickhouse-format. It does not cover:

  • Stored definitions keep the literal as written: SHOW CREATE shows 0.90, not 0.9, and a view keeps the column types it was created with.
  • Mutations and dictionary layout parameters read when the dictionary loads: they run with the default profile, not with the settings of the session that issued them.
  • The text of a CAST of a literal in brackets or in hexadecimal is decided in the parser, so CAST((0.10000000000000000000001) AS Decimal256(76)) keeps every digit either way.
  • A setting value above UInt64 is a wide integer either way.

Closes: #74312
Related: #121554

Changelog category (leave one):

  • Backward Incompatible Change

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

Numeric literals are now typed by the context they are used in instead of by their spelling. A decimal integer literal that doesn't fit Int64/UInt64 becomes a big integer (UInt128/Int128/UInt256/Int256) instead of Float64, or a Float64 when used with floating-point or Decimal arguments. A literal compared with a Decimal column is parsed exactly from its text, so decimal_col = 1.123456789012345678 and decimal_col IN (...) compare exactly instead of through Float64, and an equality like decimal_col = 1.1 can now use a primary key on that column. Arithmetic with a Decimal column still treats the literal as a Float64. This may change result types and results of queries that relied on Float64 behavior for numeric literals. The behavior is controlled by the new setting enable_context_typed_number_literals (enabled by default); disable it to restore the previous Float64 typing.


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

When a numeric literal overflows Int64/UInt64 (e.g. 100000000000000000000000),
store it as a `NumberLiteral` (unparsed string) instead of Float64 which loses
precision. The actual parsing to a concrete type (UInt128/Int128/UInt256/Int256)
is deferred to when the target type is known.

This fixes silent precision loss in queries like:
  WHERE action_id BETWEEN 100000000000000000000000 AND 100000000000000000000500
- Add `writeText` overload for `NumberLiteral` in Field.cpp (fixes `fieldToString`)
- Guard `convertNumberLiteralToType` with `if constexpr` for float vs int
- Remove heavy IO includes from `FieldVisitorConvertToNumber.h`; throw instead
  of parsing (the real conversion is in `convertFieldToType`)
- Add explicit `safeGet<NumberLiteral>` template instantiation
- Revert unneeded protocol version bump (query is sent as SQL text, server re-parses)
Tests that integer literals exceeding UInt64 range are parsed as UInt128/Int128
instead of Float64, preserving precision for BETWEEN queries and arithmetic.
Extend `NumberLiteral` to also store decimal-point and exponent literals
(3.14, 1e10) instead of eagerly parsing to Float64. The default type from
`FieldToDataType` is still Float64 for backward compat, but the original
text is preserved on `ConstantNode` so that `castNodeToType` can convert
directly from string to the target type (e.g. Decimal) without Float64
precision loss.

Changes:
- Parser: `try_read_float` stores regular numbers as `NumberLiteral` (NaN/Inf stay as Float64)
- `FieldToDataType`: returns Float64 for decimal-looking NumberLiterals, UInt128/Int128 for integers
- `ConstantNode`: saves `number_literal_text` when constructed from a NumberLiteral field
- `castNodeToType`: when source is a NumberLiteral constant, casts from string text directly
- `SettingsFields`: handle NumberLiteral field in settings conversion
Store `NumberLiteral` as String in `ConstantNode` (no Float64 intermediate).
In `resolveFunction`, before function resolution, replace `NumberLiteral`
constants with properly typed values based on the other arguments:

- If comparing with a Decimal column, parse text directly to Decimal
- If comparing with a UInt128 column, parse text to UInt128
- If the value doesn't fit the reference type, use the intrinsic type
- If no reference type, use `FieldToDataType` default (Float64/UInt128)

This fixes precision loss in comparisons like `WHERE decimal_col = 3.14`
where the literal was previously converted Float64 → Decimal, losing
trailing digits.
Store ALL non-special float literals as NumberLiteral (not just integer
overflow). Handle NumberLiteral comprehensively:

- Field::resolveNumberLiteral: converts to Float64 (for decimal) or
  UInt128/Int128/etc (for big integers)
- Field::safeGet<T>: auto-resolves NumberLiteral when accessed as a
  concrete numeric type — this is the systemic fix that handles all code
  paths (settings, index params, background tasks, etc.)
- convertFieldToTypeImpl: resolves NumberLiteral before conversion
- FieldToDataType: delegates to resolveNumberLiteral then infers type
- getFieldFromIndexArgumentAST: resolves before returning
- Analyzer resolveFunction: replaces NumberLiteral constants with
  properly typed constants based on context (Decimal, big int, etc.)
- ConstantNode: saves number_literal_text for Analyzer deferred parsing
- SettingsFields: handles NumberLiteral field type
When a NumberLiteral constant has no reference type (e.g. standalone
SELECT 3.14), reference_type is null. Guard WhichDataType construction
against null by using default_type as fallback.
When resolveNumberLiteral encounters a pure-integer string that doesn't
fit in any wide integer type (e.g. a 309-digit number), fall back to
Float64 via strtod instead of throwing. This preserves the old behavior
for extremely large integer literals.
tryReadIntText silently wraps on overflow for wide integer types.
Verify correctness by roundtrip: parse → writeText → compare with
original digits. This correctly handles boundary values like UInt128
max+1, UInt256 max+1, and numbers too large for any integer type.
Add comprehensive test cases:
- UInt64/Int64 boundary (max, max+1)
- UInt128/Int128 boundary (max, max+1, min, min-1)
- UInt256 boundary (max, max+1 → Float64)
- Negative big integers
- Numbers exceeding all integer types → Float64 fallback
- Decimal precision via deferred parsing
- Positive and negative value preservation
- Int128 column comparisons with big literals

Fix overflow detection: verify wide integer parsing via roundtrip
(parse → writeText → compare) since tryReadIntText silently wraps.
- In resolveFunction, use resolveNumberLiteral (strtod) for non-Decimal
  targets, and String→Decimal direct conversion for Decimal targets.
  This fixes subnormal floats (4.9E-324) which strtod handles but
  readFloatText does not.
- Update 02428_decimal_in_floating_point_literal reference: Decimal IN
  with float literals now uses exact string parsing, fixing false
  positives from Float64 precision loss.
- Update 02124_comparison_betwwen_decimal_and_float reference: same
  improvement in Decimal vs literal comparison precision.
When DataTypeAggregateFunction parses parameters like
meanZTest(1., 1., 0.95), the float literals are now NumberLiteral.
Call resolveNumberLiteral before passing to the aggregate function
factory which calls safeGet<Float64>.
When resolveFunction converts a NumberLiteral to a Decimal reference type,
check if the literal has more decimal digits than the reference scale.
If so, use Decimal256 with the literal's full scale to avoid truncation
that causes false IN matches (e.g. 1.5551 truncated to 1.555).

Restore original reference for 02428_decimal_in_floating_point_literal
(behavior now matches master exactly).

Update 02124_comparison_betwwen_decimal_and_float line 18: the query
  0.1000000000000000055511151231257827021181583404541015625::Decimal256(70) = 0.1
now correctly returns 0 (the exact decimal 0.1 differs from the Float64
approximation). Previously both sides went through Float64 imprecision.

Fix aggregate function parameters: resolve NumberLiteral in
DataTypeAggregateFunction parameter extraction.
The shared helper parseAggregateFunctionParameters (used by arrayReduce,
initializeAggregation, Graphite) extracts literal values from AST for
aggregate function parameters. Call resolveNumberLiteral so float
parameters like aggThrow(0.0001) work correctly.
@Algunenano Algunenano self-assigned this Apr 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0239e91]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, sequential) FAIL
05243_query_condition_cache_top_k_parquet FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) FAIL
05243_query_condition_cache_top_k_parquet FAIL cidb
Stateless tests (arm_binary, sequential) FAIL
05243_query_condition_cache_top_k_parquet FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) FAIL
05243_query_condition_cache_top_k_parquet FAIL cidb
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) FAIL
05243_query_condition_cache_top_k_parquet FAIL cidb
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) FAIL
05239_written_rows_quota_interval_rollover FAIL cidb
00952_insert_into_distributed_with_materialized_column NOT_FAILED cidb
03008_deduplication_cases_from_docs NOT_FAILED cidb
03008_deduplication_insert_into_partitioned_table NOT_FAILED cidb
02912_ingestion_mv_deduplication NOT_FAILED cidb
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) FAIL
05243_query_condition_cache_top_k_parquet FAIL cidb
01168_mutations_isolation_3 NOT_FAILED cidb
Stateless tests (arm_asan_ubsan, azure, sequential) ERROR
05243_query_condition_cache_top_k_parquet FAIL cidb

AI Review

Summary

This PR introduces deferred NumberLiteral parsing so wide integers and Decimal comparisons keep precision, and it has clearly been narrowed to avoid the earlier arithmetic regressions in stored expressions and index keys. I still see one remaining semantic mismatch in the exact-comparison surface: comparison / IN expressions that are stored in table metadata are still analyzed through the legacy ExpressionAnalyzer, so they keep the old Float64 literal semantics while the same query predicate now resolves its literal exactly. That can silently disable pruning / projection matching for those definitions.

Findings

⚠️ Majors

  • [src/Interpreters/resolveNumberLiteral.cpp:160] Exact-Decimal retargeting is still applied to comparison / IN expressions even though KeyDescription, IndicesDescription, and projection keys are still built through the legacy analyzer. A stored expression such as INDEX idx (price = 1.1) or ORDER BY (price IN (1.1, 2.2)) therefore keeps a Float64 RHS in table metadata, while the same predicate in a query now resolves the RHS as an exact Decimal, so expression matching can silently stop and those structures may no longer be used.

💡 Nits

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/102646#discussion_r4224644137] clickhouse-format still exposes only enable_context_typed_number_literals in programs/format/Format.cpp:99-101, so the documented compatibility < 26.10 rollback path is still unavailable for that binary even though the PR description and setting docs describe it as part of the supported surface.
  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/102646#discussion_r4224644141] src/Core/Settings.cpp:9133 still says formatted queries keep a literal’s “original spelling”, but 05218_cast_literal_canonical_text still locks in canonicalization for cases like 1_000 -> 1000, 0xFF -> 255, and +1 -> 1. The wording is still broader than the implementation.
Final Verdict

⚠️ Changes needed before merge: the arithmetic regressions look addressed, but exact comparison / IN expressions stored in keys, skip indexes, and projections still appear to diverge from query-time analysis.

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Apr 14, 2026
Comment thread src/Core/Field.cpp Resolved
Add NumberLiteral resolution in ActionsVisitor for the old analyzer path:
- Before addFunction, check AST arguments for NumberLiteral fields
- When a sibling argument has Decimal type, re-resolve the NumberLiteral
  as Decimal with proper scale (same logic as new analyzer)
- Skip IN/NOT IN functions (second argument is a Set, not a scalar)
- Resolve NumberLiteral in function parameter extraction
- Also resolve in parseAggregateFunctionParameters shared helper

Both old and new analyzers now produce identical results for Decimal
precision tests.
FieldVisitorConvertToNumber, dictionary params, and workload settings

- ConstantExpressionTemplate: resolve NumberLiteral to default type
  before setting data type (fixes 12 VALUES template failures)
- SettingsFields: resolve NumberLiteral via resolveNumberLiteral (not
  stringToNumber) so scientific notation like 1e9 works for int settings
- FieldVisitorConvertToNumber: resolve via strtod+Float64 path instead
  of throwing (fixes Buffer engine params like 1e6)
- Dictionary layout params: resolve before type check
- WorkloadSettings: resolve before safeGet<Float64>
- Old analyzer ActionsVisitor: resolve for function parameters
dictionary params, Decimal scale, and update test references

Core fixes:
- ConstantExpressionTemplate: handle Number field type (12 VALUES failures)
- SettingsFields: resolve via resolveNumberLiteral (13 settings failures)
- FieldVisitorConvertToNumber: resolve via strtod (5 Buffer engine failures)
- Dictionary layout params: resolve before type check
- WorkloadSettings: resolve before safeGet
- Restrict Decimal conversion to comparison functions only (equals, less,
  etc.) to avoid scale overflow in arithmetic (Decimal32(5) * 1.5)

Test updates (use explicit types to preserve original test intent):
- 01065_if_not_finite: toUInt64/toFloat64 for incompatible type test
- 03667_accurate_cast_datetime_overflow: toFloat64 for overflow test
- 01666_gcd_ubsan: toFloat64/toInt128 chain for Float64-approximated values

Reference updates for expected behavioral changes:
- 03456_wide_integer_cross_platform_consistency: Int128 precision
- 03371_dynamic_values_parsing_templates: big numbers as UInt128
- 04098_number_literal_type: regenerated
…nction

- Fix verifyRoundtrip in resolveNumberLiteral: compare the full signed
  string representation instead of negating the value (which overflows
  for Int128_min and Int256_min)
- Resolve NumberLiteral in SimpleAggregateFunction parameter parsing
  for parity with AggregateFunction and parseAggregateFunctionParameters.
  No supported SimpleAggregateFunction currently takes float params, so
  this is a preventive fix.
- Add regression tests for exact Int128_min and Int256_min literals
FieldVisitorConvertToNumber, dictionary params, Decimal scale, and
update test references

Core fixes:
- ConstantExpressionTemplate: handle Number field type
- SettingsFields: resolve via resolveNumberLiteral (handles 1e9 for int settings)
- FieldVisitorConvertToNumber: resolve via strtod instead of throwing
- Dictionary layout params: resolve before type check
- WorkloadSettings: resolve before safeGet
- Restrict Decimal conversion to comparison functions only, and skip
  scientific notation (e.g. 1e-2) since scale cannot be derived from
  exponent form
- Old analyzer: implement deferred parsing in ActionsVisitor with same
  comparison-only restriction, skip IN functions

Test updates (use explicit types to preserve original test intent):
- 01065_if_not_finite: use toUInt64/toFloat64 for type mismatch test
- 03667_accurate_cast_datetime_overflow: use toFloat64 for overflow test
- 01666_gcd_ubsan, 01666_lcm_ubsan: use toFloat64/toInt128 chain

Reference updates:
- 02740_hashed_dictionary_load_factor_smoke: SHOW CREATE now preserves
  the original literal text (0.90 stays as 0.90 instead of being
  normalized to 0.9 through Float64 roundtrip)
- 03456_wide_integer_cross_platform_consistency: Int128 precision
- 03371_dynamic_values_parsing_templates: big numbers as UInt128
- 03978_alter_table_execute_expire_snapshots_parse: AST dump shows
  Number_ prefix instead of Float64_
- 04098_number_literal_type: added scientific notation Decimal test
Update docs/en/sql-reference/syntax.md to document the numeric literal
parsing changes introduced in version 25.5. The docs now clearly
separate pre-25.5 and post-25.5 behavior:

- Wide integer literals (>UInt64) are now parsed as UInt128/Int128/
  UInt256/Int256 natively, without requiring string-based conversion
- Decimal-point literals use deferred type resolution for exact
  Decimal comparisons

Each change is explicitly tagged with version numbers so readers on
older versions understand which behavior applies to them.
Comment thread src/Interpreters/ActionsVisitor.cpp Resolved
dictionary params, Decimal scale, and update test references

Core fixes:
- ConstantExpressionTemplate: handle Number field type
- SettingsFields: resolve via resolveNumberLiteral for both typed and
  custom settings (fixes custom_c showing Number_98.11 instead of
  Float64_98.11 in system.settings)
- FieldVisitorConvertToNumber: resolve via strtod instead of throwing
- Dictionary layout params: resolve before type check
- WorkloadSettings: resolve before safeGet
- Restrict Decimal conversion to comparison functions only, and skip
  scientific notation (e.g. 1e-2) since scale cannot be derived from
  exponent form
- Old analyzer: implement deferred parsing in ActionsVisitor with same
  restrictions, skip IN functions

Test updates (use explicit types to preserve original test intent):
- 01065_if_not_finite: use toUInt64/toFloat64 for type mismatch test
- 03667_accurate_cast_datetime_overflow: use toFloat64 for overflow test
- 01666_gcd_ubsan, 01666_lcm_ubsan: use toFloat64/toInt128 chain
- 00972_geohashesInBox: use toFloat64 for mixed Float32/Float64 test

Reference updates for expected behavioral changes:
- 02740_hashed_dictionary_load_factor_smoke: SHOW CREATE preserves
  original literal text (0.90 stays as 0.90, not normalized to 0.9)
- 03456_wide_integer_cross_platform_consistency: Int128 precision
- 03371_dynamic_values_parsing_templates: big numbers as UInt128
- 03978_alter_table_execute_expire_snapshots_parse: AST dump shows
  Number_ prefix
- 03777_highlight_digit_groups_in_format: 123456e78 preserved as-is
- 04098_number_literal_type: added scientific notation Decimal test
fix custom settings, fix geohashesInBox, fix highlight test

- Extract NumberLiteral-to-typed-Field resolution into shared
  resolveNumberLiteral.h/cpp, used by both new and old analyzers.
  Eliminates duplicated logic for Decimal scale computation, type
  family matching, and fallback handling.
- Guard against Decimal256 scale overflow for literals with >76
  fractional digits (falls back to default Float64 resolution).
- Fix SettingFieldCustom to resolve NumberLiteral on store, so
  system.settings shows Float64_98.11 not Number_98.11.
- Fix 00972_geohashesInBox: use explicit toFloat64 for mixed-type test.
- Fix 03777_highlight_digit_groups_in_format: 123456e78 preserved as-is.
Algunenano and others added 2 commits October 5, 2026 19:16
A literal too wide for `Decimal256` now compares through `Float64` in
every spelling; a wide integer kept `UInt256` and threw `DECIMAL_OVERFLOW`.

In a comparison the literal keeps its own scale but takes the `Decimal`
supertype precision instead of always 76, so it is no wider than needed
and the rescale cannot overflow.

The common-type check moves to each literal, so a mismatched key in a
tuple compared with IN no longer drops the exact type of a `Decimal`
position.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Interpreters/executeQuery.cpp
@Algunenano
Algunenano marked this pull request as ready for review October 6, 2026 15:55
When disabled, every `NumberLiteral` is resolved to the `Float64` the parser produced before, so the context typing does not apply. Tests changed by the literal typing now run the old query with the setting disabled, followed by the new or adjusted query.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: a18386a8-e5ff-46f1-ba4e-6b78dc0d1253
  • MIRAI run: 1f26157e-5181-4473-a576-0ebebdb277ce
  • PR check IDs:
    • clickbench_574465_1791565387
    • clickbench_574471_1791565387
    • clickbench_574494_1791565388
    • tpch_adapted_1_official_574508_1791565387
    • tpch_adapted_1_official_574522_1791565387
    • tpch_adapted_1_official_574536_1791565388

Comment thread docs/reference/syntax.mdx Resolved

@yakov-olkhovskiy yakov-olkhovskiy left a comment

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.

Analyzed by Cursor Agent:

I tested the build_amd_release binary of b557d7ac against the master build of the merge base 252b266b. The later commits only add the enable_context_typed_number_literals gate, which is on by default, so the default behavior is the same as the current head 5509b004.

❌ Blockers

1. Existing table definitions change meaning on upgrade

The description says the old-analyzer path (ActionsVisitor) is "still used by mutations, TTL and DEFAULT expressions" and keeps the previous Float64 semantics. That is not what happens:

  • DEFAULT/MATERIALIZED values are computed at INSERT (and at read time for columns missing from a part) by createExpressionsAnalyzer in src/Interpreters/inplaceBlockConversions.cpp, which runs QueryAnalyzer.
  • Mutations (ALTER UPDATE, MATERIALIZE COLUMN) also produce the new results.

So stored expressions of existing tables pick up the new Decimal semantics after a routine upgrade with default settings.

How I reproduced it: I created the tables with master and inserted a row, then opened the same data directory with the PR build.

-- created with master
CREATE TABLE d.t   (price Decimal64(2), r Float64 DEFAULT price / 3.0, a Float64 ALIAS price / 3.0) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE d.t32 (p Decimal32(5), r Float64 MATERIALIZED p / 1.5) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO d.t (price) VALUES (1);
INSERT INTO d.t32 (p) VALUES (1);

-- then, with the PR binary on the same data directory
INSERT INTO d.t (price) VALUES (1);
SELECT price, r, a FROM d.t ORDER BY r;
INSERT INTO d.t32 (p) VALUES (1);
Case master PR, after upgrade
r Float64 DEFAULT price / 3.0 0.3333333333333333 new rows get 0.33; old rows keep 0.3333… in the same column
a Float64 ALIAS price / 3.0 0.3333333333333333 0.33, for old rows too
r Float64 MATERIALIZED p / 1.5, p Decimal32(5) INSERT works every INSERT fails with DECIMAL_OVERFLOW
z Float64 DEFAULT price / 0.0 inf INSERT fails with ILLEGAL_DIVISION
ALTER UPDATE u = price / 3.0, MATERIALIZE COLUMN m (m DEFAULT price / 3.0) 0.333… 0.33

So one column ends up holding values computed two different ways, the results of ALIAS columns change for data already stored, and INSERTs into existing tables can start failing after the upgrade. Materialized views and row policies take the same path; I did not test them.

Possible fixes:

  • Record the literal semantics when an object is created and use them when it is loaded (resolve its literals as Float64 for objects created before 26.10).
  • Or, as the description already promises, do not apply the non-comparison retargeting to stored table expressions (DEFAULT/MATERIALIZED/ALIAS, mutations, TTL).

Either way, please add a regression test for these expressions.

2. Primary key and skip index pruning stops working for expressions with a decimal literal next to a Decimal column

KeyDescription and IndicesDescription still build their expressions through TreeRewriter/ExpressionAnalyzer, where the literal stays Float64. The query goes through the analyzer, where the same literal becomes a Decimal. The two expressions no longer match, so the index is skipped. This also happens on freshly created tables, not only after an upgrade.

CREATE TABLE t (price Decimal64(2)) ENGINE = MergeTree ORDER BY toInt64(price * 100.0) SETTINGS index_granularity = 2;
INSERT INTO t SELECT number FROM numbers(20);
EXPLAIN indexes = 1 SELECT count() FROM t WHERE toInt64(price * 100.0) = 500;
-- master: Condition: (toInt64(multiply(price, 100.)) in [500, 500]), Granules: 1/10
-- PR:     Condition: true, Granules: 10/10

The same happens with a skip index such as INDEX idx price / 3.0 TYPE minmax GRANULARITY 1: master uses it for WHERE price / 3.0 > 5, but on the PR it is missing from EXPLAIN indexes = 1.

It does not happen for the Float32 narrowing (ORDER BY toInt64(f * 0.5)) or for wide-integer key expressions; both still prune. Partition-key minmax pruning and projection matching probably have the same problem, but I did not verify them.

The result is a silent switch to full scans on tables whose key or index expression contains such a literal. The key and index description paths should type literals the same way the query does. Please add a test with EXPLAIN indexes = 1.

⚠️ Majors

3. Division by a literal next to a Decimal now loses precision

Decimal division keeps the scale of the dividend. Writing / 7.0 instead of / 7 is a common way to force floating-point division, and it now truncates:

SELECT toDecimal64(1, 2) / 3.0;                      -- master: 0.3333333333333333 (Float64); PR: 0.33 (Decimal(18, 2))
SELECT sum(toDecimal64(number, 2)) / 7.0 FROM numbers(3); -- master: 0.42857142857142855;      PR: 0.42
SELECT toDecimal64(1, 2) / 0.0;                      -- master: inf;                           PR: ILLEGAL_DIVISION
SELECT toDecimal32(1, 5) / 1.5;                      -- master: 0.6666666666666666;            PR: DECIMAL_OVERFLOW

This goes against the "precision-preserving" promise in the title. 05243_number_literal_sibling_family_arithmetic pins these results as intended. I'd suggest excluding divide (and probably intDiv/modulo) from the non-comparison retargeting. If the current behavior stays, the changelog entry should state the truncation and the new exceptions explicitly. Right now it only mentions "overflow errors".

4. The description and docs contradict the code in places

  • The ActionsVisitor claim about mutations and DEFAULT expressions (see Blocker 1).
  • "Overflowing binary (0b) literals stay Float64": they are a syntax error on both master and this PR. syntax.mdx already says this correctly.
  • syntax.mdx says "a literal used with non-Decimal arguments are still Float64". But greatest(toFloat32(x), 1.5) is Float32 (while 1.1 stays Float64), as 05242_number_literal_mixed_numeric_siblings shows.
  • The changelog entry should also say that existing DEFAULT/MATERIALIZED/ALIAS expressions, materialized views and mutations pick up the new semantics after an upgrade, and how to keep the old behavior: set enable_context_typed_number_literals = 0 in the default profile, which also covers mutations because they use the default.

@Algunenano

Copy link
Copy Markdown
Member Author

I tested the build_amd_release binary of b557d7a against the master build of the merge base 252b266. The later commits only add the enable_context_typed_number_literals gate, which is on by default, so the default behavior is the same as the current head 5509b00.

Thanks a lot for the reviews. About the issues:

  1. Existing table definitions change meaning on upgrade

It's not an issue, because it respects compatibility:

┌─────────────────────────────┬─────────┬────────────────────────────┬──────────────────────────────┬─────────────────────────────┐
│            Case             │  old    │            head            │ head, compatibility=26.9 in  │     head, session SET       │
│                             │ binary  │                            │       default profile        │    compatibility='26.9'     │
├─────────────────────────────┼─────────┼────────────────────────────┼──────────────────────────────┼─────────────────────────────┤
│ DEFAULT price / 3.0, new    │ 0.333…  │ 0.33 (old rows keep        │ 0.333…                       │ 0.333…                      │
│ row                         │         │ 0.333…)                    │                              │                             │
├─────────────────────────────┼─────────┼────────────────────────────┼──────────────────────────────┼─────────────────────────────┤
│ ALIAS price / 3.0           │ 0.333…  │ 0.33, old rows too         │ 0.333…                       │ 0.333…                      │
├─────────────────────────────┼─────────┼────────────────────────────┼──────────────────────────────┼─────────────────────────────┤
│ MATERIALIZED p / 1.5        │ works   │ every INSERT fails with    │ works                        │ works                       │
│ (Decimal32(5))              │         │ DECIMAL_OVERFLOW           │                              │                             │
├─────────────────────────────┼─────────┼────────────────────────────┼──────────────────────────────┼─────────────────────────────┤
│ DEFAULT price / 0.0         │ inf     │ INSERT fails with          │ inf                          │ inf                         │
│                             │         │ ILLEGAL_DIVISION           │                              │                             │
├─────────────────────────────┼─────────┼────────────────────────────┼──────────────────────────────┼─────────────────────────────┤
│ ALTER UPDATE / MATERIALIZE  │ 0.333…  │ 0.33                       │ 0.333…                       │ 0.33                        │
│ COLUMN                      │         │                            │                              │                             │
├─────────────────────────────┼─────────┼────────────────────────────┼──────────────────────────────┼─────────────────────────────┤
│ MV TO table, VIEW (not      │ 0.333…  │ 0.33                       │ —                            │ 0.333… (view)               │
│ tested by the reviewer)     │         │                            │                              │                             │
└─────────────────────────────┴─────────┴────────────────────────────┴──────────────────────────────┴─────────────────────────────┘

What this means for compatibility:
- In the default profile, compatibility or enable_context_typed_number_literals = 0 restores everything, mutations included.
- At session level it covers INSERT defaults, ALIAS and views, but not mutations, which use the default profile.
- So a DEFAULT value depends on the settings of whoever inserts the row.

The description says the old-analyzer path (ActionsVisitor) is "still used by mutations, TTL and DEFAULT expressions" and keeps the previous Float64 semantics.

Agree, this is incorrect. I think it comes from the beginning of the PR, when analyzer wasn't still being used for mutations. Will fix.

  1. Primary key and skip index pruning stops working for expressions with a decimal literal next to a Decimal column

Agree. If using compatibility it will keep working exactly as now, but when not using it then the index analysis and the query analysis disagree, because KeyDescription (primary/sorting/partition keys), IndicesDescription (skip indices) and TTLDescription still build their expressions with the old analyzer.

I can either teach the old analyzer the new way of handling, or try migrating these modes to the new one. Both have issues (indices created with one meaning, changing to another one). Will have a look at both.

In addition, there is a bug where SELECT * FROM (EXPLAIN ...) and the view() table function both silently use the old Float64 typing.

  1. Division by a literal next to a Decimal now loses precision

Agree, but also respects compatibility and it doesn't "lose precision", instead it changes the the where operations are done to decimal division, because both values are decimal. This is also how other databases work.

  1. The description and docs contradict the code in places

Good points. Will fix.

The analyzer rebuilt the AST of table function arguments it does not
analyze (`view`, `viewIfPermitted`, `viewExplain`) from the query tree,
which wrote untyped number literals as `Float64` values. The table
function then analyzed them with the previous typing: `view` returned
different results than the same query, `viewIfPermitted` rejected its
`ELSE` structure, and `SELECT * FROM (EXPLAIN ...)` showed a plan that
differed from the executed one. Keep the original literal text for
these arguments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only a comparison with a `Decimal` argument now parses a number literal
into a wide `Decimal`. In arithmetic the literal stays a `Float64`, as
before. Keys, skip indices and projections are built by the old
analyzer with `Float64` literals, so a `Decimal` literal in the query
never matched them and they were not used; stored `DEFAULT`, `ALIAS`
and `MATERIALIZED` expressions, materialized views and mutations of
existing tables changed their results; and division by a literal
truncated to the scale of the dividend or threw instead of returning
`inf`.

Restore the tests that pinned the `Decimal` arithmetic to their master
versions and add tests for the stored expressions and index usage.

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

Copy link
Copy Markdown
Member Author

@yakov-olkhovskiy After iterating and trying to find a good way to handle indices, projections, etc on table definitions I didn't see a simple way forward that doesn't involve a huge refactor or a major headache for everyone, so I've decided to limit the scope of this PR instead and keep the usage of NumberLiteral only for IN and comparisons (equal, lt, gt and so on). I've removed it completely for other functions (arithmetics where the main cause here).

We can do that in the future if we need to, probably requiring MT settings, a deprecated old analyzer or some other ideas on how to handle compatibility. Points 1 and 3 from the issues and my responses no longer apply, since the behaviour is fully reverted back.

I'm fixing the other findings, updating description and adding tests that verify the behaviour that works now and would have been broken by the changes if introduced.

Comment thread programs/format/Format.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
…_countmin_numeric_types

The test covers `countmin` statistics on a `Float32` column compared with a
`Float64` constant. Number literals are now typed by context also in an
`EXPLAIN` subquery, so `1.5` next to a `Float32` column became `Float32` and
the test no longer compared against a `Float64` value. Cast the literal to
`Float64` explicitly to keep the original test case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/formatQuery.cpp Resolved
Comment thread src/Functions/parseQueryToJSON.cpp Resolved
@Algunenano Algunenano removed their assignment Oct 9, 2026

/// Only a comparison is retargeted to `Decimal`. Arithmetic keeps `Float64`, so a stored expression
/// (`DEFAULT price / 3.0`) and a key built by the old analyzer compute the same value as before.
if (isDecimal(*ref) && is_comparison)

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.

This still leaves table-definition expressions that are analyzed through the legacy ExpressionAnalyzer out of sync for comparison / IN expressions themselves.

KeyDescription, IndicesDescription, and projection key expressions are still built through TreeRewriter + ExpressionAnalyzer, so a definition like INDEX idx (price = 1.1) or ORDER BY (price IN (1.1, 2.2)) keeps the RHS on the old Float64 path there. The same predicate in a query now comes through this exact-Decimal retargeting branch, so the stored expression and the query expression no longer match even though 05341 now covers the arithmetic cases.

That means pruning / projection matching can still silently stop for tables whose stored expression itself is one of these exact-comparison forms. I think this either needs the same exact-literal handling on the DDL side before enabling comparisons here, or this branch needs to stay on the old Float64 semantics for expressions that must agree with old-analyzer table metadata.

@Algunenano

Algunenano commented Oct 13, 2026 •

Copy link
Copy Markdown
Member Author

🤖 Blocked by #125612.

Projections, skip indices and keys don't follow the settings that change function results: projection data is computed with the settings of the session that inserts it, and a query uses a projection, skip index or key even when its session computes the expression differently.

enable_context_typed_number_literals runs into the same problem. With this PR, a projection on a comparison with a Decimal column (price < 0.1) is not used by queries, because table definitions still type such a literal as Float64 while queries compare exactly. Making table definitions compare exactly too lets the projection match, but it then returns wrong results after an INSERT with the setting disabled, or after the setting changes and the table is attached again, for the same reason as the issue.

This needs a global fix for all such settings, not a special case (a new file in the part) for this one, so this PR waits for it.

@Algunenano
Algunenano marked this pull request as draft October 13, 2026 13:38
@Algunenano

Copy link
Copy Markdown
Member Author

Closing for now to reduce noise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

UInt128 values are ignored in SELECT queries

4 participants