1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
use std::collections::{BTreeMap, HashMap};
use rsigma_eval::pipeline::state::PipelineState;
use rsigma_parser::*;
use crate::error::{ConvertError, Result};
impl super::PostgresBackend {
/// Format a field name for use in a SELECT column list.
///
/// Inspired by the pySigma Athena backend's `_format_select_field`:
/// - Expressions containing parentheses (function calls) pass through unchanged
/// - `field as alias` is split and both sides are quoted independently
/// - Plain field names are quoted via `field_expr`
pub(super) fn format_select_field(&self, field: &str) -> Result<String> {
if field == "*" {
return Ok("*".to_string());
}
if field.contains('(') && field.contains(')') {
return Ok(field.to_string());
}
if let Some((expr, alias)) = field.split_once(" as ") {
let quoted_expr = self.field_expr(expr.trim())?;
let quoted_alias = self.field_expr(alias.trim())?;
return Ok(format!("{quoted_expr} AS {quoted_alias}"));
}
if let Some((expr, alias)) = field.split_once(" AS ") {
let quoted_expr = self.field_expr(expr.trim())?;
let quoted_alias = self.field_expr(alias.trim())?;
return Ok(format!("{quoted_expr} AS {quoted_alias}"));
}
self.field_expr(field)
}
/// Build the CTE prefix and source for non-temporal correlations.
///
/// When per-rule converted queries are available (from `_rule_queries`
/// injected by `convert_collection`), wraps them in a
/// `WITH combined_events AS (q1 UNION ALL q2 ...)` CTE. The aggregate
/// query then reads from `combined_events` instead of the raw table.
///
/// When no per-rule queries are available, falls back to the original
/// behavior: scan the full table with a time-window filter.
///
/// Returns `(cte_prefix, source_table, time_filter)`.
pub(super) fn build_correlation_source(
&self,
rule_refs: &[String],
rule_queries: &HashMap<String, String>,
default_table: &str,
ts: &str,
window_secs: u64,
) -> (String, String, String) {
let matched: Vec<&str> = rule_refs
.iter()
.filter_map(|r| rule_queries.get(r).map(|q| q.as_str()))
.collect();
if matched.is_empty() {
let time_filter = format!(" WHERE {ts} >= NOW() - INTERVAL '{window_secs} seconds'");
(String::new(), default_table.to_string(), time_filter)
} else {
let union = matched.join(" UNION ALL ");
let cte = format!("WITH combined_events AS ({union}) ");
(cte, "combined_events".to_string(), String::new())
}
}
/// Build a sliding window query for `event_count` correlations.
///
/// Generates a two-CTE query inspired by the pySigma Athena backend:
/// ```sql
/// WITH combined_events AS (...),
/// event_counts AS (
/// SELECT *, COUNT(*) OVER (
/// PARTITION BY {group_by}
/// ORDER BY {time_field}
/// RANGE BETWEEN INTERVAL '{N}' SECOND PRECEDING AND CURRENT ROW
/// ) AS correlation_event_count
/// FROM combined_events
/// )
/// SELECT * FROM event_counts WHERE correlation_event_count >= {threshold}
/// ```
///
/// This produces a per-row sliding window that emits every event crossing
/// the threshold within its trailing window.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_sliding_window_query(
&self,
cte_prefix: &str,
source_table: &str,
time_filter: &str,
group_by: &[String],
ts: &str,
window_secs: u64,
condition: &CorrelationCondition,
) -> Result<String> {
let partition_clause = if group_by.is_empty() {
String::new()
} else {
let cols: Vec<String> = group_by
.iter()
.map(|g| self.field_expr(g))
.collect::<Result<_>>()?;
format!("PARTITION BY {} ", cols.join(", "))
};
let where_clause = self.build_threshold_where("correlation_event_count", condition)?;
// When there is a CTE prefix (combined_events), chain the window CTE
// onto it. Otherwise, build a standalone source CTE from the table.
let full_cte = if cte_prefix.is_empty() {
format!(
"WITH source AS (\
SELECT * FROM {source_table}{time_filter}\
), \
event_counts AS (\
SELECT *, COUNT(*) OVER (\
{partition_clause}\
ORDER BY {ts} \
RANGE BETWEEN INTERVAL '{window_secs} seconds' PRECEDING AND CURRENT ROW\
) AS correlation_event_count \
FROM source\
) "
)
} else {
// cte_prefix already has "WITH combined_events AS (...) "
// Strip the trailing space and append the window CTE
let base = cte_prefix.trim_end();
format!(
"{base}, \
event_counts AS (\
SELECT *, COUNT(*) OVER (\
{partition_clause}\
ORDER BY {ts} \
RANGE BETWEEN INTERVAL '{window_secs} seconds' PRECEDING AND CURRENT ROW\
) AS correlation_event_count \
FROM {source_table}\
) "
)
};
Ok(format!(
"{full_cte}SELECT * FROM event_counts WHERE {where_clause}"
))
}
/// Build a WHERE clause from a correlation condition for sliding window queries.
fn build_threshold_where(&self, column: &str, cond: &CorrelationCondition) -> Result<String> {
match cond {
CorrelationCondition::Threshold { predicates, .. } => {
let parts: Vec<String> = predicates
.iter()
.map(|(op, val)| {
let op_str = match op {
ConditionOperator::Lt => "<",
ConditionOperator::Lte => "<=",
ConditionOperator::Gt => ">",
ConditionOperator::Gte => ">=",
ConditionOperator::Eq => "=",
ConditionOperator::Neq => "<>",
};
format!("{column} {op_str} {val}")
})
.collect();
Ok(parts.join(" AND "))
}
CorrelationCondition::Extended(_) => Err(ConvertError::UnsupportedCorrelation(
"extended boolean conditions not yet supported for PostgreSQL".into(),
)),
}
}
/// Aggregate SELECT expression and its column alias for a correlation type.
///
/// Shared by the tumbling and session builders. Temporal types are handled
/// by [`build_temporal_query`](Self::build_temporal_query) and are rejected
/// here.
pub(super) fn correlation_aggregate(
&self,
rule: &CorrelationRule,
value_field: Option<&str>,
) -> Result<(String, &'static str)> {
let field = match value_field {
Some(f) => self.field_expr(f)?,
None => "'unknown_field'".to_string(),
};
Ok(match rule.correlation_type {
CorrelationType::EventCount => ("COUNT(*)".to_string(), "event_count"),
CorrelationType::ValueCount => (format!("COUNT(DISTINCT {field})"), "value_count"),
CorrelationType::ValueSum => (format!("SUM({field})"), "value_sum"),
CorrelationType::ValueAvg => (format!("AVG({field})"), "value_avg"),
CorrelationType::ValuePercentile | CorrelationType::ValueMedian => {
let percentile = if rule.correlation_type == CorrelationType::ValueMedian {
0.5
} else {
match &rule.condition {
CorrelationCondition::Threshold { percentile, .. } => {
percentile.map(|p| p as f64 / 100.0).unwrap_or(0.95)
}
_ => 0.95,
}
};
(
format!("PERCENTILE_CONT({percentile}) WITHIN GROUP (ORDER BY {field})"),
"pct_value",
)
}
CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
return Err(ConvertError::UnsupportedCorrelation(
"temporal correlations are handled by a dedicated builder".into(),
));
}
})
}
/// Build a tumbling-window correlation query for the non-temporal aggregate
/// types: events are grouped into fixed, boundary-aligned buckets of size
/// `window_secs` (via `time_bucket` on TimescaleDB, or `date_bin` aligned to
/// the epoch on plain PostgreSQL) plus the rule's group-by columns.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_tumbling_correlation(
&self,
rule: &CorrelationRule,
cte_prefix: &str,
source_table: &str,
ts: &str,
window_secs: u64,
value_field: Option<&str>,
use_time_bucket: bool,
) -> Result<String> {
let (agg, alias) = self.correlation_aggregate(rule, value_field)?;
let bucket_expr = if use_time_bucket {
format!("time_bucket('{window_secs} seconds', {ts})")
} else {
format!("date_bin('{window_secs} seconds', {ts}, TIMESTAMPTZ 'epoch')")
};
let group_exprs: Vec<String> = rule
.group_by
.iter()
.map(|g| self.field_expr(g))
.collect::<Result<_>>()?;
let group_by_select = if group_exprs.is_empty() {
String::new()
} else {
format!("{}, ", group_exprs.join(", "))
};
let mut gb = vec![bucket_expr.clone()];
gb.extend(group_exprs);
let group_by_clause = format!(" GROUP BY {}", gb.join(", "));
let having = self
.build_having_clause(&rule.condition)?
.replace("{agg}", &agg);
Ok(format!(
"{cte_prefix}SELECT {bucket_expr} AS correlation_bucket, \
{group_by_select}{agg} AS {alias} \
FROM {source_table}\
{group_by_clause} \
HAVING {having}"
))
}
/// Build a session-window correlation query for the non-temporal aggregate
/// types using the gaps-and-islands pattern: `LAG` flags the first event of
/// each session (a gap larger than `gap_secs`), a running `SUM` assigns a
/// per-group session id, and the aggregate is computed per session.
///
/// The `gap` is honored exactly. The `timespan` cap can only be enforced as
/// a post-aggregation filter (sessions longer than the cap are dropped, not
/// split mid-session as the runtime does), which is recorded in `warnings`.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_session_correlation(
&self,
rule: &CorrelationRule,
cte_prefix: &str,
source_table: &str,
ts: &str,
window_secs: u64,
gap_secs: u64,
value_field: Option<&str>,
warnings: &mut Vec<String>,
) -> Result<String> {
let (agg, alias) = self.correlation_aggregate(rule, value_field)?;
let group_exprs: Vec<String> = rule
.group_by
.iter()
.map(|g| self.field_expr(g))
.collect::<Result<_>>()?;
let partition = if group_exprs.is_empty() {
String::new()
} else {
format!("PARTITION BY {} ", group_exprs.join(", "))
};
let group_by_select = if group_exprs.is_empty() {
String::new()
} else {
format!("{}, ", group_exprs.join(", "))
};
let mut final_group = group_exprs;
final_group.push("session_id".to_string());
let final_group_clause = final_group.join(", ");
let having = self
.build_having_clause(&rule.condition)?
.replace("{agg}", &agg);
warnings.push(format!(
"PostgreSQL session window: the {gap_secs}s gap is exact, but the {window_secs}s \
'timespan' cap is enforced as a post-aggregation filter (sessions exceeding it are \
dropped, not split)"
));
let cap_clause =
format!(" AND (MAX({ts}) - MIN({ts})) <= INTERVAL '{window_secs} seconds'");
// Chain onto an existing combined_events CTE when present, otherwise
// open the WITH chain with a plain source CTE.
let (head, src) = if cte_prefix.is_empty() {
(
format!("WITH source AS (SELECT * FROM {source_table}), "),
"source".to_string(),
)
} else {
(
format!("{}, ", cte_prefix.trim_end()),
source_table.to_string(),
)
};
Ok(format!(
"{head}\
marked AS (\
SELECT *, \
CASE WHEN LAG({ts}) OVER ({partition}ORDER BY {ts}) IS NULL \
OR {ts} - LAG({ts}) OVER ({partition}ORDER BY {ts}) > INTERVAL '{gap_secs} seconds' \
THEN 1 ELSE 0 END AS is_new_session \
FROM {src}\
), \
sessions AS (\
SELECT *, SUM(is_new_session) OVER (\
{partition}ORDER BY {ts} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\
) AS session_id \
FROM marked\
) \
SELECT {group_by_select}session_id, {agg} AS {alias}, \
MIN({ts}) AS first_seen, MAX({ts}) AS last_seen \
FROM sessions \
GROUP BY {final_group_clause} \
HAVING {having}{cap_clause}"
))
}
/// Build HAVING clause from correlation condition predicates.
/// Uses `{agg}` as placeholder for the aggregate expression.
pub(super) fn build_having_clause(&self, cond: &CorrelationCondition) -> Result<String> {
match cond {
CorrelationCondition::Threshold { predicates, .. } => {
let parts: Vec<String> = predicates
.iter()
.map(|(op, val)| {
let op_str = match op {
ConditionOperator::Lt => "<",
ConditionOperator::Lte => "<=",
ConditionOperator::Gt => ">",
ConditionOperator::Gte => ">=",
ConditionOperator::Eq => "=",
ConditionOperator::Neq => "<>",
};
format!("{{agg}} {op_str} {val}")
})
.collect();
Ok(parts.join(" AND "))
}
CorrelationCondition::Extended(_) => Err(ConvertError::UnsupportedCorrelation(
"extended boolean conditions not yet supported for PostgreSQL".into(),
)),
}
}
/// Build a temporal or temporal_ordered correlation query.
///
/// When all referenced rules target the same table, produces a single-table
/// CTE filtering on `rule_name IN (...)`. When rules target different tables
/// (from `_rule_tables` pipeline state), produces a `UNION ALL` CTE with one
/// leg per rule.
///
/// **Schema compatibility requirement:** The multi-table path uses
/// `SELECT * ... UNION ALL SELECT * ...`. PostgreSQL requires all legs of a
/// `UNION ALL` to produce the same number of columns with compatible types.
/// This works when all referenced tables share an identical schema (e.g. a
/// normalized event schema). If the tables have different column layouts the
/// query will fail at execution time. Callers should ensure that pipeline
/// field-mappings normalize the schemas, or use a single-table approach with
/// a discriminator column instead.
/// Build the inner SELECT for the temporal `matched` CTE (the SQL between
/// `matched AS (` and `)`), tagging each row with a `rule_name`.
///
/// Single-table references filter a `rule_name` column with `IN (...)`;
/// multi-table references (from `_rule_tables`) become a `UNION ALL` with a
/// literal `rule_name` discriminator per leg. `include_time_filter` adds the
/// relative `NOW() - INTERVAL` window used by the default (sliding) temporal
/// query; tumbling and session windows omit it because they derive their
/// own bounds from the data.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_temporal_matched_inner(
&self,
rule: &CorrelationRule,
default_table: &str,
ts: &str,
window_secs: u64,
rule_tables: &HashMap<String, String>,
pipeline_state: &PipelineState,
include_time_filter: bool,
) -> Result<String> {
let rule_schemas: HashMap<String, String> = pipeline_state
.state
.get("_rule_schemas")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
// Collect per-rule tables, qualifying each with its own schema
let mut table_to_rules: BTreeMap<String, Vec<String>> = BTreeMap::new();
for rule_ref in &rule.rules {
let raw_table = rule_tables.get(rule_ref).map(|s| s.as_str());
let per_rule_schema = rule_schemas.get(rule_ref).map(|s| s.as_str());
let qualified = match raw_table {
Some(t) => self.qualify_table_name(t, &pipeline_state.state, per_rule_schema)?,
None => default_table.to_string(),
};
table_to_rules
.entry(qualified)
.or_default()
.push(rule_ref.clone());
}
if table_to_rules.len() <= 1 {
let rule_names = rule.rules.join("', '");
let time_filter = if include_time_filter {
format!(" AND {ts} >= NOW() - INTERVAL '{window_secs} seconds'")
} else {
String::new()
};
Ok(format!(
"SELECT *, rule_name FROM {default_table} \
WHERE rule_name IN ('{rule_names}'){time_filter}"
))
} else {
let time_filter = if include_time_filter {
format!(" WHERE {ts} >= NOW() - INTERVAL '{window_secs} seconds'")
} else {
String::new()
};
let tf = time_filter.as_str();
let union_parts: Vec<String> = table_to_rules
.iter()
.flat_map(|(tbl, rules)| {
rules.iter().map(move |rule_ref| {
format!("SELECT *, '{rule_ref}' AS rule_name FROM {tbl}{tf}")
})
})
.collect();
Ok(union_parts.join(" UNION ALL "))
}
}
/// Build a temporal or temporal_ordered correlation query.
///
/// When all referenced rules target the same table, produces a single-table
/// CTE filtering on `rule_name IN (...)`. When rules target different tables
/// (from `_rule_tables` pipeline state), produces a `UNION ALL` CTE with one
/// leg per rule.
///
/// **Schema compatibility requirement:** The multi-table path uses
/// `SELECT * ... UNION ALL SELECT * ...`. PostgreSQL requires all legs of a
/// `UNION ALL` to produce the same number of columns with compatible types.
/// This works when all referenced tables share an identical schema (e.g. a
/// normalized event schema). If the tables have different column layouts the
/// query will fail at execution time. Callers should ensure that pipeline
/// field-mappings normalize the schemas, or use a single-table approach with
/// a discriminator column instead.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_temporal_query(
&self,
rule: &CorrelationRule,
default_table: &str,
ts: &str,
window_secs: u64,
group_by_select: &str,
group_by_clause: &str,
having_clause: &str,
rule_tables: &HashMap<String, String>,
pipeline_state: &PipelineState,
) -> Result<String> {
let agg = "COUNT(DISTINCT rule_name)";
let having = having_clause.replace("{agg}", agg);
let inner = self.build_temporal_matched_inner(
rule,
default_table,
ts,
window_secs,
rule_tables,
pipeline_state,
true,
)?;
Ok(format!(
"WITH matched AS (\
{inner}\
) \
SELECT {group_by_select}\
{agg} AS distinct_rules, \
MIN({ts}) AS first_seen, MAX({ts}) AS last_seen \
FROM matched\
{group_by_clause} \
HAVING {having}"
))
}
/// Build a tumbling-window temporal correlation query: events from the
/// referenced rules are grouped into fixed, boundary-aligned buckets of size
/// `window_secs`, and each bucket counts the distinct referenced rules that
/// fired.
///
/// Like the default temporal path, this counts distinct `rule_name`s and
/// does not enforce the firing order, so `temporal` and `temporal_ordered`
/// render identically (see the backend's ordering limitation).
#[allow(clippy::too_many_arguments)]
pub(super) fn build_temporal_tumbling(
&self,
rule: &CorrelationRule,
default_table: &str,
ts: &str,
window_secs: u64,
use_time_bucket: bool,
having_clause: &str,
rule_tables: &HashMap<String, String>,
pipeline_state: &PipelineState,
) -> Result<String> {
let agg = "COUNT(DISTINCT rule_name)";
let having = having_clause.replace("{agg}", agg);
let inner = self.build_temporal_matched_inner(
rule,
default_table,
ts,
window_secs,
rule_tables,
pipeline_state,
false,
)?;
let bucket_expr = if use_time_bucket {
format!("time_bucket('{window_secs} seconds', {ts})")
} else {
format!("date_bin('{window_secs} seconds', {ts}, TIMESTAMPTZ 'epoch')")
};
let group_exprs: Vec<String> = rule
.group_by
.iter()
.map(|g| self.field_expr(g))
.collect::<Result<_>>()?;
let group_by_select = if group_exprs.is_empty() {
String::new()
} else {
format!("{}, ", group_exprs.join(", "))
};
let mut gb = vec![bucket_expr.clone()];
gb.extend(group_exprs);
let group_by_clause = format!(" GROUP BY {}", gb.join(", "));
Ok(format!(
"WITH matched AS (\
{inner}\
) \
SELECT {bucket_expr} AS correlation_bucket, {group_by_select}\
{agg} AS distinct_rules, \
MIN({ts}) AS first_seen, MAX({ts}) AS last_seen \
FROM matched\
{group_by_clause} \
HAVING {having}"
))
}
/// Build a session-window temporal correlation query: the referenced rules'
/// events are sessionized per group with the gaps-and-islands pattern, and
/// each session counts the distinct referenced rules that fired.
///
/// The `gap` is honored exactly; the `timespan` cap is a post-aggregation
/// filter (recorded in `warnings`). Order is not enforced, matching the
/// backend's other temporal paths.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_temporal_session(
&self,
rule: &CorrelationRule,
default_table: &str,
ts: &str,
window_secs: u64,
gap_secs: u64,
having_clause: &str,
rule_tables: &HashMap<String, String>,
pipeline_state: &PipelineState,
warnings: &mut Vec<String>,
) -> Result<String> {
let agg = "COUNT(DISTINCT rule_name)";
let having = having_clause.replace("{agg}", agg);
let inner = self.build_temporal_matched_inner(
rule,
default_table,
ts,
window_secs,
rule_tables,
pipeline_state,
false,
)?;
let group_exprs: Vec<String> = rule
.group_by
.iter()
.map(|g| self.field_expr(g))
.collect::<Result<_>>()?;
let partition = if group_exprs.is_empty() {
String::new()
} else {
format!("PARTITION BY {} ", group_exprs.join(", "))
};
let group_by_select = if group_exprs.is_empty() {
String::new()
} else {
format!("{}, ", group_exprs.join(", "))
};
let mut final_group = group_exprs;
final_group.push("session_id".to_string());
let final_group_clause = final_group.join(", ");
warnings.push(format!(
"PostgreSQL session window: the {gap_secs}s gap is exact, but the {window_secs}s \
'timespan' cap is enforced as a post-aggregation filter (sessions exceeding it are \
dropped, not split)"
));
let cap_clause =
format!(" AND (MAX({ts}) - MIN({ts})) <= INTERVAL '{window_secs} seconds'");
Ok(format!(
"WITH matched AS (\
{inner}\
), \
marked AS (\
SELECT *, \
CASE WHEN LAG({ts}) OVER ({partition}ORDER BY {ts}) IS NULL \
OR {ts} - LAG({ts}) OVER ({partition}ORDER BY {ts}) > INTERVAL '{gap_secs} seconds' \
THEN 1 ELSE 0 END AS is_new_session \
FROM matched\
), \
sessions AS (\
SELECT *, SUM(is_new_session) OVER (\
{partition}ORDER BY {ts} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\
) AS session_id \
FROM marked\
) \
SELECT {group_by_select}session_id, {agg} AS distinct_rules, \
MIN({ts}) AS first_seen, MAX({ts}) AS last_seen \
FROM sessions \
GROUP BY {final_group_clause} \
HAVING {having}{cap_clause}"
))
}
}