Skip to content

Fall back to local execution in make_distributed_plan for any query that resolves a dictionary or a Join table - #121567

Merged
antoniofilipovic merged 14 commits into
masterfrom
afilipovic-click-gap-dictionary-fallback-fixes
Sep 25, 2026
Merged

antoniofilipovic merged 14 commits into
masterfrom
afilipovic-click-gap-dictionary-fallback-fixes

Conversation

@antoniofilipovic

@antoniofilipovic antoniofilipovic commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Closes: #121486
Closes: #121487
Closes: #121489
Closes: https://github.com/ClickHouse/clickhouse-private/issues/76829
Related: #121198

Dictionaries and join tables are not shipped to the workers. In #121198 we fixed the problem by walking every ActionsDAG of the plan for known function names. Three issues showed the limits manual walk: assignCentroid with a Nullable/LowCardinality name (#121486), joinGet (#121487), and a dictGet inside a column DEFAULT that never appears in the plan at all (#121489).

The problem is that inspection needs to look for usages of dictionary, which can be arbitrarily nested inside the function.

Fix

The decision no longer looks for function names in the plan. Every function that needs a server-local object obtains
it from a small number of resolvers while the query is analyzed, so those resolvers now record the use on the query
context (UsedServerLocalObjects, a sibling of QueryFactoriesInfo that is not gated on log_queries):

  • ExternalDictionariesLoader::resolveDictionaryName(name, context) and qualifyDictionaryNameWithDatabase(name, context),
    which every path naming a dictionary goes through (dictGet family, naiveBayesClassifier, dictionary());
  • joinGet's table lookup (Join tables);
  • Context::getEmbeddedDictionaries (the regionTo* functions);
  • assignCentroid, which resolved its dictionary only at execution and now qualifies the name at return-type time.

getReasonPlanCannotBeDistributed reads the record after walking the plan and falls back with the object named in the reason.

The one thing which needs manual intervention are column defaults as they are not analyzed on initiator and they may reference dictionary. For all default columns required in the scan in the ReadFromMergeTree the coordinator does same verification as worker would (resolveMissingDefaults, extracted from
evaluateMissingDefaults), which makes the same resolvers record the use of dictionaries, and so we make the fallback.

Scope

For now all usages and references of dictionaries are recorded, and we fail back even queries which might not use them - MATERIALIZED column with dictionary, unused ALIAS dictGet columns. The scope might be limited if necessary but since we are working on PR to support dictionaries in stateless workers, this would be tolerated for now.

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

...
make_distributed_plan now falls back to local execution when a query depends on initiator-only dictionaries, joinGet tables, or MergeTree column defaults that workers cannot resolve.


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2c8ee51]

Summary: ✅


AI Review

Summary

This PR replaces the old name-based distributed-plan fallback with query-context tracking of initiator-local dictionaries, Join tables, embedded dictionaries, and MergeTree default expressions. It fixes the original missed-detection cases, but the new tracker now fires before object-level access checks and still codifies two false-positive fallbacks that keep valid remote plans local, so I would not merge it yet.

Findings

❌ Blockers

  • src/Interpreters/ExternalDictionariesLoader.cpp:97-107 The new dictionary tracker writes happen before the matching dictGet access check. A trace like dictGet -> FunctionDictGetNoType::getReturnTypeImpl -> FunctionDictHelper::getDictionaryStructure -> ExternalDictionariesLoader::resolveDictionaryName(..., context) records the dictionary, and QueryPlan::applyDistributedPlanFallbackToLocal can now return SUPPORT_IS_DISABLED / a fallback reason naming it before any checkAccess(AccessType::dictGet, ...) runs. The same applies to assignCentroid via qualifyDictionaryNameWithDatabase.
  • src/Functions/FunctionJoinGet.cpp:155-175 joinGet now records the resolved Join table before FunctionJoinGet::prepare performs its SELECT check. Under make_distributed_plan, an unauthorized query can therefore fail with SUPPORT_IS_DISABLED mentioning db.table instead of ACCESS_DENIED, which makes the fallback reason a new metadata surface.

⚠️ Majors

Final Verdict

Request changes. The access-check regressions are blockers, and the two dismissed false-positive fallbacks are still unresolved behavior regressions in make_distributed_plan.

LLVM Coverage Report

Measured on commit 2c8ee51.

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

Changed lines: Changed C/C++ lines covered: 168/188 (89.36%) · Uncovered code

Full report · Diff report

@antoniofilipovic

Copy link
Copy Markdown
Member Author

@groeneai can you review the new approach?

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 22, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2c8ee51e5 with master dc770fc7a (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

462 object files changed (+83.74 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/makeDistributed.cpp.o 562.50 KiB 601.57 KiB +39.07 KiB (+6.95%)

716 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

1324 translation units recompiled, 8370 s compile time in total, 1323 of them have a recent master baseline.

Job report

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The approach is right, and better than the walk it replaces: recording at resolution time catches a use because it happened, not because a function name matched, which is why one mechanism covers 121486, 121487 and 121489 instead of three more cases in findDictionaryFunction. It also closes a gap the walk never covered. Four things.

1. dictionary() still bypasses the record for RegExpTree, and this is the one I would fix before merge. TableFunctionDictionary::getActualTableStructure calls resolveDictionaryName() and load() directly, neither of which records, and for a RegExpTree dictionary it returns before getDictionaryStructure(), the only recording call on that path. ReadFromTableFunctionStep::isSerializable() is true and the step carries the function's serialized AST, so a worker resolves the name in its own catalog. A recordUse before that early return closes it.

Worth separating from the rest: it is not a regression. On master the walk never inspected an ISourceStep, and such a plan holds no dictGet node, so the same query ships today; your change closes that gap for every other layout as a side effect. I checked the code path, not a running cluster, and exposure needs the table function read to sit in a plan that gets distributed at all (the exchange comes from a ReadFromMergeTree), so the reachable shape is dictionary('regexp_dict') joined against a MergeTree table rather than a bare SELECT * FROM dictionary(...).

2. The invariant written on recordUse is stronger than the code. "Every path by which a query reaches a dictionary by name passes here" does not hold: resolveDictionaryName and load are reachable directly, and the three friend classes do reach them, which is exactly how 1 happens. That comment is what the author of the fourth caller will trust, so I would either state what is true (these entry points record; a caller that resolves through resolveDictionaryName or load does not), or route the friends through a recording helper.

3. A null record reads as "nothing was used". Context::getUsedServerLocalObjects() returns nullptr without a query context, QueryPlanOptimizationSettings stores whatever that gave, and both readers skip the check when the pointer is null; the Settings-based constructor cannot set the field at all. The paths that matter use the ContextPtr constructor, so I did not find a live null, but the walk needed only the plan while this needs the record to exist, and the default is the unsafe direction. A chassert if it cannot be null under make_distributed_plan = 1, or "cannot distribute" if it can.

4. getReasonColumnDefaultsCannotBeShipped assumes the worst part, and the step already knows its parts. A table with nm String DEFAULT dictGet(...) now never distributes a query selecting nm, even when every selected part holds the column and no reader will evaluate the default. It also pays for the answer on every make_distributed_plan query over that table: a createColumn() per physical column to build columns_without_default, plus buildQueryTree and QueryAnalyzer::resolve whenever a default exists. ReadFromMergeTree::getParts() is public and IMergeTreeDataPart::hasColumnFiles() answers exactly what the check is guessing at, so gating the resolution on "some selected part actually lacks a required column that has a default" restores the materialized case and skips the work in the common one. Conservative is the right default here; I would just rather it were not permanent for a fully materialized column. Your call whether that belongs in this PR.

Nit: the new call sits in a second if (const auto * read = typeid_cast<const ReadFromMergeTree *>(&step)) immediately after the first one; they can be one block.

On CI: the only complete run is on e2415ae3 ("fix temp"), the first of the four commits, so the six red test_distributed_plan_dictionary_fallback tests in the summary predate "properly track dictionaries usage". The head 90689d3f has no run yet.

Comment on lines -83 to -119
std::optional<String> found;
auto is_dictionary_function = [&](const IFunctionBase & function)
{
const auto & name = function.getName();
/// `assignCentroid` reads a dictionary only when its second argument is a `String` (the name); the other form
/// carries the centroids inline as an array and ships fine.
const auto & argument_types = function.getArgumentTypes();
bool is_assign_centroid_over_dictionary = name == "assignCentroid" && argument_types.size() == 2 && isString(argument_types[1]);
if (!functionIsDictGet(name) && !is_assign_centroid_over_dictionary)
return false;
found = name;
return true;
};

for (const auto & node : dag.getNodes())
{
if (node.type == ActionsDAG::ActionType::FUNCTION && node.function_base && is_dictionary_function(*node.function_base))
return found;
if (ActionsDAG::hasUnsafeHiddenLambdaBody(node, is_dictionary_function))
return found;
}
return std::nullopt;
};

if (const auto * expression = typeid_cast<const ExpressionStep *>(&step))
return find_in_dag(expression->getExpression());
if (const auto * filter = typeid_cast<const FilterStep *>(&step))
return find_in_dag(filter->getExpression());
if (const auto * join = typeid_cast<const JoinStepLogical *>(&step))
return find_in_dag(join->getActionsDAG());
if (const auto * limit_range = typeid_cast<const LimitRangeStep *>(&step))
return find_in_dag(limit_range->getConditions());
if (const auto * filling = typeid_cast<const FillingStep *>(&step))
{
if (const auto & interpolate = filling->getInterpolateDescription())
return find_in_dag(interpolate->actions);
return std::nullopt;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This old visit method is removed completely. Now we track dictionary used in the ExternalDictionariesLoader.cpp which makes context collect usages of dictionaries.

/// inside the defaults then resolve to columns, so no call folds into a constant that would run here.
Block columns_present_in_parts;
for (const auto & column : columns.getAllPhysical())
if (!columns.getDefault(column.name))

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.

This assumes every defaulted column is missing from every selected part, so the check fires even when the worker will never evaluate the default. The new t_mat case shows the regression: after ALTER ... MATERIALIZE COLUMN m, every selected part already stores m, so a worker read would consume bytes only and never resolve d_both, but resolveMissingDefaults still records it and forces the whole query local. ReadFromMergeTree already knows the selected parts (getParts()), so this needs to check whether any selected part actually lacks the requested defaulted column before treating the default expression as a remote dependency.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

For now we accepted that even if column is materialized from dictionary, it will be discarded for distributed_plan. It would need checking individual parts, and checking if part name was altered. I would at least leave it out of this PR and if needed we can introduce it later

LOG_TRACE(getLogger("makeDistributedPlan"), "No record of the server-local objects the query resolved; assuming none");
return std::nullopt;
}
if (auto entry = used->first())

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.

This query-level gate is broader than "objects a worker fragment will resolve". The added t_alias case shows the regression: SELECT k FROM t_alias falls back solely because table initialization resolved the unused ALIAS dictGet(...) column. The same shared used_server_local_objects record will also make parent plans fall back when only a local child plan or scalar subquery resolved the object. The decision needs to be scoped to objects that survive into remote-executed fragments, not every object touched anywhere during analysis.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Example is valid. If column is ALIASed it is still resolved and it means resolving usage of dictionary which results in not shipping the query as make_distributed_plan. All this will soon go away in any case as we want to support dictionaries, so this is just to avoid DAG walk with many different function names in it and manually checking dict references.

Comment on lines -222 to -226
std::optional<ActionsDAG> createExpressionsAnalyzer(
const Block & header,
ASTPtr expr_list,
bool save_unneeded_columns,
ContextPtr context)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Refactored to extract the main part about resolving expression list in resolveExpressionList.

@antoniofilipovic antoniofilipovic changed the title Fallback to local execution all references of dictionary Fall back to local execution in make_distributed_plan for any query that resolves a dictionary or a Join table Sep 23, 2026
@antoniofilipovic
antoniofilipovic marked this pull request as ready for review September 23, 2026 14:18
@@ -94,9 +94,28 @@ void ExternalDictionariesLoader::updateObjectFromConfigWithoutReloading(IExterna
dict.updateDictionaryComment(config.getString(key_in_config + ".comment", ""));
}

void ExternalDictionariesLoader::recordUse(const std::string & dictionary_name, const ContextPtr & local_context) const

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we call this only during analysis or during execution? If it's execution than we will call this for each block and addUsedServerLocalObject can potentially accumulate millions of objects.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right, I though it is planning thing only. Let me check how to stop collection during execution

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I decide to record only first offender. Like with all other steps in the static check, we only care if we find one offending step/part

static std::string_view kindName(Kind kind);

private:
std::vector<Entry> entries;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should it be set/unordered_set to avoid duplicates?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not sure, to be honest, maybe we can just record the first offender and not care about the rest.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Updated to only record the first offender

@alesapin alesapin self-assigned this Sep 23, 2026
Comment thread src/Processors/QueryPlan/QueryPlan.cpp Resolved

private:
std::once_flag once;
std::optional<Entry> entry;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

To it looks like we still need kind of mutex here, but I'm not 100% sure. Feels like get() and add() potentially can be called concurrently.

@antoniofilipovic antoniofilipovic Sep 24, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Aha, actually they can't be called concurrently. Get is only called after planning is done. The synchronization of whole call is need only for subquery execution which can spawn multiple threads, but after that we have synchronous calls only to get(). So it is safe without.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

There is some obscure case of parallel_view_processing which can happen with sync get and add so decided to add mutex to be on safe side. Thanks for raising this :)

@antoniofilipovic
antoniofilipovic added this pull request to the merge queue Sep 24, 2026
@antoniofilipovic
antoniofilipovic removed this pull request from the merge queue due to a manual request Sep 24, 2026
std::string ExternalDictionariesLoader::resolveDictionaryName(const std::string & dictionary_name, ContextPtr local_context) const
{
auto resolved = resolveDictionaryName(dictionary_name, local_context->getCurrentDatabase());
local_context->addDistributedPlanLocalObject(DistributedPlanLocalObject::Kind::Dictionary, resolved.qualified_name.getFullName());

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.

Recording the dictionary here makes make_distributed_plan observable before the query has passed its dictionary privilege check. A concrete trace is dictGet -> FunctionDictGetNoType::getReturnTypeImpl -> FunctionDictHelper::getDictionaryStructure -> ExternalDictionariesLoader::resolveDictionaryName(..., context) -> Context::addDistributedPlanLocalObject; QueryPlan::applyDistributedPlanFallbackToLocal can then raise SUPPORT_IS_DISABLED / the fallback reason naming the dictionary before FunctionDictHelper::getDictionary ever reaches checkAccess(AccessType::dictGet, ...). The qualifyDictionaryNameWithDatabase(..., ContextPtr) overload below has the same problem for assignCentroid. That turns an authorization failure into an unsupported-plan error and makes the fallback reason a new metadata surface. Please move the tracker write after the relevant access check, or add an early dictGet check on the structure/layout/qualification paths before recording.

@antoniofilipovic antoniofilipovic Sep 24, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This will throw on access before the check on fallback so it is okay, strict mode is only for tests, hence should not be observable by user

if (!storage_join)
throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Table {} should have engine StorageJoin", join_name);
/// Resolved on the executing server: a `make_distributed_plan` worker would look it up in its own catalog.
context->addDistributedPlanLocalObject(DistributedPlanLocalObject::Kind::JoinTable, storage_id.getFullTableName());

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.

joinGet now records the resolved Join table before FunctionJoinGet::prepare performs its SELECT check. With make_distributed_plan = 1, buildImpl can therefore mark the query unsupported and QueryPlan::applyDistributedPlanFallbackToLocal / convertToDistributed will fail with SUPPORT_IS_DISABLED mentioning db.table before the user ever reaches context->checkAccess(AccessType::SELECT, ...) in prepare. That changes the primary user-visible failure from ACCESS_DENIED to an unsupported-plan error and makes the table name part of the fallback surface. The access check needs to move into getJoin (or be duplicated there) before this tracker write.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same as above

@antoniofilipovic
antoniofilipovic added this pull request to the merge queue Sep 25, 2026
Merged via the queue into master with commit 4cafc26 Sep 25, 2026
339 of 341 checks passed
@antoniofilipovic
antoniofilipovic deleted the afilipovic-click-gap-dictionary-fallback-fixes branch September 25, 2026 09:19
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 25, 2026
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 13, 2026
…nt-subquery-loading-dependency"

This reverts commit 659cc1c, reversing
changes made to f75df10.

Conflicts resolved by removing only what ClickHouse#114923 added: the narrow
qualification pass in AddDefaultDatabaseVisitor.h is removed together with
the parts ClickHouse#114908 later added inside it; InterpreterCreateQuery.cpp keeps
the expansion bound of ClickHouse#122362 on the neighbouring call; the string overload
of qualifyDictionaryNameWithDatabase in ExternalDictionariesLoader is kept,
because the dictionary usage record of ClickHouse#121567 is built on it.
04908_constraint_subquery_loading_dependency.sh (edited by ClickHouse#124408) is
deleted with the rest of the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... 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

4 participants