Skip to content

Propagate non-type exceptions from FunctionDynamicAdaptor - #121280

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-dynamic-adaptor-propagate-non-type-exceptions
Sep 25, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-dynamic-adaptor-propagate-non-type-exceptions

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #102855
Related: #115982

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 FunctionDynamicAdaptor reporting LOGICAL_ERROR for a function over a Dynamic column when an unrelated exception, such as MEMORY_LIMIT_EXCEEDED, was raised while converting the nested result to the declared result type. Such exceptions now keep their own error code, message and stack instead of being reported as an internal error.

Description

ExecutableFunctionDynamicAdaptor::executeImpl calls castColumn to reconcile a nested function's result type with the one it declares for Dynamic arguments. Three of those calls wrapped every DB::Exception the cast could raise into LOGICAL_ERROR without inspecting e.code(). That check runs in the Exception constructor, so no caller can intercept it: a debug or sanitizer server dies, and a release build reports code 49 for what is code 241, burying the OOM signal.

Observed on master in Stress test (arm_asan_ubsan) for a1cfa11 (report), where an injected memory-tracker fault surfaced as:

Logical error: 'Cannot convert nested result of function upper with type String to the
expected result type FixedString(1048577): Query memory tracker: fault injected. ...'

That message prints its two type names in swapped slots: the cast runs FixedString(1048577) to String.

#102855 fixed the identical defect in the sibling FunctionVariantAdaptor, guarding all seven of its cast sites. This applies that guard verbatim to the three the Dynamic adaptor still has unguarded, on master and on every release branch from 24.10 to 26.9.

Nothing is downgraded: the four type-conversion codes are still relabelled, so a value-dependent failure reporting one still becomes LOGICAL_ERROR. Only the first site is observed in CI; the other two are fixed for consistency, and the four castColumn calls that carry no relabel are left alone, since wrapping them would add abort paths.

New test 05233_dynamic_adaptor_propagate_exceptions covers all three sites with a real max_memory_usage aimed inside the cast; each case reproduces the message above on an unfixed binary.

CIDB: the two nested-exception classes behind this shared message (90 days)
SELECT multiIf(position(test_context_raw, 'fault injected') > 0
            OR position(test_context_raw, 'memory limit exceeded') > 0,
               'RESOURCE: memory', 'TYPE: illegal type') AS nested_class,
       count() AS rows_,
       countIf(head_ref = 'master' AND pull_request_number = 0) AS true_master,
       uniqExactIf(pull_request_number, pull_request_number > 0) AS distinct_prs,
       min(check_start_time) AS first_seen, max(check_start_time) AS last_seen
FROM default.checks
WHERE test_name LIKE '%Cannot convert nested result of function%'
  AND test_status IN ('FAIL', 'ERROR')
  AND check_start_time > now() - INTERVAL 90 DAY
GROUP BY nested_class ORDER BY rows_ DESC
nested_class        rows_  true_master  distinct_prs  first_seen           last_seen
TYPE: illegal type  95     5            78            2026-07-08 14:17:56  2026-09-14 20:46:37
RESOURCE: memory    1      1            0             2026-09-21 02:36:11  2026-09-21 02:36:11

The TYPE class is the JSON_EXISTS-over-Dynamic divergence that #109944 fixed at the call site;
it is still arriving, which is why the LOGICAL_ERROR relabel is narrowed here rather than removed.
The RESOURCE row is this defect.


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

Version info

  • Merged into: 26.10.1.675-master (included in 26.10 and later)

ExecutableFunctionDynamicAdaptor::executeImpl reconciles a nested function's
actual result type with the type it declares for Dynamic arguments by calling
castColumn. Three of those calls wrapped every DB::Exception the cast could
raise into LOGICAL_ERROR without inspecting e.code(), so a resource or
cancellation error raised inside the cast was reported as an internal invariant
violation: on a debug or sanitizer build the Exception constructor then reaches
abortOnFailedAssertion and kills the server, and on a release build the user
gets code 49 for what is actually code 241, which also buries the OOM signal.

Observed on master in Stress test (arm_asan_ubsan) for commit a1cfa11,
where a stress-injected memory-tracker fault surfaced as

  Logical error: 'Cannot convert nested result of function upper with type
  String to the expected result type FixedString(1048577): Query memory
  tracker: fault injected. ...'

The same defect was fixed in the sibling FunctionVariantAdaptor by ClickHouse#102855,
which guarded all seven of its cast sites. This applies that guard verbatim to
the three relabel sites the Dynamic adaptor still had unguarded. Only the four
type-conversion error codes are still relabelled, so the diagnostic for a real
adaptor type-contract bug is preserved byte for byte, and every other exception
keeps its own code, message and stack.

The four remaining castColumn calls in the file (the isDynamic(result_type)
paths) are deliberately left alone: they carry no relabel, so they cannot
misclassify anything, and wrapping them would add new abort paths.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings; coverage: all three
changed files in full, both adaptor implementations end to end, the generic function callers,
castColumn, the related tests, plus 10 runs of the new test and inspection of all three
cast-site stacks). My own cold review of the resulting code raised 3 nits, 0 blockers, 0 majors.

# Sev Finding Verdict Evidence / action
1 💡 The relabel message prints its two type names in swapped slots, so the quoted CI text reads backwards: the cast is FixedString(1048577) to String (FunctionDynamicAdaptor.cpp:191, :307, :539) AGREE, not fixed here Pre-existing, outside this diff, identical at the 7 sibling sites; fixing it would edit already-merged code. FunctionStringToString.h:51-65 gives the real direction, and the PR body states the swap so the quote cannot be misread.
2 💡 A value-dependent cast failure reporting one of the four type-conversion codes is still relabelled AGREE, deliberate castColumn has no build/exec split and those codes are polysemous, so narrowing further would drop the diagnostic for the invariant it exists to report. Not reproduced, and absent from CIDB. Stated in the PR body.
3 💡 The oracle is a memory-accounting threshold, so on a build whose accounting differs enough the limit can trip before the guarded cast and the case would pass without exercising it AGREE, no change It fails safe: vacuous, never red. The merged sibling 04101 carries the same property, and the three blockNumber() reference rows pin fixture drift.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Two claims I re-measured independently rather than taking from the write-up, since both decide
whether this PR is correct as scoped:

  • All three relabel sites, and only those, need the guard. The 4 bare castColumn calls carry
    no relabel, so they cannot misclassify, and grep -rn "Cannot convert nested result" src/ hits
    only these two adaptors. The codes the guard rethrows are exactly those an outer
    try_build/try_execute does not swallow into an all-NULL result, so it cannot turn a loud
    failure into a silent one.
  • The stable-release category. Per-site census on release branch 26.9: relabel sites at 185,
    297 and 525, the only two bare throw; at 84 and 111 (both try_build/try_execute lambdas).
    So 3 relabel sites, 0 guarded, on a shipped branch.

Session id: cron:clickhouse-review-slot-10:20260921-053006

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, no fault injection: SELECT upper(d) FROM t SETTINGS max_memory_usage = 120000000, max_threads = 1, max_untracked_memory = 0 over a Dynamic column holding FixedString(1048577). Reproduced on every attempt across the whole verified window per site (A [70, 200] MB, B [150, 260] MB, C [80, 220] MB); outside it the limit trips before the cast.
b Root cause explained? FunctionStringToString declares String as its Dynamic result type but returns FixedString(N) for a FixedString(N) variant, so executeImpl legitimately calls castColumn to build a String column of the same byte width, which is the query's peak allocation. The surrounding catch (const Exception & e) did not inspect e.code() and relabelled MEMORY_LIMIT_EXCEEDED as LOGICAL_ERROR; that check runs in the Exception constructor, so no caller can intercept it.
c Fix matches root cause? Yes, at the throw site, the only place that still holds e.code(): rethrow unchanged unless the code is one of the four type-conversion codes. No widened bound, no size reduction, no tag, no symptom guard.
d Test intent preserved / new tests added? New test 05233_dynamic_adaptor_propagate_exceptions (.sql + .reference), mirroring the merged sibling 04101_variant_adaptor_propagate_exceptions: one case per relabel site asserting serverError MEMORY_LIMIT_EXCEEDED, plus a block-count pin and a positive control per fixture. No existing test weakened.
e Both directions demonstrated? Yes, on two Build-ID-verified binaries (unfixed b135f7d0, fixed c664e08a). Unfixed: all three cases exit 134 with Logical error: 'Cannot convert nested result of function upper ...' at FunctionDynamicAdaptor.cpp:185 / :297 / :525. Fixed: all three return code 241, the server stays up, and the whole file gives [ OK ] 0.74 sec.
f Fix is general across code paths? All three relabel sites are fixed in one push, not just the CIDB-observed one; the sibling FunctionVariantAdaptor was already guarded 7/7 by #102855, so every site in both files now carries a guard. The four castColumn calls that carry no relabel are deliberately left alone: wrapping them would add new abort paths.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes by construction: the guard tests only e.code(), so it is independent of type, wrapper and value (Nullable, LowCardinality, Const and Sparse are unwrapped above this frame by IFunction.cpp). The three fixtures still cover the distinct column shapes that reach these sites: a variant without NULLs, one with NULLs (observed types Nullable(...)), and multiple FixedString widths.
h Backward compatible? Yes. No setting, no serialization, no ABI, no header; SettingsChangesHistory.cpp correctly untouched. The only observable change is an error code becoming more accurate, from 49 to the exception's real code.
i Invariants and contracts preserved? Yes. The invariant is that this catch may relabel as LOGICAL_ERROR only when the exception reports the two types were not convertible; the guard states exactly that. throw; preserves the original code, message and stack instead of flattening them into e.message(). 14 insertions, 0 deletions, so the existing LOGICAL_ERROR path and its format string are unchanged. No lock, allocation or ownership contract is touched.

Session id: cron:clickhouse-impl-slot-6:20260921-041800

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b80c9cf]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
space_filling_curve #1 FAIL dashboard IGNORED

AI Review

Summary

This PR centralizes the nested-result cast/relabel logic shared by the Dynamic and Variant adaptors and fixes the original FunctionDynamicAdaptor bug by rethrowing non-type exceptions unchanged. I reviewed the current diff, the surrounding code in both adaptor implementations, the existing review thread, and the current PR discussion, and I did not find any remaining correctness, compatibility, or coverage issues in the updated implementation.

Final Verdict

✅ Approve. The current code matches the PR's contract, the helper extraction preserves the previously reviewed Variant behaviour while fixing the Dynamic path, and the regression coverage is adequate with 05233_dynamic_adaptor_propagate_exceptions plus the existing 04101_variant_adaptor_propagate_exceptions. Residual risk is low and mostly limited to the inherently memory-window-sensitive nature of these regression tests, but PR #121280 is currently all-green in CI.

LLVM Coverage Report

Measured on commit b80c9cf.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 37/54 (68.52%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... labels Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 0871868906ccf86395e004f10021ecdef5568500 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 31dae11

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Segmentation fault (STID: 3422-39ed) trunk crash, not from this diff: a null planner_context is dereferenced by PlannerContext::getQueryContext inside buildQueryTreeDistributed (src/Storages/StorageDistributed.cpp:773, reached from StorageDistributed::read at :893), on the old interpreter path through ExecuteScalarSubqueriesMatcher::visit, so a scalar subquery over a Distributed table crashes. The STID carries 4 rows on 4 unrelated pull requests, all on 2026-09-21 between 08:55Z and 12:40Z, 0 on true master, and the same buildQueryTreeDistributed frame carries 3 distinct STIDs on 7 pull requests since 2026-09-17. This PR changes only exception propagation in FunctionDynamicAdaptor a fix task is created and already at full effort in review (fixing-PR link to follow on this PR)
Performance Comparison (arm_release, master_head, 2/6) / optimize_time_filter_with_preimage #6 measurement verdict, not a slowdown from this diff: the shard reports 3 too long, 1 slower, 3 unstable; 1 confirmed regression(s) on the performance dashboard, and that same query carries the slower verdict on 228 rows over 107 distinct pull requests in 14 days, including 10 true-master rows over 5 master commits #121189 (mine, open) for the lost per-query thresholds, with #121090 (mine, open) for the dashboard-verdict gate
Sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR aggregator statuses mirroring the rows above the two fixing PRs above plus a fix task is created

Gates (a) to (d): 0 of 176 check runs queued or running, Config Workflow, Style check and Finish Workflow all success, 192 min since the last job finished (anchor 2026-09-21T11:02:17Z), and every failing row above has an owner.

Session id: cron:our-pr-ci-monitor:20260921-140539

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Segmentation fault (STID: 3422-39ed) row of the ledger above: #121418. It moves the scalar-subquery producer in ExecuteScalarSubqueriesVisitor onto InterpreterSelectQueryAnalyzer, so a SelectQueryInfo reaching StorageDistributed::read carries a planner context again.

@Algunenano Algunenano self-assigned this Sep 24, 2026
The type-error guard, and the LOGICAL_ERROR relabel it guards, were written at
all three cast sites. castNestedResult() now holds both, so each site is one
call and the file is shorter than it was before the guard was added. Requested
in review.

The relabel also filled the message's two type slots the wrong way round (the
expected result type was printed as the type being converted); the helper
reports the type it casts from. Nothing else changes: MEMORY_LIMIT_EXCEEDED
still reaches the caller with its own code from all three sites, and a genuine
type mismatch is still LOGICAL_ERROR.
Requested in review: one common helper, so a new error code or a new case is
edited in one place. castNestedResult() and the type-mismatch predicate it
needs now live in Functions/castNestedResult.h, and both adaptors use them:
three relabel sites in the Dynamic one, seven in the Variant one, plus the
four-code predicate their build/execute fallbacks repeated. The two .cpp files
lose 168 lines and gain 18.

The helper is header-only on purpose. A new .cpp under src/Functions lands in
clickhouse_functions, while both callers are extracted into dbms by
DBMS_FUNCTIONS, so the fuzzer targets (which link dbms alone) would not resolve
it.

Behaviour is unchanged. The seven Variant messages now all name the source type
in the "with type" slot: four of them already did, three had the two names
swapped.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b80c9cf

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) / space_filling_curve #1 false red of the dashboard gate: client_time 0.8167 -> 0.9396 (+15.0%), tier confirmed_regression, while the shard's own report agrees with nothing. Its info string is 4 too long; 1 confirmed regression(s) on the performance dashboard, with no slower and no unstable query, and all 1434 per-query rows this shard wrote to CIDB are success, so perf_dashboard_gate was the only red-maker. This PR cannot reach that query: the fixture is SELECT sum(mortonEncode((1, 2), number, number * 2)) FROM numbers(120000000) over plain UInt64 arguments, while the only source files changed here are FunctionDynamicAdaptor.cpp, FunctionVariantAdaptor.cpp and castNestedResult.h, none of which is constructed on that path. Breadth: 10542 success rows over 1563 distinct pull requests in 14 days, 1954 of them on true master, against a slower verdict on only 2 unrelated pull requests, both in this same shard on 2026-09-20; and in the 4 hours around this run the same gate reddened 22 other pull requests over 27 shards ClickHouse/performance-comparison#5 for the dashboard's confidence scoring, which its author names as where noisy queries are handled. #121847 is deliberately NOT linked: it is measured PRESENT in the tree this job built (job 107737969253 of run 36010764590 checked out Merge b80c9cf9f13f into 19254aa9d688, 4 hits for a symbol the fix introduces, against 0 pre-fix and 4 at the fix), and neither mechanism it repairs fired here, since the job log carries no threshold-fetch warning and consumed historical-thresholds.tsv, and the shards ran 16:55 to 18:15 UTC so its local-time date rollover cannot apply
Mergeable Check, PR rollup: red only because of the row above, no independent failure ClickHouse/performance-comparison#5

Gates (a) to (d): 0 of 172 check runs queued or running, Config Workflow, Style check,
Finish Workflow and CH Inc sync all success, 56 min since the last job finished (anchor
2026-09-24T19:14:30Z), and every failing row above has an owner. CIDB carries no FAIL or ERROR
row on this head.

Master merge deliberately not pushed: the one repo-side fix in this family is already in the tree
these jobs built, so restarting CI would only re-roll the same dashboard verdict.

Session id: cron:our-pr-ci-monitor:20260924-200137

@Algunenano
Algunenano added this pull request to the merge queue Sep 25, 2026
Merged via the queue into ClickHouse:master with commit c454835 Sep 25, 2026
170 of 172 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants