coralogix-cli 0.1.38

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::error::{CxError, Result};
use crate::Tier;

use crate::api_client::CxClient;

// ── Log types ─────────────────────────────────────────────────────────────────

/// A parsed log record ready for display or JSON serialisation.
#[derive(Debug, Serialize, Deserialize)]
pub struct LogRecord {
    pub timestamp: Option<String>,
    pub severity: Option<String>,
    pub text: Option<Value>,
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

// ── Span / trace types ────────────────────────────────────────────────────────

#[derive(Debug, Serialize, Deserialize)]
pub struct Span {
    pub trace_id: String,
    pub span_id: String,
    pub operation_name: String,
    pub duration: u64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Trace {
    pub trace_id: String,
    pub spans: Vec<Span>,
}

/// Generic query response used by `cx dataprime query` and the shared
/// execute/merge/render pipeline.  Source-agnostic - no log- or span-specific
/// fields.
#[derive(Default)]
pub struct QueryGenericResponse {
    pub raw_results: Vec<Value>,
    pub warnings: Vec<Value>,
    pub query_id: Option<String>,
    pub statistics: Option<Value>,
    pub is_aggregate: bool,
}

// ── API ───────────────────────────────────────────────────────────────────────

pub struct DataprimeApi<'a> {
    client: &'a CxClient,
    strict_fields_validation: bool,
    warning_profile: Option<&'a str>,
}

impl<'a> DataprimeApi<'a> {
    pub fn new(client: &'a CxClient) -> Self {
        Self {
            client,
            strict_fields_validation: false,
            warning_profile: None,
        }
    }

    pub fn with_strict_fields_validation(mut self, enabled: bool) -> Self {
        self.strict_fields_validation = enabled;
        self
    }

    pub fn with_warning_profile(mut self, profile: &'a str) -> Self {
        self.warning_profile = Some(profile);
        self
    }

    /// POST to `/api/v1/dataprime/query` and return the raw result rows from
    /// the NDJSON response.
    ///
    /// `source` becomes the `defaultSource` metadata field, which Dataprime
    /// uses when the query does not include an explicit `source` command.
    /// Common values: `"logs"`, `"spans"`.
    async fn post_query(
        &self,
        query: &str,
        start_time: &str,
        end_time: &str,
        limit: u32,
        tier: Tier,
        source: &str,
    ) -> Result<ParsedQueryResponse> {
        let mut body = build_dataprime_body(query, start_time, end_time, limit, tier, source);
        body["metadata"]["strictFieldsValidation"] = self.strict_fields_validation.into();
        let raw = self
            .client
            .post_raw("/api/v1/dataprime/query", &body)
            .await
            .map_err(|error| self.with_field_validation_hint(error))?;
        parse_ndjson_with_warnings(&raw, |warning| {
            let mut envelope = json!({"warning": warning});
            if let Some(profile) = self.warning_profile {
                envelope["profile"] = profile.into();
            }
            eprintln!("{envelope}");
        })
        .map_err(|error| self.with_field_validation_hint(error))
    }

    // Strict validation is opt-in (the flag, or strict_fields_validation in
    // ~/.cx/config.toml), matching the API default.
    // It can reject real fields: new fields not yet in the schema, fields the schema dropped for
    // cardinality protection, and every field when the time range has no data.
    // The hint names both the flag (one run) and the config key (the default).
    fn with_field_validation_hint(&self, mut error: CxError) -> CxError {
        if self.strict_fields_validation {
            let message = match &mut error {
                CxError::Api {
                    status: 400,
                    message,
                }
                | CxError::QueryStream(message) => Some(message),
                _ => None,
            };
            if let Some(message) = message {
                // The public query API does not expose warning codes. Matching on strings for now (it is fragile).
                // API V2 is expected to add error/warning codes
                if message.starts_with("Compilation errors:")
                    && message.lines().any(|line| {
                        line.trim_start()
                            .starts_with("- keypath does not exist at [")
                    })
                {
                    message.push_str(
                        "\nHint: add --no-strict-fields-validation, or set strict_fields_validation = false in ~/.cx/config.toml.",
                    );
                }
            }
        }
        error
    }

    /// Execute a generic Dataprime query as-is, with no default source.
    ///
    /// The query must include its own `source` command (e.g. `source logs | ...`).
    /// Used by `cx dataprime query` and as the shared foundation for logs/spans.
    pub async fn query_generic(
        &self,
        query: &str,
        start_time: &str,
        end_time: &str,
        limit: u32,
        tier: Tier,
        source: &str,
    ) -> Result<QueryGenericResponse> {
        let parsed = self
            .post_query(query, start_time, end_time, limit, tier, source)
            .await?;
        let rows = parsed.rows;
        let aggregate = is_aggregation_query(query);
        let raw_results = if aggregate {
            rows.iter().map(normalize_aggregate_row).collect()
        } else {
            rows.iter().map(normalize_row).collect()
        };
        Ok(QueryGenericResponse {
            raw_results,
            warnings: parsed.warnings,
            query_id: parsed.query_id,
            statistics: parsed.statistics,
            is_aggregate: aggregate,
        })
    }
}

// ── Request building ──────────────────────────────────────────────────────────

/// Build the JSON request body for a Dataprime query.
pub fn build_dataprime_body(
    query: &str,
    start_time: &str,
    end_time: &str,
    limit: u32,
    tier: Tier,
    source: &str,
) -> Value {
    let mut body = json!({
        "query": query,
        "metadata": {
            "tier": tier.as_api_str(),
            "syntax": "QUERY_SYNTAX_DATAPRIME",
            "startDate": start_time,
            "endDate": end_time,
            "limit": limit
        }
    });
    if !source.is_empty() {
        body["metadata"]["defaultSource"] = source.into();
    }
    body
}

// ── NDJSON parsing ────────────────────────────────────────────────────────────

/// Query rows and complete API diagnostics from an NDJSON response.
///
/// The Dataprime endpoint returns NDJSON:
/// - line 1: `{"queryId": {...}}`
/// - line 2+: `{"result": {"results": [...]}}` (one or more batches)
/// - optional: `{"warning": {"compileWarning": {"warningMessage": "..."}}}` lines
#[derive(Debug, Default)]
pub struct ParsedQueryResponse {
    pub rows: Vec<Value>,
    pub warnings: Vec<Value>,
    pub query_id: Option<String>,
    pub statistics: Option<Value>,
}

pub fn parse_ndjson_response(raw: &str) -> Result<ParsedQueryResponse> {
    parse_ndjson_with_warnings(raw, |_| {})
}

fn parse_ndjson_with_warnings(
    raw: &str,
    mut on_warning: impl FnMut(&Value),
) -> Result<ParsedQueryResponse> {
    let mut parsed = ParsedQueryResponse::default();
    for line in raw.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let value: Value = serde_json::from_str(line)?;
        if let Some(id) = value.pointer("/queryId/queryId").and_then(Value::as_str) {
            parsed.query_id = Some(id.to_string());
        } else if let Some(batch) = value
            .get("result")
            .and_then(|r| r.get("results"))
            .and_then(|r| r.as_array())
        {
            parsed.rows.extend(batch.iter().cloned());
        } else if let Some(warning) = value.get("warning") {
            on_warning(warning);
            parsed.warnings.push(warning.clone());
        } else if let Some(stats) = value.get("statistics") {
            // Every query - success or failure - ends with a statistics
            // envelope. `status` is the authoritative outcome: a query that
            // died mid-execution (e.g. an engine OOM) reports a non-COMPLETED
            // status here rather than an HTTP-level error, since the 200
            // response has already been sent by the time it happens.
            let status = stats.get("status").and_then(|s| s.as_str()).unwrap_or("");
            if status != "COMPLETED" {
                return Err(crate::error::CxError::QueryStream(format!(
                    "query did not complete successfully (status: {status}): {line}"
                )));
            }
            parsed.statistics = Some(stats.clone());
        } else if value.get("error").is_some() || value.get("errors").is_some() {
            // Explicit mid-stream error envelope: the engine can report a
            // failure in the response body after the 200 has been sent, rather
            // than via the terminal `statistics` status. Surface it instead of
            // reporting whatever rows arrived first as a complete success.
            let detail =
                crate::api_client::extract_error_detail(line).unwrap_or_else(|| line.to_string());
            return Err(crate::error::CxError::QueryStream(detail));
        }
        // Any other line is an unrecognized, non-error envelope (e.g. a future
        // progress/heartbeat line). Skip it rather than failing an
        // otherwise-successful query - the authoritative outcome is the
        // terminal `statistics` status handled above, and a real failure also
        // arrives as a non-COMPLETED status or an explicit error envelope.
    }
    Ok(parsed)
}

// ── Aggregate-query detection ─────────────────────────────────────────────────

/// Return `true` when the query contains an aggregating command.
///
/// The aggregating commands are `aggregate`, `groupby`, `multigroupby`,
/// `count`, `countby`, and `distinct`.  A command is recognised when it is
/// the first token of the query string or the first token of a pipe-separated
/// segment (i.e. it appears immediately after a `|`).  The check is
/// case-insensitive.
pub fn is_aggregation_query(query: &str) -> bool {
    const AGG_COMMANDS: &[&str] = &[
        "aggregate",
        "groupby",
        "multigroupby",
        "count",
        "countby",
        "distinct",
    ];

    for segment in query.split('|') {
        let first = segment.split_whitespace().next().unwrap_or("");
        if AGG_COMMANDS.contains(&first.to_lowercase().as_str()) {
            return true;
        }
    }
    false
}

// ── Row normalization ─────────────────────────────────────────────────────────

/// Normalize a raw Dataprime result row for output:
///
/// - `metadata` `[{key, value}]` → `{key: value}` object
/// - `labels`   `[{key, value}]` → `{key: value}` object
/// - `userData` JSON-encoded string → parsed JSON value (falls back to the
///   original string if it cannot be parsed)
pub fn normalize_row(record: &Value) -> Value {
    let mut out = match record {
        Value::Object(m) => m.clone(),
        _ => return record.clone(),
    };

    for field in ["metadata", "labels"] {
        if let Some(arr) = out.get(field).and_then(|v| v.as_array()) {
            let map: serde_json::Map<String, Value> = arr
                .iter()
                .filter_map(|item| {
                    let k = item.get("key")?.as_str()?.to_string();
                    let v = item.get("value")?.clone();
                    Some((k, v))
                })
                .collect();
            out.insert(field.to_string(), Value::Object(map));
        }
    }

    if let Some(raw) = out.get("userData").and_then(|v| v.as_str()) {
        if let Ok(parsed) = serde_json::from_str::<Value>(raw) {
            out.insert("userData".to_string(), parsed);
        }
    }

    Value::Object(out)
}

/// Normalize a raw Dataprime result row from an aggregation query.
///
/// Aggregate rows always have empty `metadata` and `labels`.  The only
/// interesting content is in `userData`, which is a JSON-encoded string
/// containing the aggregated fields (e.g. `{"region":"us1","total_logs":16}`).
/// This function extracts and parses that string and returns the inner object
/// directly, discarding the empty envelope fields.
///
/// If `userData` cannot be parsed as JSON the original string value is
/// returned as-is.
pub fn normalize_aggregate_row(record: &Value) -> Value {
    let raw = record
        .get("userData")
        .and_then(|v| v.as_str())
        .unwrap_or("{}");
    serde_json::from_str::<Value>(raw).unwrap_or_else(|_| Value::String(raw.to_string()))
}

// ── Log record parsing ────────────────────────────────────────────────────────

/// Convert a single normalized result row into a `LogRecord`.
///
/// Expects rows that have already been passed through `normalize_row`:
/// `metadata` and `labels` are objects, and `userData` is a parsed JSON value.
pub fn parse_log_record(record: &Value) -> LogRecord {
    let user_data: Value = record.get("userData").cloned().unwrap_or(Value::Null);

    let timestamp = extract_field(
        &user_data,
        &[
            "$m.timestamp",
            "coralogix.timestamp",
            "timestamp",
            "@timestamp",
        ],
    );

    // Severity is always in the required metadata.severity field.
    let severity = extract_severity(record.get("metadata").unwrap_or(&Value::Null));

    let extra: HashMap<String, Value> = match &user_data {
        Value::Object(map) => map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
        _ => HashMap::new(),
    };

    LogRecord {
        timestamp,
        severity,
        text: if user_data.is_null() {
            None
        } else {
            Some(user_data)
        },
        extra,
    }
}

/// Extract and normalize severity from a normalized metadata object.
///
/// Expects the `metadata` value after `normalize_row` has been applied,
/// i.e. an object with a `"severity"` key.
/// Maps Coralogix numeric codes to human-readable strings.
pub fn extract_severity(metadata: &Value) -> Option<String> {
    let raw = metadata.get("severity").and_then(|v| v.as_str())?;
    // Coralogix numeric severity: 1=DEBUG 2=VERBOSE 3=INFO 4=WARNING 5=ERROR 6=CRITICAL
    Some(match raw {
        "1" => "DEBUG".to_string(),
        "2" => "VERBOSE".to_string(),
        "3" => "INFO".to_string(),
        "4" => "WARNING".to_string(),
        "5" => "ERROR".to_string(),
        "6" => "CRITICAL".to_string(),
        other => other.to_uppercase(),
    })
}

// ── Span record parsing ───────────────────────────────────────────────────────

/// Parse a single normalized Dataprime result row into a `Span`.
///
/// Expects rows that have already been passed through `normalize_row`, so
/// `userData` is a parsed JSON value rather than a JSON-encoded string.
/// Falls back to the raw record itself so the function also handles
/// pre-parsed/flat JSON objects in tests.
pub fn parse_span_record(record: &Value) -> Option<Span> {
    let user_data: Value = record
        .get("userData")
        .cloned()
        .unwrap_or_else(|| record.clone());

    let trace_id = extract_field(&user_data, &["traceID", "trace_id", "$d.traceID"])?;
    let span_id = extract_field(&user_data, &["spanID", "spanId", "span_id", "$d.spanId"])?;
    let operation_name = extract_field(
        &user_data,
        &["operationName", "operation_name", "$l.operationName"],
    )
    .unwrap_or_default();
    let duration = extract_field(&user_data, &["duration", "$m.duration"])
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(0);

    Some(Span {
        trace_id,
        span_id,
        operation_name,
        duration,
    })
}

/// Group a flat list of span rows into traces, preserving the insertion order
/// of each trace's first occurrence.
pub fn group_spans_into_traces(rows: Vec<Value>) -> Vec<Trace> {
    let mut map: HashMap<String, Vec<Span>> = HashMap::new();
    let mut order: Vec<String> = Vec::new();

    for row in &rows {
        if let Some(span) = parse_span_record(row) {
            let tid = span.trace_id.clone();
            if !map.contains_key(&tid) {
                order.push(tid.clone());
            }
            map.entry(tid).or_default().push(span);
        }
    }

    order
        .into_iter()
        .map(|tid| {
            let spans = map.remove(&tid).unwrap_or_default();
            Trace {
                trace_id: tid,
                spans,
            }
        })
        .collect()
}

// ── Shared field extraction ───────────────────────────────────────────────────

/// Walk a dot-separated path (e.g. `"$m.timestamp"`) through a JSON value and
/// return the first one that yields a non-null result.
pub fn extract_field(v: &Value, paths: &[&str]) -> Option<String> {
    for path in paths {
        let mut current = v;
        let mut ok = true;
        for segment in path.split('.') {
            match current.get(segment) {
                Some(next) => current = next,
                None => {
                    ok = false;
                    break;
                }
            }
        }
        if ok && !current.is_null() {
            return Some(match current {
                Value::String(s) => s.clone(),
                other => other.to_string(),
            });
        }
    }
    None
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn kv_array(pairs: &[(&str, &str)]) -> Value {
        Value::Array(
            pairs
                .iter()
                .map(|(k, v)| json!({"key": k, "value": v}))
                .collect(),
        )
    }

    #[test]
    fn preserves_all_warning_payloads_query_id_and_statistics() {
        let warnings = vec![
            json!({"compileWarning": {"warningMessage": "unknown field"}}),
            json!({"timeRangeWarning": {"warningMessage": "adjusted", "startDate": "2026-01-01T00:00:00Z"}}),
            json!({"numberOfResultsLimitWarning": {"numberOfResultsLimit": 100}}),
            json!({"bytesScannedLimitWarning": {}}),
            json!({"deprecationWarning": {"warningMessage": "deprecated"}}),
            json!({"blocksLimitWarning": {}}),
            json!({"aggregationBucketsLimitWarning": {"aggregationBucketsLimit": 1000}}),
            json!({"archiveWarning": {"missingData": {}}}),
            json!({"scrollTimeoutWarning": {}}),
            json!({"fieldCountLimitWarning": {}}),
            json!({"shuffleFileSizeLimitReachedWarning": {}}),
            json!({"filesReadLimitWarning": {}}),
            json!({"sidebarFilterCardinalityLimitWarning": {"fields": ["$d.name"], "cardinalityLimit": "100"}}),
            json!({"futureWarning": {"nested": {"details": [1, 2]}}}),
        ];
        let statistics = json!({"status": "COMPLETED", "outputRowCount": "0", "storage": {"objectStore": {"bytesRead": "123"}}});
        let mut lines = vec![json!({"queryId": {"queryId": "query-123"}}).to_string()];
        lines.extend(warnings.iter().map(|w| json!({"warning": w}).to_string()));
        lines.push(json!({"statistics": statistics}).to_string());
        let parsed = parse_ndjson_response(&lines.join("\n")).unwrap();
        assert_eq!(parsed.query_id.as_deref(), Some("query-123"));
        assert_eq!(parsed.warnings, warnings);
        assert_eq!(parsed.statistics, Some(statistics));
    }

    #[test]
    fn emits_warnings_before_a_later_query_failure() {
        for failure in [
            json!({"error": {"message": "failed"}}),
            json!({"statistics": {"status": "FAILED"}}),
        ] {
            let warning = json!({"archiveWarning": {"bucketAccessDenied": {}}});
            let raw = format!("{}\n{}", json!({"warning": warning}), failure);
            let mut emitted = Vec::new();
            assert!(parse_ndjson_with_warnings(&raw, |w| emitted.push(w.clone())).is_err());
            assert_eq!(emitted, vec![warning]);
        }
    }

    // ── parse_ndjson_response ─────────────────────────────────────────────────

    #[test]
    fn ndjson_query_id_does_not_become_a_result_row() {
        let raw = r#"{"queryId":{"queryId":"test-query-id"}}
{"result":{"results":[{"metadata":[],"labels":[],"userData":"{}"}]}}"#;
        let ParsedQueryResponse { rows, warnings, .. } = parse_ndjson_response(raw).unwrap();
        assert_eq!(rows.len(), 1);
        assert!(warnings.is_empty());
    }

    #[test]
    fn ndjson_completed_statistics_line_is_benign() {
        let raw = r#"{"queryId":{"queryId":"test-query-id"}}
{"result":{"results":[{"metadata":[],"labels":[],"userData":"{}"}]}}
{"statistics":{"status":"COMPLETED","outputRowCount":"1"}}"#;
        let ParsedQueryResponse { rows, warnings, .. } = parse_ndjson_response(raw).unwrap();
        assert_eq!(rows.len(), 1);
        assert!(warnings.is_empty());
    }

    #[test]
    fn ndjson_completed_statistics_line_on_zero_rows_is_not_an_error() {
        // A query that legitimately matches nothing still ends with a
        // COMPLETED statistics line and no `result` line at all.
        let raw = r#"{"queryId":{"queryId":"test-query-id"}}
{"statistics":{"status":"COMPLETED","outputRowCount":"0"}}"#;
        let ParsedQueryResponse { rows, warnings, .. } = parse_ndjson_response(raw).unwrap();
        assert!(rows.is_empty());
        assert!(warnings.is_empty());
    }

    #[test]
    fn ndjson_non_completed_statistics_status_returns_query_stream_err() {
        let raw = r#"{"queryId":{"queryId":"test-query-id"}}
{"statistics":{"status":"FAILED","outputRowCount":"0"}}"#;
        let err = parse_ndjson_response(raw).unwrap_err();
        match err {
            crate::error::CxError::QueryStream(msg) => {
                assert!(msg.contains("FAILED"), "got: {msg}");
            }
            other => panic!("expected QueryStream error, got: {other:?}"),
        }
    }

    #[test]
    fn ndjson_error_envelope_with_message_returns_query_stream_err() {
        let raw = r#"{"queryId":{"queryId":"test-query-id"}}
{"error":{"message":"engine out of memory"}}"#;
        let err = parse_ndjson_response(raw).unwrap_err();
        match err {
            crate::error::CxError::QueryStream(msg) => {
                assert!(msg.contains("engine out of memory"), "got: {msg}");
            }
            other => panic!("expected QueryStream error, got: {other:?}"),
        }
    }

    #[test]
    fn ndjson_unknown_benign_envelope_is_skipped() {
        // An unrecognized, non-error envelope (e.g. a future progress/heartbeat
        // line) must not fail an otherwise-successful query: the authoritative
        // outcome is the terminal COMPLETED statistics status.
        let raw = r#"{"queryId":{"queryId":"test-query-id"}}
{"progress":{"percent":50}}
{"result":{"results":[{"metadata":[],"labels":[],"userData":"{}"}]}}
{"statistics":{"status":"COMPLETED","outputRowCount":"1"}}"#;
        let ParsedQueryResponse { rows, warnings, .. } = parse_ndjson_response(raw).unwrap();
        assert_eq!(rows.len(), 1);
        assert!(warnings.is_empty());
    }

    #[test]
    fn normalize_metadata_list_to_object() {
        let row = json!({
            "metadata": kv_array(&[("severity", "Error"), ("logid", "abc123")]),
            "labels": [],
            "userData": "{}"
        });
        let out = normalize_row(&row);
        assert_eq!(out["metadata"]["severity"], json!("Error"));
        assert_eq!(out["metadata"]["logid"], json!("abc123"));
    }

    #[test]
    fn normalize_labels_list_to_object() {
        let row = json!({
            "metadata": [],
            "labels": kv_array(&[("applicationname", "api"), ("subsystemname", "us1")]),
            "userData": "{}"
        });
        let out = normalize_row(&row);
        assert_eq!(out["labels"]["applicationname"], json!("api"));
        assert_eq!(out["labels"]["subsystemname"], json!("us1"));
    }

    #[test]
    fn normalize_user_data_string_to_json() {
        let row = json!({
            "metadata": [],
            "labels": [],
            "userData": r#"{"message":"hello","level":"INFO"}"#
        });
        let out = normalize_row(&row);
        assert_eq!(out["userData"]["message"], json!("hello"));
        assert_eq!(out["userData"]["level"], json!("INFO"));
    }

    #[test]
    fn normalize_user_data_non_json_stays_as_string() {
        let raw_str = "plain text log line";
        let row = json!({
            "metadata": [],
            "labels": [],
            "userData": raw_str
        });
        let out = normalize_row(&row);
        assert_eq!(out["userData"], json!(raw_str));
    }

    #[test]
    fn normalize_full_record_matches_expected_cli_output() {
        let row = json!({
            "metadata": kv_array(&[
                ("severity", "Error"),
                ("timestamp", "2026-03-21T09:05:47.879644")
            ]),
            "labels": kv_array(&[
                ("applicationname", "api"),
                ("subsystemname", "us3")
            ]),
            "userData": r#"{"message":"Health check timeout","levelname":"ERROR"}"#
        });
        let out = normalize_row(&row);
        assert!(out["metadata"].is_object());
        assert!(out["labels"].is_object());
        assert!(out["userData"].is_object());
        assert_eq!(out["metadata"]["severity"], json!("Error"));
        assert_eq!(out["labels"]["applicationname"], json!("api"));
        assert_eq!(out["userData"]["message"], json!("Health check timeout"));
    }

    // ── is_aggregation_query ──────────────────────────────────────────────────

    #[test]
    fn agg_query_groupby_after_pipe() {
        assert!(is_aggregation_query(
            "source logs | groupby $l.subsystemname as region aggregate count() as total_logs"
        ));
    }

    #[test]
    fn agg_query_aggregate_after_pipe() {
        assert!(is_aggregation_query("source logs | aggregate count()"));
    }

    #[test]
    fn agg_query_count_after_pipe() {
        assert!(is_aggregation_query("source logs | count"));
    }

    #[test]
    fn agg_query_countby_after_pipe() {
        assert!(is_aggregation_query("source logs | countby $l.app"));
    }

    #[test]
    fn agg_query_multigroupby_after_pipe() {
        assert!(is_aggregation_query(
            "source logs | multigroupby a, b aggregate count()"
        ));
    }

    #[test]
    fn agg_query_distinct_after_pipe() {
        assert!(is_aggregation_query("source logs | distinct $d.field"));
    }

    #[test]
    fn agg_query_keyword_at_start_without_source() {
        assert!(is_aggregation_query("groupby $l.app aggregate count()"));
    }

    #[test]
    fn agg_query_keyword_case_insensitive() {
        assert!(is_aggregation_query(
            "source logs | GroupBy $l.app aggregate count()"
        ));
    }

    #[test]
    fn non_agg_query_filter_is_not_aggregate() {
        assert!(!is_aggregation_query(
            r#"source logs | filter $d.message ~= "timeout""#
        ));
    }

    #[test]
    fn non_agg_query_source_only() {
        assert!(!is_aggregation_query("source logs"));
    }

    #[test]
    fn non_agg_query_word_containing_count_in_value_is_not_aggregate() {
        // "countby" must be at a command position (first token of a segment)
        assert!(!is_aggregation_query(
            r#"source logs | filter $d.label == "countby-region""#
        ));
    }

    // ── normalize_aggregate_row ───────────────────────────────────────────────

    #[test]
    fn aggregate_row_extracts_user_data() {
        let row = json!({
            "metadata": [],
            "labels": [],
            "userData": r#"{"region":"us1","total_logs":16}"#
        });
        let out = normalize_aggregate_row(&row);
        assert_eq!(out["region"], json!("us1"));
        assert_eq!(out["total_logs"], json!(16));
        assert!(out.get("metadata").is_none());
        assert!(out.get("labels").is_none());
    }

    #[test]
    fn aggregate_row_non_json_user_data_kept_as_string() {
        let row = json!({"metadata": [], "labels": [], "userData": "not json"});
        let out = normalize_aggregate_row(&row);
        assert_eq!(out, json!("not json"));
    }

    #[test]
    fn aggregate_rows_from_groupby_example() {
        // Mirror of the example provided in the task description
        let rows = [
            json!({"metadata": [], "labels": [], "userData": r#"{"region":"us1","total_logs":16}"#}),
            json!({"metadata": [], "labels": [], "userData": r#"{"region":"us2","total_logs":20}"#}),
            json!({"metadata": [], "labels": [], "userData": r#"{"region":"us3","total_logs":12}"#}),
        ];
        let results: Vec<_> = rows.iter().map(normalize_aggregate_row).collect();
        assert_eq!(results[0]["region"], json!("us1"));
        assert_eq!(results[1]["total_logs"], json!(20));
        assert_eq!(results[2]["region"], json!("us3"));
        // Envelope fields must not appear in the output
        for r in &results {
            assert!(r.get("metadata").is_none());
            assert!(r.get("labels").is_none());
            assert!(r.get("userData").is_none());
        }
    }
}