Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
duckdb::CommonSubplanFinder Class Reference
Collaboration diagram for duckdb::CommonSubplanFinder:

Classes

struct  OperatorInfo
struct  StackNode
struct  SubplanStats

Public Member Functions

 CommonSubplanFinder (ClientContext &context)
void FindCommonSubplans (reference< unique_ptr< LogicalOperator > > root)
void FilterSubplans ()
void ConvertSubplansToCTEs (Optimizer &optimizer, unique_ptr< LogicalOperator > &op)

Private Member Functions

arena_ptr< PlanSignature > CreatePlanSignature (const unique_ptr< LogicalOperator > &op)
arena_vector< ColumnBinding > GetCanonicalBindings (LogicalOperator &op)
unique_ptr< LogicalOperator > & LowestCommonAncestor (reference< unique_ptr< LogicalOperator > > a, reference< unique_ptr< LogicalOperator > > b)
bool ShouldMaterialize (const SubplanInfo &subplan_info) const
vector< reference< subplan_map_t::value_type > > GetSortedSubplans ()

Static Private Member Functions

static SubplanStats GetSubplanStats (const LogicalOperator &op)
static bool IsSelectiveMultiTablePlan (unique_ptr< LogicalOperator > &op)

Private Attributes

PlanSignatureCreateState state
 State for creating PlanSignature with reusable data structures.
reference_map_t< unique_ptr< LogicalOperator >, OperatorInfo > operator_infos
 Mapping from operator to info.
subplan_map_t subplans
 Mapping from subplan signature to subplan information.
unordered_map< idx_t, idx_t > to_canonical_table_index
 Mapping from original table index to canonical table index.
optional_idx min_cte_idx
 Minimum CTE index created by this optimizer.

Constructor & Destructor Documentation

◆ CommonSubplanFinder()

duckdb::CommonSubplanFinder::CommonSubplanFinder ( ClientContext & context)
inlineexplicit
304996 : state(context) {
304997 }
PlanSignatureCreateState state
State for creating PlanSignature with reusable data structures.
Definition duckdb.cpp:305435

Member Function Documentation

◆ FindCommonSubplans()

void duckdb::CommonSubplanFinder::FindCommonSubplans ( reference< unique_ptr< LogicalOperator > > root)
inline
305038 {
305039 // Find first operator with more than 1 child
305040 while (root.get()->children.size() == 1) {
305041 root = root.get()->children[0];
305042 }
305043
305044 // Recurse through query plan using stack-based recursion
305045 arena_vector<StackNode> stack(state.allocator);
305046 stack.emplace_back(root);
305047 operator_infos.emplace(root, OperatorInfo(root, 0));
305048
305049 while (!stack.empty()) {
305050 auto &current = stack.back();
305051
305052 // Depth-first
305053 if (current.HasMoreChildren()) {
305054 auto &child = current.GetNextChild();
305055 operator_infos.emplace(child, OperatorInfo(current.op, stack.size()));
305056 stack.emplace_back(child);
305057 continue;
305058 }
305059
305060 if (!RefersToSameObject(current.op, root.get())) {
305061 // We have all child information for this operator now, compute signature
305062 auto &signature = operator_infos.find(current.op)->second.signature;
305063 signature = CreatePlanSignature(current.op);
305064
305065 // Add to subplans (if we got actually got a signature)
305066 if (signature) {
305067 const auto current_op_table_index = current.op->GetTableIndex();
305068 auto it = subplans.find(*signature);
305069 if (it == subplans.end()) {
305070 // New subplan, map table indices
305071 arena_vector<idx_t> canonical_table_indices(state.allocator);
305072 for (auto &table_index : current_op_table_index) {
305073 const auto next_canonical_table_index = to_canonical_table_index.size();
305074 canonical_table_indices.push_back(next_canonical_table_index);
305075 D_ASSERT(to_canonical_table_index.find(table_index) == to_canonical_table_index.end());
305076 to_canonical_table_index.emplace(table_index, next_canonical_table_index);
305077 }
305078
305079 // Add new subplan
305080 SubplanInfo subplan_info(state.allocator, current.op, std::move(canonical_table_indices),
305081 GetCanonicalBindings(*current.op));
305082 subplans.emplace(*signature, std::move(subplan_info));
305083 } else {
305084 auto &info = it->second;
305085 // Matches existing subplan, map already existing table indices
305086 D_ASSERT(current_op_table_index.size() == info.canonical_table_indices.size());
305087 for (idx_t i = 0; i < current_op_table_index.size(); i++) {
305088 to_canonical_table_index.emplace(current_op_table_index[i],
305089 info.canonical_table_indices[i]);
305090 }
305091
305092 // Add subplan to existing
305093 info.subplans.push_back({current.op, GetCanonicalBindings(*current.op)});
305094 info.lowest_common_ancestor = LowestCommonAncestor(info.lowest_common_ancestor, current.op);
305095 }
305096 }
305097 }
305098
305099 // Done with current
305100 stack.pop_back();
305101 }
305102 }
unordered_map< idx_t, idx_t > to_canonical_table_index
Mapping from original table index to canonical table index.
Definition duckdb.cpp:305441
reference_map_t< unique_ptr< LogicalOperator >, OperatorInfo > operator_infos
Mapping from operator to info.
Definition duckdb.cpp:305437
subplan_map_t subplans
Mapping from subplan signature to subplan information.
Definition duckdb.cpp:305439
bool RefersToSameObject(const reference< T > &a, const reference< T > &b)
Returns whether or not two reference wrappers refer to the same object.
Definition duckdb.hpp:2191
uint64_t idx_t
a saner size_t for loop indices etc
Definition duckdb.hpp:237
Definition duckdb.cpp:305000

◆ FilterSubplans()

void duckdb::CommonSubplanFinder::FilterSubplans ( )
inline
305104 {
305105 // Filter out redundant or ineligible subplans before returning
305106 vector<subplan_map_t::key_type> to_remove;
305107 for (auto &entry : subplans) {
305108 auto &signature = entry.first.get();
305109 auto &subplan_info = entry.second;
305110 if (signature.OperatorCount() == 1) {
305111 to_remove.push_back(signature); // Just one operator in this subplan
305112 continue;
305113 }
305114 if (subplan_info.subplans.size() == 1) {
305115 to_remove.push_back(signature); // No other identical subplan
305116 continue;
305117 }
305118
305119 auto &parent_op = operator_infos.find(subplan_info.subplans[0].op)->second.parent;
305120 auto &parent_signature = operator_infos.find(parent_op)->second.signature;
305121 if (parent_signature) {
305122 auto parent_it = subplans.find(*parent_signature);
305123 if (parent_it != subplans.end()) {
305124 const auto subplan_count = subplan_info.subplans.size() * signature.OperatorCount();
305125 const auto parent_count = parent_it->second.subplans.size() * parent_signature->OperatorCount();
305126 if (parent_count >= subplan_count) {
305127 to_remove.push_back(signature); // Parent is better, this one is redundant
305128 continue;
305129 }
305130 }
305131 }
305132
305133 // Collect all subplan bindings, and figure out which subplan has the most outgoing bindings
305134 idx_t max_subplan_idx = 0;
305135 for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) {
305136 const auto &subplan_bindings = subplan_info.subplans[subplan_idx].canonical_bindings;
305137 const auto &max_subplan_bindings = subplan_info.subplans[max_subplan_idx].canonical_bindings;
305138 if (subplan_bindings.size() > max_subplan_bindings.size()) {
305139 max_subplan_idx = subplan_idx;
305140 }
305141 }
305142
305143 // Move the "maximum subplan" to the front
305144 std::swap(subplan_info.subplans[0], subplan_info.subplans[max_subplan_idx]);
305145
305146 // We can bail on a subplan for various reasons (some of which could potentially be fixed)
305147 bool bail = false;
305148
305149 // Insert the bindings of the subplan with the most bindings into a set
305150 column_binding_set_t max_subplan_column_binding_set;
305151 for (auto &cb : subplan_info.subplans[0].canonical_bindings) {
305152 if (max_subplan_column_binding_set.find(cb) != max_subplan_column_binding_set.end()) {
305153 bail = true; // Subplan contains duplicate column bindings, i.e., another nested duplicate subplan
305154 break;
305155 }
305156 max_subplan_column_binding_set.insert(cb);
305157 }
305158
305159 // Check if the maximum subplan fully contains the column bindings of the other subplans
305160 for (idx_t subplan_idx = 1; subplan_idx < subplan_info.subplans.size() && !bail; subplan_idx++) {
305161 const auto &subplan_bindings = subplan_info.subplans[subplan_idx].canonical_bindings;
305162 for (auto &cb : subplan_bindings) {
305163 if (max_subplan_column_binding_set.find(cb) == max_subplan_column_binding_set.end()) {
305164 bail = true; // Subplan does not fully contain the the other subplans
305165 break;
305166 }
305167 }
305168 }
305169
305170 if (bail) {
305171 to_remove.push_back(signature);
305172 }
305173 }
305174
305175 // Only remove them all at the end so the logic above doesn't get affected
305176 for (auto &signature : to_remove) {
305177 subplans.erase(signature);
305178 }
305179 }

◆ ConvertSubplansToCTEs()

void duckdb::CommonSubplanFinder::ConvertSubplansToCTEs ( Optimizer & optimizer,
unique_ptr< LogicalOperator > & op )
inline
305181 {
305182 const auto sorted_subplans = GetSortedSubplans();
305183 idx_t index = 1;
305184 for (auto &entry : sorted_subplans) {
305185 auto &subplan_info = entry.get().second;
305186 if (!ShouldMaterialize(subplan_info)) {
305187 continue; // No longer worth materializing due to other materializations
305188 }
305189
305190 const auto cte_index = optimizer.binder.GenerateTableIndex();
305191 const auto cte_name = StringUtil::Format("__common_subplan_%llu", index++);
305192 if (!min_cte_idx.IsValid()) {
305193 min_cte_idx = cte_index;
305194 }
305195
305196 // Resolve types to be used for creating the materialized CTE and refs
305197 op->ResolveOperatorTypes();
305198
305199 // Get types and names
305200 const auto &primary_subplan = subplan_info.subplans[0];
305201 const auto &types = primary_subplan.op.get()->types;
305202 vector<string> col_names;
305203 for (idx_t i = 0; i < types.size(); i++) {
305204 col_names.emplace_back(StringUtil::Format("%s_col_%llu", cte_name, i + 1));
305205 }
305206 const auto &primary_subplan_bindings = primary_subplan.canonical_bindings;
305207 column_binding_map_t<idx_t> primary_binding_index;
305208 for (idx_t i = 0; i < primary_subplan_bindings.size(); i++) {
305209 primary_binding_index.emplace(primary_subplan_bindings[i], i);
305210 }
305211 vector<vector<idx_t>> cte_column_indexes(subplan_info.subplans.size());
305212 vector<bool> needs_projection(subplan_info.subplans.size(), false);
305213 for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) {
305214 const auto &subplan = subplan_info.subplans[subplan_idx];
305215 const auto &canonical_bindings = subplan.canonical_bindings;
305216 cte_column_indexes[subplan_idx].reserve(canonical_bindings.size());
305217 needs_projection[subplan_idx] = canonical_bindings.size() != types.size();
305218 for (idx_t i = 0; i < canonical_bindings.size(); i++) {
305219 const auto &cb = canonical_bindings[i];
305220 const auto entry = primary_binding_index.find(cb);
305221 D_ASSERT(entry != primary_binding_index.end()); // guaranteed by FilterSubplans
305222 const auto cte_col_idx = entry->second;
305223 // Types must match: same canonical binding = same base column = same type
305224 D_ASSERT(subplan.op.get()->types[i] == types[cte_col_idx]);
305225 cte_column_indexes[subplan_idx].push_back(cte_col_idx);
305226 needs_projection[subplan_idx] = needs_projection[subplan_idx] || cte_col_idx != i;
305227 }
305228 }
305229
305230 // Create CTE refs and figure out column binding replacements
305231 vector<unique_ptr<LogicalOperator>> cte_refs;
305232 ColumnBindingReplacer replacer;
305233 for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) {
305234 const auto &subplan = subplan_info.subplans[subplan_idx];
305235 const auto cte_ref_index = optimizer.binder.GenerateTableIndex();
305236 cte_refs.emplace_back(make_uniq<LogicalCTERef>(cte_ref_index, cte_index, types, col_names));
305237 if (subplan.op.get()->has_estimated_cardinality) {
305238 cte_refs.back()->SetEstimatedCardinality(subplan.op.get()->estimated_cardinality);
305239 }
305240 const auto old_bindings = subplan.op.get()->GetColumnBindings();
305241 auto new_bindings = cte_refs.back()->GetColumnBindings();
305242 if (needs_projection[subplan_idx]) {
305243 // Preserve each subplan's original output order when it differs from the
305244 // primary materialized CTE.
305245 vector<unique_ptr<Expression>> select_list;
305246 for (auto cte_col_idx : cte_column_indexes[subplan_idx]) {
305247 select_list.emplace_back(make_uniq<BoundColumnRefExpression>(
305248 types[cte_col_idx], ColumnBinding(cte_ref_index, cte_col_idx)));
305249 }
305250
305251 // Place the projection on top
305252 auto proj =
305253 make_uniq<LogicalProjection>(optimizer.binder.GenerateTableIndex(), std::move(select_list));
305254 proj->children.emplace_back(std::move(cte_refs.back()));
305255 cte_refs.back() = std::move(proj);
305256 new_bindings = cte_refs.back()->GetColumnBindings();
305257 }
305258 D_ASSERT(old_bindings.size() == new_bindings.size());
305259 for (idx_t i = 0; i < old_bindings.size(); i++) {
305260 replacer.replacement_bindings.emplace_back(old_bindings[i], new_bindings[i]);
305261 }
305262 }
305263
305264 // Create the materialized CTE and replace the common subplans with references to it
305265 auto &lowest_common_ancestor = subplan_info.lowest_common_ancestor.get();
305266 const auto materialized_column_count = types.size();
305267 auto materialized_subplan = std::move(primary_subplan.op.get());
305268 auto remainder = std::move(lowest_common_ancestor);
305269 vector<unique_ptr<Expression>> materialized_select_list;
305270 const auto materialized_bindings = materialized_subplan->GetColumnBindings();
305271 for (idx_t i = 0; i < materialized_bindings.size(); i++) {
305272 materialized_select_list.emplace_back(
305273 make_uniq<BoundColumnRefExpression>(types[i], materialized_bindings[i]));
305274 }
305275 auto materialized_projection = make_uniq<LogicalProjection>(optimizer.binder.GenerateTableIndex(),
305276 std::move(materialized_select_list));
305277 materialized_projection->children.emplace_back(std::move(materialized_subplan));
305278 auto cte = make_uniq<LogicalMaterializedCTE>(cte_name, cte_index, materialized_column_count,
305279 std::move(materialized_projection), std::move(remainder),
305280 CTEMaterialize::CTE_MATERIALIZE_DEFAULT);
305281 for (idx_t subplan_idx = 0; subplan_idx < subplan_info.subplans.size(); subplan_idx++) {
305282 const auto &subplan = subplan_info.subplans[subplan_idx];
305283 subplan.op.get() = std::move(cte_refs[subplan_idx]);
305284 }
305285 lowest_common_ancestor = std::move(cte);
305286
305287 // Replace bindings of subplans with those of the CTE refs
305288 replacer.stop_operator = lowest_common_ancestor.get();
305289 replacer.VisitOperator(*op); // Replace from the root until CTE
305290 replacer.VisitOperator(*lowest_common_ancestor->children[1]); // Replace in CTE child
305291
305292 // We have to be careful with the order in which we place the CTEs created by this optimizer
305293 // Pipeline dependencies cannot be set up if CTEs are in the wrong order
305294 // This performs "CTE pushdown" until the CTEs are in the correct order
305295 reference<unique_ptr<LogicalOperator>> current_op = lowest_common_ancestor;
305296 while (true) {
305297 auto &rhs_child = current_op.get()->children[1];
305298 if (rhs_child->type == LogicalOperatorType::LOGICAL_MATERIALIZED_CTE) {
305299 const auto child_table_index = rhs_child->Cast<LogicalMaterializedCTE>().table_index;
305300 if (child_table_index >= min_cte_idx.GetIndex() && child_table_index < cte_index) {
305301 auto tmp = std::move(rhs_child->children[1]);
305302 rhs_child->children[1] = std::move(current_op.get());
305303 current_op.get() = std::move(rhs_child);
305304 rhs_child = std::move(tmp);
305305 current_op = current_op.get()->children[1];
305306 continue;
305307 }
305308 }
305309 break;
305310 }
305311 }
305312 }
optional_idx min_cte_idx
Minimum CTE index created by this optimizer.
Definition duckdb.cpp:305443
static string Format(const string fmt_str, ARGS... params)
Format a string using printf semantics.
Definition duckdb.hpp:4002
index

◆ CreatePlanSignature()

arena_ptr< PlanSignature > duckdb::CommonSubplanFinder::CreatePlanSignature ( const unique_ptr< LogicalOperator > & op)
inlineprivate
305315 {
305316 vector<reference<PlanSignature>> child_signatures;
305317 for (auto &child : op->children) {
305318 auto it = operator_infos.find(child);
305319 D_ASSERT(it != operator_infos.end());
305320 if (!it->second.signature) {
305321 return nullptr; // Failed to create signature from one of the children
305322 }
305323 child_signatures.emplace_back(*it->second.signature);
305324 }
305325 return PlanSignature::Create(state, *op, std::move(child_signatures));
305326 }

◆ GetCanonicalBindings()

arena_vector< ColumnBinding > duckdb::CommonSubplanFinder::GetCanonicalBindings ( LogicalOperator & op)
inlineprivate
305328 {
305329 // Compute the canonical column bindings coming out of this operator for convenience later
305330 const auto &table_index_map = state.table_index_map.GetMap();
305331 const auto original_bindings = op.GetColumnBindings();
305332 arena_vector<ColumnBinding> canonical_bindings(state.allocator);
305333 for (idx_t col_idx = 0; col_idx < original_bindings.size(); col_idx++) {
305334 auto &cb = original_bindings[col_idx];
305335 const auto canonical_table_index = to_canonical_table_index.at(cb.table_index);
305336 auto &table_map = table_index_map.at(cb.table_index);
305337 if (table_map.Empty<ConversionType::TO_CANONICAL>()) {
305338 canonical_bindings.emplace_back(canonical_table_index, cb.column_index);
305339 } else {
305340 const auto canonical_col_idx = table_map.Get<ConversionType::TO_CANONICAL>(cb.column_index);
305341 canonical_bindings.emplace_back(canonical_table_index, canonical_col_idx);
305342 }
305343 }
305344 return canonical_bindings;
305345 }

◆ LowestCommonAncestor()

unique_ptr< LogicalOperator > & duckdb::CommonSubplanFinder::LowestCommonAncestor ( reference< unique_ptr< LogicalOperator > > a,
reference< unique_ptr< LogicalOperator > > b )
inlineprivate
305348 {
305349 auto a_it = operator_infos.find(a);
305350 auto b_it = operator_infos.find(b);
305351 D_ASSERT(a_it != operator_infos.end() && b_it != operator_infos.end());
305352
305353 // Get parents of a and b until they're at the same depth
305354 while (a_it->second.depth > b_it->second.depth) {
305355 a = a_it->second.parent;
305356 a_it = operator_infos.find(a);
305357 D_ASSERT(a_it != operator_infos.end());
305358 }
305359 while (b_it->second.depth > a_it->second.depth) {
305360 b = b_it->second.parent;
305361 b_it = operator_infos.find(b);
305362 D_ASSERT(b_it != operator_infos.end());
305363 }
305364
305365 // Move up one level at a time for both until ancestor is the same
305366 while (!RefersToSameObject(a, b)) {
305367 a_it = operator_infos.find(a);
305368 b_it = operator_infos.find(b);
305369 D_ASSERT(a_it != operator_infos.end() && b_it != operator_infos.end());
305370 a = a_it->second.parent;
305371 b = b_it->second.parent;
305372 }
305373
305374 return a.get();
305375 }

◆ ShouldMaterialize()

bool duckdb::CommonSubplanFinder::ShouldMaterialize ( const SubplanInfo & subplan_info) const
inlineprivate
305377 {
305378 auto &subplan = subplan_info.subplans[0].op.get();
305379 return CTEInlining::EndsInAggregateOrDistinct(*subplan) || IsSelectiveMultiTablePlan(subplan);
305380 }

◆ GetSubplanStats()

SubplanStats duckdb::CommonSubplanFinder::GetSubplanStats ( const LogicalOperator & op)
inlinestaticprivate
305382 {
305383 SubplanStats subplan_stats;
305384 if (op.children.empty()) {
305385 subplan_stats.base_table_count = 1;
305386 subplan_stats.max_base_table_cardinality = op.has_estimated_cardinality ? op.estimated_cardinality : 0;
305387 } else {
305388 subplan_stats = GetSubplanStats(*op.children[0]);
305389 for (idx_t i = 1; i < op.children.size(); i++) {
305390 subplan_stats.Combine(GetSubplanStats(*op.children[i]));
305391 }
305392 }
305393 return subplan_stats;
305394 }
Definition duckdb.cpp:305026

◆ IsSelectiveMultiTablePlan()

bool duckdb::CommonSubplanFinder::IsSelectiveMultiTablePlan ( unique_ptr< LogicalOperator > & op)
inlinestaticprivate
305396 {
305397 static constexpr idx_t CARDINALITY_THRESHOLD = 2048;
305398 static constexpr idx_t CARDINALITY_RATIO = 2;
305399
305400 // Must have an estimated cardinality
305401 if (!op->has_estimated_cardinality) {
305402 return false;
305403 }
305404
305405 // Must select more than 1 base table
305406 const auto subplan_stats = GetSubplanStats(*op);
305407 if (subplan_stats.base_table_count < 2) {
305408 return false;
305409 }
305410
305411 // If it has this cardinality or less, just materialize
305412 if (op->estimated_cardinality <= CARDINALITY_THRESHOLD) {
305413 return true;
305414 }
305415
305416 // Otherwise, materialize if it is selective enough
305417 return op->estimated_cardinality < subplan_stats.max_base_table_cardinality / CARDINALITY_RATIO;
305418 }

◆ GetSortedSubplans()

vector< reference< subplan_map_t::value_type > > duckdb::CommonSubplanFinder::GetSortedSubplans ( )
inlineprivate
305420 {
305421 // Grab entries from map, and sort by smallest plans first
305422 vector<reference<subplan_map_t::value_type>> subplan_infos;
305423 for (auto &entry : subplans) {
305424 subplan_infos.push_back(entry);
305425 }
305426 std::sort(subplan_infos.begin(), subplan_infos.end(),
305427 [](reference<subplan_map_t::value_type> lhs, reference<subplan_map_t::value_type> rhs) {
305428 return lhs.get().first.get().OperatorCount() < rhs.get().first.get().OperatorCount();
305429 });
305430 return subplan_infos;
305431 }

The documentation for this class was generated from the following file: