Skip to content

Propagate the cluster-function read-task callback into SQL SECURITY views - #113371

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-definer-view-cluster-function-read-task-callback
Aug 5, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-definer-view-cluster-function-read-task-callback

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110972

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 a LOGICAL_ERROR Next task callback is not set for query when a SQL SECURITY DEFINER or SQL SECURITY NONE view over a cluster table function (s3Cluster, urlCluster, fileCluster) was read as a secondary query, for example through remote or clusterAllReplicas. The unsupported nesting is now rejected with a normal query error instead of aborting the server in debug and sanitizer builds.

Description

Found by CI: Stress test (amd_tsan) on #110972. 6 hits in 30 days, over 5 unrelated pull requests by different authors plus one master run, so it is a trunk bug, not any one PR's fault.

What breaks: a SELECT through a SQL SECURITY DEFINER or NONE view over a cluster table function aborts a debug or sanitizer server when that SELECT arrives as a secondary query. The failing CI query was SELECT count() FROM remoteSecure(..., 'test_view'), wrapped by the AST fuzzer. Read locally the view always worked, so no stateless test caught this.

Root cause: StorageInMemoryMetadata::getSQLSecurityOverriddenContext rebuilds the view context from the global context for those two branches, so the definer does not inherit the invoker's identity, then re-propagates query state item by item. It carried the three MergeTree parallel-replicas callbacks but not next_task_callback, so the cluster function inside the view could not reach the initiator that decides whether to serve its read task. The ordinary Context copy constructor does carry it, and INVOKER uses that constructor, so an INVOKER view already worked: the omission was accidental, not policy.

The fix propagates the callback for the other two branches, above the NONE early return so both are covered, mirroring 7f75908b72374e3 which fixed the same bug class here for the MergeTree callbacks. The unsupported nesting then lands on the existing rejection in RemoteQueryExecutor::processReadTaskRequest and reports BAD_ARGUMENTS, as INVOKER already did, with the server alive. Legitimate distribution is unaffected, since those paths install a task iterator on the initiator, and the LOGICAL_ERROR at the three consumers stays a genuine invariant.

New test 04810_definer_view_over_cluster_function covers the three security modes across the three cluster functions and both analyzers, with INVOKER as control.

Validation matrix (18 cells, before and after)

Note on a similar message: Context::getMergeTreeAllRangesCallback throws Next task callback is not set for query with id:, but reads a different member. That is the parallel-replicas variant tracked by #111677, which this PR does not address.

Each cell is a SQL SECURITY <mode> view over the named cluster function, read via remote(...) with prefer_localhost_replica = 0. The server was restarted before every cell and its buildId asserted against the binary under test, because a LOGICAL_ERROR aborts a debug server and would otherwise silently blind later cells.

cell pristine HEAD with this change
DEFINER / s3Cluster, urlCluster, fileCluster (analyzer 1 and 0) LOGICAL_ERROR, server aborted (6/6) BAD_ARGUMENTS, server alive (6/6)
NONE / s3Cluster, urlCluster, fileCluster (analyzer 1 and 0) LOGICAL_ERROR, server aborted (6/6) BAD_ARGUMENTS, server alive (6/6)
INVOKER / s3Cluster, urlCluster, fileCluster (analyzer 1 and 0) BAD_ARGUMENTS, server alive (6/6) BAD_ARGUMENTS, server alive (6/6)

The INVOKER row is the control: it never lost the callback, and its verdict is identical on both arms, so the difference in the other twelve cells is attributable to the change rather than to the environment.

Test 04810 fails on pristine HEAD with the LOGICAL_ERROR in the server log and passes with the change; 50/50 passes with randomized settings. 03850_nested_cluster_table_function_task_iterator passes unchanged, which is the evidence that legitimate distribution still reads each task exactly once, as does 03667_view_with_s3_cluster_and_sql_security_definer. A 56-test sweep of everything touching a cluster table function or SQL SECURITY gives identical verdicts on both arms.

Version info

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

…iews

A SELECT through a SQL SECURITY DEFINER or NONE view whose inner query is a
cluster table function (s3Cluster, urlCluster, fileCluster) aborted the server
in debug and sanitizer builds when the SELECT itself arrived as a secondary
query, for example when the view is read through remote() or clusterAllReplicas,
or when the AST fuzzer wraps the query in remoteSecure():

  Logical error: Next task callback is not set for query <id>

StorageInMemoryMetadata::getSQLSecurityOverriddenContext rebuilds the view
context from the global context for the DEFINER and NONE branches, so the
definer must not inherit the invoker's identity, then re-propagates the
query-scoped state item by item. It carried the three MergeTree parallel-replicas
callbacks but not next_task_callback, so the cluster table function inside the
view could no longer reach the initiator that decides whether to serve the read
task, and Context::getClusterFunctionReadTaskCallback threw.

The ordinary Context copy constructor does carry next_task_callback, and the
INVOKER branch uses that constructor, so the same query through an INVOKER view
already worked. That differential shows the omission was accidental rather than
a policy, so the callback is now propagated for the other two branches as well.
The propagation is placed above the NONE early return so both branches are
covered, mirroring commit 7f75908, which fixed the same bug class in
this function for the MergeTree callbacks.

The unsupported nesting now lands on the existing rejection in
RemoteQueryExecutor::processReadTaskRequest and reports BAD_ARGUMENTS "A cluster
table function (s3Cluster, urlCluster, fileCluster, ...) cannot be nested inside
another distributed query", which is what an INVOKER view already produced, and
the server stays alive. Legitimate distribution is unaffected because those
paths install a task iterator on the initiator.

The LOGICAL_ERROR at the three callback consumers is deliberately kept: once the
propagation is correct, a missing callback under distributed processing is a
genuine internal invariant violation, and turning it into a user-facing error
would mask future propagation gaps.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 issues fixed, 2 declined with evidence)

An independent model reviewed this change cold against the repository review checklist, separately
from the model that wrote it. Verdicts below; the two fixed items were both in this description,
so the code is unchanged from what was reviewed.

⚠️ Fixed before publishing

The provenance link did not render. Related: https://.../pull/110972 sat only inside the
leading HTML comment block, so it produced no visible line and no cross-reference. #110972 inside
the report URL's link text is plain text, not an autolink. A rendered Related: #110972 line was
added.

The breadth figure undercounted. The draft said 4 hits over 4 pull requests. Re-measured on
public CIDB over 30 days, keyed on the error text and split by STID so the similarly worded
parallel-replicas variant cannot pool in: STID 4567-5424 has 6 rows, all 6 carrying the
StorageObjectStorageSource frame, over 5 distinct pull requests plus one master run
(2026-08-03 11:55Z to 2026-08-04 10:27Z). The description now says that. The master row is the
first for this signature in the current era.

💡 Declined, with reasoning

"The test asserts the message, not the BAD_ARGUMENTS code, so a LOGICAL_ERROR carrying the
same text would pass."
True about the oracle, but the failure it protects against cannot occur,
and asserting the code would make the test weaker:

  • Exactly one throw in src/ produces that sentence, RemoteQueryExecutor::processReadTaskRequest
    at RemoteQueryExecutor.cpp:836-839, and its code is BAD_ARGUMENTS. The LOGICAL_ERROR next to
    it at :849-852 has different text.
  • If such a LOGICAL_ERROR were ever introduced, the test would redden rather than pass:
    Exception::handleErrorCode (Exception.cpp:112-116) aborts inside the exception constructor,
    before the message can reach the client, whenever the build is debug or sanitizer or the
    abort_on_logical_error server setting is on, and tests/config/install.sh:245-247 installs that
    setting for every non-fasttest stateless run, which is the set this test runs in. Both the message
    line and the --- server alive --- line would go missing. This is what the pristine-HEAD arm
    actually did: the server aborted with exit 134.
  • The message is the stronger assertion of the two. BAD_ARGUMENTS is shared with the sibling
    parallel-replicas refusal at :844-847, which 03850_nested_cluster_table_function_task_iterator
    exists to tell apart, so pinning the code alone would let those two swap silently. That test uses
    this same message oracle for the same rejection.

A multi-source note, not a regression. In a query whose outer table expression is itself a
cluster function over source A, a definer view over cluster function B shipped in the same secondary
query receives A's task stream, because the read-task response carries a path and no source
identity. This is unchanged by this PR: an INVOKER view carries the same callback through the
ordinary Context copy constructor today, as does a directly written nested cluster function. It is
a property of the initiator-decides model documented at TableFunctionObjectStorageCluster.cpp:46-52
rather than something this change introduces, and this PR's contract is INVOKER parity.

Session id: cron:clickhouse-review-slot-51:20260804-171931

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Gate Answer
a Deterministic repro? Yes. CREATE VIEW v SQL SECURITY DEFINER AS SELECT * FROM s3Cluster(...) then SELECT count() FROM remote('127.0.0.1:PORT', db, 'v') SETTINGS prefer_localhost_replica = 0. Fires on demand, 12/12 cells, not a rate. The stack matches the CI signature exactly: Context.cpp:8029 getClusterFunctionReadTaskCallback <- StorageObjectStorageSource.cpp:337 createFileIterator <- ReadFromObjectStorageStep.cpp:170 createIterator <- :98 initializePipeline.
b Root cause explained? Yes. getSQLSecurityOverriddenContext rebuilds the DEFINER/NONE view context from the global context and re-propagates query-scoped state item by item, carrying the three MergeTree parallel-replicas callbacks but not next_task_callback. The cluster function inside the view then cannot reach the initiator that decides whether to serve the read task, and the getter throws.
c Fix matches root cause? Yes. It restores the one missing propagation at the single place that loses it, not a guard at the crash site. The LOGICAL_ERROR at the three consumers is deliberately kept so a future propagation gap is not masked.
d Test intent preserved / new tests added? Yes. No existing test was weakened. New 04810_definer_view_over_cluster_function asserts the rejection message, the still-working local read, and server liveness.
e Demonstrated in BOTH directions? Yes. 04810 fails on pristine HEAD with the LOGICAL_ERROR in the server log and passes with the change, both against binaries whose Build ID was asserted per run (b85287a8 vs 35c5689f).
f General across CODE paths? Yes. All three consumers (StorageObjectStorageSource.cpp:337, StorageFile.cpp:1445, StorageURL.cpp:1331) are fixed by the single upstream change, and the test exercises all three. Every hand-rolled global-context rebuild was enumerated (10 sites); only this one is reachable with a cluster function. InterpreterExecuteAsQuery.cpp:27 has the same shape but is not reachable: it copies query_kind verbatim so it never manufactures a secondary query, and nothing forwards EXECUTE AS to another server (empty grep over ClusterProxy/ and StorageDistributed.cpp). It is deliberately left untouched rather than patched without a reproducer. All 17 callers of the helper, including materialized views, are fixed for free.
g Generalizes across INPUTS? Yes. Matrix of 3 security modes x 3 cluster functions x enable_analyzer 1 and 0 = 18 cells, plus the local-read shape and an explicit-schema variant. Type wrappers do not apply on this path.
h Backward compatible? Yes. One file, five lines, no settings, no serialization format, so no SettingsChangesHistory.cpp entry. A query that previously aborted the server now returns a clear error; nothing that previously succeeded changes behavior.
i Invariants and contracts preserved? Yes. The callback is transport wiring, captured on the connection handler, and the definer user is still set separately afterwards, so the security boundary is unchanged; the INVOKER branch already carried it. 03850_nested_cluster_table_function_task_iterator passes unchanged, which is the direct evidence that legitimate distribution still reads each task exactly once.

Non-regression: 03850 and 03667 pass; a 56-test sweep of everything touching a cluster table function or SQL SECURITY gives identical verdicts on pristine HEAD and with the change. 04810 passes 50/50 with randomized settings.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @SmitaRKulkarni @devcrafter, could you review this? A SQL SECURITY DEFINER or NONE view rebuilds its context from the global context and re-propagated every query-scoped callback except next_task_callback, so a cluster table function inside the view lost its channel to the initiator and hit a logical error that aborts debug and sanitizer builds; an INVOKER view already worked because that branch uses the ordinary Context copy constructor. @devcrafter, you own the sibling #111677, which is the similarly worded merge_tree_all_ranges_callback variant and is not what this fixes.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [81f1a79]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
04357_distributed_alias_same_expression FAIL cidb IGNORED
BuzzHouse (arm_asan_ubsan) FAIL
Logical error: Sending a distributed query with unknown (zero) client version. The query context was not initialized as an initial query (STID: 4148-4291) FAIL cidb IGNORED

AI Review

Summary

This PR propagates the missing ClusterFunctionReadTaskCallback through StorageInMemoryMetadata::getSQLSecurityOverriddenContext for SQL SECURITY DEFINER and SQL SECURITY NONE views, bringing them back in line with the existing INVOKER path and turning the bad LOGICAL_ERROR into the existing user-facing BAD_ARGUMENTS rejection for nested distributed reads. I reviewed the current diff, surrounding callback plumbing, prior discussion, and current all-green CI, and I did not find a remaining correctness, safety, or coverage issue that needs action.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 81f1a793e with master d0758c6f8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e75fe0854; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 688.57 MiB 685.93 MiB -2.65 MiB (-0.38%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

1373 object files changed (+1.47 MiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/GeoFilter.cpp.o new 860.64 KiB +860.64 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/SharedPartColumns.cpp.o new 294.32 KiB +294.32 KiB
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/Reader.cpp.o 558.56 KiB 634.53 KiB +75.97 KiB (+13.60%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/IMergeTreeDataPart.cpp.o 1.38 MiB 1.33 MiB -46.27 KiB (-3.28%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/ColumnsSubstreams.cpp.o 132.58 KiB 154.18 KiB +21.60 KiB (+16.29%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

7 translation units recompiled, 10 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 81f1a79

Every failure below has an owner: a fixing PR (ours 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
BuzzHouse (arm_asan_ubsan) / Sending a distributed query with unknown (zero) client version, STID 4148-4291 pre-existing trunk bug in the distributed client-version handling #109408 (external, merged 2026-08-04) - this build predates the fix
Stateless tests (arm_binary, parallel) / 04357_distributed_alias_same_expression flaky, pre-existing: duplicate-ALIAS GROUP BY over a Distributed table under two-level aggregation #108855 (ours, open)

Session id: cron:our-pr-ci-monitor:20260805-033000

@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit c068f0e Aug 5, 2026
177 of 180 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Propagate the cluster-function read-task callback into SQL SECURITY views

ClickGap verified: reproduced it with the script below on 26.7; tested 6 version(s) — 5 affected, 1 clean (see Affects); present since the feature was introduced in v24.8 (not a recent regression).

Reproduction

-- Needs a server with a cluster `test_cluster_two_shards_localhost` (two self-pointing shards)
-- and a debug/sanitizer (or RelWithDebInfo) build so the LOGICAL_ERROR is visible.
CREATE OR REPLACE VIEW v SQL SECURITY DEFINER AS
  SELECT * FROM fileCluster('test_cluster_two_shards_localhost', 'data.tsv', 'TSV', 'x UInt8');
SELECT count() FROM remote('127.0.0.1:9000', currentDatabase(), 'v')
  SETTINGS prefer_localhost_replica = 0;
-- Observed (pre-fix): LOGICAL_ERROR "Next task callback is not set for query <id>: While executing File"
--   which aborts a debug/sanitizer server. Fixed: BAD_ARGUMENTS "... cannot be nested inside
--   another distributed query", server stays alive. Same for SQL SECURITY NONE and s3Cluster/urlCluster.

Bisect

  • The reproducer requires enable_analyzer, introduced in v24.8 — so this is not pre-existing: it was introduced no earlier than v24.8, and the introducing change is in the 24.8–master range (most likely the change that added the feature). Every release line down to there reproduces.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Does NOT reproduce on: master
  • Backport needed: 26.7, 26.6, 26.5, 26.3, 25.8

Suggested next step

The fix has landed on master; 26.7, 26.6, 26.5, 26.3, 25.8 still need the backport.

Component: comp-view
Severity: P2


ClickGap · Finding: phase_d_pr113371

Triage metadata

  • Primary component: comp-view
  • Secondary components: comp-distributed, comp-testing

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 groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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.

5 participants