Skip to content

Fix propagation of settings in accurateCastOrDefault - #109946

Merged
Avogar merged 9 commits into
masterfrom
respect-settings-accurate-cast-or-default
Aug 13, 2026
Merged

Avogar merged 9 commits into
masterfrom
respect-settings-accurate-cast-or-default

Conversation

@Avogar

@Avogar Avogar commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

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

Fix propagation of settings in accurateCastOrDefault. Closes #109943

Version info

  • Backported to: 26.7.4.32

`FunctionCastOrDefault` was calling `castColumnAccurateOrNull` which
internally creates a cast function with nullptr context, losing all
query-level settings. Instead, create a `CastOverloadResolverImpl`
in the constructor (which properly holds the context) and use it to
build and execute the cast at runtime.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Avogar Avogar added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5638e24]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04561_ie_join_storage_join FAIL cidb IGNORED
Stress test (arm_release) FAIL
Hung check failed, possible deadlock found FAIL cidb IGNORED

AI Review

Summary

This PR rewires accurateCastOrDefault to use the public cast resolver, so query settings, DataTypeValidationSettings, and DateTime time-zone substitution now line up with CAST and accurateCastOrNull. That part looks correct, but I do not approve yet because the execution path still returns the wrong result for Nullable(T) targets with an explicit default: it cannot distinguish a successful cast to NULL from an actual conversion failure.

Findings

❌ Blockers

  • [src/Functions/castOrDefault.cpp:162-209] [dismissed by author -- https://github.com/Fix propagation of settings in accurateCastOrDefault #109946#discussion_r3589762457] The loop still treats every 1 bit in cast_result_nullable.getNullMapData() as “conversion failed” and substitutes the explicit default. That also catches valid source NULLs when the target itself is Nullable(T), so accurateCastOrDefault(NULL, 'Nullable(UInt32)', CAST(42, 'Nullable(UInt32)')) still returns 42 instead of NULL. Suggested fix: preserve the source-null map separately from real cast failures, or otherwise bypass default substitution for rows that were already NULL, and add a regression covering the explicit-default case.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Preserve successful source NULLs for Nullable(T) targets even when accurateCastOrDefault is called with an explicit default.
  2. Add a focused regression test for that scalar Nullable + explicit-default case.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.80% -0.10%

Changed lines: Changed C/C++ lines covered: 25/27 (92.59%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 9, 2026
Comment thread src/Functions/castOrDefault.cpp Resolved
Comment thread src/Functions/castOrDefault.cpp Resolved
The previous fix used `createInternalCastOverloadResolver` which sets
`internal=true`, causing permissive `DataTypeValidationSettings` and
skipping timezone substitution. Rename to `createCastOverloadResolver`
with `internal=false` so that query-level settings like
`allow_suspicious_fixed_string_types` and timezone from DateTime
sources are properly respected.

Also delegate `getReturnTypeImpl` to the resolver so type validation
and timezone substitution are applied consistently in both
`getReturnTypeImpl` and `executeImpl`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@antonio2368 antonio2368 self-assigned this Jul 13, 2026
Avogar and others added 2 commits July 15, 2026 15:25
…:ClickHouse/ClickHouse into respect-settings-accurate-cast-or-default
When the target type is already `Nullable` (e.g. `Nullable(Bool)`), the
`accurateOrNull` resolver does not add another `Nullable` wrapper.
The unconditional `removeNullable` then incorrectly strips the
user-requested `Nullable`, making the return type non-nullable and
causing failed casts to return the inner type's default value (e.g.
`false`) instead of NULL.

Fix by parsing the user-specified target type and re-applying
`makeNullable` when it was explicitly `Nullable`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Functions/castOrDefault.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 28.60% 85.90% +57.30%
Functions 39.40% 92.70% +53.30%
Branches 20.60% 78.10% +57.50%

Changed lines: Changed C/C++ lines covered: 25/27 (92.59%) · Uncovered code

Full report · Diff report

Avogar and others added 4 commits August 5, 2026 15:44
…:ClickHouse/ClickHouse into respect-settings-accurate-cast-or-default
…:ClickHouse/ClickHouse into respect-settings-accurate-cast-or-default
The test accesses the `json.d` subcolumn, which is only resolvable by the
analyzer; under the old analyzer it fails with `UNKNOWN_IDENTIFIER`. Set
`enable_analyzer = 1` so the test always runs against the analyzer.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Aug 11, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 11, 2026
@Avogar
Avogar added this pull request to the merge queue Aug 11, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Dear @antonio2368, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@Avogar
Avogar added this pull request to the merge queue Aug 13, 2026
Merged via the queue into master with commit 5f7379d Aug 13, 2026
177 of 180 checks passed
@Avogar
Avogar deleted the respect-settings-accurate-cast-or-default branch August 13, 2026 18:43
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 13, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 13, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 13, 2026
Backport #109946 to 26.7: Fix propagation of settings in `accurateCastOrDefault`
@alexey-milovidov

Copy link
Copy Markdown
Member

Reverted due to a bug: #114769

alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Aug 17, 2026
The `-- MATERIALIZED default whose cast overflows` arm took its expected
value from `toDateTimeOrDefault`, so it asserted that a `to<Type>OrDefault`
function honours `date_time_overflow_behavior`. That only holds while
ClickHouse#109946 is in the tree. It is reverted on master by ClickHouse#114911, where
`FunctionCastOrDefault` goes back to `castColumnAccurateOrNull` with a null
context and therefore always saturates. The arm passes on this pull
request's base, which predates the revert, and fails against master:

  2149-06-06  2013-04-29 17:31:44   expected, wrap-around
  2149-06-06  2106-02-06 00:00:00   actual, saturating

That is why the private sync reported this test as the only new failure,
in every stateless job it ran in, while the public checks stayed green.

Spelling the conversion as an explicit `CAST` pins the arm to
`CastOverloadResolverImpl`, which is what this change is about, and makes
it read the same before and after the revert. Verified against three
binaries - master `d59f2be34ed3` with the revert in effect, this pull
request's head, and the private sync build - all of which reproduce the
reference byte for byte. The reference file is unchanged.

Related: ClickHouse#109946
Related: ClickHouse#114911
Related: ClickHouse#114912

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 18, 2026
CastOverloadResolverImpl inherited WithContext, which holds only a
weak_ptr<const Context>, and buildImpl passed getContext() to
createFunctionBaseCast. That is safe only during analysis, while a caller
still holds a strong ContextPtr.

PR ClickHouse#109946 made FunctionCastOrDefault store that resolver as a member and
call build() at execute time. The ActionsDAG keeps the resolver alive but
nothing keeps its context alive, and both affected paths build the DAG from
a function-local Context::createCopy that dies on return
(inplaceBlockConversions.cpp for materialized-column defaults,
MutationsInterpreter.cpp for mutations). Evaluating such a stored expression
later throws LOGICAL_ERROR "Context has expired": an exception in release
builds, a server abort under debug and sanitizer builds. The AST fuzzer hit
it on two unrelated PRs within five minutes of that merge, and the signature
has no prior occurrence in 90 days of CI history.

Capture the conversion settings in the resolver's constructor, while the
context is alive, and have buildImpl consume that snapshot. FunctionCast used
its ContextPtr for nothing but building the same FunctionConvertSettings, so
this moves an existing snapshot one step earlier in the same call chain
rather than introducing a new one. The resolver now holds no context at all,
so the WithContext exception for this file in various_checks.sh is removed.

The two build paths keep their distinct DateTimeOverflowBehavior: Saturate
for createInternalCast, Ignore for buildImpl, the sentinel that defers to
date_time_overflow_behavior. Sharing one snapshot between them would
silently change date-time conversion, so they are built separately.

The snapshot is threaded as a shared_ptr so that CastOverloadResolver.cpp can
keep forward-declaring the factory instead of including the whole of
FunctionsConversion.h.

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 24, 2026
Edited following .claude/skills/edit-changelog/SKILL.md, by hand on a
workstation: the editing step of the NightlyChangelog job has been failing
its own verification since 2026-08-12, so three raw blocks had accumulated
(47 + 84 + 628 entries).

Of the 759 raw entries, 482 are integrated into the in-progress 26.8 section
and 277 are dropped:

- Section 3: the 300 `NOT FOR CHANGELOG / INSIGNIFICANT` entries are dropped,
  except 41 that describe a user-visible change and are promoted into a real
  category, among them a server abort on a corrupt `ORC` stripe footer
  (#114924), `EXPLAIN ANALYZE` for streaming queries (#112445), `SELECT` from
  `TimeSeries` (#115622), streaming watermarks (#106169), and the
  `clickhouse-local` CORS overrides (#115129).
- Section 2: every revert in the range cancels out inside it, so neither side
  appears. Two are re-applications: #114912 re-applies the
  `accurateCastOrDefault` fix, so #109946 keeps its entry with both links and
  the intervening revert #114911 is gone; #114409 re-applies the PromQL
  streaming plan, recorded on the #113656 entry.
- Section 4: `Build/Testing/Packaging Improvement` keeps the seven entries a
  user, packager or from-source builder notices (musl `getaddrinfo` and
  `sched_getcpu`, signed macOS artifacts, Debian packages for release builds
  only, zstd-compressed Docker layers, `unit_tests_dbms` without the full
  library set, vendored Rust built with optimizations locally) and drops the
  CI plumbing.
- Sections 5 and 6: bare pull request URLs converted to links, settings put
  in backticks, four entries rewritten from developer notes into user-visible
  descriptions, and three moved into `Performance Improvement`.

No entry of a strict-retention category was deleted: the job's own
`verify_edit` passes on this edit.

Not done here, because the release manager does it at release time: the full
significance sort, the aggressive merging of sibling pull requests, and the
`FIXME` release date and presentation links.
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Address review: `resolve_reverted_originals` granted deletion credit to every
raw-block revert with a `Reverts owner/repo#N` marker, even when that revert
was itself reverted later in the same range — so an edit dropping `#109946`
(reverted by `#114911`, which `#114912` reverted in turn) still passed
verification while the fix ships in the release.

Now the resolved reverts are walked in descending PR-number order (a revert
always has a higher number than its target): an uncancelled revert cancels
the reverts it targets and only uncancelled reverts contribute deletion
credit. Because a revert of a revert made through the web UI can lack the
body marker (`#114912` has none), the target is also resolved from the
nested title — `Revert "Revert "X""` binds to the earlier range revert
titled `Revert "X"`.

PR: #116221

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
`verify_edit` was only net-effect aware inside one raw block, while the job
edits a release cycle in ~30 nightly increments and a revert chain routinely
spans them:

1. run N integrates `#109946`;
2. run N+1 sees `#114911` and deletes `#109946`;
3. run N+2 sees only raw `#114912`.

On run N+2 nothing disappears in the edit — `#109946` went away the previous
day — so verification passed with a shipped fix missing from `CHANGELOG.md`,
and the editing agent had no way to know the entry ever existed: it is gone
from the file, and the intervening revert is gone from the raw blocks.

The branch now carries that memory itself, in trailers on its own edit
commits, the same way `Changelog-generated-up-to:` carries the generation
point:

    Changelog-revert: <revert> <reverted> <title of the revert>
    Changelog-deleted-entry: <pull request> <its bullet as it was deleted>

`analyze_reverts` resolves each run's reverts against that ledger and reduces
the *cumulative* graph, so a chain spread over several runs behaves exactly
like one arriving in a single raw block, at any depth:

- the reduction is what decides deletion credit, so a cancelled revert
  licenses nothing;
- an entry recorded as deleted whose revert is no longer uncancelled has to
  be back in `CHANGELOG.md` — `verify_edit` fails the run while it is not,
  and the prompt asks for it by name, quoting the bullet from the ledger;
- the recorded titles also let a web-UI `Revert "Revert "X""` (which carries
  no `Reverts owner/repo#N` marker) bind to an earlier revert the job saw
  days ago.

A branch whose edit commits predate the trailers has an empty ledger and
keeps the previous behaviour.

`ci/tests/test_changelog_nightly_revert_ledger.py` pins the timelines: the
whole chain in one block, the revert alone, the revert of the revert arriving
after the deletion, a revert of the re-apply, an empty ledger, and an
unresolvable revert.
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
The restore path asked whether `/pull/<pr>)` appears anywhere in the
in-progress section, which a bare link inside somebody else's bullet
satisfies: a `This closes` reference, or a follow-up named in prose. The
entry then never comes back as its own attribution and `verify_edit` accepts
the edit. `entry_placement` had the same hole from the other side - it fell
back to a merely mentioning bullet, so the category check read the category of
an unrelated entry.

This is not theoretical: the current `CHANGELOG.md` links 17 pull requests
that way without ever attributing them, while exactly one of its 4165 bullets
carries a link and no attribution at all. The attribution
`[#N](.../pull/N) ([Author](...))` is what the generator emits for every entry
and what a merge (skill section 7) appends per merged pull request, so
requiring it costs nothing and is what "the entry is there" means.

`is_attributed` is now the test for all three restore questions - is the entry
missing, is a sibling's bullet still there to merge into, and (through an
attribution-only `entry_placement`) which category it landed in.

`test_an_inline_mention_does_not_stand_in_for_the_restoration` drives
`verify_edit` with a section whose only occurrence of `#109946` is a mention
inside a bullet attributed to `#120000`: rejected, and accepted once the real
entry is there beside it.
`test_a_sibling_only_mentioned_inline_is_not_a_bullet_to_merge_into` covers
the sibling side. Both fail without the fix.
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
**The retention path judged entries by any link, the restore path by
attribution.** The previous commit fixed the restore side only, so a strict raw
entry still counted as preserved when another bullet merely mentioned its pull
request in prose — and `revert_licensed_deletions` then had no attributed
bullet to snapshot, making the entry unrecoverable as well as gone. Both halves
of `disappeared_entries` now use the attribution, which also removes a
spurious failure in the other direction: rewording a bullet and dropping an
inline reference to another pull request is not the loss of that pull
request's entry.

**A restoration did not have to record the pull request that re-applied the
change.** Skill section 2.5 appends its link to the entry, and that link is
the only trace of the re-apply left in the release, since its own revert
bullet is deleted. Restoring a bare `#109946` without `#114912` passed.
`verify_edit` now requires it, on the bullet the entry landed on rather than
somewhere in the section, and only for this run's restorations — a later edit
may reword the entry.

**The duplicate guard compared sets of duplicated pull requests.** An entry
already written twice could gain a third copy without changing the set.
`duplicate_attributions` becomes `attribution_counts`, and the check is
`count > max(1, count before the edit)`: no increase is allowed, while the
count an edit inherits is left alone (removing an entry is what the retention
rule forbids).

Four tests added; each fails without its fix.
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
`reapplied_by` walked one level out from the direct remover, so it found the
revert that first put a change back and stopped there. With
`#109946` ← `#114911` ← `#114912` ← `#115500` ← `#116000` — out, back, out,
back, all inside one cycle — it reported only `#114912`, which the recorded
bullet already carried from the first restoration. The re-apply check was
therefore satisfied by the stale line and `#116000` was lost for good: a
revert of a revert has no bullet of its own, so the link on the entry is its
only trace in the release.

`revert_chain` now walks the whole chain above the entry, and the uncancelled
reverts of that chain are the ones that ship, so they are the ones that belong
on the bullet. `removed_by` is the complement — the cancelled ones — which also
makes the prompt name both removals of a repeated cycle instead of the first.
The three-pull-request case is unchanged: one remover, one re-applier.

The prompt asks for the links of every re-applier, noting that some may
already be on the recorded line from an earlier restoration.

`test_a_longer_chain_records_every_reapply` walks the five-pull-request
timeline and asserts `removed_by == ['114911', '115500']`,
`reapplied_by == ['114912', '116000']`, that replaying the recorded line is
rejected for missing `#116000`, and that appending it passes. It fails with
the one-level walk.
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
…llow them

Two fail-open paths, both from the verifier only ever checking one direction.

**`credits` allowed a deletion but never required it.** An uncancelled revert
made the disappearance of an entry acceptable; leaving the entry in place was
acceptable too, so a change that is out of the release could be published. The
`withheld` check now covers all of `credits`, not only the entries an earlier
run had already deleted: a revert arriving today licenses a deletion the agent
still has to make. With the fix and its revert in one raw block, keeping the
entry now fails with `Entries whose revert still stands are in the in-progress
section (['#109946 (reverted by #114911)'])`.

**The re-apply link was only required of entries being restored.** When the
whole chain arrives in one raw block the entry never left the section, so
`missing` is empty and the link went unchecked - the same loss as before, by a
different route. The requirement is now stated for every entry that ships and
was ever reverted, and checked wherever that entry sits. The prompt gets the
matching "Entries to amend" list, so it asks for exactly what the verifier
requires; the cancelled revert left visible next to such an entry is caught by
the first fix.

Two tests added, the ones the review asked for, plus the "cancelled revert
still visible" variant. `changelog()` in the tests now builds a raw block with
several `#### Category` sections, the shape the generator really emits, so the
same-range case can put the fix under a strict category and its revert under
`NO CL ENTRY`.
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Aug 28, 2026
The editing step of the `NightlyChangelog` job has been failing its own
verification every night since 2026-08-12, always the same way:

    Entries disappeared in the edit without a matching revert (['103182', '109946'])

`verify_edit` requires that every raw entry of a strict-retention category
keeps its pull request link - an entry may be rewritten, merged or moved, but
not dropped, because the generation point has already moved past it and no
later run will offer it again. The prompt never said so, and the skill stated
the rule only implicitly, so the agent pruned entries it judged
insignificant: `ClickHouse#103182` (`Lightweight Updates v2`, a `Backward Incompatible
Change`) was deleted outright.

The second half of the same failure is the revert handling. `ClickHouse#109946` fixed
the propagation of settings in `accurateCastOrDefault`, `ClickHouse#114911` reverted
it, and `ClickHouse#114912` reverted that revert - all three in one range. The skill
covers this in section 2.5, but the agent reached the "landed and then
reverted, so delete both" rule first and lost a fix that ships.

So:

- The prompt now lists the strict-retention categories (from
  `STRICT_RETENTION_CATEGORIES`, so the two cannot drift apart), says which
  entries may be deleted and why deleting anything else is unrecoverable, and
  states the revert-of-revert rule.
- The skill gets a retention rule ahead of the individual edits, and the
  walk over `NO CL ENTRY` checks whether a revert is itself reverted before
  it concludes that a change was reverted. The `accurateCastOrDefault` chain
  is written out there as the worked example.
- A retry now tells the agent why the previous attempt was rejected. Without
  it, all three attempts of a run reproduced the same edit and the same
  rejection - visible in every run from 2026-08-12 on.

A hand edit that followed these rules passed `verify_edit` on the first try,
which is how the 26.8 backlog (759 raw entries) was cleared in
ClickHouse#111720.

Related: ClickHouse#111720
Related: ClickHouse#116138
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

accurateCastOrDefault to JSON ignores json_type_escape_dots_in_keys, splitting dotted keys

5 participants