hamelin_lib 0.22.1

Core library for Hamelin query language
Documentation
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
//! Regression tests for bugs discovered during development
//!
//! Each test documents a specific bug that was found and fixed.

use crate::err::TranslationErrors;
use crate::tree::ast::pipeline::Pipeline;
use crate::tree::ast::query::Query;
use crate::tree::ast::ParseWithErrors;
use crate::tree::tests::shared::{catalog_with_tables, type_check_with_catalog};
use crate::types::array::Array;
use crate::types::decimal_type::Decimal;
use crate::types::map::Map;
use crate::types::struct_type::Struct;
use crate::types::{Type, DOUBLE, INT, STRING, TIMESTAMP};
use pretty_assertions::assert_eq;
use rstest::rstest;

/// Helper to create the minimal simba:sysmon_events schema needed for regression tests
fn sysmon_events_schema() -> Vec<(&'static str, Vec<(&'static str, Type)>)> {
    let sysmon_event_struct = Struct::default()
        .with_str("code", STRING)
        .with_str("original", STRING)
        .into();
    let winlog_struct = Struct::default()
        .with_str("event_data", Map::new(STRING, STRING).into())
        .into();
    let host_struct = Struct::default().with_str("name", STRING).into();

    vec![(
        "simba:sysmon_events",
        vec![
            ("timestamp", TIMESTAMP),
            ("event", sysmon_event_struct),
            ("winlog", winlog_struct),
            ("host", host_struct),
        ],
    )]
}

// ======================== Regression Test Cases ========================

/// Bug: DROP command lost fields added by SET commands that appeared before it.
///
/// Example:
/// ```hamelin
/// FROM table
/// | SET reg_key = ...
/// | DROP some_field
/// | WHERE regexp_like(reg_key, ...)  // Error: reg_key not found!
/// ```
///
/// Root cause: DROP created output schema with `base: None`, discarding the
/// environment chain that contained fields from previous SET commands.
///
/// Fix: Changed DROP to preserve the base chain: `base: input_schema.base.clone()`
///
/// ---
///
/// Bug: FROM command with aliased CTEs didn't flatten the CTE's environment chain,
/// causing fields to be lost.
///
/// Example:
/// ```hamelin
/// DEF cte = FROM table
/// | SET host = host.name
/// | DROP some_field;
///
/// FROM x = cte
/// | SELECT timestamp  // Error: timestamp not found!
/// ```
///
/// Root cause: FROM command used `env.fields` instead of flattening the entire
/// environment chain. When a CTE had a base chain (from SET commands), only the
/// top-level fields were exposed, not the fields from the base.
///
/// Fix: Added `flatten_environment_fields()` helper that recursively collects all
/// fields from the environment chain.
///
/// ---
///
/// Bug: JOIN/LOOKUP commands didn't flatten the right-side environment, losing fields
/// from the base chain when joining with CTEs that had SET fields.
///
/// Root cause: JOIN used `right_env.fields.clone()` instead of flattening the environment.
///
/// Fix: Changed JOIN to use `nest_into()` which flattens and nests in one operation.
///
/// ---
///
/// Bug: UNNEST command's flatten helper didn't use the new `Environment::flatten()` method.
///
/// Fix: Simplified `flatten_environment()` helper to use `Environment::flatten()`.
#[rstest]
// DROP preserves SET fields
#[case::drop_preserves_set_fields(
    sysmon_events_schema(),
    r#"
FROM simba:sysmon_events
| SET reg_key = coalesce(winlog.event_data["TargetObject"], '')
| DROP winlog.event_data
| WHERE regexp_like(lower(reg_key), '(?i).*test.*')
"#,
    Struct::default()
        .with_str("reg_key", STRING)
        .with_str("timestamp", TIMESTAMP)
        .with_str("event", Struct::default().with_str("code", STRING).with_str("original", STRING).into())
        .with_str("host", Struct::default().with_str("name", STRING).into())
)]
// FROM with CTEs flattens environment
#[case::from_cte_flattens_environment(
    sysmon_events_schema(),
    r#"
DEF registry_events = FROM simba:sysmon_events
| WHERE event.code == "13"
| SET reg_key = coalesce(winlog.event_data["TargetObject"], '')
| SET host = host.name
| DROP winlog.event_data, event.original;

FROM x = registry_events
| SELECT timestamp, host, reg_key
"#,
    Struct::default()
        .with_str("timestamp", TIMESTAMP)
        .with_str("host", STRING)
        .with_str("reg_key", STRING)
)]
#[case::from_aliased_ctes_preserves_all_fields(
    sysmon_events_schema(),
    r#"
DEF registry_events = FROM simba:sysmon_events
| WHERE event.code == "13"
| SET reg_key = coalesce(winlog.event_data["TargetObject"], '')
| SET host = host.name
| DROP winlog.event_data, event.original;

FROM x = registry_events, y = registry_events
| SELECT x.timestamp, y.timestamp, x.host, y.host
"#,
    Struct::default()
        .with_str("x", Struct::default().with_str("timestamp", Type::Timestamp).with_str("host", STRING).into())
        .with_str("y", Struct::default().with_str("timestamp", Type::Timestamp).with_str("host", STRING).into())
)]
#[case::window_finds_timestamp_after_cte_from(
    sysmon_events_schema(),
    r#"
DEF registry_events = FROM simba:sysmon_events
| WHERE event.code == "13"
| SET host = host.name
| DROP winlog.event_data;

DEF process_events = FROM simba:sysmon_events
| WHERE event.code == "1"
| SET host = host.name
| DROP winlog.event_data;

FROM registry_event = registry_events, process_event = process_events
| WINDOW process_event = last_value(process_event),
         registry_event = last_value(registry_event)
  BY host WITHIN 1s
"#,
    Struct::default()
        .with_str("process_event", Struct::default()
            .with_str("host", STRING)
            .with_str("timestamp", TIMESTAMP)
            .with_str("event", Struct::default()
                .with_str("code", STRING)
                .with_str("original", STRING)
                .into())
            .into())
        .with_str("registry_event", Struct::default()
            .with_str("host", STRING)
            .with_str("timestamp", TIMESTAMP)
            .with_str("event", Struct::default()
                .with_str("code", STRING)
                .with_str("original", STRING)
                .into())
            .into())
        .with_str("host", STRING)
        .with_str("timestamp", TIMESTAMP)
        .with_str("event", Struct::default().with_str("code", STRING).with_str("original", STRING).into())
)]
// JOIN preserves base chain
#[case::join_preserves_base_chain(
    sysmon_events_schema(),
    r#"
DEF enriched = FROM simba:sysmon_events
| WHERE event.code == "1"
| SET hostname = host.name
| SET process_name = winlog.event_data["Image"]
| DROP winlog.event_data;

FROM simba:sysmon_events
| WHERE event.code == "3"
| JOIN x = enriched ON host.name == x.hostname
| SELECT timestamp, x.process_name, x.hostname
"#,
    Struct::default()
        .with_str("timestamp", TIMESTAMP)
        .with_str("x", Struct::default().with_str("process_name", STRING).with_str("hostname", STRING).into())
)]
// UNNEST with SET fields
#[case::unnest_with_set_fields(
    sysmon_events_schema(),
    r#"
FROM simba:sysmon_events
| WHERE event.code == "1"
| SET hostname = host.name
| SET process_info = {pid: winlog.event_data["ProcessId"], name: winlog.event_data["Image"]}
| UNNEST process_info
| SELECT hostname, pid, name
"#,
    Struct::default()
        .with_str("hostname", STRING)
        .with_str("pid", STRING)
        .with_str("name", STRING)
)]
#[case::stddev_int_returns_double(
    vec![("metrics", vec![("host", STRING), ("value", INT)])],
    r#"
FROM metrics
| AGG stddev_value = stddev(value) BY host
"#,
    Struct::default()
        .with_str("host", STRING)
        .with_str("stddev_value", DOUBLE)
)]
#[case::stddev_double_returns_double(
    vec![("metrics", vec![("host", STRING), ("value", DOUBLE)])],
    r#"
FROM metrics
| AGG stddev_value = stddev(value) BY host
"#,
    Struct::default()
        .with_str("host", STRING)
        .with_str("stddev_value", DOUBLE)
)]
#[case::stddev_decimal_returns_double(
    vec![(
        "metrics",
        vec![
            ("host", STRING),
            ("value", Type::Decimal(Decimal::new(10, 2).unwrap()))
        ]
    )],
    r#"
FROM metrics
| AGG stddev_value = stddev(value) BY host
"#,
    Struct::default()
        .with_str("host", STRING)
        .with_str("stddev_value", DOUBLE)
)]
// JOIN with CTE, reference joined fields in SET, then DROP the joined struct
#[case::join_then_drop_joined_struct(
    vec![("events", vec![("timestamp", TIMESTAMP), ("count", INT)])],
    r#"
DEF baseline = FROM events
| AGG avg = avg(count), stddev = stddev(count);

FROM events
| AGG count = count() BY timestamp = timestamp@h
| JOIN baseline ON true
| SET threshold_upper = baseline.avg + baseline.stddev
| SET threshold_lower = baseline.avg - baseline.stddev
| DROP baseline
"#,
    Struct::default()
        .with_str("threshold_lower", DOUBLE)
        .with_str("threshold_upper", DOUBLE)
        .with_str("timestamp", TIMESTAMP)
        .with_str("count", INT)
)]
// Rebinding a top-level struct field to a scalar should completely shadow the struct
#[case::rebind_struct_to_scalar_shadows_children(
    vec![(
        "logs",
        vec![
            ("timestamp", TIMESTAMP),
            ("message", STRING),
            ("host", Type::Struct(
                Struct::default()
                    .with_str("name", STRING)
                    .with_str("ip", STRING)
                    .with_str("os", Type::Struct(
                        Struct::default()
                            .with_str("name", STRING)
                            .with_str("version", STRING)
                    ))
            ))
        ]
    )],
    r#"
FROM logs
| SET host = host.name
"#,
    Struct::default()
        .with_str("host", STRING)
        .with_str("timestamp", TIMESTAMP)
        .with_str("message", STRING)
)]
// Rebinding a nested struct field to a scalar should completely shadow the struct
#[case::rebind_nested_struct_to_scalar_shadows_children(
    vec![(
        "events",
        vec![
            ("timestamp", TIMESTAMP),
            ("event", Type::Struct(
                Struct::default()
                    .with_str("id", STRING)
                    .with_str("host", Type::Struct(
                        Struct::default()
                            .with_str("name", STRING)
                            .with_str("ip", STRING)
                            .with_str("os", Type::Struct(
                                Struct::default()
                                    .with_str("name", STRING)
                                    .with_str("version", STRING)
                            ))
                    ))
            ))
        ]
    )],
    r#"
FROM events
| SET event.host = event.host.name
"#,
    Struct::default()
        .with_str("event", Type::Struct(
            Struct::default()
                .with_str("id", STRING)
                .with_str("host", STRING)
        ))
        .with_str("timestamp", TIMESTAMP)
)]
// Test rebinding after AGG with array_agg - matches pattern from DET_33LF1U2.hmln
#[case::rebind_after_array_agg(
    vec![(
        "events",
        vec![
            ("id", INT),
            ("data", Type::Struct(
                Struct::default()
                    .with_str("host", Type::Struct(
                        Struct::default()
                            .with_str("name", STRING)
                            .with_str("ip", STRING)
                    ))
            ))
        ]
    )],
    r#"
FROM events
| AGG all_data = array_agg(data)
| SET first_data = all_data[0]
| SET first_data.host = first_data.host.name
"#,
    Struct::default()
        .with_str("first_data", Type::Struct(
            Struct::default()
                .with_str("host", STRING)
        ))
        .with_str("all_data", Array::new(Type::Struct(
            Struct::default()
                .with_str("host", Type::Struct(
                    Struct::default()
                        .with_str("name", STRING)
                        .with_str("ip", STRING)
                ))
        )).into())
)]
// Test rebinding a struct field created in previous SET to a value from within that struct
#[case::rebind_struct_field_from_same_level(
    vec![(
        "events",
        vec![
            ("id", INT),
            ("name", STRING),
            ("ip", STRING)
        ]
    )],
    r#"
FROM events
| SET event = {host: {name: name, ip: ip}}
| SET event.host = event.host.name
"#,
    Struct::default()
        .with_str("event", Type::Struct(
            Struct::default()
                .with_str("host", STRING)
        ))
        .with_str("id", INT)
        .with_str("name", STRING)
        .with_str("ip", STRING)
)]
fn test_regressions(
    #[case] tables: Vec<(&str, Vec<(&str, Type)>)>,
    #[case] query_str: &str,
    #[case] expected_schema: Struct,
) -> Result<(), TranslationErrors> {
    let query = Query::parse_result(query_str)?;
    let catalog = catalog_with_tables(tables);
    let typed = type_check_with_catalog(query, catalog).into_result()?;

    let actual_schema = typed.schema();

    assert_eq!(actual_schema, expected_schema);
    Ok(())
}

/// Verify that parse → Display → parse round-trips produce equivalent ASTs.
///
/// Any Hamelin syntax that fails to round-trip through Display can be added as a case here.
#[rstest]
#[case::from_aliased("FROM x = events")]
#[case::join_aliased("FROM users | JOIN o = orders ON o.user_id == user_id")]
#[case::join_qualified_aliased("FROM users | JOIN o = schema.orders ON o.id == id")]
#[case::lookup_aliased("FROM users | LOOKUP o = orders ON o.user_id == user_id")]
fn test_display_roundtrip(#[case] input: &str) {
    let original = Pipeline::parse_result(input).expect("input should parse");
    let displayed = original.to_string();
    let reparsed = Pipeline::parse_result(&displayed);

    assert!(
        reparsed.is_ok(),
        "Failed to re-parse displayed pipeline.\n  Input:     {input}\n  Displayed: {displayed}\n  Error: {}",
        reparsed.unwrap_err()
    );

    assert_eq!(
        reparsed.unwrap(),
        original,
        "Round-tripped AST differs from original.\n  Input:     {input}\n  Displayed: {displayed}"
    );
}