Skip to content

Keep the predicate of indexHint in a serialized query plan - #126329

Open
groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/index-hint-serialized-plan
Open

groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/index-hint-serialized-plan

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126219

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 indexHint losing its predicate when the query plan is sent serialized (serialize_query_plan = 1), which made a remote server return rows outside the granules the hint selects.

Description

On 26.8.21.12, SELECT sum(b), count() FROM remote('127.0.0.2', db, t) WHERE indexHint(a < 10) SETTINGS serialize_query_plan = 1 (remote server with process_query_plan_packet = 1) returns every row instead of the hinted granules' rows.

indexHint keeps its predicate in its own ActionsDAG, not in the node's children. ActionsDAG::serialize wrote only the function name, so the receiver rebuilt an empty hint, which selects every granule. make_distributed_plan lost it the same way.

The change:

  • ActionsDAG::serialize writes the hint's DAG behind a new column_flags bit, and deserialize rebuilds the hint from it. A required IndexHintActions parameter says whether the stream can carry it; Refuse throws.
  • Every plan step carrying an ActionsDAG gets a new step version at plan serialization version 21. A peer below 21 gets no plan since Remove the binary settings serialization from the query plan #129973.
  • The filter a cluster table function sends to its replicas (Send the filter on a table read by a cluster function to the replicas #125615) leaves indexHint out: the hint is always true on rows and may hold an unbuilt set.
  • Plan-based parallel replicas keep a fragment local when a set inside a hint, a lambda body or another set's plan (also its LIMIT ... AFTER and INTERPOLATE) cannot be shipped.
  • The read steps also carry the column identifiers a local read maps back to columns, so a hint on a read column or on numbers selects the same granules remotely.
  • The hint's DAG counts towards the nesting-depth limit of a deserialized ActionsDAG.

Validation: the new test fails on master and passes with the fix (also make_distributed_plan without local fallback, hints on a read column and on numbers). It guards the new shipping paths: a cluster table function query that fails if its filter carries the hint, plan-based parallel replicas with unshippable sets in hints, a hint in a shipped ARRAY JOIN filter. 05427_query_plan_deserialize_deep_recursion gets a case with 1500 nested hints.

🤖 Generated with Claude Code


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

groeneai and others added 4 commits October 16, 2026 14:07
`indexHint` keeps its predicate in its own `ActionsDAG`, not in the children
of the node. `ActionsDAG::serialize` wrote only the function name, so a
receiver of a serialized plan (`serialize_query_plan = 1` with
`process_query_plan_packet`, or `make_distributed_plan`) rebuilt the hint
from `FunctionFactory` with an empty DAG. An empty hint is `ALWAYS_TRUE` for
index analysis and evaluates to 1, so a query filtered by `indexHint`
returned every row instead of the rows of the granules the hint selects, and
the hints derived by `optimize_and_compare_chain` / `optimize_or_like_chain`
stopped pruning there.

`ActionsDAG::serialize` now writes the hint's DAG behind bit 8 of
`column_flags`, and `deserialize` rebuilds `FunctionIndexHint` from it. The
new required `IndexHintActions` parameter tells whether the stream can carry
it; it is a scoped enum so that the old calls passing `input_header` do not
compile silently. With `Refuse`, a hint that has a predicate throws
`SUPPORT_IS_DISABLED` instead of being dropped. Lambda captures, function
constants and nested hints inherit the mode.

The steps that ship an `ActionsDAG` (Expression, Filter, Join, LimitRange,
Filling, TotalsHaving, and the row-level filter and PREWHERE of
ReadFromMergeTree) get a new step version introduced at query plan
serialization version 21, which is the 26.11 bump. A build at the same
global version without this change refuses those step versions up front
instead of misparsing bit 8. ArrayJoin's element filter (only serialized
locally), ObjectFilter (old analyzer only), `ReadFromFormatInfo` and the
cluster-function schema transform keep their bytes and pass `Refuse`.

Toward a peer below 21 a plan whose query contains `indexHint` (written or
derived) is sent as SQL through the fallback the execution limits already
use: `createLocalPlan` marks the shipped plan with
`QueryPlan::setMinSerializationVersion` when its AST contains `indexHint`,
and `RemoteQueryExecutor` checks it against the connections. A hint that
the AST does not show (only in `additional_table_filters`) reaches the
encoder and fails with `SUPPORT_IS_DISABLED` during the upgrade rather than
returning wrong rows.

The bump also raises `DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_PARALLEL_REPLICAS`,
which is tied to the current version, so a 26.11 initiator excludes 26.10
replicas from a plan-shipping parallel-replicas query during the upgrade.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two arms run `make_distributed_plan = 1` with
`distributed_plan_fallback_to_local_execution = 0`, so the query cannot
silently fall back to local execution. Without the fix both return every
row of the table (49695450, 100000); with it the hinted granules only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t test

The stateless CI profile (tests/config/users.d/limits.yaml) sets
max_rows_to_group_by to 10G. make_distributed_plan refuses an aggregation
with a GROUP BY limit, and with distributed_plan_fallback_to_local_execution
= 0 that refusal is thrown as SUPPORT_IS_DISABLED, so both arms failed in
every stateless job. Set the limit to 0 on these two queries, as other
make_distributed_plan tests do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the per-step version comments the constant names already state and a narrating line in RemoteQueryExecutor; condense the two ProtocolDefines.h entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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; 2 findings over 2 runs: a full pass and a delta recheck that raised none).

# Sev Finding Verdict Evidence / action
1 ❌ An older initiator (plan version 20) still sends indexHint without its predicate; the new receiver rebuilds an empty hint and returns all rows. DISAGREE The predicate is lost by the old sender: version 20 bytes carry no hint DAG, so old -> new returns what old -> old returns (measured). The receiver cannot tell such a hint from one derived by the default-on optimize_and_compare_chain, whose empty form is result-correct, so refusing version-20 hints would fail correct queries (including old initiator -> new parallel replicas) during the upgrade. Refusing them instead is possible if preferred.
2 ⚠️ The test did not cover make_distributed_plan and did not prove that plan shipping fired. AGREE in part, fixed @ 101ac2a Added two make_distributed_plan arms with distributed_plan_fallback_to_local_execution = 0: master 49695450/100000, fix 496857/1024, every query distributed. No firing oracle for the remote() arms: they fail on master, which needs the plan to be shipped.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261016-161600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05404_index_hint_serialize_query_plan against a server with process_query_plan_packet = 1 fails every run on master (1/1 without and 5/5 with randomized settings): each serialize_query_plan = 1 line returns all 100000 rows.
b Root cause explained? indexHint keeps its predicate in a private ActionsDAG; ActionsDAG::serialize wrote only the function name, so the receiver rebuilt an empty hint, which selects every granule and evaluates to 1.
c Fix matches root cause? Yes. The hint's DAG is serialized with the node (new column_flags bit, per-step versions at plan version 21); toward an older peer it is refused, never dropped, and a query containing indexHint is sent as SQL.
d Test intent preserved / new tests added? New stateless test: WHERE, PREWHERE, nested hints and an IN subquery hint, each with serialize_query_plan 0 and 1, plus two make_distributed_plan arms (a WHERE hint and an IN subquery hint) run with distributed_plan_fallback_to_local_execution = 0.
e Both directions demonstrated? Yes, on one tree: base build returns 49695450/100000 for the serialized arms, the fixed build 496857/1024 like the unserialized ones. 50/50 randomized runs pass; the runs used the CI users profile (limits.yaml included).
f Fix is general across code paths? All DAG-carrying steps (Expression, Filter, Join, LimitRange, Filling, TotalsHaving, ReadFromMergeTree row filter and PREWHERE) are versioned; nested DAGs (lambda captures, function constants, nested hints) follow; make_distributed_plan reads are fixed too (measured). Paths that never reach a peer with a hint pass Refuse.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked Nullable and LowCardinality keys, tuple IN, empty indexHint(), scalar subquery, lambdas inside and around the hint, HAVING, JOIN ON, OR of hints: serialized and unserialized results equal, no errors.
h Backward compatible? (maintainer-approved exception only) Yes. An old initiator writes the old bytes, which the new reader still reads; an old receiver gets step version 0 and SQL for queries with indexHint (measured both ways). A hint only in additional_table_filters fails with SUPPORT_IS_DISABLED toward 26.9/26.10 during the upgrade instead of returning wrong rows.
i Invariants and contracts preserved? A deserialized indexHint carries its DAG; the reader accepts the new bit only on indexHint and never with the capture bit; cache-key bytes are unchanged; min_serialization_version follows every QueryPlan copy like max_threads.

Session id: cron:clickhouse-impl-self-slot-57:20261016-131300

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @davenger, could you review this? With serialize_query_plan = 1 the receiver rebuilt indexHint from its name only and lost its predicate, so the remote returned every row; this writes the hint's ActionsDAG in new step versions (plan version 21) and sends a query containing indexHint to an older peer as SQL.

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a56d349]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, 2/5) FAIL
test_backup_restore_on_cluster/test.py::test_async_backups_to_same_destination[http-False] FAIL cidb

AI Review

Summary

The change preserves the private predicate DAG of indexHint in serialized query plans, versions the affected steps, restores read-column identifiers, and extends parallel-replica shipping checks. Reviewed head: a56d34954af566916a3978497a004b351f6e2642. One previously reported Major remains: the round trip still loses whether a hint was inferred. The earlier preflight and fused ARRAY JOIN findings are addressed in the current code.

Findings

⚠️ Majors

  • src/Interpreters/ActionsDAG.cpp:5523: Preserve the inferred-hint marker. The writer sends only the hint's predicate; the reader constructs FunctionIndexHint with its default implied = false. Thus an inferred hint becomes a user-written hint after deserialization. This changes optimizer behavior: tryPushDownFilter allows only implied hints across aggregation and LIMIT BY, and ActionsDAG::mergeInplace rebinds hidden inputs through expression prefixes only for implied hints. For example, the hint derived from HAVING a < m AND m < 120, where m = max(b), can no longer cross the aggregation on the receiver, losing pruning on a. Serialize and restore isImplied alongside the predicate. This is the existing open finding; no duplicate inline comment was posted.
Tests
  • ⚠️ Add a focused round-trip regression for an inferred hint crossing aggregation or LIMIT BY, plus an expression-prefix case that requires hidden-input rebinding. Assert the resulting pruning or plan behavior; equal result rows alone cannot detect this loss. The new 05404 cases exercise user-written hints.
Missing context / blind spots
  • ⚠️ No local execution was performed: this checkout has no runnable ClickHouse binary or build. The current-head Fast test report has no failures but skips 05404_index_hint_serialize_query_plan; the broader functional checks had not completed when checked. A passing focused functional report would close that execution gap. CI report.
Final Verdict

⚠️ Request changes. Preserve the inferred-hint marker and add regression coverage proving that its pushdown and rebinding behavior survives serialization.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Oct 16, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2fa05fd

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
Integration tests (arm_binary, 3/4) / test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py (both tests) not from this PR: this branch predates the fix, so the old server image is still 26.8.28, which applies remote_url_allow_hosts to SQL disks, and the first CREATE fails with Code: 491 ... is not allowed in configuration file. Same red on other PRs whose branch predates the fix #126289 (mine, merged)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the row above #126289 (the owner of the first row)

Session id: cron:our-pr-ci-monitor:20261017-113010

groeneai and others added 2 commits October 31, 2026 11:38
…-serialized-plan

# Conflicts:
#	src/Core/ProtocolDefines.h
#	src/Interpreters/ActionsDAG.cpp
Master now limits the nesting depth of a deserialized ActionsDAG to 1000
levels (ClickHouse#126548), counted through the recursive calls for lambda captures.
The predicate of indexHint is deserialized by the same recursion, but the
call did not pass the depth, so a QueryPlan packet with nested indexHint
nodes was not covered by the limit (only by checkStackSize). Measured on a
debug build: chains of 1001, 1500 and 3000 levels were accepted, 5000 was
rejected by checkStackSize. Now every chain above 1000 levels gets
TOO_DEEP_RECURSION, and 05427 has an indexHint arm at 1500 levels.

Also use FunctionIndexHint::tryGet, which ClickHouse#126219 added on master, instead
of the same two casts.

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

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a56d34954 with master 1e0344d69 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

176 object files changed (+887.43 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/SelectQueryInfo.cpp.o 141.02 KiB 210.05 KiB +69.03 KiB (+48.95%)
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.53 MiB 1.54 MiB +17.13 KiB (+1.10%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp.o 271.82 KiB 288.27 KiB +16.45 KiB (+6.05%)

711 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

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

Job report

groeneai and others added 5 commits November 15, 2026 15:37
…-serialized-plan

Conflicts: `ProtocolDefines.h` (both sides' version 21 entries kept; plan version stays 21, the 26.11 value),
`ActionsDAG.cpp` (master's post-order node walk and `isConstantValueInCacheKey`, with the `IndexHintActions`
parameter), `SelectQueryInfo.h` (master's `QueryPlanStepSerialization` spelling).

Two new call sites of `ActionsDAG::serialize` on master need the parameter: the filter that
`ReadFromCluster` sends to the replicas of a cluster table function (ClickHouse#125615) writes the predicate of
`indexHint` (the replica rebuilds the filter with the same release), and the ActionsDAG deserialization
gtest refuses it (the DAG has no `indexHint`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#129973 the oldest supported query-plan serialization version is 21: no plan is serialized
for a peer below it (`QueryPlan::serialize` throws `NOT_IMPLEMENTED`), so such a peer can no longer
receive a plan with the predicate of `indexHint` dropped. The fallback that sent a query containing
`indexHint` to it as SQL protected only that case, and made those queries the one exception to the
documented failure. Remove it with `QueryPlan::min_serialization_version` and the sentence in
`protocol.mdx`.

`Refuse` is now reached only from the call sites that never write the predicate (the array join
element filter, `ObjectFilterStep`, the prewhere of a file read), so its error no longer names a
version that the peer already has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…able function

The filter that a cluster table function sends to its replicas (ClickHouse#125615) is built from the conjuncts that
`isSerializableFilterNode` accepts. That check walks the children of a node, but the predicate of `indexHint`
is a separate DAG it does not walk. Writing the predicate there made a query fail that works on master:

    SELECT count() FROM icebergLocalCluster(...) AS t, (SELECT number AS k FROM numbers(1000)) AS n
    WHERE t.a = n.k AND t.a % 2 = 0 AND indexHint(t.a IN (SELECT number FROM numbers(10)))
    -- Code: 344. Cannot ship an IN-subquery set to distributed-plan worker tasks (the set is not built)

On rows `indexHint` is always true, so before this PR the replicas got a hint rebuilt without its predicate
that filtered nothing. Leaving the conjunct out keeps the rows each replica sends unchanged, and the filter is
now serialized with `Refuse`, so a hint that reaches it fails instead of being dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The style check requires every query to system.query_log to filter on
current_database = currentDatabase(). The replica queries of
icebergLocalCluster are logged with current_database = 'default', so
they are now selected through the query_id of the initiator, which is
scoped to the test database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A non-empty cluster_table_function_pushed_down_filter does not prove
that the ordinary conjunct survived once indexHint is left out. The
replicas return 500 of the 1000 rows when t.a % 2 = 0 reaches them and
all 1000 when nothing pushable does, so assert sum(result_rows) < 1000,
as 05394 does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment on lines +5523 to +5525
auto index_hint = std::make_shared<FunctionIndexHint>();
index_hint->setActions(ActionsDAG::deserialize(in, registry, context, max_type_complexity, nesting_depth + 1));
function = std::make_shared<FunctionToOverloadResolverAdaptor>(std::move(index_hint));

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.

[Major] Preserve the inferred-hint marker in the round trip

Only the predicate is restored here: the new FunctionIndexHint retains its default implied = false, even when the sender's hint came from createImplied. The receiver optimizes the received plan again, and this flag controls more than diagnostics: tryPushDownFilter permits only implied hints through GROUP BY/LIMIT BY, and ActionsDAG::mergeInplace only rebinds an implied hint's hidden inputs through an expression prefix.

Consequently, a derived hint that still needs those passes on the receiver is treated as user-written. For example, the inferred indexHint(a < 120) from HAVING a < m AND m < 120 (m = max(b)) can no longer cross the aggregation, losing the only pruning condition on a despite preserving its DAG. Alias rebinding is skipped as well.

Serialize and restore isImplied together with the predicate, and cover an inferred hint through a serialized plan with an aggregation or alias prefix; the added tests currently exercise user-written hints only.

@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 15, 2026
groeneai and others added 2 commits November 15, 2026 20:19
Now that the predicate of `indexHint` is serialized with its sets, plan-based
parallel replicas ship those sets too, but `dagReferencesUnshippableSubquerySet`
only scanned the outer DAG, where the hint has no children. A hint holding an
`IN` set that is not shippable was therefore accepted, and serializing the
fragment failed: `indexHint(a IN (SELECT ... FROM generateRandom(...)))` on a
key column reached `Cannot serialize FutureSetFromSubquery with no query plan`
(LOGICAL_ERROR, the set was built in place by index analysis), on another column
`ReadFromStorageStep serialization is implemented only for StorageSystemOne`.
The same happened for such a hint inside a lambda body, and inside the subquery
plan of another `IN` set (`b IN (SELECT a FROM t WHERE indexHint(a IN (...)))`),
neither of which the check visited. Master keeps the fragment remote and answers
all of these, since it does not ship the hint's sets at all.

The check now descends into every DAG `ActionsDAG::serialize` writes inside a
node (a lambda body, as a function or as a folded constant, and the predicate of
`indexHint`) and into the sets referenced by a shipped set's own plan, so such a
fragment stays local, while a hint whose set is shippable is still distributed.
The last part also keeps local a plain nested `IN` whose inner source cannot be
serialized, which failed the same way on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…an fragment

`LimitRangeStep::serialize` and `FillingStep::serialize` write their DAGs, now
with the predicate of `indexHint`, but `checkQueryPlanActionDAGs` did not visit
them. A hint holding an unshippable set there, inside an `IN` subquery of a
plan-based parallel replicas query, passed the preflight and the fragment
failed to serialize (`NOT_IMPLEMENTED` for `generateRandom`), where master
answers because it drops the hint's DAG. The same walk also keeps local a
plain such set in those steps, which failed on master too.

Example (05404 settings): `b IN (SELECT number FROM numbers(10) LIMIT 3 AFTER
indexHint(number IN (SELECT length(x) FROM generateRandom('x String', 1, 0, 1)
LIMIT 3)))` -> master 303, previous head NOT_IMPLEMENTED, now 303 (kept local);
a shippable hint there still runs on the replicas.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 4 commits November 15, 2026 23:24
The planner names a hint column by its column identifier (`__table1.a`)
when the query also reads that column, and always for a non-MergeTree
source. A local read maps the identifiers back to column names before
index analysis (`SelectQueryInfo::buildNodeNameToInputNodeColumn`, from
the planner context). A read rebuilt from a serialized plan has no planner
context, so the map was empty, the hint kept `__table1.a`, `KeyCondition`
found no key column and the receiver read every granule:
`SELECT sum(a), count() FROM remote('127.0.0.2', db, t) WHERE indexHint(a < 10)`
returned `49950000 100000` with `serialize_query_plan = 1` and `4740 1024`
without it.

The sender's read steps now carry the (identifier, column name) pairs of
the local map: `ReadFromTableStep` and `ReadFromTableFunctionStep` (step
version 1, remote and Distributed tables), `ReadFromSystemNumbersStep`
(step version 1, a numbers read in a shipped join) and `ReadFromMergeTree`
(inside the unreleased step version 2, plan-based parallel replicas and
`make_distributed_plan`). The receiver keeps a pair only when its own
storage snapshot has the column, typed as stored there, and
`buildNodeNameToInputNodeColumn` returns that map when there is no
planner context, so `buildFilterActionsDAG` and both `applyFilters` stay
as they are. A hint through a subquery alias still does not prune, on any
path, as before.

05404 gains the sqp0/sqp1 pairs for a hint on a read column (WHERE and
PREWHERE) and on `remote(..., numbers(100000))`, the subquery-alias
parity pair, a `make_distributed_plan` line, and plan-based parallel
replica lines incl. a hint on the `numbers` side of a shipped join. On
the previous head every new sqp1, `make_distributed_plan` and
`parallel_replicas_local_plan = 0` line returned all rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`query_plan_optimize_join_order_randomize` is nonzero in 95% of randomized
runs; a randomized join order can keep the `numbers` join on the
initiator, and then the `JoinLogical` check of the shipped join fails
(11 of 50 randomized runs, all on that one line, with the trigger isolated
to that setting alone). Pin it on the two join queries only: 0 of 50 with
the pin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Plan-based parallel replicas with `serialize_query_plan = 0` fuse a filter
into an `ArrayJoin` step (`tryFuseFilterIntoArrayJoin`) and can ship that
step, e.g. on the broadcast side of a shipped join. `ArrayJoinStep::serialize`
wrote the element filter with `IndexHintActions::Refuse`, so an `indexHint`
inside a lambda that captures the joined element (it stays in the lambda's
DAG, so the whole filter fuses) threw `SUPPORT_IS_DISABLED` where master
answers:

    SELECT count(), sum(l.b) FROM t AS l
    INNER JOIN (SELECT number AS k FROM numbers(20) ARRAY JOIN [number] AS elem
                WHERE arrayExists(y -> y = elem AND indexHint(y < 10), [elem])) AS r
    ON l.a = r.k

Give `ArrayJoin` step version 1 at
`DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_INDEX_HINT_ACTIONS`, which
writes hint predicates like `Filter`; the reader needs no change
(`ActionsDAG::deserialize` reads the hint flag at any step version). The
parallel-replicas preflight already walks the element filter and its nested
DAGs, so an unshippable set inside such a hint still keeps the query local.
Cache keys are unchanged: `ActionsDAG::serialize` skips the hint branch for
`for_cache_key`.

05404 gains that query and an EXPLAIN check (05138 style) that the fused
`ArrayJoin` is in the shipped fragment; both pin `serialize_query_plan = 0`
because fusion is skipped for serialized plans (the distributed-plan CI lane
sets it to 1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The function already returns early when `planner_context` is null.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 16, 2026 02:29
…-serialized-plan

# Conflicts:
#	src/Processors/QueryPlan/ReadFromTableStep.h
#	src/Storages/SelectQueryInfo.h
Master enabled `modernize-use-nodiscard` as an error, which flags the three
const getters this PR adds (`ReadFromTableStep`, `ReadFromTableFunctionStep`,
`SelectQueryInfo::getColumnIdentifiers`).

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

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

Pre-publication review of this push by an independent model (engine: codex; 3 findings on the first pass, 0 on the recheck after the fix round, 1 on the recheck after the master merge).

# Sev Finding Verdict Evidence / action
1 ❌ A hint inside a lambda in a filter fused into a shipped ARRAY JOIN makes serialization throw SUPPORT_IS_DISABLED (ArrayJoinStep.cpp). AGREE, fixed @ 8d1805b ArrayJoin gets a step version that writes hint predicates, like the other steps that carry an ActionsDAG. Reproduced first: the broadcast side of a shipped join threw on the previous head and answers now; covered in 05404.
2 ⚠️ The native-protocol doc does not describe the new indexHint encoding. DISAGREE The QueryPlan section leaves the plan stream's internal layout to the serialization version and documents no step layout.
3 💡 A redundant if (planner_context) after the new early return (SelectQueryInfo.cpp). AGREE, fixed @ 964bc30 none
4 ⚠️ ReadFromFormatInfo::serialize passes Refuse, so an object-storage plan with a hint in PREWHERE would throw instead of carrying the predicate (prepareReadingFromFormat.cpp). DISAGREE It has no caller in this repository: the step that would call it is serializable only under CLICKHOUSE_CLOUD. Such a caller lost the predicate silently before; Refuse makes it an error. Writing it needs a step version registered in that build.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261116-031600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd, could you review this? indexHint keeps its predicate in its own ActionsDAG, which plan serialization dropped, so with serialize_query_plan = 1 a remote server read every granule; the DAG-carrying steps now write the hint's DAG at plan version 21, and the read steps carry the column identifiers the hint maps back to columns.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the previous head de4cb9628f419, 05404_index_hint_serialize_query_plan with the new lines fails every run: SELECT sum(a), count() FROM remote('127.0.0.2', db, t) WHERE indexHint(a < 10) SETTINGS serialize_query_plan = 1 returns 49950000 100000 instead of 4740 1024, and remote('127.0.0.2', numbers(100000)) with indexHint(number < 10) returns 100000 instead of 10.
b Root cause explained? When the query also reads the hinted column, or the source is not MergeTree, the planner names it __table1.a. A local read maps that back to a from the planner context before index analysis; a read rebuilt from a serialized plan has no planner context, so the hint kept __table1.a and KeyCondition found no key column.
c Fix matches root cause? Yes. The sender's read steps carry the same (identifier, column name) pairs the local map is built from, and the receiver's buildNodeNameToInputNodeColumn returns them when there is no planner context. Index analysis itself is unchanged.
d Test intent preserved / new tests added? 05404 gains lines only: sqp0/sqp1 pairs for WHERE and PREWHERE hints on a read column and for remote(..., numbers(100000)), a subquery-alias parity pair, a make_distributed_plan line, and plan-based parallel replicas lines including a hint on the numbers side of a shipped join, with an EXPLAIN check that the join is shipped, and a hint inside a lambda in a filter fused into a shipped ARRAY JOIN with an EXPLAIN check that the fused ArrayJoin is in the fragment.
e Both directions demonstrated? Yes. Previous head: every new sqp1, make_distributed_plan, parallel_replicas_local_plan = 0 and numbers line fails; this head: passes. Four mutations, one per receiver path, each redden exactly their own lines. The ARRAY JOIN line throws SUPPORT_IS_DISABLED on the previous head 260b077aa4e65 in every lane and passes with the fix (master answers it). 50/50 randomized runs pass.
f Fix is general across code paths? Every serializable read step that can do range selection carries the pairs: ReadFromTable (remote, Distributed), ReadFromTableFunction, ReadFromMergeTree (parallel replicas, make_distributed_plan), ReadFromSystemNumbers. Both consumers (ReadFromMergeTree::applyFilters, SourceStepWithFilter::applyFilters) go through the one fallback. ArrayJoin now writes hint predicates in its element filter like Filter, at the same step version scheme.
g Fix generalizes across inputs (params/datatypes/wrappers)? Types come from the receiver's own storage snapshot, and the existing type-equality check in buildFilterActionsDAG still applies, so Nullable/LowCardinality columns map as stored there, and a column missing on the receiver is not mapped. WHERE, PREWHERE and a hint through a subquery alias (no pruning on any path, unchanged) are tested.
h Backward compatible? (maintainer-approved exception only) Same shape as the rest of this PR: new step version 1 of ReadFromTable, ReadFromTableFunction and ReadFromSystemNumbers at plan version 21, extra bytes inside the unreleased version 2 of ReadFromMergeTree. Measured: a server without these steps refuses the new version (cannot be read at serialization version 1); an old initiator's version 0 still reads with the old behaviour.
i Invariants and contracts preserved? A read without a planner context now maps identifiers exactly as the local read does (index analysis only; rows are still filtered by the plan's filters). The wire count is bounded before allocation and a duplicate identifier is rejected. The map is a value member, so it follows every SelectQueryInfo copy.

Session id: cron:clickhouse-impl-self-slot-57:20261115-231000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a56d349

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
Integration tests (arm_binary, 2/5) / test_backup_restore_on_cluster/test.py::test_async_backups_to_same_destination[http-False] flaky, not from this PR (no backup or replication code, the test file is untouched): node2's non-ON CLUSTER backup won the destination race before node2 had fetched the inserted part, so the restored table is empty (assert '' == '1\n' at test.py:935). Same signature on 1 other PR in the last day a fix task is created (investigating at full effort, fixing-PR link to follow here)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261116-073013

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_backup_restore_on_cluster/test.py::test_async_backups_to_same_destination[http-False] line of the ledger above: #131921 (mine, open).

zoomxi pushed a commit to zoomxi/ClickHouse that referenced this pull request Nov 19, 2026
…me_destination

The `http-False` variant of `test_async_backups_to_same_destination` runs
`BACKUP TABLE tbl TO <dest> ASYNC` without `ON CLUSTER` on node1 and node2
right after the `INSERT` on node1. Such a backup contains only the parts of
the local replica, and only one of the two backups to the same destination
succeeds. When node2's backup won before node2 had fetched `all_0_0_0`, the
successful backup held only the table metadata (`num backup entries=1` in
node2's log), `RESTORE` on node1 created an empty table, and the final check
failed with `assert '' == '1\n'`.

Run `SYSTEM SYNC REPLICA ON CLUSTER 'cluster' tbl` after the insert, as the
other tests of this file do. The two backups still race for the destination.

CI reports:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126329&sha=a56d34954af566916a3978497a004b351f6e2642&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%202%2F5%29
(ClickHouse#126329)
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109453&sha=806162ffe23baed3bee142174285056d8247ab1d&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%202%2F5%29
(ClickHouse#109453)

Related: ClickHouse#89141

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

This branch has not been deployed

No deployments
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... 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