Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions apps/macos/Sequins/Views/Visualization/VisualizationRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand All @@ -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 }
}
Expand All @@ -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
Expand Down
21 changes: 15 additions & 6 deletions apps/macos/Sequins/Views/Visualization/VisualizationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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.
Expand All @@ -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()
Expand Down
24 changes: 19 additions & 5 deletions apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}

Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
16 changes: 16 additions & 0 deletions apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
75 changes: 66 additions & 9 deletions crates/seql-ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TimeRange>,
}

/// Signal type to query
Expand Down Expand Up @@ -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 ────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -417,15 +422,31 @@ pub struct AggregateStage {
pub aggregations: Vec<Aggregation>,
}

/// 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 {
/// Expression to group by
pub expr: Expr,
/// Optional alias for the group key column
pub alias: Option<String>,
/// Optional time bin width in nanoseconds (for time bucketing)
pub bin_ns: Option<u64>,
/// Optional time bucketing spec (for time series). Resolved to a concrete
/// nanosecond width at compile time (see [`BinSpec`]).
pub bin: Option<BinSpec>,
}

/// An aggregation computation
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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<WindowItem>,
}

/// 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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -669,7 +726,7 @@ mod tests {
name: "service_name".into(),
}),
alias: Some("service".into()),
bin_ns: None,
bin: None,
}],
aggregations: vec![
Aggregation {
Expand Down Expand Up @@ -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 {
Expand Down
12 changes: 6 additions & 6 deletions crates/seql-ast/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand All @@ -167,18 +167,18 @@ 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 {
QueryAst {
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,
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/seql-parser/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
8 changes: 4 additions & 4 deletions crates/seql-parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
})
);
}
}
Loading
Loading