Conversation
This was referenced Oct 3, 2026
zzylol
marked this pull request as draft
October 3, 2026 19:29
Contributor
Author
|
Parked as draft: PR priorities changed (see #528). Order is now (A) finish #511 operator sharing, (B) the #572 crate/module reorganization, (C) #509 end-to-end stages. This PR sits on the old 🤖 Generated with Claude Code |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem: selection picks per root, but #509 asks for the cheapest complete plan for the whole workload
#509 §Stages and their decisions says a candidate is a DAG "for the whole workload, not for one query", and that stage 3 is "the only step that chooses one candidate DAG". #509 §3 Plan selection says:
#509 §Pass 2 adds: "Applying a rule adds a shared candidate and keeps the independent candidates, so selection can compare both."
The shipped
MajorPassdoes not do this. It ranks choices locally, assembles each root, interns identical producers with CSE, and then reconciles shared states.replacement.rssays so itself: "This is not an exhaustive search over combinations of choices for a provably-global optimum". Two cases it cannot get right:Example 1: locally expensive, globally cheaper
The fixture in
crates/integration-tests/tests/complete_workload_selection.rshas two queries over one table:Its cost model (
InteractingCosts) quotes:Compared root by root, raw (1.0) beats a summary build (10.0) for each query. The cheapest complete workload is "both summaries" at 0.25. A per-root comparison never sees that number.
Example 2: share some consumers, not all
Three identical
SUM(value)queries read one producer. The possible sharing layouts are the set partitions of the three readers:CSE interns all three into one state (
{0,1,2}), andMajorPassfalls back to unshared roots only when the union cannot be costed. The three partial layouts are never generated, so they cannot win even when they are cheapest.planner-layering-status.mdlisted both gaps before this PR: "It does not enumerate all partial sharing partitions", and the cheapest complete candidate guarantee "need[s] a complete workload search/selection path".Scope
This PR covers the #509 §3 requirement "choose the cheapest valid plan for the whole workload" over the candidates the planner can already generate: registered Pass 1 alternatives, exact pane compositions from #566 (window-composition rule), partial sharing of identical producers (Pass 2 identical-expression rule), and the lifecycle (materialization) alternatives of each state. It leaves out: resizing a shared summary to its strictest consumer (#509 §Pass 2), parallelism, partitioning and resources (TODO in #509 §2), new accuracy certificates, and asserting the illustrative 54/156 inventory counts from #509's examples.
Proposed method
A new pass,
CompletePass(namecomplete), runs as stage 3 plan selection. It enumerates complete workload assignments, prices each one with a single workload-level cost hook, and returns the cheapest. It is opt-in.majorstays the default because it accepts rank-only cost models, and a rank cannot certify a complete cost.CompletePass::enumeratedoes five nested steps. Every step is bounded bymax_candidates.search_workload_with_targetsand the default strategies, then list every workload DAG withCandidateLogicalASAPDAGs::enumerate_candidate_dags. Itsrejected_assembliesseed the inventory's rejection list.enumerate_window_compositions(Generate exact window composition and materialization candidates #566) returns the original state plus each exact pane composition. The pass takes the Cartesian product across roots.sharing_partitionsfirst interns the roots withshare_common_sub_dags. Every node reached by more than one reader forms a class. For each class it enumerates every set partition of its readers. It then rebuilds each reader's DAG: readers in the same group get the sameRc, others get their own copy.enumerate_assembled_plansre-enumerates each deployment's lifecycle alternatives against that union, so a shared state is costed with all of its consumers and an unshared one with only its own.SummaryMaintenanceLifecycleCandidates::enumerate_plansreturns every legal, fully costed lifecycle combination for a root, instead of only the cheapest. The pass takes the product across roots.Each full assignment is then checked and priced:
compatiblerejects it if one sharedRchas different lifecycle guarantees or window frameworks in different plans. Every plan must also passexecution_timed_dag().CostModel::complete_workload_candidate_costquotes the whole assignment.Noneor a non-finite/negative value is recorded as a rejection reason, never treated as zero.PlanOutputs withworkload_total_costset.optimizereturns the candidate with the smallestworkload_total_cost, or an error listing all rejection reasons. Exceeding any budget (logical, pane, partition, assembly, lifecycle, or assignment) is an error even if a priced candidate was already found. There is no heuristic fallback.The default cost hook is additive. It sums each root's selected total cost and subtracts a deployment's cost each time the same
Rcappears again, so a shared producer is charged once. Deployments whose roots interact (as in Example 1) override the hook. Workloads with scalar roots need an override too: the default returnsNonebecause the per-root hooks do not price scalar execution.Key code interfaces
crates/asap-aware-mapping/src/pass/complete.rs(new):crates/asap-aware-mapping/src/cost_model.rs, newCostModelmethod with an additive default:crates/asap-aware-mapping/src/pass/mod.rs:crates/asap-aware-mapping/src/summary_maintenance_lifecycle.rs:Usage:
Crate-private helpers:
enumerate_assembled_plans(new),enumerate_with_profile(nowpub(crate)),sharing_partitions,compatible,product.Fields
CompletePassmax_candidatesusizeOptimizeError::CompleteSelectionwith no partial inventory.0is rejected ("requires a positive budget"). Default65_536. Set by the caller.CompletePass::enumerateinput: OptimizationInput<'_>PlanningModels(cost, accuracy, evidence, capabilities) andLifecycleInput(now_ms,horizon). Validated first.CompleteWorkloadInventoryCompleteWorkloadInventorycandidatesVec<PlanOutput>QueryLifecyclePlanper workload entry,scalar_rootscopied from the workload, andworkload_total_cost = Some(..).rejectedVec<String>rejected_assemblies, lifecycle enumeration errors, "shared state has inconsistent lifecycle/window assignment", "complete workload cost is unknown", "complete workload cost is invalid".OptimizationPass for CompletePassname()"complete"; the key inPassRegistry.optimize(input)enumerateand returns the candidate with the minimumworkload_total_cost(f64::total_cmp). No candidate →CompleteSelection("no feasible priced complete workload: <reasons>").CostModel::complete_workload_candidate_costplansSummaryMaintenanceLifecyclePlanper workload root, in the assembly's root order. A shared state is the sameRcin each plan that reads it.scalar_rootsOption<Cost>Nonemeans unknown; the pass records it as a rejection.The default reads these existing plan fields:
selected_raw_recomputepicksraw_recompute_total_costorsummary_total_costas the root's cost;deployments[].summary(byRc::as_ptr) detects repeats; for a repeat,summary_maintenance_lifecycle_guaranteenames the chosen lifecycle and the matching entry inalternativessupplies thetotal_costto subtract. It returnsNoneifscalar_rootsis non-empty, if any needed cost or guarantee is missing, or if a cost is non-finite or negative.PlanOutput::workload_total_cost:Option<Cost>. Set by a complete-cost pass to the certified quote of the selected workload.MajorPassleaves itNone.check_contractrejects a non-finite or negative value withContractViolation("invalid complete workload cost").OptimizeError::CompleteSelection(String): everyCompletePassfailure: budget exceeded, zero budget, no feasible priced workload, logical or pane enumeration errors.SummaryMaintenanceLifecycleCandidates::enumerate_planslimit: usize0, overflow, or a product abovelimit→BudgetExceeded.Vec<SummaryMaintenanceLifecyclePlan>select. Combinations that fail withNoCompleteEstimateorIncompatibleEvaluationSchedulesare skipped. Any other error is returned.SummaryMaintenanceLifecycleChoiceError::BudgetExceeded: new variant for the case above.CompletePassturns any lifecycle error containing "budget" into a hard error; other lifecycle errors become rejection reasons.#[derive(Clone)]onSummaryMaintenanceLifecycleCandidates: needed becauseselectconsumesselfandenumerate_planscalls it once per combination.Examples
End to end: Example 1 (
globally_cheapest_assignment_executes_both_queries)Input: the two-query fixture (
SUM,MAXoverevents),InteractingCosts,LifecycleInput::new(0),CompletePass { max_candidates: 4096 }.eventsscan) form sharing classes, and their partitions are enumerated.Output: the inventory contains an all-raw candidate, but
optimizereturns the all-summary one withworkload_total_cost == Some(Cost(0.25)). The test then executes both selected roots on rows[1.0, 2.0]and gets3.0(SUM) and2.0(MAX).Partial sharing (
three_consumers_can_share_only_a_subset)Three identical
SUM(value)entries.PartialSharingCostsquotes 0.1 only when reader 0 and reader 1 share a state and reader 2 does not; otherwise 10.0, and raw is 1000.0. The result hasworkload_total_cost == Some(Cost(0.1)),states[0]andstates[1]are the sameRc, andstates[2]is a different one. This is the{0,1} {2}layout from Example 2.Shared producer charged once (
shared_producer_cost_is_not_multiplied_by_consumer_count)Two identical
SUM(value)entries, data at rest,Horizon(100.0),AdditiveCosts(default hook, build cost 10.0, other lifecycle costs zero). The selected plans share oneRcwith the same lifecycle guarantee, the lifecycle isSummaryMaintenanceLifecycle::Shared { .. }, andworkload_total_cost == Some(Cost(10.0)): one build, not two.Accepted and rejected cases
Rcwith different lifecycle guarantee or window framework across plansexecution_timed_dag()failsNone(e.g. default hook with missing costs or scalar roots)Err: "no feasible priced complete workload: …" (test usesPlanningModels::builtin())max_candidatesErrcontaining "budget", no inventory (test usesmax_candidates: 1)max_candidates == 0Err: "complete search requires a positive budget"Out of scope
complete_workload_candidate_costoverride prices. Nativecompile_materialization_candidatessupplies the executable frontier for such models.Stack and validation
Stack: #566 → #568 → #569. Base:
stack/509-21-window-composition(#566). Next: #569, which adds the temporal merge timestamp regression and fix. Addresses the complete workload selection path in #509 (§3 Plan selection).docs/develop_docs/planner-layering-status.mdupdates the sharing and whole-workload rows and adds a "Complete workload selection acceptance" section.Validation: 1,637 workspace tests/doctests pass (2 existing ignores). The four tests in
crates/integration-tests/tests/complete_workload_selection.rsexecute a globally winning combination that local ranking misses, select a partial sharing partition, verify one retained producer is charged once, and reject unknown costs and budget exhaustion. All-feature workspace Clippy, formatting and diff checks pass.🤖 Generated with Claude Code