diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift b/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift index dd4d591..3e21673 100644 --- a/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift +++ b/apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift @@ -22,8 +22,10 @@ final class VisualizationRunner: SeQLSink { var columnRoles: [SeQLColumnRole] { schema?.columnRoles ?? [] } var shape: ResponseShape { schema?.shape ?? .table } - /// (Re)start the query. Cancels any prior stream first. - func start(dataSource: DataSource, query: String, isLive: Bool) { + /// (Re)start the query. Cancels any prior stream first. A non-nil `timeRange` + /// is passed structurally and overrides the query's inline scope (dashboards + /// pass the picker's range so a saved query honors the selected window). + func start(dataSource: DataSource, query: String, isLive: Bool, timeRange: TimeRange? = nil) { stop() errorMessage = nil rows = [] @@ -37,7 +39,7 @@ final class VisualizationRunner: SeQLSink { do { if isLive { - let stream = try dataSource.executeLiveSeQL(query) + let stream = try dataSource.executeLiveSeQL(query, timeRange: timeRange) stream.onSchemaCallback = { [weak self] s in Task { @MainActor in self?.schema = s } } @@ -52,7 +54,7 @@ final class VisualizationRunner: SeQLSink { rebuildFromLive() isLoading = false } else { - snapshotStream = try dataSource.executeSeQL(query, sink: self) + snapshotStream = try dataSource.executeSeQL(query, timeRange: timeRange, sink: self) } } catch { errorMessage = error.localizedDescription diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift index 8d236b5..e372e4c 100644 --- a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift +++ b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift @@ -37,10 +37,14 @@ struct VisualizationView: View { VizFormat.firstNumeric(inFirstRowOf: prevRunner.rows) } - /// The query to execute — time-scope rewritten when `applyTimeRange` is set. - private var effectiveQuery: String { - applyTimeRange ? timeRange.applied(to: visualization.seql) : visualization.seql - } + /// The query to execute — run verbatim; when `applyTimeRange` is set the + /// selected range is passed *structurally* (see `appliedTimeRange`), which + /// overrides the query's inline scope without rewriting the string. + private var effectiveQuery: String { visualization.seql } + + /// The range to inject structurally, or nil to honor the query's inline scope + /// (the chat/one-off path passes nil; dashboards pass the picker's range). + private var appliedTimeRange: TimeRange? { applyTimeRange ? timeRange : nil } /// Restart key — re-runs the query when the query, live flag, or time window change. /// @@ -81,7 +85,10 @@ struct VisualizationView: View { } .task(id: reloadKey) { guard let dataSource else { return } - runner.start(dataSource: dataSource, query: effectiveQuery, isLive: isLive) + runner.start( + dataSource: dataSource, query: effectiveQuery, isLive: isLive, + timeRange: appliedTimeRange + ) } .task(id: "\(reloadKey)|stat=\(effectiveVizType == .stat)") { // For a stat, run the same query one window earlier for the delta. @@ -94,7 +101,9 @@ struct VisualizationView: View { start: bounds.start.addingTimeInterval(-duration), end: bounds.start ) - prevRunner.start(dataSource: dataSource, query: prior.applied(to: visualization.seql), isLive: false) + prevRunner.start( + dataSource: dataSource, query: visualization.seql, isLive: false, timeRange: prior + ) } .onDisappear { runner.stop() diff --git a/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift index 8cf7c10..9bdd7b5 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift @@ -472,12 +472,25 @@ extension DataSource { /// - Returns: A `SeQLStream` that can be cancelled /// - Throws: `SequinsError` on failures (parse errors are reported via sink.onError) @discardableResult - public func executeSeQL(_ query: String, sink: any SeQLSink) throws -> SeQLStream { + public func executeSeQL( + _ query: String, timeRange: TimeRange? = nil, sink: any SeQLSink + ) throws -> SeQLStream { // The SeQL snapshot path shares the exact schema→data→complete callback vtable // with the plain-SQL path, so it reuses the shared framed driver — the only // difference is the FFI entry point (`sequins_seql_query`). - try withSpan("DataSource.executeSeQL") { _ in - try executeFramedSQL(query, sink: sink, invoke: sequins_seql_query, label: "SeQL") + // + // A supplied `timeRange` overrides the query's inline scope (kind 0 = + // use the inline scope), so it is captured by the invoke closure rather + // than passing `sequins_seql_query` directly. + let r = timeRange?.ffiScalars ?? (kind: 0, a: 0, b: 0) + return try withSpan("DataSource.executeSeQL") { _ in + try executeFramedSQL( + query, + sink: sink, + invoke: { handle, queryPtr, vtable, ctx in + sequins_seql_query(handle, queryPtr, r.kind, r.a, r.b, vtable, ctx) + }, + label: "SeQL") } } @@ -490,7 +503,7 @@ extension DataSource { /// - Parameter query: SeQL query text (time range is used as initial window only) /// - Returns: A `LiveSeQLStream` with `@Observable` properties (`batches`, `schema`, etc.) /// - Throws: `SequinsError` if the stream handle cannot be created - public func executeLiveSeQL(_ query: String) throws -> LiveSeQLStream { + public func executeLiveSeQL(_ query: String, timeRange: TimeRange? = nil) throws -> LiveSeQLStream { return try withSpan("DataSource.executeLiveSeQL") { _ in let stream = LiveSeQLStream() let context = LiveSeQLContext(stream: stream) @@ -585,8 +598,9 @@ extension DataSource { DispatchQueue.main.async { ctx.stream?.applyError(code: code, message: message) } } + let r = timeRange?.ffiScalars ?? (kind: 0, a: 0, b: 0) let handle = query.withCString { queryPtr in - sequins_seql_query_live(rawPointer, queryPtr, vtable, ctxRaw) + sequins_seql_query_live(rawPointer, queryPtr, r.kind, r.a, r.b, vtable, ctxRaw) } guard let handle else { diff --git a/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift b/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift index e57b25f..8183d49 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift @@ -28,6 +28,22 @@ public enum TimeRange: Equatable, Sendable { return false } + /// The `(range_kind, range_a_ns, range_b_ns)` triple passed to + /// `sequins_seql_query[_live]`. Supplying this to a query overrides its inline + /// time scope, so a saved visualization runs against the selected range. + /// kind 1 = relative sliding window (`a` = duration ns); 2 = absolute + /// (`a` = start ns, `b` = end ns). + public var ffiScalars: (kind: UInt32, a: UInt64, b: UInt64) { + switch self { + case .relative(let duration): + return (1, UInt64(max(0, duration) * 1_000_000_000), 0) + case .absolute(let start, let end): + let s = UInt64(max(0, start.timeIntervalSince1970) * 1_000_000_000) + let e = UInt64(max(0, end.timeIntervalSince1970) * 1_000_000_000) + return (2, s, e) + } + } + /// The duration of this time range public var duration: TimeInterval { switch self { diff --git a/crates/seql-ast/src/ast.rs b/crates/seql-ast/src/ast.rs index d307108..00e5295 100644 --- a/crates/seql-ast/src/ast.rs +++ b/crates/seql-ast/src/ast.rs @@ -39,8 +39,10 @@ pub enum QueryMode { pub struct Scan { /// Which signal type to scan pub signal: Signal, - /// Time range to scan - pub time_range: TimeRange, + /// Time range to scan. `None` marks a **query template** whose range is + /// supplied separately at execution (e.g. the dashboard's selected range); + /// an inline scope fills this at parse time. + pub time_range: Option, } /// Signal type to query @@ -118,6 +120,9 @@ pub enum Stage { Merge(MergeStage), /// Filter by time range (sliding window) TimeRange(TimeRangeStage), + /// Window functions over the (time-ordered) result — moving averages, running + /// totals, period-over-period deltas. + Window(WindowStage), } // ── Filter ──────────────────────────────────────────────────────────────────── @@ -417,6 +422,21 @@ pub struct AggregateStage { pub aggregations: Vec, } +/// How a time-bucketing `ts() bin …` width is specified. +/// +/// `Percent`/`Auto` are resolved to a concrete nanosecond width at compile time +/// from the query's effective time window, so bucketing scales with the selected +/// range instead of being pinned to a fixed duration. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub enum BinSpec { + /// Fixed width in nanoseconds (`bin 5m`). + Fixed(u64), + /// Percentage of the query time window (`bin 10%` → ~10 buckets). + Percent(f64), + /// A "nice"-rounded width derived from the query window (`bin auto`). + Auto, +} + /// An expression used for grouping #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GroupExpr { @@ -424,8 +444,9 @@ pub struct GroupExpr { pub expr: Expr, /// Optional alias for the group key column pub alias: Option, - /// Optional time bin width in nanoseconds (for time bucketing) - pub bin_ns: Option, + /// Optional time bucketing spec (for time series). Resolved to a concrete + /// nanosecond width at compile time (see [`BinSpec`]). + pub bin: Option, } /// An aggregation computation @@ -458,6 +479,13 @@ pub enum AggregateFn { P95(Expr), /// 99th percentile of a field P99(Expr), + /// Arbitrary percentile of a field. The `f64` is the quantile in `0.0..=1.0` + /// (e.g. `0.90` for p90). + Percentile(Expr, f64), + /// Standard deviation of a field + Stddev(Expr), + /// Variance of a field + Variance(Expr), /// Error rate (fraction of rows with status=Error) ErrorRate, /// Request throughput (rows per second) @@ -513,6 +541,35 @@ pub struct UniqueStage { pub field: FieldRef, } +/// Window stage — compute window functions over the ordered result. Applied +/// after aggregation, ordered by the time-bucket column (or the first temporal +/// column), so a time series can gain moving averages / running totals / deltas. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct WindowStage { + /// The window computations, each producing one new aliased column. + pub items: Vec, +} + +/// One window computation and the column name it produces. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct WindowItem { + /// The window function to apply. + pub function: WindowFn, + /// Output column name. + pub alias: String, +} + +/// A window function over the ordered result. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum WindowFn { + /// Moving average of `expr` over a trailing frame of `n` rows (inclusive). + MovingAvg(Expr, u64), + /// Running (cumulative) sum of `expr` from the first row to the current row. + Cumulative(Expr), + /// Period-over-period difference: `expr - lag(expr, 1)`. + Delta(Expr), +} + /// Patterns stage — detect patterns in string fields #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct PatternsStage { @@ -572,9 +629,9 @@ mod tests { bindings: vec![], scan: Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![ Stage::Filter(FilterStage { @@ -669,7 +726,7 @@ mod tests { name: "service_name".into(), }), alias: Some("service".into()), - bin_ns: None, + bin: None, }], aggregations: vec![ Aggregation { @@ -733,10 +790,10 @@ mod tests { name: "errors".into(), scan: Scan { signal: Signal::Spans, - time_range: TimeRange::Absolute { + time_range: Some(TimeRange::Absolute { start_ns: 1_700_000_000_000_000_000, end_ns: 1_700_003_600_000_000_000, - }, + }), }, stages: vec![Stage::Filter(FilterStage { predicate: Predicate::Compare(CompareExpr { diff --git a/crates/seql-ast/src/schema.rs b/crates/seql-ast/src/schema.rs index 2eda46e..ca9c5cd 100644 --- a/crates/seql-ast/src/schema.rs +++ b/crates/seql-ast/src/schema.rs @@ -143,7 +143,7 @@ pub fn infer_shape(ast: &QueryAst) -> ResponseShape { } // Time-bucketed group by → time series for group in &agg.group_by { - if group.bin_ns.is_some() { + if group.bin.is_some() { return ResponseShape::TimeSeries; } } @@ -167,8 +167,8 @@ pub fn infer_shape(ast: &QueryAst) -> ResponseShape { mod tests { use super::*; use crate::ast::{ - AggregateFn, AggregateStage, Aggregation, AttrScope, Expr, FieldRef, GroupExpr, LimitStage, - NavigateStage, PatternsStage, QueryMode, Scan, Stage, TimeRange, + AggregateFn, AggregateStage, Aggregation, AttrScope, BinSpec, Expr, FieldRef, GroupExpr, + LimitStage, NavigateStage, PatternsStage, QueryMode, Scan, Stage, TimeRange, }; fn base_ast(signal: Signal) -> QueryAst { @@ -176,9 +176,9 @@ mod tests { bindings: vec![], scan: Scan { signal, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![], mode: QueryMode::Snapshot, @@ -237,7 +237,7 @@ mod tests { name: "start_time".into(), }), alias: Some("bucket".into()), - bin_ns: Some(60_000_000_000), // 1-minute buckets + bin: Some(BinSpec::Fixed(60_000_000_000)), // 1-minute buckets }], aggregations: vec![Aggregation { function: AggregateFn::Count, diff --git a/crates/seql-parser/src/lexer.rs b/crates/seql-parser/src/lexer.rs index 3f1f722..a3b91e4 100644 --- a/crates/seql-parser/src/lexer.rs +++ b/crates/seql-parser/src/lexer.rs @@ -29,6 +29,7 @@ pub const KW_UNIQ: &str = "uniq"; pub const KW_PATTERNS: &str = "patterns"; pub const KW_NAVIGATE: &str = "navigate"; pub const KW_MERGE: &str = "merge"; +pub const KW_WINDOW: &str = "window"; pub const KW_LET: &str = "let"; pub const KW_AS: &str = "as"; pub const KW_ASC: &str = "asc"; diff --git a/crates/seql-parser/src/lib.rs b/crates/seql-parser/src/lib.rs index c645aa1..862d3b8 100644 --- a/crates/seql-parser/src/lib.rs +++ b/crates/seql-parser/src/lib.rs @@ -175,19 +175,19 @@ mod tests { let today = parse_with_options("spans today", options).unwrap(); assert_eq!( today.scan.time_range, - seql_ast::ast::TimeRange::Absolute { + Some(seql_ast::ast::TimeRange::Absolute { start_ns: day_ns * 3, end_ns: day_ns * 4, - } + }) ); let yesterday = parse_with_options("spans yesterday", options).unwrap(); assert_eq!( yesterday.scan.time_range, - seql_ast::ast::TimeRange::Absolute { + Some(seql_ast::ast::TimeRange::Absolute { start_ns: day_ns * 2, end_ns: day_ns * 3, - } + }) ); } } diff --git a/crates/seql-parser/src/stages.rs b/crates/seql-parser/src/stages.rs index 0b0727f..08f04e1 100644 --- a/crates/seql-parser/src/stages.rs +++ b/crates/seql-parser/src/stages.rs @@ -3,15 +3,16 @@ use crate::expr::{parse_expr, parse_predicate}; use crate::lexer::{ identifier, keyword, uint_literal, ws, ws1, KW_AS, KW_ASC, KW_BY, KW_COMPUTE, KW_DESC, KW_GROUP, KW_LAST, KW_MERGE, KW_NAVIGATE, KW_OFFSET, KW_PATTERNS, KW_SELECT, KW_SORT, KW_TAKE, - KW_UNIQ, KW_WHERE, + KW_UNIQ, KW_WHERE, KW_WINDOW, }; use crate::time::{duration_ns, parse_time_scope_at}; use crate::{ParseError, ParseOptions}; use seql_ast::ast::{ - AggregateFn, AggregateStage, Aggregation, AttrScope, CompareExpr, CompareOp, ComputeStage, - Derivation, Expr, FieldRef, FilterStage, GroupExpr, LimitStage, Literal, MergeStage, - NavigateStage, PatternsStage, Predicate, ProjectField, ProjectStage, QueryAst, QueryMode, Scan, - Signal, SortExpr, SortStage, Stage, TimeRange, TimeRangeStage, UniqueStage, + AggregateFn, AggregateStage, Aggregation, AttrScope, BinSpec, CompareExpr, CompareOp, + ComputeStage, Derivation, Expr, FieldRef, FilterStage, GroupExpr, LimitStage, Literal, + MergeStage, NavigateStage, PatternsStage, Predicate, ProjectField, ProjectStage, QueryAst, + QueryMode, Scan, Signal, SortExpr, SortStage, Stage, TimeRange, TimeRangeStage, UniqueStage, + WindowFn, WindowItem, WindowStage, }; use winnow::combinator::{alt, delimited, opt, preceded, separated}; use winnow::token::literal; @@ -41,8 +42,14 @@ fn parse_signal(input: &mut &str) -> ModalResult { fn parse_scan_with_options(input: &mut &str, options: ParseOptions) -> ModalResult { let signal = parse_signal.parse_next(input)?; - ws1.parse_next(input)?; - let time_range = parse_time_scope_at(input, options.now_ns)?; + // The leading time scope is optional: when present it must be whitespace- + // separated; when absent the query is a template whose range is supplied at + // execution. `opt` over the (ws1, scope) pair backtracks the whitespace when + // there is no scope (e.g. `spans | group by …`), leaving stage parsing intact. + let time_range = opt(preceded(ws1, |i: &mut &str| { + parse_time_scope_at(i, options.now_ns) + })) + .parse_next(input)?; Ok(Scan { signal, time_range }) } @@ -103,7 +110,7 @@ fn parse_id_lookup(input: &mut &str) -> ModalResult { bindings: vec![], scan: Scan { signal, - time_range: TimeRange::SlidingWindow { start_ns }, + time_range: Some(TimeRange::SlidingWindow { start_ns }), }, stages: vec![ Stage::Filter(FilterStage { @@ -160,6 +167,38 @@ fn parse_agg_fn(input: &mut &str) -> ModalResult { literal("p99("), (parse_expr, literal(")")).map(|(e, _)| AggregateFn::P99(e)), ), + preceded( + literal("stddev("), + (parse_expr, literal(")")).map(|(e, _)| AggregateFn::Stddev(e)), + ), + // `variance(` before `var(` — the trailing `(` already disambiguates, + // but keep the longer literal first for clarity. + preceded( + literal("variance("), + (parse_expr, literal(")")).map(|(e, _)| AggregateFn::Variance(e)), + ), + preceded( + literal("var("), + (parse_expr, literal(")")).map(|(e, _)| AggregateFn::Variance(e)), + ), + // `percentile(, )` — q is a quantile in 0..=1 (e.g. 0.90). A value + // > 1 is treated as a 0–100 percentile and divided by 100. + preceded( + literal("percentile("), + ( + parse_expr, + ws, + literal(","), + ws, + winnow::ascii::float::<_, f64, _>, + ws, + literal(")"), + ) + .map(|(e, _, _, _, q, _, _)| { + let q = if q > 1.0 { q / 100.0 } else { q }; + AggregateFn::Percentile(e, q) + }), + ), preceded( literal("distinct("), (parse_expr, literal(")")).map(|(e, _)| AggregateFn::Distinct(e)), @@ -230,6 +269,21 @@ fn parse_compute_stage(input: &mut &str) -> ModalResult { Ok(Stage::Compute(ComputeStage { derivations })) } +/// Parse a `ts() bin …` width: `auto`, `%` (a percentage of the query +/// window), or a fixed `` like `5m`. Percentage/`auto` are resolved +/// to a concrete width at compile time so bucketing scales with the range. +fn parse_bin_spec(input: &mut &str) -> ModalResult { + use winnow::ascii::float; + alt(( + literal("auto").map(|_| BinSpec::Auto), + // `%` must be tried before a bare duration: `float` parses the + // leading digits and the `%` distinguishes it from `5m`/`30s`. + (float::<_, f64, _>, ws, literal("%")).map(|(pct, _, _)| BinSpec::Percent(pct)), + duration_ns.map(BinSpec::Fixed), + )) + .parse_next(input) +} + fn parse_aggregate_stage(input: &mut &str) -> ModalResult { literal(KW_GROUP).parse_next(input)?; ws1.parse_next(input)?; @@ -245,14 +299,14 @@ fn parse_aggregate_stage(input: &mut &str) -> ModalResult { parse_expr, // ws (not ws1): parse_expr's loops consume trailing whitespace, // so there may be 0 spaces left before "bin" / "as". - opt(preceded((ws, literal("bin"), ws1), duration_ns)), + opt(preceded((ws, literal("bin"), ws1), parse_bin_spec)), opt(preceded((ws, literal(KW_AS), ws1), identifier)), ws, ) - .map(|(_, expr, bin_ns, alias, _)| GroupExpr { + .map(|(_, expr, bin, alias, _)| GroupExpr { expr, alias: alias.map(str::to_string), - bin_ns, + bin, }), (ws, literal(","), ws), ), @@ -465,6 +519,62 @@ fn parse_stage(input: &mut &str) -> ModalResult { parse_unique_stage, parse_patterns_stage, parse_time_range_stage, + parse_window_stage, + )) + .parse_next(input) +} + +/// `window { as , … }` — window functions over the ordered result. +fn parse_window_stage(input: &mut &str) -> ModalResult { + keyword(KW_WINDOW).parse_next(input)?; + ws.parse_next(input)?; + let items: Vec = delimited( + (literal("{"), ws), + separated(1.., parse_window_item, (ws, literal(","), ws)), + (ws, literal("}")), + ) + .parse_next(input)?; + Ok(Stage::Window(WindowStage { items })) +} + +fn parse_window_item(input: &mut &str) -> ModalResult { + let function = parse_window_fn.parse_next(input)?; + (ws, keyword(KW_AS), ws1).parse_next(input)?; + let alias = identifier.parse_next(input)?; + Ok(WindowItem { + function, + alias: alias.to_string(), + }) +} + +fn parse_window_fn(input: &mut &str) -> ModalResult { + alt(( + preceded( + literal("moving_avg("), + ( + parse_expr, + ws, + literal(","), + ws, + uint_literal, + ws, + literal(")"), + ) + .map(|(e, _, _, _, n, _, _)| WindowFn::MovingAvg(e, n)), + ), + // `cumulative(` and `running_sum(` are synonyms. + preceded( + literal("cumulative("), + (parse_expr, literal(")")).map(|(e, _)| WindowFn::Cumulative(e)), + ), + preceded( + literal("running_sum("), + (parse_expr, literal(")")).map(|(e, _)| WindowFn::Cumulative(e)), + ), + preceded( + literal("delta("), + (parse_expr, literal(")")).map(|(e, _)| WindowFn::Delta(e)), + ), )) .parse_next(input) } @@ -562,9 +672,9 @@ mod tests { assert_eq!(ast.scan.signal, Signal::Spans); assert_eq!( ast.scan.time_range, - TimeRange::SlidingWindow { + Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000 - } + }) ); assert!(ast.stages.is_empty()); } @@ -644,7 +754,7 @@ mod tests { .unwrap(); if let Stage::Aggregate(agg) = &ast.stages[0] { assert_eq!(agg.group_by.len(), 1); - assert!(agg.group_by[0].bin_ns.is_some()); + assert!(agg.group_by[0].bin.is_some()); assert_eq!(agg.group_by[0].alias.as_deref(), Some("bucket")); } else { panic!("expected aggregate stage"); @@ -1072,9 +1182,9 @@ mod tests { assert_eq!(ast.scan.signal, Signal::Spans); assert_eq!( ast.scan.time_range, - TimeRange::SlidingWindow { + Some(TimeRange::SlidingWindow { start_ns: 24 * 60 * 60 * 1_000_000_000 - } + }) ); // Should have Filter + Limit assert_eq!(ast.stages.len(), 2); diff --git a/crates/seql-substrait/src/compiler.rs b/crates/seql-substrait/src/compiler.rs index 4aa5cd7..20a9211 100644 --- a/crates/seql-substrait/src/compiler.rs +++ b/crates/seql-substrait/src/compiler.rs @@ -21,9 +21,10 @@ use datafusion_functions_aggregate::expr_fn::{ use datafusion_substrait::logical_plan::producer::to_substrait_plan; use datafusion_substrait::substrait::proto::extensions::AdvancedExtension; use seql_ast::ast::{ - AggregateFn, AggregateStage, ArithOp, CompareOp, ComputeStage, Expr as AstExpr, FieldRef, - FilterStage, GroupExpr, LimitStage, Literal, MergeStage, Predicate, ProjectStage, QueryAst, - QueryMode, ScalarFn, Scan, Signal, SortStage, Stage, TimeRange, UniqueStage, + AggregateFn, AggregateStage, ArithOp, BinSpec, CompareOp, ComputeStage, Expr as AstExpr, + FieldRef, FilterStage, GroupExpr, LimitStage, Literal, MergeStage, Predicate, ProjectStage, + QueryAst, QueryMode, ScalarFn, Scan, Signal, SortStage, Stage, TimeRange, UniqueStage, + WindowFn, WindowStage, }; use seql_ast::correlation::{merge_join_key, navigate_join_key}; use seql_ast::schema::infer_shape; @@ -59,10 +60,22 @@ use prost::Message; /// - `relations[1..N]`: auxiliary tables from Merge stages /// - `advanced_extensions.enhancement`: `SeqlExtension` protobuf Any pub async fn compile(seql: &str, ctx: &SessionContext) -> Result, QueryError> { + compile_with_range(seql, None, ctx).await +} + +/// Like [`compile`], but with an optional structured time range supplied +/// out-of-band. When present it **overrides** any inline scope, so a saved +/// query template (`spans | group by { ts() bin 10% } { count() }`) can be run +/// against the dashboard's selected range. See [`compile_ast_with_range`]. +pub async fn compile_with_range( + seql: &str, + time_range: Option, + ctx: &SessionContext, +) -> Result, QueryError> { let ast = seql_parser::parse(seql).map_err(|e| QueryError::InvalidAst { message: format!("Parse error at offset {}: {}", e.offset, e.message), })?; - compile_ast(ast, ctx).await + compile_ast_with_range(ast, time_range, ctx).await } /// Compile a parsed `QueryAst` into a multi-root Substrait plan with `SeqlExtension` metadata. @@ -70,6 +83,22 @@ pub async fn compile(seql: &str, ctx: &SessionContext) -> Result, QueryE /// Unlike `compile()`, this accepts a pre-parsed AST, allowing the caller to /// modify the AST before compilation (e.g., set `mode = QueryMode::Live`). pub async fn compile_ast(ast: QueryAst, ctx: &SessionContext) -> Result, QueryError> { + compile_ast_with_range(ast, None, ctx).await +} + +/// Compile an AST with an optional structured time range that **overrides** the +/// scan's inline scope (if any). This is how the range becomes a separable input: +/// a scope-less template carries `scan.time_range == None` and gets its range +/// here at execution; an injected range also replaces an inline one so the +/// dashboard's selected range always wins. +pub async fn compile_ast_with_range( + mut ast: QueryAst, + time_range: Option, + ctx: &SessionContext, +) -> Result, QueryError> { + if time_range.is_some() { + ast.scan.time_range = time_range; + } let (primary_plan, auxiliary_plans) = ast_to_logical_plan(&ast, ctx).await?; // Serialize primary plan to Substrait @@ -100,7 +129,7 @@ pub async fn compile_ast(ast: QueryAst, ctx: &SessionContext) -> Result, // Build SeqlExtension let response_shape = infer_shape(&ast); - let time_range_proto = time_range_to_proto(&ast.scan.time_range); + let time_range_proto = ast.scan.time_range.as_ref().map(time_range_to_proto); let mode_val = match ast.mode { QueryMode::Snapshot => crate::seql_ext::QueryMode::Snapshot as i32, QueryMode::Live => crate::seql_ext::QueryMode::Live as i32, @@ -108,7 +137,7 @@ pub async fn compile_ast(ast: QueryAst, ctx: &SessionContext) -> Result, let seql_ext = crate::seql_ext::SeqlExtension { response_shape: response_shape.as_str().to_string(), signal: signal_to_name(ast.scan.signal).to_string(), - time_range: Some(time_range_proto), + time_range: time_range_proto, mode: mode_val, cursor: None, auxiliary_aliases, @@ -352,7 +381,10 @@ pub async fn raw_scan_plan( ); let ast = QueryAst { bindings: vec![], - scan: Scan { signal, time_range }, + scan: Scan { + signal, + time_range: Some(time_range), + }, stages: vec![], mode: if live { QueryMode::Live @@ -376,6 +408,7 @@ async fn apply_common_stage( mut current_signal: Signal, ctx: &SessionContext, nav_context: &str, + window_ns: Option, ) -> Result { match stage { Stage::Filter(filter) => { @@ -388,7 +421,7 @@ async fn apply_common_stage( builder = apply_compute(builder, compute, current_signal, ctx)?; } Stage::Aggregate(aggregate) => { - builder = apply_aggregate(builder, aggregate, current_signal, ctx)?; + builder = apply_aggregate(builder, aggregate, current_signal, ctx, window_ns)?; } Stage::Sort(sort) => { builder = apply_sort(builder, sort, current_signal, ctx)?; @@ -463,6 +496,9 @@ async fn apply_common_stage( Stage::Patterns(_) => { // Patterns stage is a no-op } + Stage::Window(window) => { + builder = apply_window(builder, window, current_signal, ctx)?; + } } Ok(StageOutcome::Updated(builder, current_signal)) @@ -495,11 +531,16 @@ pub async fn ast_to_logical_plan( })?; // Apply time range filter - builder = apply_time_range_filter(builder, current_signal, &ast.scan.time_range)?; + builder = apply_time_range_filter(builder, current_signal, ast.scan.time_range.as_ref())?; + + // The concrete window this scan covers — threaded into aggregation so + // time-relative features (throughput rate, `ts() bin N%`) scale to it. + // `None` for a scope-less template with no injected range. + let window_ns = effective_window_ns(ast.scan.time_range.as_ref()); // Apply each stage in order for stage in &ast.stages { - match apply_common_stage(builder, stage, current_signal, ctx, "").await? { + match apply_common_stage(builder, stage, current_signal, ctx, "", window_ns).await? { StageOutcome::Updated(b, s) => { builder = b; current_signal = s; @@ -518,7 +559,7 @@ pub async fn ast_to_logical_plan( merge, &primary_plan, current_signal, - &ast.scan.time_range, + ast.scan.time_range.as_ref(), ctx, ) .await?; @@ -546,7 +587,7 @@ fn compile_merge_aux<'a>( merge: &'a MergeStage, parent_plan: &'a LogicalPlan, parent_signal: Signal, - time_range: &'a TimeRange, + time_range: Option<&'a TimeRange>, ctx: &'a SessionContext, ) -> MergeAuxFuture<'a> { Box::pin(async move { @@ -613,9 +654,17 @@ fn compile_merge_aux<'a>( let mut current_signal = merge.target; let mut nested_aux_plans: Vec<(String, LogicalPlan, Signal)> = Vec::new(); + let merge_window_ns = effective_window_ns(time_range); for stage in &merge.stages { - match apply_common_stage(aux_builder, stage, current_signal, ctx, "(inside merge)") - .await? + match apply_common_stage( + aux_builder, + stage, + current_signal, + ctx, + "(inside merge)", + merge_window_ns, + ) + .await? { StageOutcome::Updated(b, s) => { aux_builder = b; @@ -943,16 +992,94 @@ pub fn time_column_for_signal(signal: Signal) -> Option<&'static str> { } } +/// The concrete duration (in nanoseconds) that a scan's time scope covers. +/// +/// Used to make time-relative query features scale to the selected range: +/// `throughput` divides by it, and `ts() bin N%` derives the bucket size from it. +/// For an absolute range it's `end - start`; for a sliding window it's the offset. +fn effective_window_ns(time_range: Option<&TimeRange>) -> Option { + time_range.map(|tr| match tr { + TimeRange::Absolute { start_ns, end_ns } => end_ns.saturating_sub(*start_ns), + TimeRange::SlidingWindow { start_ns } => *start_ns, + }) +} + +/// Resolve a [`BinSpec`] to a concrete bucket width in nanoseconds, given the +/// query's effective window. `Percent`/`Auto` scale with `window_ns` so a saved +/// time-series re-buckets sensibly as the selected range changes. Always ≥ 1ns. +/// +/// `Percent`/`Auto` require a known window; on a scope-less template with no +/// range supplied they error rather than guess. +fn resolve_bin_ns(bin: &BinSpec, window_ns: Option) -> Result { + let need_window = || { + window_ns.ok_or_else(|| QueryError::InvalidAst { + message: "`ts() bin N%`/`bin auto` needs a time range: add a scope \ + (e.g. `last 1h`) or supply one at execution" + .to_string(), + }) + }; + let ns = match bin { + BinSpec::Fixed(ns) => *ns, + // `bin 10%` → 10 buckets: width = window * 10/100. `max(0.0001)` guards a + // degenerate/zero percentage from collapsing the divisor. + BinSpec::Percent(pct) => ((need_window()? as f64) * (pct.max(0.0001) / 100.0)) as u64, + BinSpec::Auto => nice_bin_ns(need_window()?), + }; + Ok(ns.max(1)) +} + +/// Pick a "nice" bucket width (~100 buckets) for `bin auto`, snapped to a human +/// duration ladder so time axes land on round intervals. Mirrors the client's +/// `MetricsViewModel.binSeconds(for:)` ladder. +fn nice_bin_ns(window_ns: u64) -> u64 { + const S: u64 = 1_000_000_000; + const LADDER: &[u64] = &[ + S, // 1s + 5 * S, // 5s + 10 * S, // 10s + 15 * S, // 15s + 30 * S, // 30s + 60 * S, // 1m + 300 * S, // 5m + 600 * S, // 10m + 900 * S, // 15m + 1800 * S, // 30m + 3600 * S, // 1h + 3 * 3600 * S, + 6 * 3600 * S, + 12 * 3600 * S, + 86_400 * S, // 1d + ]; + let target = (window_ns / 100).max(1); + LADDER + .iter() + .copied() + .find(|&step| step >= target) + .unwrap_or_else(|| *LADDER.last().unwrap()) +} + fn apply_time_range_filter( builder: LogicalPlanBuilder, signal: Signal, - time_range: &TimeRange, + time_range: Option<&TimeRange>, ) -> Result { let time_col = match time_column_for_signal(signal) { Some(col) => col, + // Signals with no time column (e.g. resources/scopes) are never + // time-filtered, so a missing range is fine. None => return Ok(builder), }; + // A time-scoped signal with no inline scope and no injected range is a + // template that was executed without a range — reject it clearly. + let time_range = time_range.ok_or_else(|| QueryError::InvalidAst { + message: format!( + "query on `{}` has no time range: add a scope (e.g. `last 1h`) \ + or supply one at execution", + signal_to_name(signal) + ), + })?; + match time_range { TimeRange::Absolute { start_ns, end_ns } => { // Cast timestamp column to Int64 for comparison (Vortex stores as Timestamp type) @@ -1077,12 +1204,24 @@ pub fn apply_aggregate( aggregate: &AggregateStage, signal: Signal, ctx: &SessionContext, + window_ns: Option, ) -> Result { + // Divisor (seconds) for rate aggregates like `throughput`: a per-bucket rate + // when the group keys include a time bin, otherwise the whole query window. + // `None` when neither is known (scope-less template, no injected range). + let bucket_ns: Option = match aggregate.group_by.iter().find_map(|ge| ge.bin.as_ref()) { + Some(bin) => Some(resolve_bin_ns(bin, window_ns)?), + None => None, + }; + let rate_divisor_secs: Option = bucket_ns + .or(window_ns) + .map(|ns| (ns as f64 / 1e9).max(f64::MIN_POSITIVE)); + // Build group expressions let group_exprs: Result, _> = aggregate .group_by .iter() - .map(|ge| group_expr_to_df_expr(ge, builder.schema(), signal, ctx)) + .map(|ge| group_expr_to_df_expr(ge, builder.schema(), signal, ctx, window_ns)) .collect(); // Build aggregation expressions @@ -1090,7 +1229,13 @@ pub fn apply_aggregate( .aggregations .iter() .map(|agg| { - let expr = aggregate_fn_to_df_expr(&agg.function, builder.schema(), signal, ctx)?; + let expr = aggregate_fn_to_df_expr( + &agg.function, + builder.schema(), + signal, + ctx, + rate_divisor_secs, + )?; let expr = if let Some(predicate) = &agg.filter { let filter_expr = predicate_to_expr(predicate, builder.schema(), signal, ctx)?; expr.filter(filter_expr) @@ -1112,6 +1257,110 @@ pub fn apply_aggregate( }) } +/// Apply a `window { … }` stage: compute window functions over the result, +/// ordered by the first temporal column (the `ts()` bucket for a time series) +/// or the first column otherwise. Each item appends one aliased column. +pub fn apply_window( + builder: LogicalPlanBuilder, + window: &WindowStage, + signal: Signal, + ctx: &SessionContext, +) -> Result { + let schema = builder.schema(); + // Order by the first Timestamp column (the time bucket), else the first column. + let order_field = schema + .fields() + .iter() + .find(|f| matches!(f.data_type(), ArrowDataType::Timestamp(_, _))) + .or_else(|| schema.fields().first()) + .ok_or_else(|| QueryError::Execution { + message: "window stage requires at least one column to order by".to_string(), + })?; + let order_by = vec![col(order_field.name()).sort(true, false)]; + + let window_exprs: Vec = window + .items + .iter() + .map(|item| { + let e = window_fn_to_df_expr(&item.function, &order_by, schema, signal, ctx)?; + Ok(e.alias(&item.alias)) + }) + .collect::>()?; + + builder + .window(window_exprs) + .map_err(|e| QueryError::Execution { + message: format!("Failed to apply window stage: {}", e), + }) +} + +/// Build a DataFusion window expression for one [`WindowFn`], ordered by +/// `order_by`. Uses only `avg`/`sum` aggregate UDFs over row frames — including +/// `delta`, which reads the previous row via a `[1 preceding, 1 preceding]` +/// frame — so no separate lag window UDF dependency is needed. +fn window_fn_to_df_expr( + fun: &WindowFn, + order_by: &[datafusion_expr::SortExpr], + schema: &datafusion::common::DFSchemaRef, + signal: Signal, + ctx: &SessionContext, +) -> Result { + use datafusion::scalar::ScalarValue; + use datafusion_expr::expr::WindowFunction; + use datafusion_expr::window_frame::{WindowFrame, WindowFrameBound, WindowFrameUnits}; + use datafusion_expr::{ExprFunctionExt, WindowFunctionDefinition}; + use datafusion_functions_aggregate::average::avg_udaf; + use datafusion_functions_aggregate::sum::sum_udaf; + + let build = |udaf, arg: DfExpr, frame: WindowFrame| -> Result { + Expr::WindowFunction(Box::new(WindowFunction::new( + WindowFunctionDefinition::AggregateUDF(udaf), + vec![arg], + ))) + .order_by(order_by.to_vec()) + .window_frame(frame) + .build() + .map_err(|e| QueryError::Execution { + message: format!("Failed to build window function: {}", e), + }) + }; + + match fun { + WindowFn::MovingAvg(expr, n) => { + let arg = ast_expr_to_df_expr(expr, schema, signal, ctx)?; + // Trailing frame of n rows: [n-1 preceding, current]. + let frame = WindowFrame::new_bounds( + WindowFrameUnits::Rows, + WindowFrameBound::Preceding(ScalarValue::UInt64(Some(n.saturating_sub(1)))), + WindowFrameBound::CurrentRow, + ); + build(avg_udaf(), arg, frame) + } + WindowFn::Cumulative(expr) => { + let arg = ast_expr_to_df_expr(expr, schema, signal, ctx)?; + // Running total: [unbounded preceding, current] (null bound = unbounded). + let frame = WindowFrame::new_bounds( + WindowFrameUnits::Rows, + WindowFrameBound::Preceding(ScalarValue::UInt64(None)), + WindowFrameBound::CurrentRow, + ); + build(sum_udaf(), arg, frame) + } + WindowFn::Delta(expr) => { + let arg = ast_expr_to_df_expr(expr, schema, signal, ctx)?; + // Previous row's value via sum over a single-row [1 preceding, 1 preceding] + // frame; delta = current - previous. + let prev_frame = WindowFrame::new_bounds( + WindowFrameUnits::Rows, + WindowFrameBound::Preceding(ScalarValue::UInt64(Some(1))), + WindowFrameBound::Preceding(ScalarValue::UInt64(Some(1))), + ); + let prev = build(sum_udaf(), arg.clone(), prev_frame)?; + Ok(arg - prev) + } + } +} + pub fn apply_sort( builder: LogicalPlanBuilder, sort: &SortStage, @@ -1458,11 +1707,13 @@ fn group_expr_to_df_expr( schema: &datafusion::common::DFSchemaRef, signal: Signal, ctx: &SessionContext, + window_ns: Option, ) -> Result { let expr = ast_expr_to_df_expr(&group_expr.expr, schema, signal, ctx)?; // Handle time binning - let expr = if let Some(bin_ns) = group_expr.bin_ns { + let expr = if let Some(bin) = &group_expr.bin { + let bin_ns = resolve_bin_ns(bin, window_ns)?; // Bin by dividing timestamp by bin size, then multiplying back. // Time columns are stored as Timestamp(ns) — cast to Int64 first so // integer arithmetic works correctly. @@ -1489,11 +1740,27 @@ fn group_expr_to_df_expr( }) } +/// `approx_percentile_cont(expr, q)` for a quantile `q` in (0,1). Shared by +/// `p95`/`p99` and the general `percentile(col, q)` aggregate. +fn approx_percentile_expr(df_expr: DfExpr, q: f64) -> DfExpr { + let udaf = + datafusion_functions_aggregate::approx_percentile_cont::approx_percentile_cont_udaf(); + Expr::AggregateFunction(datafusion_expr::expr::AggregateFunction::new_udf( + udaf, + vec![df_expr, lit(q)], + false, // distinct + None, // filter + vec![], // order_by + None, // null_treatment + )) +} + fn aggregate_fn_to_df_expr( agg_fn: &AggregateFn, schema: &datafusion::common::DFSchemaRef, signal: Signal, ctx: &SessionContext, + rate_divisor_secs: Option, ) -> Result { match agg_fn { AggregateFn::Count => Ok(count(lit(1))), @@ -1518,39 +1785,29 @@ fn aggregate_fn_to_df_expr( // Use median which is equivalent to P50 Ok(datafusion_functions_aggregate::expr_fn::median(df_expr)) } - AggregateFn::P95(expr) => { - let df_expr = ast_expr_to_df_expr(expr, schema, signal, ctx)?; - // Use approx_percentile_cont UDAF with percentile parameter - let udaf = - datafusion_functions_aggregate::approx_percentile_cont::approx_percentile_cont_udaf( - ); - Ok(Expr::AggregateFunction( - datafusion_expr::expr::AggregateFunction::new_udf( - udaf, - vec![df_expr, lit(0.95)], - false, // distinct - None, // filter - vec![], // order_by - None, // null_treatment - ), + AggregateFn::P95(expr) => Ok(approx_percentile_expr( + ast_expr_to_df_expr(expr, schema, signal, ctx)?, + 0.95, + )), + AggregateFn::P99(expr) => Ok(approx_percentile_expr( + ast_expr_to_df_expr(expr, schema, signal, ctx)?, + 0.99, + )), + AggregateFn::Percentile(expr, q) => { + // Clamp to the open interval (0,1) approx_percentile_cont accepts. + let q = q.clamp(f64::MIN_POSITIVE, 1.0 - f64::EPSILON); + Ok(approx_percentile_expr( + ast_expr_to_df_expr(expr, schema, signal, ctx)?, + q, )) } - AggregateFn::P99(expr) => { + AggregateFn::Stddev(expr) => { let df_expr = ast_expr_to_df_expr(expr, schema, signal, ctx)?; - // Use approx_percentile_cont UDAF with percentile parameter - let udaf = - datafusion_functions_aggregate::approx_percentile_cont::approx_percentile_cont_udaf( - ); - Ok(Expr::AggregateFunction( - datafusion_expr::expr::AggregateFunction::new_udf( - udaf, - vec![df_expr, lit(0.99)], - false, // distinct - None, // filter - vec![], // order_by - None, // null_treatment - ), - )) + Ok(datafusion_functions_aggregate::expr_fn::stddev(df_expr)) + } + AggregateFn::Variance(expr) => { + let df_expr = ast_expr_to_df_expr(expr, schema, signal, ctx)?; + Ok(datafusion_functions_aggregate::expr_fn::var_sample(df_expr)) } AggregateFn::Distinct(expr) => { let df_expr = ast_expr_to_df_expr(expr, schema, signal, ctx)?; @@ -1577,11 +1834,15 @@ fn aggregate_fn_to_df_expr( Ok(error_count / total_count) } AggregateFn::Throughput => { - // COUNT(*) / time_range_seconds - // This requires knowing the time range, which we don't have here - // For now, just return COUNT(*) - // TODO: Divide by time range duration in seconds - Ok(count(lit(1))) + // COUNT(*) / seconds — a per-second rate. `rate_divisor_secs` is the + // time-bin width when the query is bucketed by `ts()`, else the whole + // query window, so the rate scales with the selected time range. + let secs = rate_divisor_secs.ok_or_else(|| QueryError::InvalidAst { + message: "`throughput()` needs a time range: add a scope \ + (e.g. `last 1h`) or supply one at execution" + .to_string(), + })?; + Ok(count(lit(1)) / lit(secs)) } AggregateFn::Heatmap(_expr) => { // Heatmap requires custom post-processing @@ -1639,6 +1900,288 @@ mod tests { assert_eq!(signal_to_table_name(Signal::Traces), "spans"); } + #[test] + fn test_effective_window_ns() { + assert_eq!( + effective_window_ns(Some(&TimeRange::SlidingWindow { + start_ns: 3_600_000_000_000 + })), + Some(3_600_000_000_000) + ); + assert_eq!( + effective_window_ns(Some(&TimeRange::Absolute { + start_ns: 1_000, + end_ns: 61_000 + })), + Some(60_000) + ); + // No range → no window (a scope-less template). + assert_eq!(effective_window_ns(None), None); + } + + /// A non-bucketed `throughput()` is `count(*) / window_seconds` (1h → 3600s), + /// not the old bare `count(*)` stub. + #[tokio::test] + async fn test_throughput_divides_by_window_seconds() { + let ctx = schema_context().expect("schema_context"); + let ast = seql_parser::parse("spans last 1h | group by {} { throughput() as tps }") + .expect("parse"); + let (plan, _) = ast_to_logical_plan(&ast, &ctx).await.expect("plan"); + let text = format!("{}", plan.display_indent()); + assert!( + text.contains("Float64(3600"), + "throughput over a 1h window should divide by 3600s; plan was:\n{text}" + ); + } + + #[test] + fn test_resolve_bin_ns() { + let hour = Some(3_600_000_000_000u64); + // `bin 10%` of a 1h window → 6-minute buckets. + assert_eq!( + resolve_bin_ns(&BinSpec::Percent(10.0), hour).unwrap(), + 360_000_000_000 + ); + // Fixed passes through unchanged — and needs no window. + assert_eq!( + resolve_bin_ns(&BinSpec::Fixed(60_000_000_000), None).unwrap(), + 60_000_000_000 + ); + // `bin auto` snaps to a nice ladder step (1% of 1h = 36s → 60s). + assert_eq!( + resolve_bin_ns(&BinSpec::Auto, hour).unwrap(), + 60_000_000_000 + ); + // Never collapses to zero. + assert!(resolve_bin_ns(&BinSpec::Percent(0.0), hour).unwrap() >= 1); + // Percent/Auto without a window is a clear error, not a guess. + assert!(resolve_bin_ns(&BinSpec::Percent(10.0), None).is_err()); + assert!(resolve_bin_ns(&BinSpec::Auto, None).is_err()); + } + + /// `ts() bin 10%` derives the bucket width from the query window so a saved + /// time-series re-buckets when the range changes (10% of 1h = 6m). + #[tokio::test] + async fn test_bin_percent_scales_with_window() { + let ctx = schema_context().expect("schema_context"); + let ast = seql_parser::parse( + "spans last 1h | group by { ts() bin 10% as bucket } { count() as n }", + ) + .expect("parse"); + let (plan, _) = ast_to_logical_plan(&ast, &ctx).await.expect("plan"); + let text = format!("{}", plan.display_indent()); + assert!( + text.contains("360000000000"), + "10% of a 1h window should bin at 6m (360000000000ns); plan was:\n{text}" + ); + } + + /// A `window { … }` stage on a time series compiles AND round-trips through + /// the backend's custom Substrait consumer (so the daemon can execute it). + #[tokio::test] + async fn test_window_stage_compiles_and_consumes() { + use datafusion_substrait::extensions::Extensions; + use datafusion_substrait::logical_plan::consumer::{ + DefaultSubstraitConsumer, SubstraitConsumer, + }; + use datafusion_substrait::substrait::proto::{plan_rel, Plan}; + + let ctx = schema_context().expect("schema_context"); + let bytes = compile( + "spans last 1h | group by { ts() bin 5m as bucket } { count() as n } \ + | window { moving_avg(n, 3) as ma, cumulative(n) as run, delta(n) as d }", + &ctx, + ) + .await + .expect("window query should compile"); + assert!(!bytes.is_empty()); + + // Consume the primary relation back, exactly as the backend does. + let plan: Plan = prost::Message::decode(&bytes[..]).expect("decode"); + let extensions = Extensions::try_from(&plan.extensions).expect("extensions"); + let state = ctx.state(); + let consumer = DefaultSubstraitConsumer::new(&extensions, &state); + let rel = match plan.relations[0].rel_type.as_ref().expect("rel_type") { + plan_rel::RelType::Root(root) => root.input.as_ref().expect("root input"), + plan_rel::RelType::Rel(rel) => rel, + }; + let consumed = consumer.consume_rel(rel).await; + assert!( + consumed.is_ok(), + "backend consumer rejected the window plan: {:?}", + consumed.err() + ); + } + + /// The new statistical aggregates (stddev/variance/arbitrary percentile) + /// parse and compile. + /// SPIKE (Phase 4): does DataFusion's Substrait producer serialize a window + /// function at all? If this errors, the `window { … }` stage must carry its + /// spec in the SeqlExtension and apply it on the backend instead. + #[tokio::test] + async fn spike_window_fn_substrait_producer() { + let ctx = schema_context().expect("schema_context"); + let sql = "SELECT trace_id, \ + avg(duration_ns) OVER (ORDER BY start_time_unix_nano \ + ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma \ + FROM spans"; + let df = ctx.sql(sql).await.expect("window SQL should plan"); + let plan = df.into_optimized_plan().expect("optimize"); + let produced = to_substrait_plan(&plan, &ctx.state()); + // Intentional: surfaces the producer's verdict in the test log. + assert!( + produced.is_ok(), + "Substrait producer rejected a window function: {:?}", + produced.err() + ); + } + + /// SPIKE (Phase 4): full round-trip — does the backend's *custom* consumer + /// (`DefaultSubstraitConsumer`) accept a window function back? If yes, the + /// `window { … }` stage can go through the normal compile→Substrait→consume + /// path with no fallback. + #[tokio::test] + async fn spike_window_fn_substrait_round_trip() { + use datafusion_substrait::extensions::Extensions; + use datafusion_substrait::logical_plan::consumer::{ + DefaultSubstraitConsumer, SubstraitConsumer, + }; + use datafusion_substrait::substrait::proto::plan_rel; + + let ctx = schema_context().expect("schema_context"); + let sql = "SELECT trace_id, \ + avg(duration_ns) OVER (ORDER BY start_time_unix_nano \ + ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma \ + FROM spans"; + let plan = ctx + .sql(sql) + .await + .expect("plan") + .into_optimized_plan() + .expect("optimize"); + let substrait = *to_substrait_plan(&plan, &ctx.state()).expect("produce"); + + let extensions = Extensions::try_from(&substrait.extensions).expect("extensions"); + let state = ctx.state(); + let consumer = DefaultSubstraitConsumer::new(&extensions, &state); + let rel = match substrait.relations[0].rel_type.as_ref().expect("rel_type") { + plan_rel::RelType::Root(root) => root.input.as_ref().expect("root input"), + plan_rel::RelType::Rel(rel) => rel, + }; + let consumed = consumer.consume_rel(rel).await; + assert!( + consumed.is_ok(), + "custom consumer rejected a window function: {:?}", + consumed.err() + ); + } + + #[tokio::test] + async fn test_new_statistical_aggregates_compile() { + let ctx = schema_context().expect("schema_context"); + let bytes = compile( + "spans last 1h | group by {} { \ + stddev(duration_ns) as sd, \ + variance(duration_ns) as v, \ + percentile(duration_ns, 0.9) as p90 }", + &ctx, + ) + .await + .expect("stddev/variance/percentile should compile"); + assert!(!bytes.is_empty()); + } + + /// `percentile(col, 90)` (a 0–100 form) is normalized to the 0..1 quantile. + #[test] + fn test_percentile_parses_0_100_form() { + let ast = seql_parser::parse( + "spans last 1h | group by {} { percentile(duration_ns, 90) as p90 }", + ) + .expect("parse"); + let Some(Stage::Aggregate(agg)) = ast.stages.first() else { + panic!("expected aggregate stage"); + }; + match &agg.aggregations[0].function { + AggregateFn::Percentile(_, q) => assert!((*q - 0.90).abs() < 1e-9, "q={q}"), + other => panic!("expected Percentile, got {other:?}"), + } + } + + /// A scope-less template parses (no inline time scope) and, when a range is + /// injected at compile time, compiles successfully. + #[tokio::test] + async fn test_template_scope_less_with_injected_range() { + let ctx = schema_context().expect("schema_context"); + let ast = + seql_parser::parse("spans | group by { ts() bin 10% as bucket } { count() as n }") + .expect("scope-less template should parse"); + assert_eq!( + ast.scan.time_range, None, + "template carries no inline scope" + ); + let bytes = compile_ast_with_range( + ast, + Some(TimeRange::SlidingWindow { + start_ns: 3_600_000_000_000, + }), + &ctx, + ) + .await + .expect("template + injected range should compile"); + assert!(!bytes.is_empty()); + } + + /// A scope-less template on a time-scoped signal errors if executed without a + /// range (rather than silently scanning everything). + #[tokio::test] + async fn test_template_without_range_errors() { + let ctx = schema_context().expect("schema_context"); + let ast = seql_parser::parse("spans | group by {} { count() as n }").expect("parse"); + assert!( + compile_ast(ast, &ctx).await.is_err(), + "a scope-less spans query with no injected range must error" + ); + } + + /// An injected range overrides an inline scope — the dashboard's selected + /// range wins. Injecting 1h into a `last 5m` query makes `bin 10%` = 6m + /// (360000000000ns), proving the 1h window, not the inline 5m, was used. + #[tokio::test] + async fn test_injected_range_overrides_inline_scope() { + let ctx = schema_context().expect("schema_context"); + let mut ast = seql_parser::parse( + "spans last 5m | group by { ts() bin 10% as bucket } { count() as n }", + ) + .expect("parse"); + // Injection is `scan.time_range = Some(range)` (as compile_ast_with_range does). + ast.scan.time_range = Some(TimeRange::SlidingWindow { + start_ns: 3_600_000_000_000, + }); + let (plan, _) = ast_to_logical_plan(&ast, &ctx).await.expect("plan"); + let text = format!("{}", plan.display_indent()); + assert!( + text.contains("360000000000") && !text.contains("30000000000"), + "injected 1h window should drive bin 10% to 6m, not the inline 5m; plan:\n{text}" + ); + } + + /// A time-bucketed `throughput()` is a per-bucket rate: divide by the bin + /// width (1m → 60s), not the whole query window. + #[tokio::test] + async fn test_throughput_bucketed_divides_by_bin_seconds() { + let ctx = schema_context().expect("schema_context"); + let ast = seql_parser::parse( + "spans last 1h | group by { ts() bin 1m as bucket } { throughput() as tps }", + ) + .expect("parse"); + let (plan, _) = ast_to_logical_plan(&ast, &ctx).await.expect("plan"); + let text = format!("{}", plan.display_indent()); + assert!( + text.contains("Float64(60") && !text.contains("Float64(3600"), + "bucketed throughput should divide by the 60s bin, not the window; plan was:\n{text}" + ); + } + fn decode_seql_extension(bytes: &[u8]) -> crate::seql_ext::SeqlExtension { use datafusion_substrait::substrait::proto::Plan; let plan: Plan = prost::Message::decode(bytes).expect("plan bytes decode"); @@ -1697,9 +2240,9 @@ mod tests { bindings: vec![], scan: Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![], mode: QueryMode::Snapshot, @@ -1717,9 +2260,9 @@ mod tests { bindings: vec![], scan: Scan { signal: Signal::Logs, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Patterns(PatternsStage { field: None })], mode: QueryMode::Snapshot, @@ -1788,9 +2331,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Filter(filter)], mode: QueryMode::Snapshot, @@ -1848,9 +2391,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Aggregate(agg_stage)], mode: QueryMode::Snapshot, @@ -1902,9 +2445,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Project(project)], mode: QueryMode::Snapshot, @@ -1929,10 +2472,10 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::Absolute { + time_range: Some(TimeRange::Absolute { start_ns: 1_000_000_000_000, end_ns: 2_000_000_000_000, - }, + }), }, stages: vec![], mode: QueryMode::Snapshot, @@ -1950,9 +2493,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, // 1 hour - }, + }), }, stages: vec![], mode: QueryMode::Snapshot, @@ -1970,9 +2513,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Logs, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::TimeRange(seql_ast::ast::TimeRangeStage { duration_ns: 1_800_000_000_000, // 30 minutes @@ -2035,9 +2578,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Filter(filter)], mode: QueryMode::Snapshot, @@ -2068,9 +2611,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Filter(filter_not)], mode: QueryMode::Snapshot, @@ -2104,9 +2647,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Sort(sort)], mode: QueryMode::Snapshot, @@ -2149,9 +2692,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Project(project)], mode: QueryMode::Snapshot, @@ -2182,9 +2725,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Unique(unique)], mode: QueryMode::Snapshot, @@ -2234,9 +2777,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Filter(filter)], mode: QueryMode::Snapshot, @@ -2342,9 +2885,9 @@ mod tests { bindings: vec![], scan: seql_ast::ast::Scan { signal: Signal::Spans, - time_range: TimeRange::SlidingWindow { + time_range: Some(TimeRange::SlidingWindow { start_ns: 3_600_000_000_000, - }, + }), }, stages: vec![Stage::Aggregate(agg_stage)], mode: QueryMode::Snapshot, diff --git a/crates/seql-substrait/src/lib.rs b/crates/seql-substrait/src/lib.rs index faa8b97..aedb38e 100644 --- a/crates/seql-substrait/src/lib.rs +++ b/crates/seql-substrait/src/lib.rs @@ -8,8 +8,9 @@ pub mod reducer; pub use compiler::{ apply_aggregate, apply_compute, apply_filter, apply_limit, apply_project, apply_sort, - apply_unique, ast_expr_to_df_expr, ast_to_logical_plan, compile, compile_ast, decode_plan_ext, - decode_plan_meta, raw_scan_plan, schema_context, set_plan_mode, set_plan_scope, - signal_table_name, time_column_for_signal, PlanMeta, + apply_unique, ast_expr_to_df_expr, ast_to_logical_plan, compile, compile_ast, + compile_ast_with_range, compile_with_range, decode_plan_ext, decode_plan_meta, raw_scan_plan, + schema_context, set_plan_mode, set_plan_scope, signal_table_name, time_column_for_signal, + PlanMeta, }; pub use reducer::*; diff --git a/crates/sequins-assistant/src/model.rs b/crates/sequins-assistant/src/model.rs index 1576596..e922840 100644 --- a/crates/sequins-assistant/src/model.rs +++ b/crates/sequins-assistant/src/model.rs @@ -416,20 +416,33 @@ Every query begins with a signal and a mandatory time scope, then optional `|` s - `where ` — e.g. `where status == 2`, `where severity_number >= 9`, `where attr.http_status_code >= 500`. Combine with `and`/`or`. - `group by { } { }` — aggregation. Empty keys `{}` = one scalar - row. Aggregations: `count()`, `avg()`, `sum()`, `min`, `max`, `p50/p90/p99()`, - each aliased `as `; a conditional count is `count() where as `. - - For a **time series** (line chart over time), bucket time in the group keys with - `ts() bin as bucket`. + row. Aggregations: `count()`, `avg`, `sum`, `min`, `max`, `p50/p95/p99()`, + `percentile(, )` (q in 0..1, e.g. 0.90), `stddev()`, `variance()`, + `distinct()`, `error_rate()`, `throughput()` (a per-second rate, scaled to the + window/bucket), each aliased `as `; a conditional count is + `count() where as `. + - For a **time series** (line chart over time), bucket time in the group keys. Prefer a + RANGE-RELATIVE bucket so the chart scales to whatever window is selected: + `ts() bin 10% as bucket` (≈10 buckets) or `ts() bin auto as bucket`. A fixed + `ts() bin 5m` also works but won't adapt to the range. + - `window { as , … }` — window functions over the time-ordered result (use + AFTER a time-bucketed `group by`): `moving_avg(, )`, `cumulative()`, + `delta()` (period-over-period change). - `take ` — limit rows. `select ` — project columns. +Time note: on a **dashboard**, the panel's selected range and live toggle are applied for +you (they override the query's `last `), so always include a sensible leading scope +like `last 1h` and use `ts() bin 10%` — the chart then follows the dashboard's range. + ## Examples - Recent errored spans: `spans last 1h | where status == 2 | take 100` - Total + error count (scalar): `spans last 1h | group by {} { count() as total, count() where status == 2 as errors }` - Count by service: `spans last 1h | group by { service_name } { count() as n }` -- Spans per minute (timeseries):`spans last 15m | group by { ts() bin 1m as bucket } { count() as span_count }` -- Avg latency over time: `spans last 1h | group by { ts() bin 1m as bucket } { avg(duration_ns) as avg_ns }` -- Error logs per minute: `logs last 1h | where severity_number >= 17 | group by { ts() bin 1m as bucket } { count() as errors }` +- Spans per bucket (timeseries):`spans last 15m | group by { ts() bin 10% as bucket } { count() as span_count }` +- Latency percentiles: `spans last 1h | group by {} { p95(duration_ns) as p95, percentile(duration_ns, 0.9) as p90, stddev(duration_ns) as sd }` +- Throughput by service: `spans last 1h | group by { service_name } { throughput() as rps }` +- Error-rate moving average: `spans last 1h | group by { ts() bin auto as bucket } { error_rate() as er } | window { moving_avg(er, 5) as er_ma }` ## Exploring the data @@ -443,6 +456,8 @@ Prefer discovery tools over guessing — observability data is dominated by attr (not in the SQL tables). `describe_schema(table)` for columns. - To keep rows where a field is present, write `where http_route != null` (it means IS NOT NULL). Bare promoted attrs (e.g. `http_route`, `http_status_code`) are real columns. +- If the request is ambiguous, state the interpretation you chose in one line and offer + a refinement. ## Presenting results @@ -499,9 +514,10 @@ mod grounding_tests { "spans last 1h | where status == 2 | take 100", "spans last 1h | group by {} { count() as total, count() where status == 2 as errors }", "spans last 1h | group by { service_name } { count() as n }", - "spans last 15m | group by { ts() bin 1m as bucket } { count() as span_count }", - "spans last 1h | group by { ts() bin 1m as bucket } { avg(duration_ns) as avg_ns }", - "logs last 1h | where severity_number >= 17 | group by { ts() bin 1m as bucket } { count() as errors }", + "spans last 15m | group by { ts() bin 10% as bucket } { count() as span_count }", + "spans last 1h | group by {} { p95(duration_ns) as p95, percentile(duration_ns, 0.9) as p90, stddev(duration_ns) as sd }", + "spans last 1h | group by { service_name } { throughput() as rps }", + "spans last 1h | group by { ts() bin auto as bucket } { error_rate() as er } | window { moving_avg(er, 5) as er_ma }", ]; for q in examples { assert!( diff --git a/crates/sequins-client/src/lib.rs b/crates/sequins-client/src/lib.rs index 5a48e73..7baeab0 100644 --- a/crates/sequins-client/src/lib.rs +++ b/crates/sequins-client/src/lib.rs @@ -14,7 +14,7 @@ use datafusion::execution::context::SessionContext; use futures::StreamExt; use prost::Message as _; use seql_ast::ast::QueryMode; -use seql_substrait::{compile, compile_ast, schema_context}; +use seql_substrait::{compile_ast_with_range, compile_with_range, schema_context}; use sequins_traits::QueryError; use sequins_traits::{QueryApi, QueryExec, SeqlStream}; use std::sync::Arc; @@ -93,11 +93,31 @@ impl RemoteClient { /// Forces `QueryMode::Live` before compiling — the server will push /// incremental Append/Update/Expire/Replace/Heartbeat frames. pub async fn query_live(&self, seql: &str) -> Result { + self.query_live_with_range(seql, None).await + } + + /// Live streaming with an optional structured time range that overrides the + /// query's inline scope (for scope-less templates run against a picker range). + pub async fn query_live_with_range( + &self, + seql: &str, + time_range: Option, + ) -> Result { let mut ast = seql_parser::parse(seql).map_err(|e| QueryError::InvalidAst { message: format!("Parse error at offset {}: {}", e.offset, e.message), })?; ast.mode = QueryMode::Live; - let plan_bytes = compile_ast(ast, &self.schema_ctx).await?; + let plan_bytes = compile_ast_with_range(ast, time_range, &self.schema_ctx).await?; + self.execute_plan(plan_bytes).await + } + + /// Snapshot query with an optional structured time range (see above). + pub async fn query_with_range( + &self, + seql: &str, + time_range: Option, + ) -> Result { + let plan_bytes = compile_with_range(seql, time_range, &self.schema_ctx).await?; self.execute_plan(plan_bytes).await } @@ -190,8 +210,7 @@ impl RemoteClient { #[async_trait] impl QueryApi for RemoteClient { async fn query(&self, seql: &str) -> Result { - let plan_bytes = compile(seql, &self.schema_ctx).await?; - self.execute_plan(plan_bytes).await + self.query_with_range(seql, None).await } async fn sql(&self, sql: &str) -> Result { diff --git a/crates/sequins-datafusion-backend/src/trait_impls.rs b/crates/sequins-datafusion-backend/src/trait_impls.rs index 32fd6ec..0d367e6 100644 --- a/crates/sequins-datafusion-backend/src/trait_impls.rs +++ b/crates/sequins-datafusion-backend/src/trait_impls.rs @@ -3,20 +3,41 @@ use crate::execution::execute_plan; use crate::DataFusionBackend; use async_trait::async_trait; -use seql_ast::ast::QueryMode; -use seql_substrait::{compile, compile_ast}; +use seql_ast::ast::{QueryMode, TimeRange}; +use seql_substrait::{compile_ast_with_range, compile_with_range}; use sequins_traits::QueryError; use sequins_traits::{QueryApi, QueryExec, SeqlStream}; impl DataFusionBackend { /// Execute a SeQL query in live streaming mode. pub async fn query_live(&self, seql: &str) -> Result { + self.query_live_with_range(seql, None).await + } + + /// Live streaming with an optional structured time range that overrides the + /// query's inline scope (for scope-less templates run against a picker range). + pub async fn query_live_with_range( + &self, + seql: &str, + time_range: Option, + ) -> Result { let ctx = self.make_session_ctx().await?; let mut ast = seql_parser::parse(seql).map_err(|e| QueryError::InvalidAst { message: format!("Parse error at offset {}: {}", e.offset, e.message), })?; ast.mode = QueryMode::Live; - let plan_bytes = compile_ast(ast, &ctx).await?; + let plan_bytes = compile_ast_with_range(ast, time_range, &ctx).await?; + self.execute(plan_bytes).await + } + + /// Snapshot query with an optional structured time range (see above). + pub async fn query_with_range( + &self, + seql: &str, + time_range: Option, + ) -> Result { + let ctx = self.make_session_ctx().await?; + let plan_bytes = compile_with_range(seql, time_range, &ctx).await?; self.execute(plan_bytes).await } } @@ -24,9 +45,7 @@ impl DataFusionBackend { #[async_trait] impl QueryApi for DataFusionBackend { async fn query(&self, seql: &str) -> Result { - let ctx = self.make_session_ctx().await?; - let plan_bytes = compile(seql, &ctx).await?; - self.execute(plan_bytes).await + self.query_with_range(seql, None).await } async fn sql(&self, sql: &str) -> Result { diff --git a/crates/sequins-ffi/include/sequins.h b/crates/sequins-ffi/include/sequins.h index d533104..363d591 100644 --- a/crates/sequins-ffi/include/sequins.h +++ b/crates/sequins-ffi/include/sequins.h @@ -2015,6 +2015,9 @@ void sequins_seql_cancel(struct CStreamHandle *handle); */ struct CStreamHandle *sequins_seql_query(struct CDataSource *data_source, const char *query_text, + uint32_t range_kind, + uint64_t range_a_ns, + uint64_t range_b_ns, struct CFrameSinkVTable vtable, void *ctx); @@ -2071,6 +2074,9 @@ struct CStreamHandle *sequins_app_state_query(struct CDataSource *data_source, */ struct CStreamHandle *sequins_seql_query_live(struct CDataSource *data_source, const char *query_text, + uint32_t range_kind, + uint64_t range_a_ns, + uint64_t range_b_ns, struct CFrameSinkVTable vtable, void *ctx); diff --git a/crates/sequins-ffi/src/data_source.rs b/crates/sequins-ffi/src/data_source.rs index 840522b..ee00e12 100644 --- a/crates/sequins-ffi/src/data_source.rs +++ b/crates/sequins-ffi/src/data_source.rs @@ -729,7 +729,8 @@ mod tests { }; let query = CString::new("spans last 1h | take 5").unwrap(); - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; assert!(!stream_handle.is_null(), "Stream handle should not be null"); @@ -824,7 +825,8 @@ mod tests { on_warning: None, on_error: Some(on_error), }; - let handle1 = unsafe { sequins_seql_query(data_source, query1.as_ptr(), vtable1, ctx1) }; + let handle1 = + unsafe { sequins_seql_query(data_source, query1.as_ptr(), 0, 0, 0, vtable1, ctx1) }; // Start second query concurrently let ctx2 = &result2 as *const _ as *mut std::ffi::c_void; @@ -838,7 +840,8 @@ mod tests { on_warning: None, on_error: Some(on_error), }; - let handle2 = unsafe { sequins_seql_query(data_source, query2.as_ptr(), vtable2, ctx2) }; + let handle2 = + unsafe { sequins_seql_query(data_source, query2.as_ptr(), 0, 0, 0, vtable2, ctx2) }; assert!(!handle1.is_null(), "First stream handle should not be null"); assert!( diff --git a/crates/sequins-ffi/src/seql.rs b/crates/sequins-ffi/src/seql.rs index 9bd228c..a3f9ae2 100644 --- a/crates/sequins-ffi/src/seql.rs +++ b/crates/sequins-ffi/src/seql.rs @@ -25,7 +25,6 @@ use seql_ast::ast::QueryAst; use seql_parser::{parse, ParseError}; use sequins_flight::{decode_metadata, SeqlMetadata}; use sequins_flight::{ipc_to_batch, SchemaFrame}; -use sequins_traits::QueryApi; use sequins_traits::QueryError; use std::ffi::CStr; use std::ffi::CString; @@ -243,11 +242,15 @@ enum QueryExecutor { } impl QueryExecutor { - async fn query(&self, seql: &str) -> Result { + async fn query_with_range( + &self, + seql: &str, + tr: Option, + ) -> Result { match self { #[cfg(feature = "local")] - QueryExecutor::Local(b) => b.query(seql).await, - QueryExecutor::Remote(c) => c.query(seql).await, + QueryExecutor::Local(b) => b.query_with_range(seql, tr).await, + QueryExecutor::Remote(c) => c.query_with_range(seql, tr).await, } } @@ -259,6 +262,18 @@ impl QueryExecutor { } } + async fn query_live_with_range( + &self, + seql: &str, + tr: Option, + ) -> Result { + match self { + #[cfg(feature = "local")] + QueryExecutor::Local(b) => b.query_live_with_range(seql, tr).await, + QueryExecutor::Remote(c) => c.query_live_with_range(seql, tr).await, + } + } + async fn sql(&self, sql: &str) -> Result { use sequins_traits::QueryApi; match self { @@ -283,6 +298,21 @@ impl QueryExecutor { } } +/// Build an optional structured time range from the FFI scalar triple. +/// `kind`: 0 = none (use the query's inline scope), 1 = relative sliding window +/// (`a` = duration ns), 2 = absolute (`a` = start ns, `b` = end ns). A supplied +/// range overrides any inline scope in the query. +fn ffi_time_range(kind: u32, a: u64, b: u64) -> Option { + match kind { + 1 => Some(seql_ast::ast::TimeRange::SlidingWindow { start_ns: a }), + 2 => Some(seql_ast::ast::TimeRange::Absolute { + start_ns: a, + end_ns: b, + }), + _ => None, + } +} + fn query_executor(ds: &DataSourceImpl) -> QueryExecutor { match ds { #[cfg(feature = "local")] @@ -329,6 +359,9 @@ pub unsafe extern "C" fn sequins_seql_cancel(handle: *mut CStreamHandle) { pub unsafe extern "C" fn sequins_seql_query( data_source: *mut CDataSource, query_text: *const c_char, + range_kind: u32, + range_a_ns: u64, + range_b_ns: u64, vtable: CFrameSinkVTable, ctx: *mut c_void, ) -> *mut CStreamHandle { @@ -336,6 +369,7 @@ pub unsafe extern "C" fn sequins_seql_query( if data_source.is_null() || query_text.is_null() { return std::ptr::null_mut(); } + let time_range = ffi_time_range(range_kind, range_a_ns, range_b_ns); // Convert C string to Rust str let query_cstr = CStr::from_ptr(query_text); @@ -377,8 +411,8 @@ pub unsafe extern "C" fn sequins_seql_query( // SAFETY: SinkCtx wraps raw C pointers that the caller guarantees are // valid and thread-safe for the lifetime of the stream. let task = RUNTIME.spawn(AssertSend(async move { - // Use QueryApi to compile and execute in one call - let mut stream = match executor.query(&query_str).await { + // Use QueryApi to compile and execute in one call (range overrides scope) + let mut stream = match executor.query_with_range(&query_str, time_range).await { Ok(s) => s, Err(e) => { let c_err = CQueryError::from_error(&e); @@ -628,12 +662,16 @@ pub unsafe extern "C" fn sequins_app_state_query( pub unsafe extern "C" fn sequins_seql_query_live( data_source: *mut CDataSource, query_text: *const c_char, + range_kind: u32, + range_a_ns: u64, + range_b_ns: u64, vtable: CFrameSinkVTable, ctx: *mut c_void, ) -> *mut CStreamHandle { if data_source.is_null() || query_text.is_null() { return std::ptr::null_mut(); } + let time_range = ffi_time_range(range_kind, range_a_ns, range_b_ns); let query_cstr = CStr::from_ptr(query_text); let query_str = match query_cstr.to_str() { @@ -671,7 +709,7 @@ pub unsafe extern "C" fn sequins_seql_query_live( }; let task = RUNTIME.spawn(AssertSend(async move { - let mut stream = match executor.query_live(&query_str).await { + let mut stream = match executor.query_live_with_range(&query_str, time_range).await { Ok(s) => s, Err(e) => { let c_err = CQueryError::from_error(&e); @@ -1309,7 +1347,8 @@ mod tests { }; let query = CString::new("spans last 1h | take 5").unwrap(); - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; assert!(!stream_handle.is_null(), "Stream handle should not be null"); @@ -1346,7 +1385,8 @@ mod tests { }; let query = CString::new("spans last 1h | select trace_id, name | take 3").unwrap(); - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; assert!(!stream_handle.is_null(), "Stream handle should not be null"); @@ -1395,7 +1435,8 @@ mod tests { // Invalid query: unknown field let query = CString::new("spans last 1h | select invalid_field_that_does_not_exist").unwrap(); - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; // For invalid queries, the handle might still be returned, but we get an error frame assert!(!stream_handle.is_null(), "Stream handle should not be null"); @@ -1439,8 +1480,9 @@ mod tests { on_warning: None, on_error: Some(on_error_callback), }; - let result = - unsafe { sequins_seql_query(std::ptr::null_mut(), query.as_ptr(), vtable1, ctx) }; + let result = unsafe { + sequins_seql_query(std::ptr::null_mut(), query.as_ptr(), 0, 0, 0, vtable1, ctx) + }; assert!(result.is_null(), "Should return null for null data_source"); // Test null query @@ -1453,7 +1495,8 @@ mod tests { on_warning: None, on_error: Some(on_error_callback), }; - let result = unsafe { sequins_seql_query(data_source, std::ptr::null(), vtable2, ctx) }; + let result = + unsafe { sequins_seql_query(data_source, std::ptr::null(), 0, 0, 0, vtable2, ctx) }; assert!(result.is_null(), "Should return null for null query"); // Cleanup @@ -1479,7 +1522,8 @@ mod tests { // UTF-8 query with special characters let query = CString::new("spans | where name = 'test-✓' | take 5").unwrap(); - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; assert!(!stream_handle.is_null(), "Stream handle should not be null"); @@ -1516,7 +1560,8 @@ mod tests { let query = CString::new("spans last 1h | take 5").unwrap(); // Create stream handle - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; assert!(!stream_handle.is_null(), "Stream handle should not be null"); // Cancel the stream @@ -1561,7 +1606,8 @@ mod tests { }; let query = CString::new("spans last 1h | take 5").unwrap(); - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; assert!(!stream_handle.is_null(), "Stream handle should not be null"); @@ -1599,7 +1645,8 @@ mod tests { }; let query = CString::new("spans last 1h | take 10").unwrap(); - let stream_handle = unsafe { sequins_seql_query(data_source, query.as_ptr(), vtable, ctx) }; + let stream_handle = + unsafe { sequins_seql_query(data_source, query.as_ptr(), 0, 0, 0, vtable, ctx) }; assert!(!stream_handle.is_null(), "Stream handle should not be null");