Skip to content

feat(planner): exclusive alternatives (Σp costing, SIL weighted choices) and a streamed copy per reader - #1558

Draft
zzylol wants to merge 7 commits into
feat/sil-intentfrom
feat/exclusive-alternatives
Draft

zzylol wants to merge 7 commits into
feat/sil-intentfrom
feat/exclusive-alternatives

Conversation

@zzylol

@zzylol zzylol commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: an uncertain operator (count 0.4 / distinct 0.3 / ...) is planned as N alternatives with requested_fraction = p, one asked per round. A query-time node they share was costed at the largest p (wrong for exclusive alternatives: it runs at Σp), and it had to be held in memory (OneEvaluation) because a streamed node is read once: e.g. 100k series, 1 h window, a held TimeRange cost 287,100/s (1.15 TB) against 1,320/s streamed.
  • Change: (1) exclusive_group marker on fixed-interval queries; a node read by one choice's alternatives runs at Σp (capped at 1). (2) SIL weighted choice {alternative: p, ...} lowered to those alternatives. (3) Stage 3 may stream one copy of a shared query-time result per alternative (own copy context, costed at that alternative's rate) instead of holding one; the MILP chooses. Workloads without alternatives select exactly as before.
  • Effect: entropy (p 0.4) + L2 (p 0.6) over 1 h of raw m: before, one held TimeRange every round; after, two streamed TimeRanges (0.4 and 0.6 of the rounds), nothing held, objective = plan_cost (exclusive_alternatives_stream_one_time_range_each).

Review guide

  • Base: feat/sil-intent (feat(sil): plan SIL intents: parse/check, lowering, hole guard, planning modes, group latency (L_G) #1553); this PR is stacked on it.
  • Read first: crates/stage3-plan-selection/src/selectable.rs (copy contexts κ_q: streamed_copy_context, only_reader, execution_reading), cost.rs::executions_per_second (rate of a copy context), crates/cost/src/plan/execution_demand/mod.rs::schedule_groups (Σp per choice).
  • Then: crates/frontend-sil/src/parse.rs::alternatives_of (choice parsing/expansion), crates/planner/src/intent.rs (lowering).
  • Mechanical: exclusive_group: None added at every FixedIntervalAt literal (tests, fixtures, doc examples).
  • Commits: tests first (bc338ddf, failing), then cost, SIL, Stage 3, style.

Behavior: before → after

Workload (PromQL, gauge m, 1,000 series, 1 sample/s, raw data kept, exact):

{"query": "entropy_over_time(m[1h])", "demand": {"fixed_interval_at": {"interval": 60000, "evaluation_phase": 0, "requested_fraction": 0.4, "exclusive_group": "q"}}}
{"query": "l2_over_time(m[1h])",      "demand": {"fixed_interval_at": {"interval": 60000, "evaluation_phase": 0, "requested_fraction": 0.6, "exclusive_group": "q"}}}
  • Before: one TimeRange(1h) OneEvaluation read by both (held every round's hour of rows), the shared Scan/TimeRange costed at 0.6 of the rounds although one alternative runs every round.
  • After: Scan → TimeRange → aggregate once per alternative, all Lifetime::None, each costed at its own p; shared-node costing at Σp = 1 where a node is still shared. Same in SIL:
INTENT u EVERY 60s;
q4: SELECT host, {count: 0.4, approx_distinct: 0.6}(dst) AS v FROM flows GROUP BY host REQUIRE ERROR rel <= 0.05 DELTA 0.01;

lowers to q4#0 (count(dst), fraction 0.4) and q4#1 (approx_distinct(dst), 0.6), exclusive_group: "q4", each with q4's REQUIRE. Serves the uncertain-operator ("universal cover") evaluation.

Interfaces

crates/types/src/workload/query.rs, planning.rs

 pub enum RepeatedDemand {
     FixedIntervalAt {
         interval: RepetitionInterval,
         evaluation_phase: TimestampMs,
         requested_fraction: Option<f64>,
+        /// The exclusive choice this query is one alternative of (at most one asked per
+        /// evaluation time); a node several read runs at the sum of their fractions. Default None.
+        #[serde(default, skip_serializing_if = "Option::is_none")]
+        exclusive_group: Option<String>,
     },
     Scheduled(Vec<TimestampMs>),
     EstimatedRate(DemandEstimate),
 }
 pub enum WorkloadError {
+    /// Bad input: a choice's alternatives on different interval/phase, or fractions adding above 1.
+    InvalidExclusiveGroup { exclusive_group: String, reason: String },
 }

crates/frontend-sil/src/lib.rs

 pub struct IntentQuery {
     pub query_id: String,
     pub round_interval_ms: u64,
     pub output_variables: Vec<Option<String>>,
     pub sql_template: String,
     pub holes: Vec<Hole>,
     pub accuracy: AccuracyTarget,
     pub max_latency_ms: Option<f64>,
     pub trigger_rate: f64,
     pub declared_result_rows: Option<u64>,
+    /// The choice this query is one alternative of; None without a choice.
+    pub exclusive_choice: Option<ExclusiveChoice>,
 }
+/// Which alternative of a weighted choice a query is (`q1#0` of `q1`).
+pub struct ExclusiveChoice {
+    /// The id as written (`q1`).
+    pub choice_query_id: String,
+    /// Position among the alternatives asked with p > 0.
+    pub alternative_index: usize,
+    /// Chance it is the one asked in a round, in (0, 1].
+    pub probability: f64,
+}
 pub enum SilError {
+    /// Bad input: probabilities outside [0, 1], adding above 1 or all 0; a choice in a binding query.
+    InvalidChoice { query_id: String, message: String },
 }

crates/planner/src/intent.rs

 pub struct IntentRoundQuery {
     pub query_id: String,
     pub query_index: usize,
     pub plan_root: Option<PhysicalASAPNodeId>,
     pub output_variables: Vec<Option<String>>,
     pub depends_on: Vec<VariableDependency>,
     pub bind_slots: Vec<BindSlot>,
     pub rate: f64,
     pub skip_if_empty: bool,
     pub accuracy: AccuracyTarget,
     pub max_latency_ms: Option<f64>,
+    /// The choice it is one alternative of (a round issues at most one); absent in JSON when None.
+    #[serde(default, skip_serializing_if = "Option::is_none")]
+    pub exclusive_choice: Option<ExclusiveChoice>,
 }

SIL grammar: choice ::= '{' text ':' p (',' text ':' p)* '}' anywhere in a query's SQL; several choices combine (product).
Usage: the workload above through asap_planner --run-until stage3, or the SIL intent through plan_intents; checked by stage3_objective::exclusive_alternatives_stream_one_time_range_each, sil_intents::a_choice_lowers_to_exclusive_alternatives and the executor test below.

Algorithm changes

Exclusive fractions (schedule_groups). Before: a fixed schedule's node rate = max fraction of its readers. After: readers in one exclusive group count as one reader at min(1, Σ fractions); max over that and other readers. Correctness: alternatives are asked at disjoint times, so a node they share runs Σp of the rounds; nested readers keep max. Complexity unchanged.

Streamed copy per reader (SelectableExecutions::new). Before: a query-time None result has one reader per context, so a result shared by two queries must be OneEvaluation (held). After: in a root evaluation context κ, where ≥ 2 queries read a None candidate's group, a consumer read by one query q alone, when every reader of the group is an alternative of one exclusive choice, (or q's output) also gets an edge to that candidate in κ_q (same grid, streamed_for_query = q); inside κ_q None inputs are q's copies and other inputs are κ's. κ_q executions cost at q's rate. The MILP picks held vs copies; the plan has one node per copy, and plan_cost rates each copy by the one query reaching it, so objective = plan_cost (tests). Complexity: extra executions ≤ (#queries reading a shared None group) × (None candidates below it); copy contexts are excluded from equivalent-context symmetry reduction. Limits: copies only where every reader is an alternative of one exclusive choice (none computed in a workload without one, so its executions, symmetry reduction and plans are unchanged); no copies under @-anchored request contexts; executor needs nothing new (copies are distinct nodes).

Decisions and open questions

  • Needs reviewer decision: none beyond the interfaces above (user-approved 2026-12-03).
  • Decided (2026-12-04, after review): streamed copies are offered only to alternatives of an exclusive choice. Offered to any two readers, they enlarged the MILP of every multi-query dashboard and disabled the equivalent-context reduction there (shared executions 3 → 0 in a probe); for independent readers they are a follow-up once that reduction maps copy contexts. A plain query and a choice query may not share an id.
  • Decided (2026-12-03): marker on FixedIntervalAt next to requested_fraction (not a new entry field), since fractions only exist there; copies as per-query copy contexts (rather than a new lifetime or an integer reader count), so all costing stays linear and exact per copy; a choice in a binding query and a GROUP over a choice are refused in v1.

Verification

Scope Result Notes
cargo test -p asap-types -p asap-cost -p asap-frontend-sil --lib --tests pass new: exclusive_alternatives_add_their_fractions, an_exclusive_choice_is_one_reader_at_its_summed_fraction, JSON + validation tests, 6 SIL choice tests (incl. a plain and a choice query sharing an id refused)
cargo test -p asap-stage3-plan-selection --lib --tests 60 + 2 pass existing MILP tests unchanged; new a_result_also_read_outside_the_choice_gets_no_streamed_copy, alternatives_may_each_read_a_streamed_copy_of_a_shared_result and without_alternatives_no_copy_is_offered_and_equivalent_contexts_stay_shared (same executions as before #1558, 20 s context still shares the 10 s one's variables, so plan and cost equal pre-#1558)
asap-planner --test planner sil_intents 25 pass new a_choice_lowers_to_exclusive_alternatives
asap-integration-tests --test integration lowest_mean_latency stage3_objective 56 pass, 1 ignored (pre-existing) lowest_mean_latency::a15 (one scan shared by two queries) passes again; new: exclusive alternatives stream one TimeRange each; objective = plan_cost with streamed copies or held
asap-executor --test executor streamed_copies 1 pass the planned copy plan runs on raw rows and each answer equals the query planned alone
clippy -D warnings (types, cost, frontend-sil, planner, stage3) clean rustfmt on changed crates
Not run: full workspace and corpus/sketch snapshots (multi-query sketch snapshots may change where copies beat holding).

Follow-ups

  • Deferred: univmon-cover sweep rerun with this build (corrected joint-vs-separate savings) — posted as a comment.
  • Deferred: streamed copies for independent readers (needs equivalent-context mapping of copy contexts + planning-time measurement); copies under @-anchored contexts; GROUP latency over a choice; choices in binding queries.
  • Stacked next: structural free variables (free GROUP BY / window via choices).

🤖 Generated with Claude Code

https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi

zzylol and others added 5 commits December 3, 2026 20:16
…s per reader (failing)

Tests first for: a node read by alternatives of one exclusive choice
costed at the sum of their fractions; the exclusive_group marker in
the workload JSON and its validation; SIL {alternative: p} choices
lowered to one query per alternative; Stage 3 streaming one copy of a
shared query-time result per reader; the executor running such a plan.
Adds the interfaces they need (RepeatedDemand::FixedIntervalAt::
exclusive_group, ExclusiveChoice, IntentQuery/IntentRoundQuery::
exclusive_choice, SilError::InvalidChoice) without behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
A node read by queries of one exclusive choice (exclusive_group: one of
them asked per evaluation time) is computed at the sum of their
requested fractions, capped at 1, not the largest; the largest stays
for readers outside a choice (nested SIL dependents). A workload whose
choice spans several schedules or whose fractions add to more than 1
is refused (WorkloadError::InvalidExclusiveGroup).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
…natives

A choice anywhere in a query's SQL (an aggregate or a constant) makes
one query per combination of alternatives (q1#0, q1#1, ...), each with
the query's REQUIRE and its probability; the planner lowers each to an
entry requested at p x rate x upstream fraction with exclusive_group =
the written id, and marks its round query with exclusive_choice.
Refused: probabilities outside [0, 1] or adding above 1, no alternative
asked, a choice in a binding query, a GROUP over a query with a choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
Where several queries of an evaluation context read a query-time
result that is not materialized, a consumer read by one query alone
(or that query's output) may read a copy streamed for that query, in
its own copy context (same grid, costed at that query's rate), instead
of one OneEvaluation result held for all. The MILP chooses between
them; the plan has one node per copy, which the executor already runs
as separate streams.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
@zzylol zzylol added enhancement New feature or request cost-model Cost formulas, statistics, ranking, and selection optimizer Workload optimization and plan selection parser External or internal query parser behavior labels Dec 3, 2026
@zzylol

zzylol commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Uncertain-operator ("universal cover") sweep rerun with this PR's build (529fbec): same 4,968 planner runs, joint workloads marked exclusive_group. Cost model 1, joint (b) vs separate plans installed (a′), median [min, max]:

Setting Mix Raw Before After
enforced uniform yes +7 % [−3 %, +33 %] +5 % [0 %, +24 %]
enforced freqheavy yes +1 % [−4 %, +9 %] +1 % [0 %, +6 %]
enforced moments yes +2 % [−3 %, +4 %] 0 % [0 %, +2 %]
enforced quantheavy yes / no +39 % / +33 % +39 % [+16 %, +44 %] / +33 % [+31 %, +44 %]
ignored (what-if) uniform no +53 % +52 % [+52 %, +55 %]
ignored (what-if) uniform yes +62 % +32 % [+23 %, +55 %]
ignored (what-if) moments no / yes +54 % / +54 % +53 % / +53 % [+2 %, +55 %]
  • Joint never costs more than separate any more (every minimum ≥ 0 %): the cases that were up to 4 % dearer were shared TimeRanges held in memory, now streamed once per alternative.
  • Shared query-time nodes are now charged at Σp, which raises the joint cost where the plan reads raw data at query time (ignored uniform with raw kept: 38.4 → 80.3/s at 1,000 groups, 5 min, 60 s); the no-raw cover (all state at ingestion) is unchanged (108.6 → 108.8/s against 228.9/s separate).
  • Feasibility is unchanged (same ok / infeasible counts in all three settings).

…; one id per written query

Review of #1558: copies were offered wherever two queries read a
streamed result, so multi-query workloads without alternatives got more
executions and lost the equivalent-context symmetry reduction (a copy
context makes a root context unshareable). Copies are now offered only
to alternatives of an exclusive choice, and not computed at all in a
workload without one: such workloads select exactly as before #1558
(the two MILP unit tests changed earlier are restored). New tests: the
copy behaviour on alternatives, and a no-alternatives workload keeping
its executions and its shared 20 s context.

SIL: a query with a choice is counted once by its written id in the
duplicate-id check, so a plain q1 and a choice q1 are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
@zzylol

zzylol commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Review fix (241926c): streamed copies are now offered only to alternatives of an exclusive choice, and not computed in a workload without one, so multi-query dashboards without alternatives keep their executions, the equivalent-context symmetry reduction, and their pre-#1558 plans and costs (new test without_alternatives_no_copy_is_offered_and_equivalent_contexts_stay_shared; the two MILP tests changed earlier are restored unchanged). Copies for independent readers are deferred until copy contexts map in that reduction. Also: a plain query and a choice query may no longer share an id. The univmon-cover sweep numbers above are unaffected (its joint workloads are all exclusive).

zzylol added a commit that referenced this pull request Dec 4, 2026
…e of one choice

A result read by an alternative and by a query outside its choice keeps
the hold-or-share selection of before (no copy for the alternative
either). lowest_mean_latency::a15 (one scan shared by two queries
without alternatives), which failed at 529fbec, passes; new test
a_result_also_read_outside_the_choice_gets_no_streamed_copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi
@zzylol

zzylol commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Blocking review fixed (0d68e82): streamed copies are offered only where every reader of the shared result is an alternative of one exclusive choice; otherwise the hold-or-share selection of before. lowest_mean_latency::a15 passes; new tests cover a no-alternatives dashboard (executions and equivalent-context sharing as before) and a result read by an alternative plus an outside query (no copy, shared scan). #1561 rebased.

zzylol added a commit that referenced this pull request Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cost-model Cost formulas, statistics, ranking, and selection enhancement New feature or request optimizer Workload optimization and plan selection parser External or internal query parser behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant