Repository navigation
Fall back to local execution in make_distributed_plan for any query that resolves a dictionary or a Join table - #121567
Conversation
|
Workflow [PR], commit [2c8ee51] Summary: ✅
AI ReviewSummaryThis PR replaces the old name-based distributed-plan fallback with query-context tracking of initiator-local dictionaries, Findings❌ Blockers
Final VerdictRequest changes. The access-check regressions are blockers, and the two dismissed false-positive fallbacks are still unresolved behavior regressions in LLVM Coverage ReportMeasured on commit 2c8ee51.
Changed lines: Changed C/C++ lines covered: 168/188 (89.36%) · Uncovered code |
|
@groeneai can you review the new approach? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes462 object files changed (+83.74 KiB total), 1 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1324 translation units recompiled, 8370 s compile time in total, 1323 of them have a recent master baseline. |
groeneai
left a comment
There was a problem hiding this comment.
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.
| 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; |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| std::optional<ActionsDAG> createExpressionsAnalyzer( | ||
| const Block & header, | ||
| ASTPtr expr_list, | ||
| bool save_unneeded_columns, | ||
| ContextPtr context) |
There was a problem hiding this comment.
Refactored to extract the main part about resolving expression list in resolveExpressionList.
| @@ -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 | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
You are right, I though it is planning thing only. Let me check how to stop collection during execution
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
Should it be set/unordered_set to avoid duplicates?
There was a problem hiding this comment.
Not sure, to be honest, maybe we can just record the first offender and not care about the rest.
There was a problem hiding this comment.
Updated to only record the first offender
|
|
||
| private: | ||
| std::once_flag once; | ||
| std::optional<Entry> entry; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 :)
| 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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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.
…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]>
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
ActionsDAGof the plan for known function names. Three issues showed the limits manual walk:assignCentroidwith aNullable/LowCardinalityname (#121486),joinGet(#121487), and adictGetinside a columnDEFAULTthat 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 ofQueryFactoriesInfothat is not gated onlog_queries):ExternalDictionariesLoader::resolveDictionaryName(name, context)andqualifyDictionaryNameWithDatabase(name, context),which every path naming a dictionary goes through (
dictGetfamily,naiveBayesClassifier,dictionary());joinGet's table lookup (Jointables);Context::getEmbeddedDictionaries(theregionTo*functions);assignCentroid, which resolved its dictionary only at execution and now qualifies the name at return-type time.getReasonPlanCannotBeDistributedreads 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
ReadFromMergeTreethe coordinator does same verification as worker would (resolveMissingDefaults, extracted fromevaluateMissingDefaults), 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
make_distributed_plannow 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
26.10.1.657-master(included in26.10and later)