Skip to content

Fix transform default-branch conversion bug (FixedString / Enum) - #104804

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-transform-default-cast-bug
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-transform-default-cast-bug

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

transform's initializeTransformCache built cache->default_column via the Field-level path: convertFieldToType((*default_col)[0], *result_type) followed by default_column->insert(f). The Field abstraction collapses some types: a FixedString value becomes a String Field keeping its raw bytes (no trailing-zero trimming), and an Enum value becomes its underlying integer Field. So when the cached default went through the String representation, FixedString defaults kept their trailing \0 bytes and Enum defaults turned into their numeric storage value -- both disagree with castColumn(default, result_type) (which is what cache->to_column already used for the matched-dst branch).

The matched branch and the default branch must agree, and both must agree with cast(default AS result_type). The fix uses castColumn for cache->default_column the same way cache->to_column does. The onlyNull() path is preserved to keep prior semantics for Nothing/only-NULL defaults (insert the default value of result_type).

This also fixes the caseWithExpression non-determinism reported by FunctionsStress.stress ("broken_determinism: different result on the same input ... while re-executing after making arguments {...} const"): caseWithExpression picks a fast transform path when all WHEN/THEN values are constant and falls back to multiIf otherwise, so the same call flips between paths when the stress test randomizes const-ness of arguments, exposing the inconsistency. The fix is in transform itself, which fixes both the direct transform(...) SQL function and the caseWithExpression fast path.

Original reproducers (now consistent):

SELECT transform(toUInt32(0), [toUInt32(1)], ['a'], toFixedString('b', 3));
-- now 'b' (was 'b\0\0'), agrees with cast(toFixedString('b', 3) AS String) = 'b'

SELECT transform(toUInt32(0), [toUInt32(1)], ['a'], cast('cV1' AS Enum8('cV1' = 42)));
-- now 'cV1' (was '42'), agrees with cast(... AS String) = 'cV1'

SELECT caseWithExpression(materialize(toUInt32(2)), toUInt64(1), 'match', toFixedString('a', 3));
-- now 'a' from both transform and multiIf paths

Linked from #104299 (pointed at by @alexey-milovidov).

CI report (failing FunctionsStress.stress): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104299&sha=af067fba3bc6ebb1b269dff7f023bb2697aa1f94&name_0=PR&name_1=Unit%20tests%20%28tsan%2C%20function_prop_fuzzer%29

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

Fixed transform returning different bytes for its default branch than for matched branches and than CAST. When the default value was a FixedString and the result type was String, trailing \0 bytes were preserved instead of trimmed; when the default value was an Enum and the result type was String, the underlying numeric storage was returned instead of the value's name. Also fixes a related caseWithExpression non-determinism where the result depended on whether WHEN/THEN arguments were const, because the function picks a fast transform path when all are const and falls back to multiIf otherwise.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

`transform`'s `initializeTransformCache` built `cache->default_column` via
the `Field`-level path: `convertFieldToType((*default_col)[0], *result_type)`
followed by `default_column->insert(f)`. The `Field` abstraction collapses
some types: a `FixedString` value becomes a `String` `Field` keeping its raw
bytes (no trailing-zero trimming), and an `Enum` value becomes its underlying
integer `Field`. So when the cached default went through the `String`
representation, `FixedString` defaults kept their trailing `\0` bytes and
`Enum` defaults turned into their numeric storage value -- both disagree
with `castColumn(default, result_type)` (which is what
`cache->to_column` already used for the matched-`dst` branch).

The matched branch and the default branch must agree, and both must agree
with `cast(default AS result_type)`. Use `castColumn` for `cache->default_column`
the same way `cache->to_column` does. The `onlyNull()` path is preserved to
keep prior semantics for `Nothing`/only-`NULL` defaults (insert the default
value of `result_type`).

This also fixes the `caseWithExpression` non-determinism reported by
`FunctionsStress.stress` ("broken_determinism: different result on the same
input ... while re-executing after making arguments {...} const"):
`caseWithExpression` picks a fast `transform` path when all `WHEN`/`THEN`
values are constant and falls back to `multiIf` otherwise, so the same call
flips between paths when the stress test randomizes `const`-ness of
arguments, exposing the inconsistency. The fix is in `transform` itself,
which fixes both the direct `transform(...)` call and the `caseWithExpression`
fast path.

Original reproducers (now consistent):

SELECT transform(toUInt32(0), [toUInt32(1)], ['a'], toFixedString('b', 3));
  -- now 'b' (was 'b\0\0', should agree with cast(toFixedString('b', 3) AS String))

SELECT transform(toUInt32(0), [toUInt32(1)], ['a'], cast('cV1' AS Enum8('cV1' = 42)));
  -- now 'cV1' (was '42', should agree with cast(... AS String))

SELECT caseWithExpression(materialize(toUInt32(2)), toUInt64(1), 'match', toFixedString('a', 3));
  -- now 'a' from both transform and multiIf paths

CI report (`FunctionsStress.stress`):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104299&sha=af067fba3bc6ebb1b269dff7f023bb2697aa1f94&name_0=PR&name_1=Unit%20tests%20%28tsan%2C%20function_prop_fuzzer%29

Pointed at by ClickHouse#104299 .

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260513-081500):

a) Deterministic repro? Yes -- at SQL level:

  • transform(toUInt32(0), [toUInt32(1)], ['a'], toFixedString('b', 3)) returns 'b\0\0' (len 3) on master; should be 'b' (len 1) to match cast(toFixedString('b', 3) AS String).
  • transform(toUInt32(0), [toUInt32(1)], ['a'], cast('cV1' AS Enum8('cV1' = 42))) returns '42' on master; should be 'cV1' to match cast(... AS String).
  • caseWithExpression(materialize(toUInt32(2)), toUInt64(1), 'match', toFixedString('a', 3)) returns 'a\0\0' from the transform fast path and 'a' from the multiIf path (the divergence FunctionsStress.stress complains about).

b) Root cause explained? Yes. transform's initializeTransformCache built cache->default_column with convertFieldToType((*default_col)[0], *result_type) + default_column->insert(f). Field doesn't carry source-column type info -- a FixedString becomes a String Field keeping raw bytes (no trim), and an Enum becomes its underlying integer Field (no name lookup). So cache->default_column ended up with bytes that disagree with castColumn(default, result_type), even though cache->to_column already used castColumn for the matched-dst side. The matched and default branches must agree, and both must agree with cast(default AS result_type).

c) Fix matches root cause? Yes -- replaces convertFieldToType + insert with castColumn, the same mechanism cache->to_column already uses. The onlyNull() branch is preserved (insert result_type's default value) to keep prior semantics for Nothing/only-NULL defaults.

d) Test intent preserved? / New tests added? Existing 13 transform / case-related stateless tests still pass against the fix:

  • 00153_transform, 00165_transform_non_const_default, 01324_if_transform_strings_to_enum, 01704_transform_with_float_key, 01733_transform_ubsan, 02832_transform_fixed_string_no_default, 02958_transform_enum, 00688_case_without_else, 03625_case_without_condition_non_constant_branches, 04005_case_with_expression_nullable_nothing, 04054_caseWithExpression_nullable_when, 04093_case_with_expression_dynamic, 04227_case_with_expression_array_result_78352. New stateless test 04237_fix_caseWithExpression_transform_const_determinism.sql checks transform's default-branch agreement with cast (for FixedString / Enum8 / Enum16 defaults) and caseWithExpression's determinism across const-ness permutations, including the original failing queries reduced from FunctionsStress.stress.

e) Both directions demonstrated? Yes -- the new regression test returns 0 for all 11 assertions against master and 1 for all 11 against the fixed build. Also ran FunctionsStress.stress locally for 30 s over all 1227 testable functions on the fixed build: 0 broken_determinism issues, 0 stuck threads, test PASSED.

f) Fix is general, not a narrow patch? Yes. The fix is in transform.cpp, which is the shared layer:

  • transform's own SQL function -- any user calling transform(x, src, dst, default) where default has a type different from the result supertype was affected (e.g. FixedString default with String-result, Enum default with String-result).
  • caseWithExpression's fast transform path -- it builds the same shape internally, so it hit the same bug.
    Both manifestations are fixed by the same one-place change. Symmetric paths: cache->to_column already uses castColumn; we just align cache->default_column to do the same.

Asking "Why did this bad state arrive here?": the bad bytes came from the Field-level extraction. The Field representation discards source-column type info, which is what made the conversion incorrect. The right level of the fix is to convert at the column level (castColumn), where the source type is still known -- not to teach Field about FixedString width / Enum names, which would be a much larger architectural change touching many call sites.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @alexey-milovidov — could you review this? Fixes a real conversion bug in transform (default branch returns different bytes than cast / matched branch for FixedString and Enum defaults), which also closes the FunctionsStress.stress caseWithExpression non-determinism reported on PR #104299. Fix is 1 file, mirrors what cache->to_column already does.

Comment thread src/Functions/transform.cpp Outdated
default_column->insertDefault();
cache->default_column = std::move(default_column);
{
/// Use `castColumn` (not `convertFieldToType` + `insert`) so the conversion is

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.

No need for this big comment here. After the change the comment about Field usage sounds strange as we don't use it anymore. Let's simplify it as much as possible.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — pushed in 70a6bb6. Stripped the big comment along with the simplification below (the comment described the old Field path which is gone).

Comment thread src/Functions/transform.cpp Outdated
Comment on lines +784 to +787
auto casted = castColumn(arguments[3], result_type)->cut(0, 1);
if (isColumnConst(*casted))
casted = casted->convertToFullColumnIfConst();
cache->default_column = std::move(casted);

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.

I think we can simplify it to:

Suggested change
auto casted = castColumn(arguments[3], result_type)->cut(0, 1);
if (isColumnConst(*casted))
casted = casted->convertToFullColumnIfConst();
cache->default_column = std::move(casted);
cache->default_column = castColumn(arguments[3], result_type)->cloneResized(1)->convertToFullColumnIfConst();

Or there is a problem with this approach?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 70a6bb6 — cloneResized(1)->convertToFullColumnIfConst() works fine. cloneResized(1) on a ColumnConst(N) returns ColumnConst(1), and the subsequent convertToFullColumnIfConst unwraps it; equivalent to the previous cut(0, 1) + explicit isColumnConst check. Re-ran the regression test 50/50 with randomization and the sibling transform tests (00153_transform, 00165_transform_non_const_default) 20/20 each.

@Avogar Avogar added the can be tested Allows running workflows for external contributors label May 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [70a6bb6]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Sort order of blocks violated for column number A, left: B, right: C. Chunk D, rows read E.F (STID: 3413-350b) FAIL cidb

AI Review

Summary

This PR fixes transform default-branch casting by switching cached constant-default materialization to castColumn, which aligns default-path behavior with matched-path behavior and with CAST semantics for FixedString/Enum conversions. I reviewed the current diff, existing discussion threads, and touched code paths/tests; I do not see unresolved contract violations or missing high-impact evidence for this bug fix.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 13, 2026
Per @Avogar's review on ClickHouse#104804 :

- Strip the now-stale comment about `Field` (the previous `convertFieldToType` path
  is gone, so the explanation no longer matches the code).
- Collapse the `cut(0, 1)` + `isColumnConst` check + `convertToFullColumnIfConst`
  sequence into a one-liner using `cloneResized(1)->convertToFullColumnIfConst()`,
  matching the suggestion in the inline comment.

Behavior is unchanged. `cloneResized(1)` on a `ColumnConst(N)` returns
`ColumnConst(1)`; the subsequent `convertToFullColumnIfConst` unwraps it to a
full one-row column — identical to the prior code, just shorter.

Verified locally:
- Regression test `04237_fix_caseWithExpression_transform_const_determinism`
  passes 50/50 with full randomization.
- Sibling transform tests (`00153_transform`, `00165_transform_non_const_default`)
  pass 20/20 each.
- Original `transform` bug repros (`FixedString` default, `Enum` default) still
  produce the corrected output.

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

clickhouse-gh Bot commented May 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing — superseded by @Algunenano's PR #104858 ("Fix more non-deterministic function results found by the functions stress test"), merged into master on 2026-05-15 16:06 UTC.

PR #104858 applies the same fix (castColumn instead of convertFieldToType) to src/Functions/transform.cpp::initializeTransformCache's constant-default path, addressing the same chronic caseWithExpression broken_determinism family our PR was targeting. CIDB verification: zero caseWithExpression failures on master since the merge (24+ hours clean as of 2026-05-16 20:30 UTC).

Same supersession pattern as our PR #104769 → @vitlibar's PR #104812 a few days ago.

Notes for the record:

  • Master HEAD's fix uses castColumn(...)->cut(0, 1) with an isColumnConst check; our last simplification (commit 70a6bb62955) used the one-liner castColumn(...)->cloneResized(1)->convertToFullColumnIfConst() (per @Avogar's review). Functionally equivalent.
  • Master HEAD's regression test 04234_transform_const_default_cast.sql also covers Date/Date32 → DateTime/DateTime64 (which our test didn't). It does NOT exercise caseWithExpression's transform-rewrite path explicitly; ours did. The FunctionsStress.stress broken_determinism check exercises that path too.
  • Our regression test 04237_fix_caseWithExpression_transform_const_determinism.sql is not on master. If reviewers think it adds value beyond 04234, I can open a tiny test-only follow-up — otherwise dropping.

Thanks @Avogar for the simplification feedback.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants