feat: general query algebra — full SQL/PromQL AST, cost optimizer, sketch allocator - #108
Merged
zzylol merged 1 commit intoApr 1, 2026
Conversation
…etch allocator (#95) Implements a fully general algebraic IR that can express all SQL and PromQL queries as an AST, including nested subqueries, CTEs, window functions, PromQL binary ops, and histogram_quantile. The optimizer applies 12 cost-based rewrite rules to a fixed point; the allocator assigns every node to a pipeline stage (Agent / Backend / Precompute / Db) with budget-driven demotion. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
7 tasks
zzylol
deleted the
95-considering-define-a-general-sketchexpression-cover-all-sqlpromql
branch
April 1, 2026 01:00
SieDeta
pushed a commit
that referenced
this pull request
Apr 17, 2026
…etch allocator (#95) (#108) Implements a fully general algebraic IR that can express all SQL and PromQL queries as an AST, including nested subqueries, CTEs, window functions, PromQL binary ops, and histogram_quantile. The optimizer applies 12 cost-based rewrite rules to a fixed point; the allocator assigns every node to a pipeline stage (Agent / Backend / Precompute / Db) with budget-driven demotion. Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
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.
Summary
Closes #95.
This PR introduces
controller/src/algebra/— a fully general query algebra that can express all SQL and PromQL queries as an AST, with cost-based rewrite rules and per-stage sketch allocation.Design answers (open questions from issue #95)
ExactAgg(Sum/Count/Min/Max)ExactAgg(Avg)StageResourceBudgetsstruct (new intypes.rs), sourced fromWorkloadCharacteristics.memory_budget_bytes; all fieldsOption<u64>soNone = unlimitedexpr_to_promql()outputs valid PromQL; sketch insertion from OTel → Precompute is a separate concernNew module:
controller/src/algebra/expr.rs— Full QueryExpr + ScalarExpr algebraQueryExpr(relational): 22 variants covering the entire SQL + PromQL surface:Source,RefFilter,ProjectAggregate(multi-function),SketchAgg(single sketch op)Window(tumbling/sliding),Partition,Dedup,TopK,MergeJoin(7 kinds),JoinSketch(sketch push-down)SetOp(Union/Intersect/Except with ALL)Sort,LimitSubquery,LetBinding(CTEs / WITH)WindowFunc(RANK/LAG/LEAD/…) with ROWS/RANGE/GROUPS framesHistogramQuantile,PromQLSubquery([range:resolution]),BinaryOpwithVectorMatch(on/ignoring/group_left/group_right)ScalarExpr(row-level): 13 variants —Column,Literal,BinaryOp,UnaryOp,FunctionCall,ScalarSubquery,InList,InSubquery,Between,IsNull,Case,Cast,VectorBinaryOpAggFunc:Count/Sum/Avg/Min/Max/StdDev/Variance/Quantile(φ)/CountDistinct/HeavyHitters{k}/Rate/Increase/Delta/CustomBridge:
QueryExpr::from_sketch_expr()converts the existingSketchExprtree, preserving full backward compatibility with all existing SQL/PromQL parsers.plan.rs— Annotated plan nodesPipelineStage:Agent < Backend < Precompute < Db(total order)ExecutionMode:Sketch | Exact | PassthroughCostEstimate: bytes/sec, memory_bytes, cpu_micros/sample, compression_ratioNodeAnnotation: sketch_type, sketch_params, delta_enabled, delta_threshold, rationale, budget_demotion flagPlanNode: wraps aQueryExprwith stage/mode/cost/annotation + childrenPlanSummary: serialisable JSON summary (bandwidth saved, agent/backend memory, per-node annotations) — suitable for inclusion in/api/v1/planresponseoptimizer.rs— Cost-based fixed-point optimizer12 rewrite rules applied until fixed point (max 32 iterations):
PredicatePushDownFilter(Window(e))→Window(Filter(e))MergeLiftingSketchAgg(Merge([a,b]))→Merge([SketchAgg(a), SketchAgg(b)])for mergeable opsHLLDedupElimHLL(Dedup(e))→HLL(e)(HLL is intrinsically distinct)FilterWindowSwapTopKFusionLimit(n, Sort([c DESC], e))→TopK(n, [c], e)HistogramQuantileFusionSubqueryDecorrelationCommonSubexprElimHydraConversionPartition(≥2 keys, SketchAgg(op))→SketchAgg(Hydra{op, keys})when cost improvesWindowMergeWindow(d, Window(d, e))→Window(d, e)PartitionElimPartition(By([]), e)→eSetOpFusionUnion(Merge(a,b), Merge(c))→Merge(a,b,c)allocator.rs—SketchAllocatorConverts
QueryExpr → PlanNodewith budget-driven stage demotion:Known gaps
QueryExpryetsql.rsandpromql.rsparsers still emitSketchExpr.QueryExpr::from_sketch_expr()bridges that, but a directQueryExprparser isn't written — soHistogramQuantile,PromQLSubquery, andWindowFuncnodes are unreachable from a real query string today.offset/@modifiersoffsetor timestamp-pin field onWindow/Source*_over_timePromQL functionsAggFuncvariants; falls back toCustom(String)LATERALjoins /GROUPING SETSJoinKind/AggregateSee issue #109 for the full coverage matrix.
Test coverage
82 new passing tests across all four modules (expr / plan / optimizer / allocator), covering:
SketchExpr→QueryExprbridge round-tripsExact(Avg)always lands at DbPlanSummarybandwidth savings and budget-demotion detectionTest plan
cargo build— cleancargo test algebra— 82/82 passSketchAllocatorintohandle_planendpoint (follow-up)PlanSummaryin/api/v1/planJSON response (follow-up)promql.rsandsql.rsto emitQueryExprdirectly (tracked in algebra: QueryExpr coverage — what SQL/PromQL is supported and what is not #109)🤖 Generated with Claude Code