diff --git a/apps/macos/Sequins/ViewModels/DashboardsViewModel.swift b/apps/macos/Sequins/ViewModels/DashboardsViewModel.swift index 0379128..f9ac17a 100644 --- a/apps/macos/Sequins/ViewModels/DashboardsViewModel.swift +++ b/apps/macos/Sequins/ViewModels/DashboardsViewModel.swift @@ -45,6 +45,22 @@ final class DashboardsViewModel { } } + /// The built-in templates available in the "New from template" gallery. + func loadTemplates(dataSource: DataSource) -> [DashboardTemplateInfo] { + (try? dataSource.listDashboardTemplates()) ?? [] + } + + /// Instantiate a template into a fresh dashboard and select it. + func createFromTemplate(id: String, dataSource: DataSource) { + do { + let created = try dataSource.instantiateTemplate(id: id) + refresh(dataSource: dataSource) + select(created.id) + } catch { + errorMessage = error.localizedDescription + } + } + func deleteSelected(dataSource: DataSource) { guard let id = selectedDashboardId else { return } do { diff --git a/apps/macos/Sequins/ViewModels/HealthViewModel.swift b/apps/macos/Sequins/ViewModels/HealthViewModel.swift index 504291f..5f2dd0d 100644 --- a/apps/macos/Sequins/ViewModels/HealthViewModel.swift +++ b/apps/macos/Sequins/ViewModels/HealthViewModel.swift @@ -100,13 +100,14 @@ final class HealthViewModel { let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) lastDuration = duration let timeWindowMinutes = max(1.0, duration / 60.0) - let durationStr = formatDuration(duration) let resourceFilter = buildResourceIdFilter(selectedService) lastResourceFilter = resourceFilter let serviceName = selectedService?.name ?? "unknown" + // Scope-less template queries β€” the selected range is passed structurally to + // `executeView` (see `timeRange:` below), overriding any inline scope. let spanQuery = - "spans last \(durationStr)\(resourceFilter)" + "spans\(resourceFilter)" + " | group by {} {" + " count() where status == 2 as error_count," + " count() as total," @@ -118,7 +119,7 @@ final class HealthViewModel { + " }" let logQuery = - "logs last \(durationStr) | where severity_number >= 9\(resourceFilter)" + "logs | where severity_number >= 9\(resourceFilter)" + " | group by {} { count() as error_logs }" print("πŸ₯ [HealthViewModel] Span query: \(spanQuery)") @@ -135,7 +136,9 @@ final class HealthViewModel { feed = newFeed do { - spanViewHandle = try dataSource.executeView(spanQuery, strategy: .aggregate) { [weak newFeed] deltas in + spanViewHandle = try dataSource.executeView( + spanQuery, timeRange: timeRange, strategy: .aggregate + ) { [weak newFeed] deltas in for d in deltas where d.type == .tableReplaced || d.type == .rowsAppended { if let batch = d.data.first { newFeed?.applySpanBatch(batch) @@ -143,7 +146,9 @@ final class HealthViewModel { } } - logViewHandle = try dataSource.executeView(logQuery, strategy: .aggregate) { [weak newFeed] deltas in + logViewHandle = try dataSource.executeView( + logQuery, timeRange: timeRange, strategy: .aggregate + ) { [weak newFeed] deltas in for d in deltas where d.type == .tableReplaced || d.type == .rowsAppended { if let batch = d.data.first { newFeed?.applyLogBatch(batch) @@ -187,12 +192,15 @@ final class HealthViewModel { } let comparisonWindowMinutes = max(1.0, lastDuration / 60.0) - let durationStr = formatDuration(lastDuration) - let cutoffNs = UInt64((Date().timeIntervalSince1970 - offsetSeconds) * 1_000_000_000) + + // The prior window `[now - offset - dur, now - offset]`, passed structurally so + // the queries stay scope-less templates (no baked `last` / cutoff filter). + let priorEnd = Date().addingTimeInterval(-offsetSeconds) + let priorStart = priorEnd.addingTimeInterval(-lastDuration) + let priorRange = TimeRange.absolute(start: priorStart, end: priorEnd) let spanQuery = - "spans last \(durationStr)\(lastResourceFilter)" - + " | where start_time_unix_nano < \(cutoffNs)" + "spans\(lastResourceFilter)" + " | group by {} {" + " count() where status == 2 as error_count," + " count() as total," @@ -204,8 +212,7 @@ final class HealthViewModel { + " }" let logQuery = - "logs last \(durationStr) | where severity_number >= 9\(lastResourceFilter)" - + " | where start_time_unix_nano < \(cutoffNs)" + "logs | where severity_number >= 9\(lastResourceFilter)" + " | group by {} { count() as error_logs }" currentFeed.clearComparison() @@ -224,7 +231,7 @@ final class HealthViewModel { let spanSink = SnapshotSink { [weak currentFeed] batch in currentFeed?.applyComparisonSpanBatch(batch, timeWindowMinutes: comparisonWindowMinutes) } - let _ = try dataSource.executeSeQL(spanQuery, sink: spanSink) + let _ = try dataSource.executeSeQL(spanQuery, timeRange: priorRange, sink: spanSink) } catch { print("πŸ₯ [HealthViewModel] Comparison span query failed: \(error)") } @@ -233,7 +240,7 @@ final class HealthViewModel { let logSink = SnapshotSink { [weak currentFeed] batch in currentFeed?.applyComparisonLogBatch(batch, timeWindowMinutes: comparisonWindowMinutes) } - let _ = try dataSource.executeSeQL(logQuery, sink: logSink) + let _ = try dataSource.executeSeQL(logQuery, timeRange: priorRange, sink: logSink) } catch { print("πŸ₯ [HealthViewModel] Comparison log query failed: \(error)") } @@ -291,13 +298,4 @@ final class HealthViewModel { let ids = service.resourceIds.map { String($0) }.joined(separator: ", ") return " | where resource_id in [\(ids)]" } - - private func formatDuration(_ duration: TimeInterval) -> String { - let hours = Int(duration / 3600) - if hours > 0 && hours <= 24 { - return "\(hours)h" - } - let minutes = Int(duration / 60) - return "\(max(minutes, 1))m" - } } diff --git a/apps/macos/Sequins/ViewModels/LogsViewModel.swift b/apps/macos/Sequins/ViewModels/LogsViewModel.swift index ec1a1ee..8e0dea1 100644 --- a/apps/macos/Sequins/ViewModels/LogsViewModel.swift +++ b/apps/macos/Sequins/ViewModels/LogsViewModel.swift @@ -215,15 +215,8 @@ final class LogsViewModel { self.dataSource = dataSource - let hours = Int(timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) / 3600) - var query: String - if hours > 0 && hours <= 24 { - query = "logs last \(hours)h" - } else { - let startNs = Int64(timeRange.bounds.start.timeIntervalSince1970 * 1_000_000_000) - let endNs = Int64(timeRange.bounds.end.timeIntervalSince1970 * 1_000_000_000) - query = "logs between(\(startNs), \(endNs))" - } + // Scope-less template β€” `timeRange` is applied structurally at execution. + var query = "logs" if let filter = buildResourceIdFilter(selectedService) { query += filter @@ -251,7 +244,7 @@ final class LogsViewModel { tableView = tv do { - try tv.startSnapshot(dataSource: dataSource, query: query) + try tv.startSnapshot(dataSource: dataSource, query: query, timeRange: timeRange) isLoading = false } catch { NSLog("πŸ“‹ SeQL execution error: \(error)") @@ -271,7 +264,7 @@ final class LogsViewModel { cancel() - var query = "logs last 1h" + var query = "logs" if let filter = buildResourceIdFilter(selectedService) { query += filter } @@ -291,7 +284,8 @@ final class LogsViewModel { tableView = tv do { - try tv.start(dataSource: dataSource, query: query) + // Live mode uses a 1h initial window, applied structurally. + try tv.start(dataSource: dataSource, query: query, timeRange: .relative(duration: 3600)) } catch { NSLog("πŸ“‹ [LogsViewModel] Live stream failed to start: \(error)") self.error = "Query failed: \(error.localizedDescription)" diff --git a/apps/macos/Sequins/ViewModels/MetricsViewModel.swift b/apps/macos/Sequins/ViewModels/MetricsViewModel.swift index 64d293b..54fe300 100644 --- a/apps/macos/Sequins/ViewModels/MetricsViewModel.swift +++ b/apps/macos/Sequins/ViewModels/MetricsViewModel.swift @@ -123,21 +123,14 @@ final class MetricsViewModel { self.timeRange = timeRange let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) - let hours = Int(duration / 3600) let binSize = binSizeString(for: duration) - let timeStr: String - if hours > 0 && hours <= 24 { - timeStr = "last \(hours)h" - } else { - let minutes = Int(duration / 60) - timeStr = "last \(max(minutes, 1))m" - } - let resourceFilter = buildResourceIdFilter(selectedService) ?? "" - let gaugeQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(binSize) as bucket, metric_id } { avg(value) as val }) as datapoints" - let histQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms" + // Scope-less templates β€” the range is applied structurally to the outer `metrics` + // scan (the nested datapoints/histograms subqueries are unchanged). + let gaugeQuery = "metrics\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(binSize) as bucket, metric_id } { avg(value) as val }) as datapoints" + let histQuery = "metrics\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms" print("πŸ“Š [MetricsViewModel] Gauge query: \(gaugeQuery)") print("πŸ“Š [MetricsViewModel] Histogram query: \(histQuery)") @@ -151,11 +144,11 @@ final class MetricsViewModel { error = nil do { - gaugeViewHandle = try dataSource.executeView(gaugeQuery, strategy: .table) { [weak self] deltas in + gaugeViewHandle = try dataSource.executeView(gaugeQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in self?.processGaugeDeltas(deltas) } - histogramViewHandle = try dataSource.executeView(histQuery, strategy: .table) { [weak self] deltas in + histogramViewHandle = try dataSource.executeView(histQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in self?.processHistogramDeltas(deltas) } } catch { @@ -207,26 +200,19 @@ final class MetricsViewModel { self.timeRange = timeRange let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) - let hours = Int(duration / 3600) let liveBinSize = binSizeString(for: duration) - let timeStr: String - if hours > 0 && hours <= 24 { - timeStr = "last \(hours)h" - } else { - let minutes = Int(duration / 60) - timeStr = "last \(max(minutes, 1))m" - } let resourceFilter = buildResourceIdFilter(selectedService) ?? "" do { - let gaugeQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(liveBinSize) as bucket, metric_id } { avg(value) as val }) as datapoints" - gaugeViewHandle = try dataSource.executeView(gaugeQuery, strategy: .table) { [weak self] deltas in + // Scope-less templates β€” range applied structurally to the outer `metrics` scan. + let gaugeQuery = "metrics\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(liveBinSize) as bucket, metric_id } { avg(value) as val }) as datapoints" + gaugeViewHandle = try dataSource.executeView(gaugeQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in self?.processGaugeDeltas(deltas) } - let histQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms" + let histQuery = "metrics\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms" histogramSnapshotComplete = false - histogramViewHandle = try dataSource.executeView(histQuery, strategy: .table) { [weak self] deltas in + histogramViewHandle = try dataSource.executeView(histQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in self?.processHistogramDeltas(deltas) } } catch { diff --git a/apps/macos/Sequins/ViewModels/ProfilesViewModel.swift b/apps/macos/Sequins/ViewModels/ProfilesViewModel.swift index 1dcb73f..edcaa52 100644 --- a/apps/macos/Sequins/ViewModels/ProfilesViewModel.swift +++ b/apps/macos/Sequins/ViewModels/ProfilesViewModel.swift @@ -52,12 +52,12 @@ final class ProfilesViewModel { self.dataSource = dataSource let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) - let durationStr = formatDuration(duration) let retentionNs = UInt64(duration * 1_000_000_000) let resourceFilter = buildResourceIdFilter(selectedService) let valueTypeFilter = selectedValueType.map { " | where value_type = '\($0)'" } ?? "" - let query = "samples last \(durationStr)\(resourceFilter)\(valueTypeFilter) <- stacks <- frames" + // Scope-less template β€” the range is applied structurally to the `samples` scan. + let query = "samples\(resourceFilter)\(valueTypeFilter) <- stacks <- frames" cancel() error = nil @@ -68,6 +68,7 @@ final class ProfilesViewModel { do { viewHandle = try dataSource.executeView( query, + timeRange: timeRange, strategy: .flamegraph, retentionNs: retentionNs ) { [weak newFeed] deltas in @@ -180,13 +181,4 @@ final class ProfilesViewModel { let ids = service.resourceIds.map { String($0) }.joined(separator: ", ") return " | where resource_id in [\(ids)]" } - - private func formatDuration(_ duration: TimeInterval) -> String { - let hours = Int(duration / 3600) - if hours > 0 && hours <= 24 { - return "\(hours)h" - } - let minutes = Int(duration / 60) - return "\(max(minutes, 1))m" - } } diff --git a/apps/macos/Sequins/ViewModels/TracesViewModel.swift b/apps/macos/Sequins/ViewModels/TracesViewModel.swift index 7c0085a..385d552 100644 --- a/apps/macos/Sequins/ViewModels/TracesViewModel.swift +++ b/apps/macos/Sequins/ViewModels/TracesViewModel.swift @@ -342,17 +342,8 @@ final class TracesViewModel { self.timeRange = timeRange self.currentServiceName = selectedService?.name ?? "unknown" - let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) - let hours = Int(duration / 3600) - let query: String - if hours > 0 && hours <= 24 { - query = "spans last \(hours)h" - } else { - let minutes = Int(duration / 60) - query = "spans last \(max(minutes, 1))m" - } - - var fullQuery = query + // Scope-less template β€” `timeRange` is applied structurally at execution. + var fullQuery = "spans" if let filter = buildResourceIdFilter(selectedService) { fullQuery += filter } @@ -368,7 +359,7 @@ final class TracesViewModel { tableView = tv do { - try tv.startSnapshot(dataSource: dataSource, query: fullQuery) + try tv.startSnapshot(dataSource: dataSource, query: fullQuery, timeRange: timeRange) isLoading = false try? await Task.sleep(nanoseconds: 200_000_000) @@ -398,17 +389,8 @@ final class TracesViewModel { self.dataSource = dataSource self.currentServiceName = serviceName - let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) - let hours = Int(duration / 3600) - let timeSpec: String - if hours > 0 && hours <= 24 { - timeSpec = "spans last \(hours)h" - } else { - let minutes = Int(duration / 60) - timeSpec = "spans last \(max(minutes, 1))m" - } - - var query = timeSpec + // Scope-less template β€” `timeRange` is applied structurally at execution. + var query = "spans" if let filter = buildResourceIdFilter(selectedService) { query += filter } @@ -420,7 +402,7 @@ final class TracesViewModel { tableView = tv do { - try tv.start(dataSource: dataSource, query: query) + try tv.start(dataSource: dataSource, query: query, timeRange: timeRange) } catch { self.error = "Live stream failed: \(error.localizedDescription)" } diff --git a/apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift b/apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift index 99fa449..3614632 100644 --- a/apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift +++ b/apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift @@ -7,6 +7,7 @@ struct DashboardListPanel: View { @Bindable var viewModel: DashboardsViewModel @State private var showingNew = false + @State private var showingGallery = false @State private var newName = "" var body: some View { @@ -15,13 +16,24 @@ struct DashboardListPanel: View { Text("Dashboards") .font(.headline) Spacer() - Button { - newName = "" - showingNew = true + Menu { + Button { + newName = "" + showingNew = true + } label: { + Label("New Dashboard", systemImage: "square.grid.2x2") + } + Button { + showingGallery = true + } label: { + Label("New from Template…", systemImage: "rectangle.stack.badge.plus") + } } label: { Image(systemName: "plus") } - .buttonStyle(.borderless) + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + .fixedSize() .help("New dashboard") } .padding(.horizontal, 10) @@ -69,6 +81,9 @@ struct DashboardListPanel: View { } Button("Cancel", role: .cancel) {} } + .sheet(isPresented: $showingGallery) { + TemplateGallerySheet(viewModel: viewModel, dataSource: appState.dataSource) + } } private var selectionBinding: Binding { diff --git a/apps/macos/Sequins/Views/Dashboards/TemplateGallerySheet.swift b/apps/macos/Sequins/Views/Dashboards/TemplateGallerySheet.swift new file mode 100644 index 0000000..821be98 --- /dev/null +++ b/apps/macos/Sequins/Views/Dashboards/TemplateGallerySheet.swift @@ -0,0 +1,99 @@ +import SwiftUI +import SequinsData + +/// "New from Template" gallery β€” lists the built-in dashboard templates and creates a +/// fresh dashboard from the chosen one. +struct TemplateGallerySheet: View { + @Bindable var viewModel: DashboardsViewModel + let dataSource: DataSource? + + @Environment(\.dismiss) private var dismiss + @State private var templates: [DashboardTemplateInfo] = [] + @State private var selectedID: String? + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Text("New from Template") + .font(.title3.weight(.semibold)) + .padding(.horizontal, 16) + .padding(.top, 16) + .padding(.bottom, 8) + + if templates.isEmpty { + VStack(spacing: 6) { + Image(systemName: "rectangle.stack") + .font(.title2) + .foregroundStyle(.tertiary) + Text("No templates available") + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .frame(minHeight: 160) + } else { + ScrollView { + VStack(spacing: 8) { + ForEach(templates) { template in + templateCard(template) + } + } + .padding(16) + } + } + + Divider() + HStack { + Spacer() + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + Button("Create") { create() } + .keyboardShortcut(.defaultAction) + .disabled(selectedID == nil || dataSource == nil) + } + .padding(16) + } + .frame(width: 460, height: 380) + .onAppear { + if let ds = dataSource { + templates = viewModel.loadTemplates(dataSource: ds) + selectedID = templates.first?.id + } + } + } + + private func templateCard(_ template: DashboardTemplateInfo) -> some View { + Button { + selectedID = template.id + } label: { + VStack(alignment: .leading, spacing: 4) { + Text(template.title) + .font(.headline) + .foregroundStyle(.primary) + Text(template.description) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(12) + .background( + RoundedRectangle(cornerRadius: 8) + .fill(selectedID == template.id + ? Color.accentColor.opacity(0.15) + : Color(nsColor: .controlBackgroundColor)) + ) + .overlay( + RoundedRectangle(cornerRadius: 8) + .strokeBorder(selectedID == template.id ? Color.accentColor : Color.clear, lineWidth: 1.5) + ) + } + .buttonStyle(.plain) + } + + private func create() { + guard let id = selectedID, let ds = dataSource else { return } + viewModel.createFromTemplate(id: id, dataSource: ds) + dismiss() + } +} diff --git a/apps/macos/Sequins/Views/Services/ServiceListView.swift b/apps/macos/Sequins/Views/Services/ServiceListView.swift index a50fae5..ac03050 100644 --- a/apps/macos/Sequins/Views/Services/ServiceListView.swift +++ b/apps/macos/Sequins/Views/Services/ServiceListView.swift @@ -121,7 +121,8 @@ struct ServiceListView: View { isLoading = true do { - let stream = try dataSource.executeLiveSeQL("resources last 24h") + let stream = try dataSource.executeLiveSeQL( + "resources", timeRange: .relative(duration: 86_400)) stream.onSchemaCallback = { _ in Task { @MainActor in diff --git a/apps/macos/Sequins/Views/Visualization/ScoreBarView.swift b/apps/macos/Sequins/Views/Visualization/ScoreBarView.swift new file mode 100644 index 0000000..ed636d3 --- /dev/null +++ b/apps/macos/Sequins/Views/Visualization/ScoreBarView.swift @@ -0,0 +1,178 @@ +import SwiftUI +import SequinsData + +/// Renders a set of **score bars** β€” one horizontal bar per factor, filled to a +/// 0…1 score and colored by band (β‰₯0.7 green, β‰₯0.3 yellow, else red) β€” matching the +/// Health tab's factor rows. Drives off whatever the query produces, so any query +/// whose columns are scores can be shown this way. +/// +/// Accepted shapes: +/// - **Wide single row**: each numeric column is a factor; the column name is the +/// label and the cell is the score. An optional companion column `"__value"` +/// supplies a raw value shown to the right. A column named `overall` or `score` is +/// rendered as an emphasized summary row at the top. +/// - **Tall** `[label, score]`: one bar per row. +struct ScoreBarView: View { + let columns: [String] + let rows: [[Any?]] + var columnTypes: [NodeTypeLabel] = [] + var columnRoles: [SeQLColumnRole] = [] + var options: VisualizationOptions = VisualizationOptions() + + private struct Factor: Identifiable { + let id = UUID() + let label: String + let score: Double + let value: String? + let isOverall: Bool + } + + var body: some View { + let factors = self.factors + if factors.isEmpty { + VizMessage(icon: "chart.bar.xaxis", text: "No scores to show") + } else { + VStack(alignment: .leading, spacing: 2) { + ForEach(factors) { factor in + if factor.isOverall { + overallRow(factor) + Divider().padding(.vertical, 2) + } else { + factorRow(factor) + } + } + } + .padding() + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + } + } + + // MARK: - Rows + + private func factorRow(_ factor: Factor) -> some View { + HStack(spacing: 12) { + Text(factor.label) + .font(.system(.body)) + .foregroundStyle(.primary) + .frame(minWidth: 120, alignment: .leading) + + GeometryReader { geometry in + ZStack(alignment: .leading) { + RoundedRectangle(cornerRadius: 4) + .fill(Color.secondary.opacity(0.2)) + RoundedRectangle(cornerRadius: 4) + .fill(bandColor(factor.score)) + .frame(width: max(0, geometry.size.width * factor.score.clamped01)) + } + } + .frame(height: 8) + + Text("\(Int((factor.score.clamped01) * 100))%") + .font(.system(.callout, design: .monospaced)) + .foregroundStyle(.secondary) + .frame(width: 44, alignment: .trailing) + + Circle() + .fill(bandColor(factor.score)) + .frame(width: 10, height: 10) + + Text(factor.value ?? "") + .font(.system(.callout, design: .monospaced)) + .foregroundStyle(.secondary) + .frame(width: 80, alignment: .trailing) + } + .padding(.vertical, 4) + } + + private func overallRow(_ factor: Factor) -> some View { + HStack(spacing: 12) { + Text(factor.label) + .font(.headline) + .frame(minWidth: 120, alignment: .leading) + Spacer(minLength: 0) + Text("\(Int((factor.score.clamped01) * 100))%") + .font(.system(.title2, design: .rounded).weight(.semibold)) + .foregroundStyle(bandColor(factor.score)) + Circle() + .fill(bandColor(factor.score)) + .frame(width: 12, height: 12) + } + .padding(.vertical, 4) + } + + // MARK: - Data mapping + + /// Column index of the `"__value"` companion for a factor column, if present. + private func valueColumnIndex(for name: String) -> Int? { + columns.firstIndex(of: "\(name)__value") + } + + private var factors: [Factor] { + guard !columns.isEmpty, !rows.isEmpty else { return [] } + + // Tall `[label, score]` β€” a text first column + a numeric second column, + // more than one row. + if rows.count > 1, columns.count >= 2, + rows.allSatisfy({ VizFormat.numeric($0.first.flatMap { $0 } ?? nil) == nil }) { + return rows.compactMap { row -> Factor? in + guard row.count >= 2, let score = VizFormat.numeric(row[1]) else { return nil } + let label = VizFormat.string(row.first ?? nil) + return Factor(label: label, score: score, value: nil, isOverall: isOverallName(label)) + } + } + + // Wide single row: each numeric, non-companion column is a factor. + let row = rows[0] + var out: [Factor] = [] + for (i, name) in columns.enumerated() { + if name.hasSuffix("__value") { continue } + guard i < row.count, let score = VizFormat.numeric(row[i]) else { continue } + let value = valueColumnIndex(for: name) + .flatMap { idx -> String? in idx < row.count ? formatValue(row[idx]) : nil } + out.append(Factor( + label: factorLabel(name), + score: score, + value: value, + isOverall: isOverallName(name) + )) + } + // Overall rows float to the top. + out.sort { $0.isOverall && !$1.isOverall } + return out + } + + private func isOverallName(_ name: String) -> Bool { + let n = name.lowercased() + return n == "overall" || n == "score" || n == "overall_score" || n == "health" + } + + /// Turn a column name into a display label: split on `_`, drop a trailing + /// `score`/`status` token, and title-case (e.g. `span_error_score` β†’ "Span Error"). + private func factorLabel(_ name: String) -> String { + var parts = name.split(separator: "_").map(String.init) + if let last = parts.last?.lowercased(), last == "score" || last == "status" { + parts.removeLast() + } + if parts.isEmpty { parts = [name] } + return parts.map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined(separator: " ") + } + + private func formatValue(_ cell: Any?) -> String? { + if let s = cell as? String { return s } + if let n = VizFormat.numeric(cell) { return VizFormat.number(n) } + return nil + } + + /// Score band β†’ status color, matching the scoreβ†’status mapping (healthy β‰₯0.7, + /// degraded β‰₯0.3, else unhealthy). + private func bandColor(_ score: Double) -> Color { + let s = score.clamped01 + if s >= 0.7 { return .green } + if s >= 0.3 { return .yellow } + return .red + } +} + +private extension Double { + var clamped01: Double { Swift.min(1.0, Swift.max(0.0, self)) } +} diff --git a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift index e372e4c..bb24703 100644 --- a/apps/macos/Sequins/Views/Visualization/VisualizationView.swift +++ b/apps/macos/Sequins/Views/Visualization/VisualizationView.swift @@ -165,6 +165,8 @@ struct VizRenderer: View { HeatmapChartView(columns: columns, rows: rows, columnTypes: columnTypes) case .trace: TraceVizView(columns: columns, rows: rows) + case .scoreBar: + ScoreBarView(columns: columns, rows: rows, columnTypes: columnTypes, columnRoles: columnRoles, options: options) } } } diff --git a/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift index 781d1aa..9ebb9dc 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/DashboardStore.swift @@ -156,6 +156,14 @@ public struct VizThreshold: Codable, Hashable, Sendable { } } +/// A built-in dashboard template listed in the "New from template" gallery +/// (mirrors the FFI `CTemplateInfo`). +public struct DashboardTemplateInfo: Codable, Hashable, Sendable, Identifiable { + public var id: String + public var title: String + public var description: String +} + /// Default dashboard row height, in points (mirrors `DEFAULT_ROW_HEIGHT` in Rust). public let defaultRowHeight: Double = 280 @@ -311,6 +319,25 @@ extension DataSource { return try DashboardJSON.decoder.decode(Dashboard.self, from: Data(json.utf8)) } + /// List the built-in dashboard templates available to instantiate. + public func listDashboardTemplates() throws -> [DashboardTemplateInfo] { + let json = try callJSON { out, err in + sequins_dashboard_templates_list(rawPointer, out, err) + } + return try DashboardJSON.decoder.decode([DashboardTemplateInfo].self, from: Data(json.utf8)) + } + + /// Instantiate a template by id, creating a fresh dashboard. Returns the stored copy. + @discardableResult + public func instantiateTemplate(id: String) throws -> Dashboard { + let json = try id.withCString { idPtr in + try callJSON { out, err in + sequins_dashboard_instantiate_template(rawPointer, idPtr, out, err) + } + } + return try DashboardJSON.decoder.decode(Dashboard.self, from: Data(json.utf8)) + } + /// Delete a dashboard by id. public func deleteDashboard(id: String) throws { var errorPtr: UnsafeMutablePointer? diff --git a/apps/macos/SequinsData/Sources/SequinsData/Models/ReactiveTableView.swift b/apps/macos/SequinsData/Sources/SequinsData/Models/ReactiveTableView.swift index ce32e22..71f02a8 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/Models/ReactiveTableView.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/Models/ReactiveTableView.swift @@ -25,16 +25,21 @@ public final class ReactiveTableView { public init() {} - /// Start a live view stream. Replaces any existing stream. + /// Start a live view stream. Replaces any existing stream. `timeRange`, when set, + /// is passed structurally to override the query's inline scope (prefer a scope-less + /// template query + this over baking `last ` into the string). public func start( dataSource: DataSource, query: String, + timeRange: TimeRange? = nil, strategy: ViewStrategy = .table, retentionNs: UInt64 = 0 ) throws { try withSpan("ReactiveTableView.start") { _ in cancel() - viewHandle = try dataSource.executeView(query, strategy: strategy, retentionNs: retentionNs) { + viewHandle = try dataSource.executeView( + query, timeRange: timeRange, strategy: strategy, retentionNs: retentionNs + ) { [weak self] deltas in self?.applyDeltas(deltas) } } @@ -44,11 +49,13 @@ public final class ReactiveTableView { /// /// Use this instead of `start` when you only need a historical snapshot and do not want /// the stream to continue receiving live updates after the initial data arrives. - public func startSnapshot(dataSource: DataSource, query: String) throws { + public func startSnapshot( + dataSource: DataSource, query: String, timeRange: TimeRange? = nil + ) throws { cancel() let sink = SnapshotSink(self) snapshotSink = sink - seqlStream = try dataSource.executeSeQL(query, sink: sink) + seqlStream = try dataSource.executeSeQL(query, timeRange: timeRange, sink: sink) } /// Cancel the current stream. diff --git a/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift b/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift index 9bdd7b5..7d98143 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/SeQLAPI.swift @@ -618,7 +618,10 @@ extension DataSource { /// Create a reactive view that transforms a live SeQL query into `ViewDelta` callbacks. /// /// - Parameters: - /// - query: SeQL query text + /// - query: SeQL query text (may be a scope-less template) + /// - timeRange: Structured time range that overrides the query's inline scope; + /// nil honors the inline scope (kind 0). Prefer this over baking `last ` + /// into the query string. /// - strategy: View strategy (table, aggregate, or flamegraph) /// - retentionNs: Retention window in nanoseconds (0 = default 1h, flamegraph only) /// - onDeltas: Callback invoked on the main thread with each batch of deltas @@ -627,6 +630,7 @@ extension DataSource { @discardableResult public func executeView( _ query: String, + timeRange: TimeRange? = nil, strategy: ViewStrategy, retentionNs: UInt64 = 0, onDeltas: @escaping ([ViewDelta]) -> Void @@ -678,8 +682,11 @@ extension DataSource { } } + let r = timeRange?.ffiScalars ?? (kind: 0, a: 0, b: 0) let handle = query.withCString { queryPtr in - sequins_view_create(rawPointer, queryPtr, strategy.rawValue, retentionNs, callback, ctxRaw) + sequins_view_create( + rawPointer, queryPtr, r.kind, r.a, r.b, + strategy.rawValue, retentionNs, callback, ctxRaw) } guard let handle else { diff --git a/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift b/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift index 8183d49..3d8db52 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/TimeRange.swift @@ -89,96 +89,3 @@ extension TimeRange { } } -// MARK: - SeQL time-scope rewriting - -extension TimeRange { - /// SeQL scan-position signal keywords (the mandatory leading token of a query). - private static let signalKeywords: Set = [ - "spans", "span_links", "logs", "datapoints", "histograms", "metrics", - "samples", "traces", "profiles", "stacks", "frames", "mappings", - "resources", "scopes", - ] - - /// The SeQL scan-level time-scope clause for this range: - /// `last ` for relative, `between(, )` for absolute. - public var seqlTimeScope: String { - switch self { - case .relative(let duration): - return "last \(TimeRange.durationClause(duration))" - case .absolute(let start, let end): - let startNs = Int64(start.timeIntervalSince1970 * 1_000_000_000) - let endNs = Int64(end.timeIntervalSince1970 * 1_000_000_000) - return "between(\(startNs), \(endNs))" - } - } - - /// Format a duration as a single SeQL duration literal (``), picking the - /// largest exact unit. SeQL has no compound durations, so a non-exact duration - /// falls back to whole seconds. - private static func durationClause(_ seconds: TimeInterval) -> String { - let total = max(1, Int(seconds.rounded())) - if total % 86_400 == 0 { return "\(total / 86_400)d" } - if total % 3_600 == 0 { return "\(total / 3_600)h" } - if total % 60 == 0 { return "\(total / 60)m" } - return "\(total)s" - } - - /// Rewrite `seql` so its leading ` ` uses this range. - /// - /// SeQL requires a time-scope immediately after the signal keyword, so we replace - /// that token. Returns the query unchanged when it doesn't begin with a recognized - /// ` ` (e.g. the `signal(id)` shorthand), so a query we can't - /// safely rewrite is never corrupted. - public func applied(to seql: String) -> String { - let full = Substring(seql) - let leadingWS = full.prefix { $0.isWhitespace } - var rest = full.dropFirst(leadingWS.count) - - let signal = rest.prefix { $0.isLetter || $0 == "_" } - guard !signal.isEmpty, TimeRange.signalKeywords.contains(String(signal)) else { - return seql - } - rest = rest.dropFirst(signal.count) - - // `signal(id)` shorthand carries no time-scope β€” leave untouched. - if rest.first == "(" { return seql } - - let midWS = rest.prefix { $0.isWhitespace } - guard !midWS.isEmpty else { return seql } - rest = rest.dropFirst(midWS.count) - - guard let tail = TimeRange.dropTimeScope(rest) else { return seql } - return "\(leadingWS)\(signal)\(midWS)\(seqlTimeScope)\(tail)" - } - - /// If `s` begins with a SeQL time-scope token, return the remainder after it; - /// otherwise `nil`. - private static func dropTimeScope(_ s: Substring) -> Substring? { - for keyword in ["today", "yesterday"] where s.hasPrefix(keyword) { - let tail = s.dropFirst(keyword.count) - if tail.isEmpty || tail.first!.isWhitespace || tail.first! == "|" { - return tail - } - } - - if s.hasPrefix("between") { - let t = s.dropFirst("between".count).drop { $0.isWhitespace } - guard t.first == "(", let close = t.firstIndex(of: ")") else { return nil } - return t[t.index(after: close)...] - } - - if s.hasPrefix("last") { - var t = s.dropFirst("last".count) - guard let boundary = t.first, boundary.isWhitespace else { return nil } - t = t.drop { $0.isWhitespace } - let digits = t.prefix { $0.isNumber } - guard !digits.isEmpty else { return nil } - t = t.dropFirst(digits.count) - if t.hasPrefix("ms") { return t.dropFirst(2) } - guard let unit = t.first, "smhd".contains(unit) else { return nil } - return t.dropFirst(1) - } - - return nil - } -} diff --git a/apps/macos/SequinsData/Sources/SequinsData/VizType.swift b/apps/macos/SequinsData/Sources/SequinsData/VizType.swift index 793782b..3df7e0f 100644 --- a/apps/macos/SequinsData/Sources/SequinsData/VizType.swift +++ b/apps/macos/SequinsData/Sources/SequinsData/VizType.swift @@ -19,6 +19,7 @@ public enum VizType: String, CaseIterable, Codable, Sendable { case table case heatmap case trace + case scoreBar /// Human-readable label for pickers. public var displayName: String { @@ -33,6 +34,7 @@ public enum VizType: String, CaseIterable, Codable, Sendable { case .table: return "Table" case .heatmap: return "Heatmap" case .trace: return "Trace" + case .scoreBar: return "Score Bars" } } @@ -49,6 +51,7 @@ public enum VizType: String, CaseIterable, Codable, Sendable { case .table: return "tablecells" case .heatmap: return "square.grid.3x3.fill" case .trace: return "arrow.triangle.branch" + case .scoreBar: return "chart.bar.xaxis" } } @@ -77,7 +80,7 @@ public enum VizType: String, CaseIterable, Codable, Sendable { /// column means it can't render and should fall back to a table). public var plotsMeasures: Bool { switch self { - case .line, .area, .bar, .stackedBar, .pie, .gauge, .heatmap: return true + case .line, .area, .bar, .stackedBar, .pie, .gauge, .heatmap, .scoreBar: return true case .stat, .table, .trace: return false } } diff --git a/apps/macos/SequinsData/Tests/SequinsDataTests/TimeRangeSeQLTests.swift b/apps/macos/SequinsData/Tests/SequinsDataTests/TimeRangeSeQLTests.swift deleted file mode 100644 index 8c1b9b9..0000000 --- a/apps/macos/SequinsData/Tests/SequinsDataTests/TimeRangeSeQLTests.swift +++ /dev/null @@ -1,57 +0,0 @@ -import XCTest -@testable import SequinsData - -final class TimeRangeSeQLTests: XCTestCase { - - func testRelativeReplacesLastClause() { - let range = TimeRange.relative(duration: 1800) // 30 minutes - XCTAssertEqual( - range.applied(to: "logs last 1h | where severity_number >= 9 | take 500"), - "logs last 30m | where severity_number >= 9 | take 500" - ) - } - - func testRelativeUnitSelection() { - XCTAssertEqual(TimeRange.relative(duration: 3600).seqlTimeScope, "last 1h") - XCTAssertEqual(TimeRange.relative(duration: 86_400).seqlTimeScope, "last 1d") - XCTAssertEqual(TimeRange.relative(duration: 300).seqlTimeScope, "last 5m") - XCTAssertEqual(TimeRange.relative(duration: 45).seqlTimeScope, "last 45s") - // 90 minutes is not a whole number of hours β†’ minutes. - XCTAssertEqual(TimeRange.relative(duration: 5400).seqlTimeScope, "last 90m") - } - - func testAbsoluteBecomesBetween() { - let start = Date(timeIntervalSince1970: 1) // 1e9 ns - let end = Date(timeIntervalSince1970: 2) // 2e9 ns - let range = TimeRange.absolute(start: start, end: end) - XCTAssertEqual( - range.applied(to: "spans last 1h | take 5"), - "spans between(1000000000, 2000000000) | take 5" - ) - } - - func testReplacesTodayAndBetween() { - let range = TimeRange.relative(duration: 3600) - XCTAssertEqual(range.applied(to: "logs today | where x == 1"), "logs last 1h | where x == 1") - XCTAssertEqual( - range.applied(to: "spans between(1000, 2000) | take 5"), - "spans last 1h | take 5" - ) - XCTAssertEqual(range.applied(to: "logs yesterday"), "logs last 1h") - } - - func testLeavesUnrewritableQueriesUntouched() { - let range = TimeRange.relative(duration: 3600) - // Not a signal keyword. - XCTAssertEqual(range.applied(to: "foobar last 1h"), "foobar last 1h") - // `signal(id)` shorthand has no time-scope. - XCTAssertEqual(range.applied(to: "span(abc123)"), "span(abc123)") - // Signal with no time-scope (malformed) β€” left as-is rather than corrupted. - XCTAssertEqual(range.applied(to: "resources"), "resources") - } - - func testPreservesLeadingWhitespace() { - let range = TimeRange.relative(duration: 3600) - XCTAssertEqual(range.applied(to: " spans last 30m"), " spans last 1h") - } -} diff --git a/crates/seql-ast/src/ast.rs b/crates/seql-ast/src/ast.rs index 00e5295..793f8fa 100644 --- a/crates/seql-ast/src/ast.rs +++ b/crates/seql-ast/src/ast.rs @@ -239,6 +239,24 @@ pub enum Expr { /// Arguments args: Vec, }, + /// A `CASE WHEN THEN ... [ELSE ] END` expression. + /// Lowers to a standard SQL `CASE` (so it stays plain-SQL-expressible); it is + /// also the desugaring target of the `score()` / `grade()` sugar functions. + Case { + /// Ordered `WHEN condition THEN result` branches; the first true condition wins. + branches: Vec, + /// Optional `ELSE` result when no branch matches (NULL when absent). + otherwise: Option>, + }, +} + +/// One `WHEN THEN ` arm of an [`Expr::Case`]. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CaseBranch { + /// The boolean condition guarding this branch. + pub condition: Predicate, + /// The value produced when `condition` is the first to hold. + pub result: Expr, } /// Arithmetic operators @@ -281,6 +299,18 @@ pub enum ScalarFn { Upper, /// The signal's primary time column (resolved at compile time) Timestamp, + /// e^x (natural exponential) β€” standard SQL `exp()`. + Exp, + /// First non-null argument β€” standard SQL `coalesce()`. + Coalesce, + /// Smallest of the arguments β€” standard SQL `least()`. + Least, + /// Largest of the arguments β€” standard SQL `greatest()`. + Greatest, + /// Cast to a 64-bit float β€” `cast(x AS DOUBLE)`. Useful to force float division. + ToFloat, + /// Cast to a 64-bit integer β€” `cast(x AS BIGINT)`. + ToInt, } /// A reference to a field on a signal row or its attributes diff --git a/crates/seql-parser/src/expr.rs b/crates/seql-parser/src/expr.rs index fe765cd..b6d6b29 100644 --- a/crates/seql-parser/src/expr.rs +++ b/crates/seql-parser/src/expr.rs @@ -5,13 +5,140 @@ use crate::lexer::{ LIT_PRODUCER, LIT_SERVER, LIT_TRACE, LIT_UNSET, LIT_WARN, }; use seql_ast::ast::{ - ArithOp, CompareExpr, CompareOp, Expr, Literal, Predicate, ScalarFn, SeverityLiteral, - SpanKindLiteral, StatusLiteral, + ArithOp, CaseBranch, CompareExpr, CompareOp, Expr, Literal, Predicate, ScalarFn, + SeverityLiteral, SpanKindLiteral, StatusLiteral, }; use winnow::combinator::{alt, delimited, opt, preceded, separated}; -use winnow::token::literal; +use winnow::error::{ContextError, ErrMode}; +use winnow::token::{literal, take_while}; use winnow::{ModalResult, Parser}; +// ── AST construction helpers (used by score()/grade() desugaring) ─────────────── + +fn e_lit(x: f64) -> Expr { + Expr::Literal(Literal::Float(x)) +} + +fn e_bin(left: Expr, op: ArithOp, right: Expr) -> Expr { + Expr::BinaryOp { + left: Box::new(left), + op, + right: Box::new(right), + } +} + +fn p_cmp(left: Expr, op: CompareOp, right: Expr) -> Predicate { + Predicate::Compare(CompareExpr { left, op, right }) +} + +fn e_call(function: ScalarFn, args: Vec) -> Expr { + Expr::FunctionCall { function, args } +} + +/// Map a lowercase identifier to a built-in scalar function, or `None` if it isn't one. +fn scalar_fn_by_name(name: &str) -> Option { + Some(match name { + "abs" => ScalarFn::Abs, + "round" => ScalarFn::Round, + "ceil" => ScalarFn::Ceil, + "floor" => ScalarFn::Floor, + "to_millis" => ScalarFn::ToMillis, + "to_seconds" => ScalarFn::ToSeconds, + "to_string" => ScalarFn::ToString, + "len" => ScalarFn::Len, + "lower" => ScalarFn::Lower, + "upper" => ScalarFn::Upper, + "exp" => ScalarFn::Exp, + "coalesce" => ScalarFn::Coalesce, + "least" => ScalarFn::Least, + "greatest" => ScalarFn::Greatest, + "float" => ScalarFn::ToFloat, + "int" => ScalarFn::ToInt, + _ => return None, + }) +} + +/// Expand `score(value, warn, err)` into the health scoring piecewise CASE (higher +/// value = worse): linear 1.0β†’0.7 below `warn`, linear 0.7β†’0.3 between `warn` and +/// `err`, then `greatest(0, 0.3Β·exp(-(value-err)/err))` above `err`. Pure sugar over +/// `Expr::Case` + arithmetic + `exp()`, so it stays plain-SQL-expressible. +fn build_score_expr(v: Expr, w: Expr, e: Expr) -> Expr { + // 1.0 - (v / w) * 0.3 + let healthy = e_bin( + e_lit(1.0), + ArithOp::Sub, + e_bin( + e_bin(v.clone(), ArithOp::Div, w.clone()), + ArithOp::Mul, + e_lit(0.3), + ), + ); + // 0.7 - ((v - w) / (e - w)) * 0.4 + let degraded = e_bin( + e_lit(0.7), + ArithOp::Sub, + e_bin( + e_bin( + e_bin(v.clone(), ArithOp::Sub, w.clone()), + ArithOp::Div, + e_bin(e.clone(), ArithOp::Sub, w.clone()), + ), + ArithOp::Mul, + e_lit(0.4), + ), + ); + // greatest(0.0, 0.3 * exp((e - v) / e)) [ = 0.3 * exp(-(v-e)/e) ] + let unhealthy = e_call( + ScalarFn::Greatest, + vec![ + e_lit(0.0), + e_bin( + e_lit(0.3), + ArithOp::Mul, + e_call( + ScalarFn::Exp, + vec![e_bin( + e_bin(e.clone(), ArithOp::Sub, v.clone()), + ArithOp::Div, + e.clone(), + )], + ), + ), + ], + ); + Expr::Case { + branches: vec![ + CaseBranch { + condition: p_cmp(v.clone(), CompareOp::Lte, w), + result: healthy, + }, + CaseBranch { + condition: p_cmp(v, CompareOp::Lte, e), + result: degraded, + }, + ], + otherwise: Some(Box::new(unhealthy)), + } +} + +/// Expand `grade(value, warn, err)` into a CASE yielding `'healthy'` / `'degraded'` +/// / `'unhealthy'` β€” the status label matching `score()`'s thresholds. +fn build_grade_expr(v: Expr, w: Expr, e: Expr) -> Expr { + Expr::Case { + branches: vec![ + CaseBranch { + condition: p_cmp(v.clone(), CompareOp::Lte, w), + result: Expr::Literal(Literal::String("healthy".into())), + }, + CaseBranch { + condition: p_cmp(v, CompareOp::Lte, e), + result: Expr::Literal(Literal::String("degraded".into())), + }, + ], + otherwise: Some(Box::new(Expr::Literal(Literal::String("unhealthy".into())))), + } +} + // ── Literals ───────────────────────────────────────────────────────────────── /// Helper to parse a case-insensitive keyword and return a value @@ -118,12 +245,107 @@ fn parse_ts_fn(input: &mut &str) -> ModalResult { }) } -/// Parse a primary expression (literal, ts() call, or field reference) +/// Parse a parenthesised sub-expression: `( )` β€” arithmetic grouping. +fn parse_paren_expr(input: &mut &str) -> ModalResult { + delimited((literal("("), ws), parse_expr, (ws, literal(")"))).parse_next(input) +} + +/// Parse a built-in scalar function call `name(arg, …)` (abs, round, exp, coalesce, +/// least, greatest, float, int, …). Backtracks when `name` isn't a known function so a +/// same-named field still parses as a field reference. +fn parse_scalar_call(input: &mut &str) -> ModalResult { + let name = take_while(1.., |c: char| c.is_ascii_lowercase() || c == '_').parse_next(input)?; + let Some(function) = scalar_fn_by_name(name) else { + return Err(ErrMode::Backtrack(ContextError::new())); + }; + ws.parse_next(input)?; + literal("(").parse_next(input)?; + let args: Vec = + separated(0.., delimited(ws, parse_expr, ws), literal(",")).parse_next(input)?; + ws.parse_next(input)?; + literal(")").parse_next(input)?; + Ok(Expr::FunctionCall { function, args }) +} + +/// Parse the `score(value, warn, err)` / `grade(value, warn, err)` sugar and expand it +/// into an `Expr::Case`. Both take exactly three arguments. +fn parse_score_grade(input: &mut &str) -> ModalResult { + let name = take_while(1.., |c: char| c.is_ascii_lowercase()).parse_next(input)?; + let is_score = match name { + "score" => true, + "grade" => false, + _ => return Err(ErrMode::Backtrack(ContextError::new())), + }; + ws.parse_next(input)?; + literal("(").parse_next(input)?; + let args: Vec = + separated(1.., delimited(ws, parse_expr, ws), literal(",")).parse_next(input)?; + ws.parse_next(input)?; + literal(")").parse_next(input)?; + if args.len() != 3 { + // A hard error (not a backtrack) so the arity mistake surfaces clearly. + return Err(ErrMode::Cut(ContextError::new())); + } + let mut it = args.into_iter(); + let v = it.next().expect("3 args"); + let w = it.next().expect("3 args"); + let e = it.next().expect("3 args"); + Ok(if is_score { + build_score_expr(v, w, e) + } else { + build_grade_expr(v, w, e) + }) +} + +/// Parse a `CASE WHEN THEN … [ELSE ] END` expression. +fn parse_case(input: &mut &str) -> ModalResult { + keyword_ci("case").parse_next(input)?; + ws1.parse_next(input)?; + + // Sub-parsers (parse_predicate / parse_expr) consume their own surrounding + // whitespace, so inter-token spacing here is `ws` (zero-or-more), not `ws1`. + let mut branches = Vec::new(); + loop { + ws.parse_next(input)?; + if opt(keyword_ci("when")).parse_next(input)?.is_none() { + break; + } + let condition = parse_predicate.parse_next(input)?; + ws.parse_next(input)?; + keyword_ci("then").parse_next(input)?; + let result = parse_expr.parse_next(input)?; + branches.push(CaseBranch { condition, result }); + } + if branches.is_empty() { + return Err(ErrMode::Cut(ContextError::new())); + } + + ws.parse_next(input)?; + let otherwise = if opt(keyword_ci("else")).parse_next(input)?.is_some() { + Some(Box::new(parse_expr.parse_next(input)?)) + } else { + None + }; + ws.parse_next(input)?; + keyword_ci("end").parse_next(input)?; + + Ok(Expr::Case { + branches, + otherwise, + }) +} + +/// Parse a primary expression: CASE, `score`/`grade` sugar, a parenthesised +/// sub-expression, a scalar function call, `ts()`, a literal, or a field reference. fn parse_primary(input: &mut &str) -> ModalResult { ws.parse_next(input)?; alt(( - literal_value.map(Expr::Literal), + parse_case, + parse_score_grade, + parse_paren_expr, parse_ts_fn, + parse_scalar_call, + literal_value.map(Expr::Literal), field_ref.map(Expr::Field), )) .parse_next(input) @@ -441,6 +663,121 @@ mod tests { ); } + #[test] + fn parse_paren_grouping() { + // Parentheses force grouping against the default precedence. + let expr = parse_expr.parse("(a + b) * c").unwrap(); + assert!( + matches!( + expr, + Expr::BinaryOp { + op: ArithOp::Mul, + .. + } + ), + "top op should be Mul over the parenthesised sum, got {:?}", + expr + ); + } + + #[test] + fn parse_scalar_call_exp() { + let expr = parse_expr.parse("exp(x)").unwrap(); + assert!(matches!( + expr, + Expr::FunctionCall { + function: ScalarFn::Exp, + .. + } + )); + } + + #[test] + fn parse_scalar_call_variadic_greatest() { + let expr = parse_expr.parse("greatest(0.0, x, y)").unwrap(); + match expr { + Expr::FunctionCall { + function: ScalarFn::Greatest, + args, + } => assert_eq!(args.len(), 3), + other => panic!("expected greatest() call, got {:?}", other), + } + } + + #[test] + fn known_fn_name_as_bare_field_still_parses() { + // `exp` without parentheses is a plain field, not a call. + let expr = parse_expr.parse("exp").unwrap(); + assert!(matches!(expr, Expr::Field(_))); + } + + #[test] + fn parse_case_expression() { + let expr = parse_expr + .parse("case when x <= 1 then 1.0 when x <= 2 then 0.5 else 0.0 end") + .unwrap(); + match expr { + Expr::Case { + branches, + otherwise, + } => { + assert_eq!(branches.len(), 2); + assert!(otherwise.is_some()); + } + other => panic!("expected Case, got {:?}", other), + } + } + + #[test] + fn parse_case_without_else() { + let expr = parse_expr.parse("case when x <= 1 then 1.0 end").unwrap(); + match expr { + Expr::Case { + branches, + otherwise, + } => { + assert_eq!(branches.len(), 1); + assert!(otherwise.is_none()); + } + other => panic!("expected Case, got {:?}", other), + } + } + + #[test] + fn score_desugars_to_case() { + let expr = parse_expr.parse("score(rate, 0.01, 0.05)").unwrap(); + match expr { + Expr::Case { + branches, + otherwise, + } => { + // Two thresholds β†’ two WHEN branches + an exp-decay ELSE. + assert_eq!(branches.len(), 2); + assert!(otherwise.is_some()); + } + other => panic!("score() should expand to Case, got {:?}", other), + } + } + + #[test] + fn grade_desugars_to_case_of_strings() { + let expr = parse_expr.parse("grade(rate, 0.01, 0.05)").unwrap(); + match expr { + Expr::Case { branches, .. } => { + assert!(matches!( + branches[0].result, + Expr::Literal(Literal::String(_)) + )); + } + other => panic!("grade() should expand to Case, got {:?}", other), + } + } + + #[test] + fn score_wrong_arity_is_error() { + assert!(parse_expr.parse("score(rate, 0.01)").is_err()); + } + #[test] fn parse_ts_fn_in_arithmetic() { // ts() can appear in arithmetic expressions diff --git a/crates/seql-substrait/src/compiler.rs b/crates/seql-substrait/src/compiler.rs index 20a9211..402bb48 100644 --- a/crates/seql-substrait/src/compiler.rs +++ b/crates/seql-substrait/src/compiler.rs @@ -1652,11 +1652,105 @@ pub fn ast_expr_to_df_expr( } Ok(datafusion::prelude::upper(arg_exprs[0].clone())) } + ScalarFn::Exp => { + if arg_exprs.len() != 1 { + return Err(QueryError::Execution { + message: "exp() expects 1 argument".into(), + }); + } + // Cast to float so integer inputs don't truncate the exponent. + scalar_udf_call( + ctx, + "exp", + vec![cast(arg_exprs[0].clone(), ArrowDataType::Float64)], + ) + } + ScalarFn::Coalesce => { + if arg_exprs.is_empty() { + return Err(QueryError::Execution { + message: "coalesce() expects at least 1 argument".into(), + }); + } + scalar_udf_call(ctx, "coalesce", arg_exprs) + } + ScalarFn::Least => { + if arg_exprs.is_empty() { + return Err(QueryError::Execution { + message: "least() expects at least 1 argument".into(), + }); + } + scalar_udf_call(ctx, "least", arg_exprs) + } + ScalarFn::Greatest => { + if arg_exprs.is_empty() { + return Err(QueryError::Execution { + message: "greatest() expects at least 1 argument".into(), + }); + } + scalar_udf_call(ctx, "greatest", arg_exprs) + } + ScalarFn::ToFloat => { + if arg_exprs.len() != 1 { + return Err(QueryError::Execution { + message: "float() expects 1 argument".into(), + }); + } + Ok(cast(arg_exprs[0].clone(), ArrowDataType::Float64)) + } + ScalarFn::ToInt => { + if arg_exprs.len() != 1 { + return Err(QueryError::Execution { + message: "int() expects 1 argument".into(), + }); + } + Ok(cast(arg_exprs[0].clone(), ArrowDataType::Int64)) + } + } + } + AstExpr::Case { + branches, + otherwise, + } => { + if branches.is_empty() { + return Err(QueryError::Execution { + message: "CASE requires at least one WHEN branch".into(), + }); + } + let mut iter = branches.iter(); + let first = iter.next().expect("branches is non-empty"); + let first_cond = predicate_to_expr(&first.condition, _schema, signal, ctx)?; + let first_res = ast_expr_to_df_expr(&first.result, _schema, signal, ctx)?; + let mut builder = when(first_cond, first_res); + for b in iter { + let cond = predicate_to_expr(&b.condition, _schema, signal, ctx)?; + let res = ast_expr_to_df_expr(&b.result, _schema, signal, ctx)?; + builder = builder.when(cond, res); } + let built = match otherwise { + Some(e) => builder.otherwise(ast_expr_to_df_expr(e, _schema, signal, ctx)?), + None => builder.end(), + }; + built.map_err(|e| QueryError::Execution { + message: format!("CASE lowering failed: {e}"), + }) } } } +/// Call a built-in scalar function registered on the session context by name +/// (e.g. `exp`, `coalesce`, `least`, `greatest`). Keeps us off version-specific +/// `expr_fn` import paths β€” the functions are standard SQL. +fn scalar_udf_call( + ctx: &SessionContext, + name: &str, + args: Vec, +) -> Result { + let udf = ctx.udf(name).map_err(|e| QueryError::Execution { + message: format!("scalar function `{name}` is not available: {e}"), + })?; + Ok(udf.call(args)) +} + fn literal_to_df_lit(lit_val: &Literal) -> Result { Ok(match lit_val { Literal::Null => lit(datafusion::scalar::ScalarValue::Null), @@ -2091,6 +2185,184 @@ mod tests { assert!(!bytes.is_empty()); } + #[tokio::test] + async fn test_case_exp_and_scalar_fns_compile() { + let ctx = schema_context().expect("schema_context"); + let bytes = compile( + "spans last 1h | group by {} { count() as n } \ + | compute greatest(0.0, least(1.0, float(n) * 0.001)) as clamped, \ + exp(0.0 - float(n) / 100.0) as decay, \ + coalesce(n, 0) as safe, \ + case when n > 100 then 1.0 when n > 10 then 0.5 else 0.0 end as bucket", + &ctx, + ) + .await + .expect("CASE + exp/least/greatest/float/coalesce should compile"); + assert!(!bytes.is_empty()); + } + + #[tokio::test] + async fn test_score_query_compiles() { + let ctx = schema_context().expect("schema_context"); + // A health-style scoring query: rate β†’ score β†’ weighted overall with + // missing-data-aware weighting (via `!= null`). + let bytes = compile( + "spans last 1h | group by {} { \ + count() where status == 2 as errs, count() as total, \ + p95(duration_ns) as p95_ns } \ + | compute float(errs) / float(total) as err_rate, p95_ns as latency \ + | compute score(err_rate, 0.01, 0.05) as err_score, \ + score(latency, 200000000, 500000000) as lat_score, \ + grade(err_rate, 0.01, 0.05) as err_status \ + | compute (err_score * 0.4 + coalesce(lat_score, 0.0) * 0.2) \ + / (0.4 + case when lat_score != null then 0.2 else 0.0 end) as overall", + &ctx, + ) + .await + .expect("scoring query should compile"); + assert!(!bytes.is_empty()); + } + + /// A `score()`/CASE/exp query must survive the full Substrait round-trip β€” the + /// backend executes by consuming the produced plan, so a producer that emits CASE + /// but a consumer that rejects it would break local execution silently. + #[tokio::test] + async fn test_score_query_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 {} { count() where status == 2 as errs, count() as total } \ + | compute float(errs) / float(total) as err_rate \ + | compute score(err_rate, 0.01, 0.05) as err_score, \ + grade(err_rate, 0.01, 0.05) as err_status", + &ctx, + ) + .await + .expect("scoring query should compile"); + + 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 scoring plan: {:?}", + consumed.err() + ); + } + + /// The real System Health dashboard scoreBar query (span factors + missing-data + /// aware weighted overall) compiles and survives the Substrait round-trip. + #[tokio::test] + async fn test_health_dashboard_query_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 q = "spans | group by {} { \ + count() where status == 2 as errs, count() as total, \ + count() where attr.http_status_code >= 500 as http_5xx, \ + count() where attr.http_status_code > 0 as http_total, \ + p95(duration_ns) as p95_ns } \ + | compute float(errs) / float(total) as span_error_rate, \ + case when http_total > 0 then float(http_5xx) / float(http_total) else null end as http_error_rate, \ + p95_ns as latency_p95 \ + | compute score(span_error_rate, 0.01, 0.05) as span_error_score, \ + case when http_error_rate != null then score(http_error_rate, 0.05, 0.15) else null end as http_error_score, \ + score(latency_p95, 200000000, 500000000) as latency_score, \ + span_error_rate * 100.0 as span_error_score__value, \ + http_error_rate * 100.0 as http_error_score__value, \ + p95_ns / 1000000.0 as latency_score__value \ + | compute (span_error_score * 0.40 + coalesce(http_error_score, 0.0) * 0.25 + latency_score * 0.20) \ + / (0.40 + case when http_error_score != null then 0.25 else 0.0 end + 0.20) as overall \ + | select overall, span_error_score, span_error_score__value, http_error_score, \ + http_error_score__value, latency_score, latency_score__value"; + // Scope-less template: a range is injected at execution (as a dashboard does). + let ast = seql_parser::parse(q).expect("health dashboard query 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("health dashboard query should compile with an injected range"); + + 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, + }; + assert!( + consumer.consume_rel(rel).await.is_ok(), + "backend consumer rejected the health dashboard plan" + ); + } + + /// The remaining System Health dashboard panel queries (stat cards, trend lines, + /// HTTP-class stacked bar) all parse and compile with an injected range. + #[tokio::test] + async fn test_health_dashboard_panel_queries_compile() { + let ctx = schema_context().expect("schema_context"); + let queries = [ + // Error-rate stat card. + "spans | group by {} { count() where status == 2 as e, count() as t } \ + | compute float(e) / float(t) * 100.0 as error_rate_pct", + // p95 latency stat card. + "spans | group by {} { p95(duration_ns) as p95_ns } | compute p95_ns / 1000000.0 as p95_ms", + // Error-log stat card. + "logs | where severity_number >= 9 | group by {} { count() as error_logs }", + // Error-rate trend line (rate from raw counts + select to plot one series). + "spans | group by { ts() bin 10% as bucket } { count() where status == 2 as e, count() as t } \ + | compute float(e) / float(t) * 100.0 as error_rate_pct | select bucket, error_rate_pct", + // Latency-percentile trend lines (ns β†’ ms). + "spans | group by { ts() bin 10% as bucket } \ + { p50(duration_ns) as p50, p95(duration_ns) as p95, p99(duration_ns) as p99 } \ + | compute p50 / 1000000.0 as p50_ms, p95 / 1000000.0 as p95_ms, p99 / 1000000.0 as p99_ms \ + | select bucket, p50_ms, p95_ms, p99_ms", + // HTTP status-class stacked bar over time (compound per-aggregate filters). + "spans | where attr.http_status_code > 0 | group by { ts() bin 10% as bucket } { \ + count() where attr.http_status_code >= 200 and attr.http_status_code < 300 as c2xx, \ + count() where attr.http_status_code >= 400 and attr.http_status_code < 500 as c4xx, \ + count() where attr.http_status_code >= 500 as c5xx }", + ]; + for q in queries { + let ast = + seql_parser::parse(q).unwrap_or_else(|e| panic!("parse failed for `{q}`: {e:?}")); + let bytes = compile_ast_with_range( + ast, + Some(TimeRange::SlidingWindow { + start_ns: 3_600_000_000_000, + }), + &ctx, + ) + .await + .unwrap_or_else(|e| panic!("compile failed for `{q}`: {e:?}")); + assert!(!bytes.is_empty(), "empty plan for `{q}`"); + } + } + /// `percentile(col, 90)` (a 0–100 form) is normalized to the 0..1 quantile. #[test] fn test_percentile_parses_0_100_form() { diff --git a/crates/sequins-assistant/src/model.rs b/crates/sequins-assistant/src/model.rs index e922840..bec3c04 100644 --- a/crates/sequins-assistant/src/model.rs +++ b/crates/sequins-assistant/src/model.rs @@ -403,15 +403,17 @@ language (NOT SQL). Do not write SQL in SeQL queries. ## SeQL syntax (follow exactly) -Every query begins with a signal and a mandatory time scope, then optional `|` stages: +Every query begins with a signal, then an OPTIONAL time scope, then optional `|` stages: - [ | ]* + [] [ | ]* - Signals: `spans`, `logs`, `metrics`, `datapoints`, `histograms`, `profiles`, `samples`, `resources`, `scopes`, `span_links`, `span_events`. -- Time scope (required, right after the signal): `last ` | `today` | `yesterday` | +- Time scope (optional, right after the signal): `last ` | `today` | `yesterday` | `between(, )`. Durations are a single integer + unit (`ms`,`s`,`m`,`h`,`d`) β€” e.g. `15m`, `1h`, `7d`. NO compound durations like `1h30m`. + Omit the scope to write a **template** that a dashboard/control bar supplies the range + for; a query executed with no range at all errors. - Stages (chained with `|`): - `where ` β€” e.g. `where status == 2`, `where severity_number >= 9`, `where attr.http_status_code >= 500`. Combine with `and`/`or`. @@ -428,6 +430,15 @@ Every query begins with a signal and a mandatory time scope, then optional `|` s - `window { as , … }` β€” window functions over the time-ordered result (use AFTER a time-bucketed `group by`): `moving_avg(, )`, `cumulative()`, `delta()` (period-over-period change). + - `compute as , …` β€” derive columns with full expressions (after a + `group by`, these operate on the aggregate columns). Arithmetic `+ - * / %` with + parentheses; scalar fns `abs/round/ceil/floor/exp/coalesce(a,…)/least(a,…)/greatest(a,…)/ + float(x)/int(x)`; and `case when then [when …] [else ] end`. + Use `float(a)/float(b)` to avoid integer division when computing a rate. + - **Thresholded scoring** (health/ranking): `score(value, warn, err)` β†’ a 0..1 score + (1=good; linear down to 0.7 at `warn`, 0.3 at `err`, then exp-decays), and + `grade(value, warn, err)` β†’ `'healthy'`/`'degraded'`/`'unhealthy'`. Both are sugar + over `case`, so they work in `compute`. Higher value = worse. - `take ` β€” limit rows. `select ` β€” project columns. Time note: on a **dashboard**, the panel's selected range and live toggle are applied for @@ -443,6 +454,7 @@ like `last 1h` and use `ts() bin 10%` β€” the chart then follows the dashboard's - 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 }` +- Health score (thresholds): `spans last 1h | group by {} { count() where status==2 as errs, count() as total } | compute float(errs)/float(total) as err_rate | compute score(err_rate, 0.01, 0.05) as err_score, grade(err_rate, 0.01, 0.05) as err_status` ## Exploring the data diff --git a/crates/sequins-companion-index/src/bloom.rs b/crates/sequins-companion-index/src/bloom.rs index 78986ba..021a37c 100644 --- a/crates/sequins-companion-index/src/bloom.rs +++ b/crates/sequins-companion-index/src/bloom.rs @@ -60,7 +60,7 @@ impl BloomFilterSet { /// Only the hash keys are pinned; the false-positive rate itself is /// unchanged, so callers still must not treat a `true` result as proof of /// membership. - #[cfg(feature = "test-util")] + #[cfg(any(test, feature = "test-util"))] pub fn build_with_seed(&mut self, field_name: String, values: I, fpr: f64, seed: &[u8; 32]) where I: IntoIterator, @@ -267,12 +267,15 @@ mod tests { fn test_multiple_filters() { let mut bloom_set = BloomFilterSet::new(); - // Use 1000+ items to avoid false positives let trace_ids: Vec = (0..1000).map(|i| format!("trace{}", i)).collect(); let user_ids: Vec = (0..1000).map(|i| format!("user{}", i)).collect(); - bloom_set.build("trace_id".to_string(), trace_ids, 0.01); - bloom_set.build("user_id".to_string(), user_ids, 0.01); + // Seeded: 1000 items makes the nominal 1% false-positive rate *accurate*, + // it does not make it zero β€” the two cross-field assertions below fail + // ~1.9% of runs against `build`'s random keys (measured over 3000 trials). + // This seed is verified to prune both cross-field values. + bloom_set.build_with_seed("trace_id".to_string(), trace_ids, 0.01, &[0u8; 32]); + bloom_set.build_with_seed("user_id".to_string(), user_ids, 0.01, &[0u8; 32]); assert_eq!(bloom_set.len(), 2); assert!(bloom_set.check("trace_id", "trace0")); diff --git a/crates/sequins-ffi/include/sequins.h b/crates/sequins-ffi/include/sequins.h index 363d591..47f676e 100644 --- a/crates/sequins-ffi/include/sequins.h +++ b/crates/sequins-ffi/include/sequins.h @@ -1599,6 +1599,31 @@ bool sequins_dashboard_save(struct CDataSource *data_source, */ bool sequins_dashboard_delete(struct CDataSource *data_source, const char *id, char **error_out); +/** + * List the built-in dashboard templates as a JSON array of `{id, title, description}`. + * Templates are compiled in, so this is identical for Local and Remote; the data + * source is accepted for ABI consistency but unused. + * + * # Safety + * `out_json`/`error_out` are out-params. + */ +bool sequins_dashboard_templates_list(struct CDataSource *_data_source, + char **out_json, + char **error_out); + +/** + * Instantiate a built-in template by id: build a **fresh** dashboard (a new id, so the + * gallery always creates a new copy) and persist it via the data source (Local or + * Remote). Writes the stored dashboard to `out_json`. + * + * # Safety + * `data_source`/`template_id` must be valid; `out_json`/`error_out` are out-params. + */ +bool sequins_dashboard_instantiate_template(struct CDataSource *data_source, + const char *template_id, + char **out_json, + char **error_out); + /** * Delete a persisted conversation by id (in-memory + durable). Local only; remote * connections report an error until the daemon exposes conversation deletion. @@ -2099,7 +2124,11 @@ void sequins_seql_stream_free(struct CStreamHandle *handle); * * # Parameters * - `data_source` β€” local data source (remote not yet supported) - * - `query` β€” SeQL query text + * - `query` β€” SeQL query text (may be a scope-less template) + * - `range_kind` β€” structured time range selector: 0 = honor the query's inline + * scope, 1 = sliding window (`range_a_ns` = start offset), 2 = absolute + * (`range_a_ns`..`range_b_ns`). A non-zero range overrides any inline scope. + * - `range_a_ns` / `range_b_ns` β€” range bounds, interpreted per `range_kind`. * - `strategy` β€” [`CViewStrategy`] variant * - `retention_ns` β€” retention window in nanoseconds; if 0, defaults to 1 hour. * Only meaningful for `Flamegraph` strategy. @@ -2118,6 +2147,9 @@ void sequins_seql_stream_free(struct CStreamHandle *handle); */ struct CViewHandle *sequins_view_create(struct CDataSource *data_source, const char *query, + uint32_t range_kind, + uint64_t range_a_ns, + uint64_t range_b_ns, uint32_t strategy, uint64_t retention_ns, void (*on_deltas)(struct CViewDelta*, uint32_t, void*), diff --git a/crates/sequins-ffi/src/dashboard.rs b/crates/sequins-ffi/src/dashboard.rs index d67b6d8..d8cc6a3 100644 --- a/crates/sequins-ffi/src/dashboard.rs +++ b/crates/sequins-ffi/src/dashboard.rs @@ -8,7 +8,7 @@ use std::ffi::{c_char, CStr, CString}; -use sequins_metadata::{Dashboard, DashboardApi}; +use sequins_metadata::{builtin_templates, template_by_id, Dashboard, DashboardApi}; use crate::data_source::{CDataSource, DataSourceImpl}; use crate::runtime::RUNTIME; @@ -165,6 +165,84 @@ pub unsafe extern "C" fn sequins_dashboard_delete( } } +/// Serializable view of a [`sequins_metadata::DashboardTemplate`] for the gallery. +#[derive(serde::Serialize)] +struct CTemplateInfo { + id: &'static str, + title: &'static str, + description: &'static str, +} + +/// List the built-in dashboard templates as a JSON array of `{id, title, description}`. +/// Templates are compiled in, so this is identical for Local and Remote; the data +/// source is accepted for ABI consistency but unused. +/// +/// # Safety +/// `out_json`/`error_out` are out-params. +#[no_mangle] +pub unsafe extern "C" fn sequins_dashboard_templates_list( + _data_source: *mut CDataSource, + out_json: *mut *mut c_char, + error_out: *mut *mut c_char, +) -> bool { + let infos: Vec = builtin_templates() + .iter() + .map(|t| CTemplateInfo { + id: t.id, + title: t.title, + description: t.description, + }) + .collect(); + if write_json(out_json, &infos) { + true + } else { + set_error(error_out, "failed to serialize templates"); + false + } +} + +/// Instantiate a built-in template by id: build a **fresh** dashboard (a new id, so the +/// gallery always creates a new copy) and persist it via the data source (Local or +/// Remote). Writes the stored dashboard to `out_json`. +/// +/// # Safety +/// `data_source`/`template_id` must be valid; `out_json`/`error_out` are out-params. +#[no_mangle] +pub unsafe extern "C" fn sequins_dashboard_instantiate_template( + data_source: *mut CDataSource, + template_id: *const c_char, + out_json: *mut *mut c_char, + error_out: *mut *mut c_char, +) -> bool { + if data_source.is_null() || template_id.is_null() { + set_error(error_out, "data source or template id is null"); + return false; + } + let tid = match CStr::from_ptr(template_id).to_str() { + Ok(s) => s, + Err(_) => { + set_error(error_out, "template id is not valid UTF-8"); + return false; + } + }; + let Some(template) = template_by_id(tid) else { + set_error(error_out, &format!("unknown dashboard template `{tid}`")); + return false; + }; + let mut dashboard = template.build(); + // Clear the built-in id so save mints a fresh one (a distinct new dashboard), + // rather than overwriting the seeded copy. + dashboard.id.clear(); + let api = dashboard_api(&*(data_source as *const DataSourceImpl)); + match RUNTIME.block_on(api.save_dashboard(dashboard)) { + Ok(stored) => write_json(out_json, &stored), + Err(e) => { + set_error(error_out, &e.to_string()); + false + } + } +} + /// Delete a persisted conversation by id (in-memory + durable). Local only; remote /// connections report an error until the daemon exposes conversation deletion. /// @@ -254,12 +332,18 @@ mod tests { let id = saved["id"].as_str().unwrap().to_string(); assert!(!id.is_empty()); - // List β†’ 1. + // List contains the saved dashboard (plus the seeded System Health one). let mut list_out: *mut c_char = std::ptr::null_mut(); let ok = unsafe { sequins_dashboard_list(ds, &mut list_out, &mut err2) }; assert!(ok); let list: serde_json::Value = serde_json::from_str(&unsafe { take(list_out) }).unwrap(); - assert_eq!(list.as_array().unwrap().len(), 1); + let ids: Vec<&str> = list + .as_array() + .unwrap() + .iter() + .filter_map(|d| d["id"].as_str()) + .collect(); + assert!(ids.contains(&id.as_str())); // Delete. let id_c = CString::new(id).unwrap(); @@ -268,4 +352,47 @@ mod tests { sequins_data_source_free(ds); } + + #[test] + fn template_gallery_and_instantiate() { + let tmp = tempfile::tempdir().unwrap(); + let db = CString::new(tmp.path().to_str().unwrap()).unwrap(); + let mut err: *mut c_char = std::ptr::null_mut(); + let ds = sequins_data_source_new_local( + db.as_ptr(), + COtlpServerConfig { + grpc_port: 0, + http_port: 0, + }, + &mut err, + ); + assert!(!ds.is_null()); + + // The gallery lists at least the System Health template. + let mut out: *mut c_char = std::ptr::null_mut(); + let mut err2: *mut c_char = std::ptr::null_mut(); + let ok = unsafe { sequins_dashboard_templates_list(ds, &mut out, &mut err2) }; + assert!(ok); + let templates: serde_json::Value = serde_json::from_str(&unsafe { take(out) }).unwrap(); + let arr = templates.as_array().unwrap(); + assert!(arr.iter().any(|t| t["id"] == "builtin-system-health")); + + // Instantiating mints a fresh dashboard (a new id, not the seeded one). + let tid = CString::new("builtin-system-health").unwrap(); + let mut out2: *mut c_char = std::ptr::null_mut(); + let ok = unsafe { + sequins_dashboard_instantiate_template(ds, tid.as_ptr(), &mut out2, &mut err2) + }; + assert!(ok); + let created: serde_json::Value = serde_json::from_str(&unsafe { take(out2) }).unwrap(); + let new_id = created["id"].as_str().unwrap(); + assert!(!new_id.is_empty()); + assert_ne!( + new_id, "builtin-system-health", + "gallery copy gets a fresh id" + ); + assert_eq!(created["title"], "System Health"); + + sequins_data_source_free(ds); + } } diff --git a/crates/sequins-ffi/src/data_source.rs b/crates/sequins-ffi/src/data_source.rs index ee00e12..0ceb8d5 100644 --- a/crates/sequins-ffi/src/data_source.rs +++ b/crates/sequins-ffi/src/data_source.rs @@ -127,6 +127,13 @@ pub extern "C" fn sequins_data_source_new_local( } }; + // Seed built-in dashboards (System Health) into a fresh store so first-run users + // land on a useful dashboard. Best-effort β€” a failure must not block startup. + if let Err(e) = crate::runtime::RUNTIME.block_on(storage.app_state().seed_builtin_dashboards()) + { + tracing::warn!(error = %e, "failed to seed built-in dashboards"); + } + // Create the shared DataFusion backend once. The SessionContext inside it is // initialised lazily on the first query and then reused for all subsequent // queries, so the expensive infer_schema call over all cold-tier Vortex files diff --git a/crates/sequins-ffi/src/seql.rs b/crates/sequins-ffi/src/seql.rs index a3f9ae2..91208d7 100644 --- a/crates/sequins-ffi/src/seql.rs +++ b/crates/sequins-ffi/src/seql.rs @@ -254,14 +254,6 @@ impl QueryExecutor { } } - async fn query_live(&self, seql: &str) -> Result { - match self { - #[cfg(feature = "local")] - QueryExecutor::Local(b) => b.query_live(seql).await, - QueryExecutor::Remote(c) => c.query_live(seql).await, - } - } - async fn query_live_with_range( &self, seql: &str, @@ -945,7 +937,11 @@ unsafe impl Send for ViewSinkCtx {} /// /// # Parameters /// - `data_source` β€” local data source (remote not yet supported) -/// - `query` β€” SeQL query text +/// - `query` β€” SeQL query text (may be a scope-less template) +/// - `range_kind` β€” structured time range selector: 0 = honor the query's inline +/// scope, 1 = sliding window (`range_a_ns` = start offset), 2 = absolute +/// (`range_a_ns`..`range_b_ns`). A non-zero range overrides any inline scope. +/// - `range_a_ns` / `range_b_ns` β€” range bounds, interpreted per `range_kind`. /// - `strategy` β€” [`CViewStrategy`] variant /// - `retention_ns` β€” retention window in nanoseconds; if 0, defaults to 1 hour. /// Only meaningful for `Flamegraph` strategy. @@ -966,6 +962,9 @@ unsafe impl Send for ViewSinkCtx {} pub unsafe extern "C" fn sequins_view_create( data_source: *mut CDataSource, query: *const c_char, + range_kind: u32, + range_a_ns: u64, + range_b_ns: u64, strategy: u32, retention_ns: u64, on_deltas: Option< @@ -982,6 +981,7 @@ pub unsafe extern "C" fn sequins_view_create( Some(cb) => cb, None => return std::ptr::null_mut(), }; + let time_range = ffi_time_range(range_kind, range_a_ns, range_b_ns); let query_str = match CStr::from_ptr(query).to_str() { Ok(s) => s.to_string(), @@ -1006,7 +1006,7 @@ pub unsafe extern "C" fn sequins_view_create( }; let task = RUNTIME.spawn(AssertSend(async move { - let seql_stream = match executor.query_live(&query_str).await { + let seql_stream = match executor.query_live_with_range(&query_str, time_range).await { Ok(s) => s, Err(e) => { tracing::error!(error = %e, "View query failed"); diff --git a/crates/sequins-metadata/src/lib.rs b/crates/sequins-metadata/src/lib.rs index 2ffef7d..693e0f4 100644 --- a/crates/sequins-metadata/src/lib.rs +++ b/crates/sequins-metadata/src/lib.rs @@ -8,10 +8,12 @@ pub mod error; pub mod store; +pub mod templates; pub mod types; pub use error::{MetadataError, Result}; pub use store::{AppStateStore, DashboardApi}; +pub use templates::{builtin_templates, template_by_id, DashboardTemplate, SYSTEM_HEALTH_ID}; pub use types::{ Conversation, ConversationItem, Dashboard, DashboardRow, RowPanel, SavedVisualization, Threshold, VisualizationOptions, DEFAULT_ROW_HEIGHT, diff --git a/crates/sequins-metadata/src/store.rs b/crates/sequins-metadata/src/store.rs index ee6daad..cef86e9 100644 --- a/crates/sequins-metadata/src/store.rs +++ b/crates/sequins-metadata/src/store.rs @@ -17,7 +17,7 @@ use object_store::path::Path as ObjPath; use object_store::{ObjectStore, ObjectStoreExt, PutPayload}; use tokio::sync::RwLock; -use crate::error::Result; +use crate::error::{MetadataError, Result}; use crate::types::{Conversation, ConversationItem, Dashboard}; fn now_ns() -> u64 { @@ -238,6 +238,27 @@ impl AppStateStore { pub async fn get_dashboard(&self, id: &str) -> Option { self.dashboards.read().await.get(id).cloned() } + + /// Instantiate a built-in template by id, persisting it as a dashboard and + /// returning the stored value. Errors if the template id is unknown. + pub async fn instantiate_template(&self, template_id: &str) -> Result { + let template = crate::templates::template_by_id(template_id).ok_or_else(|| { + MetadataError::Other(format!("unknown dashboard template `{template_id}`")) + })?; + self.upsert_dashboard(template.build()).await + } + + /// Seed the default built-in dashboards, but only into a **fresh** (empty) store, so + /// a first run lands on a useful dashboard while a user who later deletes it isn't + /// nagged by it reappearing. Idempotent once any dashboard exists. + pub async fn seed_builtin_dashboards(&self) -> Result<()> { + if !self.dashboards.read().await.is_empty() { + return Ok(()); + } + self.upsert_dashboard(crate::templates::system_health()) + .await?; + Ok(()) + } } /// Read/write dashboards. Implemented for `Storage` (local, delegating to diff --git a/crates/sequins-metadata/src/templates.rs b/crates/sequins-metadata/src/templates.rs new file mode 100644 index 0000000..28a49f5 --- /dev/null +++ b/crates/sequins-metadata/src/templates.rs @@ -0,0 +1,242 @@ +//! Built-in dashboard **templates** β€” pre-built [`Dashboard`]s a user can instantiate +//! (or that are seeded on first run). Templates are plain `Dashboard` values whose +//! panels carry **scope-less** SeQL (the range comes from the dashboard's control bar). +//! +//! The flagship template, [`system_health`], reproduces the app's Health tab as an +//! ordinary dashboard: the per-factor **scores** and weighted **overall** are computed +//! in SeQL via `score()` (thresholds mirror `sequins_types::HealthThresholdConfig`), +//! rendered by the `scoreBar` visualization, alongside key metric cards, trend lines, +//! and an HTTP status-class breakdown. + +use crate::types::{Dashboard, DashboardRow, RowPanel, SavedVisualization, VisualizationOptions}; + +/// The stable id of the seeded System Health dashboard (so re-seeding is idempotent). +pub const SYSTEM_HEALTH_ID: &str = "builtin-system-health"; + +/// A named, buildable dashboard template. +#[derive(Clone, Copy)] +pub struct DashboardTemplate { + /// Stable template id. + pub id: &'static str, + /// Human-readable title (also the created dashboard's title). + pub title: &'static str, + /// One-line description for the template gallery. + pub description: &'static str, + builder: fn() -> Dashboard, +} + +impl DashboardTemplate { + /// Build a fresh [`Dashboard`] from this template (unsaved; id set for built-ins). + pub fn build(&self) -> Dashboard { + (self.builder)() + } +} + +/// Every built-in template, in gallery order. +pub fn builtin_templates() -> Vec { + vec![DashboardTemplate { + id: SYSTEM_HEALTH_ID, + title: "System Health", + description: "Service reliability at a glance β€” health-factor scores and a \ + weighted overall, key latency/error/throughput metrics, trends, and \ + an HTTP status breakdown. Mirrors the Health tab as a dashboard.", + builder: system_health, + }] +} + +/// Look up a built-in template by id. +pub fn template_by_id(id: &str) -> Option { + builtin_templates().into_iter().find(|t| t.id == id) +} + +// ── Panel/option helpers ──────────────────────────────────────────────────────── + +fn panel( + title: &str, + shape: &str, + seql: &str, + weight: f64, + options: VisualizationOptions, +) -> RowPanel { + RowPanel { + visualization: SavedVisualization { + seql: seql.to_string(), + title: title.to_string(), + shape: Some(shape.to_string()), + options, + }, + weight, + } +} + +fn unit(u: &str) -> VisualizationOptions { + VisualizationOptions { + unit: Some(u.to_string()), + ..Default::default() + } +} + +// ── System Health template ────────────────────────────────────────────────────── + +/// Build the **System Health** dashboard. +pub fn system_health() -> Dashboard { + Dashboard { + id: SYSTEM_HEALTH_ID.to_string(), + title: "System Health".to_string(), + created_at_ns: 0, + updated_at_ns: 0, + rows: vec![ + // Overall + per-factor score bars. + DashboardRow { + height: 220.0, + panels: vec![panel( + "Service Health", + "scoreBar", + SCORECARD_QUERY, + 1.0, + VisualizationOptions::default(), + )], + }, + // Key metric cards. + DashboardRow { + height: 130.0, + panels: vec![ + panel("Error Rate", "stat", ERROR_RATE_QUERY, 1.0, unit("%")), + panel("p95 Latency", "stat", P95_QUERY, 1.0, unit("ms")), + panel("Throughput", "stat", THROUGHPUT_QUERY, 1.0, unit("req/s")), + panel( + "Error Logs", + "stat", + ERROR_LOG_QUERY, + 1.0, + VisualizationOptions::default(), + ), + ], + }, + // Trends. + DashboardRow { + height: 260.0, + panels: vec![ + panel( + "Error rate over time", + "line", + ERROR_RATE_TREND_QUERY, + 1.0, + unit("%"), + ), + panel( + "Latency over time", + "line", + LATENCY_TREND_QUERY, + 1.0, + unit("ms"), + ), + ], + }, + // HTTP status breakdown. + DashboardRow { + height: 240.0, + panels: vec![panel( + "HTTP status classes", + "stackedBar", + HTTP_BREAKDOWN_QUERY, + 1.0, + VisualizationOptions::default(), + )], + }, + ], + } +} + +// ── Queries (scope-less templates; the dashboard supplies the range) ───────────── +// +// Thresholds/weights mirror `sequins_types::health::HealthThresholdConfig::default()`: +// span_error_rate 0.01/0.05 w0.40 Β· http_error_rate 0.05/0.15 w0.25 Β· +// latency_p95 200ms/500ms w0.20 Β· (error_log_rate 5/20 w0.15 lives in a separate panel). +// Validated by `seql-substrait` compile+consume tests. + +/// Per-factor scores + weighted overall (missing HTTP traffic drops out of the weight). +/// The final `select` keeps only the score columns (+ `__value` companions the scoreBar +/// shows as raw values) so intermediate rates don't render as extra bars. +const SCORECARD_QUERY: &str = "spans | group by {} { \ + count() where status == 2 as errs, count() as total, \ + count() where attr.http_status_code >= 500 as http_5xx, \ + count() where attr.http_status_code > 0 as http_total, \ + p95(duration_ns) as p95_ns } \ + | compute float(errs) / float(total) as span_error_rate, \ + case when http_total > 0 then float(http_5xx) / float(http_total) else null end as http_error_rate, \ + p95_ns as latency_p95 \ + | compute score(span_error_rate, 0.01, 0.05) as span_error_score, \ + case when http_error_rate != null then score(http_error_rate, 0.05, 0.15) else null end as http_error_score, \ + score(latency_p95, 200000000, 500000000) as latency_score, \ + span_error_rate * 100.0 as span_error_score__value, \ + http_error_rate * 100.0 as http_error_score__value, \ + p95_ns / 1000000.0 as latency_score__value \ + | compute (span_error_score * 0.40 + coalesce(http_error_score, 0.0) * 0.25 + latency_score * 0.20) \ + / (0.40 + case when http_error_score != null then 0.25 else 0.0 end + 0.20) as overall \ + | select overall, span_error_score, span_error_score__value, http_error_score, \ + http_error_score__value, latency_score, latency_score__value"; + +const ERROR_RATE_QUERY: &str = + "spans | group by {} { count() where status == 2 as e, count() as t } \ + | compute float(e) / float(t) * 100.0 as error_rate_pct"; + +const P95_QUERY: &str = + "spans | group by {} { p95(duration_ns) as p95_ns } | compute p95_ns / 1000000.0 as p95_ms"; + +const THROUGHPUT_QUERY: &str = "spans | group by {} { throughput() as rps }"; + +const ERROR_LOG_QUERY: &str = + "logs | where severity_number >= 9 | group by {} { count() as error_logs }"; + +const ERROR_RATE_TREND_QUERY: &str = + "spans | group by { ts() bin 10% as bucket } { count() where status == 2 as e, count() as t } \ + | compute float(e) / float(t) * 100.0 as error_rate_pct | select bucket, error_rate_pct"; + +const LATENCY_TREND_QUERY: &str = "spans | group by { ts() bin 10% as bucket } \ + { p50(duration_ns) as p50, p95(duration_ns) as p95, p99(duration_ns) as p99 } \ + | compute p50 / 1000000.0 as p50_ms, p95 / 1000000.0 as p95_ms, p99 / 1000000.0 as p99_ms \ + | select bucket, p50_ms, p95_ms, p99_ms"; + +const HTTP_BREAKDOWN_QUERY: &str = + "spans | where attr.http_status_code > 0 | group by { ts() bin 10% as bucket } { \ + count() where attr.http_status_code >= 200 and attr.http_status_code < 300 as c2xx, \ + count() where attr.http_status_code >= 400 and attr.http_status_code < 500 as c4xx, \ + count() where attr.http_status_code >= 500 as c5xx }"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn system_health_builds_expected_shape() { + let d = system_health(); + assert_eq!(d.id, SYSTEM_HEALTH_ID); + assert_eq!(d.title, "System Health"); + assert_eq!(d.rows.len(), 4); + // The first panel is the score card. + assert_eq!( + d.rows[0].panels[0].visualization.shape.as_deref(), + Some("scoreBar") + ); + assert!(d.panel_count() >= 7); + // Panels are scope-less templates (no baked `last`/`between`). + for row in &d.rows { + for p in &row.panels { + let q = &p.visualization.seql; + assert!(!q.contains(" last "), "panel query has a baked scope: {q}"); + assert!( + !q.contains("between("), + "panel query has a baked scope: {q}" + ); + } + } + } + + #[test] + fn template_lookup() { + assert!(template_by_id(SYSTEM_HEALTH_ID).is_some()); + assert!(template_by_id("nope").is_none()); + assert_eq!(builtin_templates().len(), 1); + } +}