coralogix-cli 0.1.36

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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use std::collections::HashMap;
use std::sync::Arc;

use anyhow::{Context, Result};
use colored::Colorize;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tabled::builder::Builder;
use toon_format::encode_default as toon_encode;

pub mod api;
pub mod semantic_search;

use api::{DataprimeApi, QueryGenericResponse};

use crate::cases_query_rules::check_cases_query_rules;
use crate::config::OutputFormat;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::spill::{maybe_spill, transform_for_toon, write_result_file, SpillOutcome};
use crate::time::parse_timestamp;
use crate::Tier;

/// YAML bundle shipped in the binary (`assets/dataprime_docs.yaml`).
const EMBEDDED_DATAPRIME_DOCS_YAML: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/assets/dataprime_docs.yaml"
));

/// A single documentation entry for a command or function.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocEntry {
    pub description: String,
    pub syntax: String,
    pub category: Vec<String>,
}

/// The complete DataPrime documentation loaded from YAML.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataprimeDocs {
    pub commands: HashMap<String, DocEntry>,
    pub functions: HashMap<String, DocEntry>,
}

/// Filter type for listing commands/functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
pub enum DataprimeFilter {
    #[default]
    All,
    Commands,
    Functions,
}

/// Load the DataPrime documentation from the bundle embedded at build time (`assets/dataprime_docs.yaml`).
pub fn load_docs() -> Result<DataprimeDocs> {
    serde_yaml::from_str(EMBEDDED_DATAPRIME_DOCS_YAML)
        .context("Failed to parse embedded dataprime documentation")
}

/// Truncate a string to a maximum length, adding ellipsis if needed.
fn truncate(s: &str, max_len: usize) -> String {
    let s = s.lines().next().unwrap_or(s);
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len - 3])
    }
}

/// Extract the first sentence from a description.
fn first_sentence(s: &str) -> String {
    let s = s.trim();
    if let Some(pos) = s.find(". ") {
        s[..=pos].to_string()
    } else if let Some(pos) = s.find(".\n") {
        s[..=pos].to_string()
    } else {
        s.lines().next().unwrap_or(s).to_string()
    }
}

/// List available DataPrime commands and/or functions.
pub fn run_list(
    filter: DataprimeFilter,
    name_pattern: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    let docs = load_docs()?;

    let mut items: Vec<(String, String, &DocEntry)> = Vec::new();

    if filter == DataprimeFilter::All || filter == DataprimeFilter::Commands {
        for (name, entry) in &docs.commands {
            if let Some(pattern) = name_pattern {
                if !name.to_lowercase().contains(&pattern.to_lowercase()) {
                    continue;
                }
            }
            items.push((name.clone(), "command".to_string(), entry));
        }
    }

    if filter == DataprimeFilter::All || filter == DataprimeFilter::Functions {
        for (name, entry) in &docs.functions {
            if let Some(pattern) = name_pattern {
                if !name.to_lowercase().contains(&pattern.to_lowercase()) {
                    continue;
                }
            }
            items.push((name.clone(), "function".to_string(), entry));
        }
    }

    items.sort_by(|a, b| a.0.cmp(&b.0));

    match output {
        OutputFormat::Json => {
            let json_items: Vec<_> = items
                .iter()
                .map(|(name, kind, entry)| {
                    serde_json::json!({
                        "name": name,
                        "type": kind,
                        "syntax": entry.syntax,
                        "description": first_sentence(&entry.description),
                        "category": entry.category,
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&json_items)?);
        }
        OutputFormat::Toon => {
            let agent_items: Vec<_> = items
                .iter()
                .map(|(name, kind, entry)| {
                    serde_json::json!({
                        "name": name,
                        "type": kind,
                        "syntax": entry.syntax,
                        "description": first_sentence(&entry.description),
                    })
                })
                .collect();
            let toon = toon_encode(&agent_items)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if items.is_empty() {
                println!("{}", "No matching items found.".yellow());
                return Ok(());
            }

            let mut builder = Builder::default();
            builder.push_record(["Name", "Type", "Description"]);
            for (name, kind, entry) in &items {
                builder.push_record([
                    name.clone(),
                    kind.clone(),
                    truncate(&first_sentence(&entry.description), 60),
                ]);
            }
            let table = builder.build().to_string();
            println!("{table}");
            println!(
                "\n{} items ({} commands, {} functions)",
                items.len(),
                items.iter().filter(|(_, k, _)| k == "command").count(),
                items.iter().filter(|(_, k, _)| k == "function").count()
            );
        }
    }

    Ok(())
}

/// Show detailed documentation for a specific command or function.
pub fn run_help(name: &str, output: OutputFormat) -> Result<()> {
    let docs = load_docs()?;

    let (kind, entry) = if let Some(entry) = docs.commands.get(name) {
        ("command", entry)
    } else if let Some(entry) = docs.functions.get(name) {
        ("function", entry)
    } else {
        let all_names: Vec<_> = docs.commands.keys().chain(docs.functions.keys()).collect();

        let suggestions: Vec<_> = all_names
            .iter()
            .filter(|n| n.to_lowercase().contains(&name.to_lowercase()))
            .take(5)
            .collect();

        let mut msg = format!("No command or function named '{}' found.", name);
        if !suggestions.is_empty() {
            msg.push_str("\n\nDid you mean one of these?\n");
            for s in suggestions {
                msg.push_str(&format!("  - {}\n", s));
            }
        }
        anyhow::bail!(msg);
    };

    match output {
        OutputFormat::Json => {
            let json = serde_json::json!({
                "name": name,
                "type": kind,
                "syntax": entry.syntax,
                "description": entry.description,
                "category": entry.category,
            });
            println!("{}", serde_json::to_string_pretty(&json)?);
        }
        OutputFormat::Toon => {
            let json = serde_json::json!({
                "name": name,
                "type": kind,
                "syntax": entry.syntax,
                "description": entry.description,
            });
            let toon =
                toon_encode(&json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            println!("{}", format!("{} ({})", name, kind).bold());
            println!();
            println!("{}", "Syntax:".cyan());
            println!("  {}", entry.syntax);
            println!();
            println!("{}", "Category:".cyan());
            println!("  {}", entry.category.join(" > "));
            println!();
            println!("{}", "Description:".cyan());
            for line in entry.description.lines() {
                println!("  {}", line);
            }
        }
    }

    Ok(())
}

// ── DataPrime query execution ────────────────────────────────────────────────

/// Options shared by logs, spans, and raw DataPrime queries.
#[derive(clap::Args, Clone, Copy, Debug, Default)]
pub struct QueryOptions {
    /// Reject keypaths absent from the schema. Unknown fields otherwise only produce
    /// warnings. Default: strict_fields_validation in config.toml, else off.
    #[arg(long, overrides_with = "no_strict_fields_validation")]
    pub strict_fields_validation: bool,

    /// Run queries with unknown keypaths (overrides strict_fields_validation in config.toml).
    #[arg(long, overrides_with = "strict_fields_validation")]
    pub no_strict_fields_validation: bool,

    /// Include results, queryId, warnings, and statistics in the stdout response.
    #[arg(long)]
    pub extended_information: bool,
}

impl QueryOptions {
    /// Apply `strict_fields_validation` from `config.toml` unless a flag set it.
    pub fn with_config_default(mut self, strict_fields_validation: bool) -> Self {
        if !self.no_strict_fields_validation {
            self.strict_fields_validation |= strict_fields_validation;
        }
        self
    }
}

/// Information for one independently executed profile query.
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryInformation {
    pub profile: String,
    pub query_id: Option<String>,
    pub warnings: Vec<Value>,
    pub statistics: Option<Value>,
}

/// Execute a generic DataPrime query against one target.
#[allow(clippy::too_many_arguments)]
async fn execute_query(
    target: Arc<ExecutionTarget>,
    query: &str,
    start_ts: &str,
    end_ts: &str,
    limit: u32,
    tier: Tier,
    source: &str,
    options: QueryOptions,
) -> Result<QueryGenericResponse> {
    let api = DataprimeApi::new(&target.client)
        .with_strict_fields_validation(options.strict_fields_validation)
        .with_warning_profile(&target.cfg.profile_name);
    Ok(api
        .query_generic(query, start_ts, end_ts, limit, tier, source)
        .await?)
}

/// Merged results from one or more profiles.
pub struct MergedResults {
    pub rows: Vec<Value>,
    pub warnings: Vec<String>,
    pub is_aggregate: bool,
    pub include_profile: bool,
    pub queries: Vec<QueryInformation>,
}

/// Merge per-profile generic responses into a single result set.
pub fn merge_results(
    per_profile: Vec<(String, Result<QueryGenericResponse>)>,
    include_profile: bool,
    cases_warning: Option<&str>,
) -> Result<MergedResults> {
    let mut rows: Vec<Value> = Vec::new();
    let mut warnings: Vec<String> = Vec::new();
    if let Some(w) = cases_warning {
        warnings.push(w.to_string());
    }
    let mut is_aggregate: Option<bool> = None;
    let mut queries = Vec::new();

    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        queries.push(QueryInformation {
            profile: profile.clone(),
            query_id: resp.query_id,
            warnings: resp.warnings,
            statistics: resp.statistics,
        });
        if is_aggregate.is_none() {
            is_aggregate = Some(resp.is_aggregate);
        }
        if include_profile {
            rows.extend(resp.raw_results.into_iter().map(|mut row| {
                if let Value::Object(ref mut m) = row {
                    m.insert("profile".to_string(), Value::String(profile.clone()));
                }
                row
            }));
        } else {
            rows.extend(resp.raw_results);
        }
    }

    Ok(MergedResults {
        rows,
        warnings,
        is_aggregate: is_aggregate.unwrap_or(false),
        include_profile,
        queries,
    })
}

/// Preserve per-profile information without inventing a combined query ID or statistics.
pub fn extended_response(merged: &MergedResults) -> Value {
    if !merged.include_profile {
        let info = merged.queries.first();
        serde_json::json!({
            "results": merged.rows,
            "queryId": info.and_then(|q| q.query_id.as_ref()),
            "warnings": info.map(|q| q.warnings.as_slice()).unwrap_or_default(),
            "statistics": info.and_then(|q| q.statistics.as_ref()),
        })
    } else {
        serde_json::json!({"results": merged.rows, "queries": merged.queries})
    }
}

fn query_information(merged: &MergedResults) -> Value {
    if merged.include_profile {
        serde_json::json!({"queries": merged.queries})
    } else {
        let info = merged.queries.first();
        serde_json::json!({
            "queryId": info.and_then(|q| q.query_id.as_ref()),
            "warnings": info.map(|q| q.warnings.as_slice()).unwrap_or_default(),
            "statistics": info.and_then(|q| q.statistics.as_ref()),
        })
    }
}

/// Render merged results to stdout.
///
/// JSON and Toon modes are handled generically. For Text mode, if a
/// `text_renderer` is provided it is used for source-specific formatting
/// (e.g. logs show timestamp/severity, spans show traceID/duration).
/// Otherwise rows are printed as pretty-printed JSON.
pub fn render_results(
    merged: &MergedResults,
    output: OutputFormat,
    max_direct: Option<usize>,
    temp_dir: &str,
    text_renderer: Option<fn(&MergedResults) -> Result<()>>,
) -> Result<()> {
    for w in &merged.warnings {
        eprintln!("{}", w.yellow());
    }

    match output {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(&merged.rows)?);
        }
        OutputFormat::Toon => {
            if merged.is_aggregate {
                let toon = toon_encode(&merged.rows)
                    .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
                println!("{toon}");
            } else {
                let agent_rows: Vec<_> = merged.rows.iter().map(transform_for_toon).collect();
                match maybe_spill(&agent_rows, max_direct, temp_dir)? {
                    SpillOutcome::Direct(json) => println!("{json}"),
                    SpillOutcome::Spilled { path, count } => {
                        println!(
                            "{count} results retrieved. Results written to: {}",
                            path.display()
                        );
                    }
                }
            }
        }
        OutputFormat::Text => {
            if let Some(renderer) = text_renderer {
                return renderer(merged);
            }
            // Generic text rendering - pretty-print each row.
            if merged.rows.is_empty() {
                println!("{}", "No results found.".yellow());
                return Ok(());
            }
            for row in &merged.rows {
                println!("{}", serde_json::to_string_pretty(row)?);
            }
        }
    }

    Ok(())
}

/// RUM lives in the `rum.events` dataset; `cx_rum` logs are the legacy format,
/// valid only as a fallback. Remind agents to try `rum.events` first.
fn rum_source_warning(query: &str) -> Option<String> {
    query.to_ascii_lowercase().contains("cx_rum").then(|| {
        "[RUM query warning] `cx_rum` logs are the legacy RUM format. Query the `rum.events` \
         dataset first: cx dataprime query --source rum.events '<query>' (fields directly \
         under $d.*, no cx_rum prefix). Use cx_rum logs only if rum.events has no data."
            .to_string()
    })
}

/// Run a generic DataPrime query across all targets with fan-out, merge, and render.
#[allow(clippy::too_many_arguments)]
pub async fn run_query(
    targets: &[Arc<ExecutionTarget>],
    query: &str,
    source: &str,
    start: &str,
    end: &str,
    limit: u32,
    tier: Option<Tier>,
    output: OutputFormat,
    max_direct: Option<usize>,
    temp_dir: &str,
    text_renderer: Option<fn(&MergedResults) -> Result<()>>,
    options: QueryOptions,
) -> Result<()> {
    eprintln!("{}", "Querying...".dimmed());

    let start_fmt = parse_timestamp(start)?;
    let end_fmt = parse_timestamp(end)?;
    let cases_warning = check_cases_query_rules(query, &start_fmt, &end_fmt);

    let include_profile = targets.len() > 1;
    let query = query.to_string();
    let source = source.to_string();
    let per_profile = fan_out(targets, |t| {
        let q = query.clone();
        let src = source.clone();
        let s = start_fmt.clone();
        let e = end_fmt.clone();
        async move {
            let effective_tier = tier.unwrap_or(t.cfg.default_tier);
            execute_query(t, &q, &s, &e, limit, effective_tier, &src, options).await
        }
    })
    .await;

    let mut merged = merge_results(per_profile, include_profile, cases_warning.as_deref())?;
    merged.warnings.extend(rum_source_warning(&query));
    if options.extended_information {
        match output {
            OutputFormat::Text => {
                render_results(&merged, output, max_direct, temp_dir, text_renderer)?;
                println!(
                    "\n{}",
                    serde_json::to_string_pretty(&query_information(&merged))?
                );
            }
            OutputFormat::Json => {
                for warning in &merged.warnings {
                    eprintln!("{warning}");
                }
                println!(
                    "{}",
                    serde_json::to_string_pretty(&extended_response(&merged))?
                );
            }
            OutputFormat::Toon => {
                for warning in &merged.warnings {
                    eprintln!("{warning}");
                }
                render_extended_toon(&merged, max_direct, temp_dir)?;
            }
        }
        return Ok(());
    }
    render_results(&merged, output, max_direct, temp_dir, text_renderer)
}

/// TOON extended output. Non-aggregated rows are renamed to `$m` / `$l` / `$d`.
/// When that encoded payload exceeds `max_direct`, the envelope is written as
/// JSON and stdout gets the spill path instead of the payload.
fn render_extended_toon(
    merged: &MergedResults,
    max_direct: Option<usize>,
    temp_dir: &str,
) -> Result<()> {
    let mut response = extended_response(merged);
    if !merged.is_aggregate {
        if let Some(rows) = response.get_mut("results").and_then(Value::as_array_mut) {
            for row in rows.iter_mut() {
                *row = transform_for_toon(row);
            }
        }
    }
    let encoded =
        toon_encode(&response).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
    let over_limit = !merged.is_aggregate && max_direct.is_some_and(|limit| encoded.len() > limit);
    if over_limit {
        let path = write_result_file(&serde_json::to_string_pretty(&response)?, temp_dir)?;
        println!(
            "{} results retrieved. Results written to: {}",
            merged.rows.len(),
            path.display()
        );
        return Ok(());
    }
    println!("{encoded}");
    Ok(())
}

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

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

    #[test]
    fn truncate_short_string() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn truncate_long_string() {
        assert_eq!(truncate("hello world", 8), "hello...");
    }

    #[test]
    fn truncate_multiline() {
        assert_eq!(truncate("line1\nline2\nline3", 100), "line1");
    }

    #[test]
    fn doc_entry_deserialize() {
        let yaml = r#"
description: "Test description"
syntax: "test <arg>"
category: ["Commands reference", "test"]
"#;
        let entry: DocEntry = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(entry.description, "Test description");
        assert_eq!(entry.syntax, "test <arg>");
        assert_eq!(entry.category, vec!["Commands reference", "test"]);
    }

    #[test]
    fn first_sentence_with_period_space() {
        assert_eq!(
            first_sentence("First sentence. Second sentence."),
            "First sentence."
        );
    }

    #[test]
    fn first_sentence_with_period_newline() {
        assert_eq!(
            first_sentence("First sentence.\nSecond sentence."),
            "First sentence."
        );
    }

    #[test]
    fn first_sentence_single_line() {
        assert_eq!(first_sentence("Only one sentence."), "Only one sentence.");
    }

    #[test]
    fn first_sentence_no_period() {
        assert_eq!(first_sentence("No period here"), "No period here");
    }

    #[test]
    fn first_sentence_multiline_no_period() {
        assert_eq!(first_sentence("First line\nSecond line"), "First line");
    }

    // ── merge_results tests ──────────────────────────────────────────────────

    use serde_json::json;

    use super::api::QueryGenericResponse;

    fn make_generic_response(
        rows: Vec<serde_json::Value>,
        is_aggregate: bool,
    ) -> QueryGenericResponse {
        QueryGenericResponse {
            raw_results: rows,
            warnings: vec![],
            is_aggregate,
            ..Default::default()
        }
    }

    #[test]
    fn extended_response_keeps_each_query_id_statistics_and_warnings_with_its_profile() {
        let responses = ["prod", "staging"].map(|profile| {
            (
                profile.to_string(),
                Ok(QueryGenericResponse {
                    raw_results: vec![json!({"userData": {"message": profile}})],
                    query_id: Some(format!("{profile}-query")),
                    statistics: Some(json!({"status": "COMPLETED", "profileSpecific": profile})),
                    warnings: vec![json!({"futureWarning": {"profileSpecific": profile}})],
                    ..Default::default()
                }),
            )
        });
        let merged = merge_results(responses.into(), true, None).unwrap();
        let value = extended_response(&merged);
        for (index, profile) in ["prod", "staging"].into_iter().enumerate() {
            assert_eq!(value["results"][index]["profile"], profile);
            assert_eq!(
                value["queries"][index]["queryId"],
                format!("{profile}-query")
            );
            assert_eq!(
                value["queries"][index]["statistics"]["profileSpecific"],
                profile
            );
            assert_eq!(
                value["queries"][index]["warnings"][0]["futureWarning"]["profileSpecific"],
                profile
            );
        }
    }

    #[test]
    fn merge_single_profile_omits_profile_field() {
        let rows = vec![json!({"userData": {"message": "hello"}})];
        let per_profile = vec![("prod".to_string(), Ok(make_generic_response(rows, false)))];
        let merged = merge_results(per_profile, false, None).unwrap();

        assert_eq!(merged.rows.len(), 1);
        assert!(!merged.include_profile);
        assert!(merged.rows[0].get("profile").is_none());
    }

    #[test]
    fn merge_multiple_profiles_tags_rows() {
        let per_profile = vec![
            (
                "prod".to_string(),
                Ok(make_generic_response(
                    vec![json!({"userData": {"msg": "a"}})],
                    false,
                )),
            ),
            (
                "staging".to_string(),
                Ok(make_generic_response(
                    vec![json!({"userData": {"msg": "b"}})],
                    false,
                )),
            ),
        ];
        let merged = merge_results(per_profile, true, None).unwrap();

        assert_eq!(merged.rows.len(), 2);
        assert_eq!(merged.rows[0]["profile"], json!("prod"));
        assert_eq!(merged.rows[1]["profile"], json!("staging"));
    }

    #[test]
    fn merge_skips_errored_profiles() {
        let per_profile: Vec<(String, anyhow::Result<QueryGenericResponse>)> = vec![
            (
                "good".to_string(),
                Ok(make_generic_response(vec![json!({"data": 1})], false)),
            ),
            ("bad".to_string(), Err(anyhow::anyhow!("network error"))),
        ];
        let merged = merge_results(per_profile, true, None).unwrap();

        assert_eq!(merged.rows.len(), 1);
        assert_eq!(merged.rows[0]["profile"], json!("good"));
    }

    #[test]
    fn merge_preserves_structured_warnings_per_profile() {
        let mut resp = make_generic_response(vec![], false);
        resp.warnings = vec![json!({"compileWarning": {"warningMessage": "too many results"}})];
        let per_profile = vec![("prod".to_string(), Ok(resp))];
        let merged = merge_results(per_profile, true, None).unwrap();

        assert_eq!(merged.queries[0].warnings.len(), 1);
        assert_eq!(merged.queries[0].profile, "prod");
    }

    #[test]
    fn merge_is_aggregate_from_first_successful() {
        let per_profile = vec![
            ("p1".to_string(), Ok(make_generic_response(vec![], true))),
            ("p2".to_string(), Ok(make_generic_response(vec![], true))),
        ];
        let merged = merge_results(per_profile, true, None).unwrap();
        assert!(merged.is_aggregate);
    }

    #[test]
    fn merge_single_profile_failure_returns_err() {
        let per_profile: Vec<(String, anyhow::Result<QueryGenericResponse>)> =
            vec![("prod".to_string(), Err(anyhow::anyhow!("boom")))];
        let result = merge_results(per_profile, false, None);

        assert!(result.is_err(), "single failing profile must bail");
    }

    #[test]
    fn merge_all_profiles_failing_returns_err() {
        let per_profile: Vec<(String, anyhow::Result<QueryGenericResponse>)> = vec![
            ("prod".to_string(), Err(anyhow::anyhow!("timeout"))),
            ("staging".to_string(), Err(anyhow::anyhow!("auth failed"))),
        ];
        let result = merge_results(per_profile, true, None);

        assert!(
            result.is_err(),
            "must bail when every profile in the fan-out failed"
        );
    }

    #[test]
    fn rum_warning_only_for_cx_rum_queries() {
        assert!(rum_source_warning("filter $l.subsystemname == 'CX_RUM'").is_some());
        assert!(
            rum_source_warning("source logs | filter $d.cx_rum.event_context.type == 'error'")
                .is_some()
        );
        assert!(rum_source_warning("filter $d.event_context.type == 'error'").is_none());
    }

    // ── check_cases_query_rules integration via merge_results ────────────────

    use crate::cases_query_rules::check_cases_query_rules;

    const CASES_START: &str = "2024-01-01T00:00:00.000Z";
    const CASES_END: &str = "2024-01-01T02:00:00.000Z";
    const CASES_QUERY: &str = "source system/labs.cases.state_updates | count";

    #[test]
    fn cases_warning_prepended_to_merged_warnings() {
        let warning = check_cases_query_rules(CASES_QUERY, CASES_START, CASES_END);
        assert!(
            warning.is_some(),
            "expected a warning from check_cases_query_rules"
        );

        let per_profile = vec![(
            "prod".to_string(),
            Ok(make_generic_response(vec![json!({"data": 1})], false)),
        )];
        let merged = merge_results(per_profile, false, warning.as_deref()).unwrap();

        assert_eq!(merged.warnings.len(), 1);
        assert!(
            merged.warnings[0].contains("[Cases query warning]"),
            "cases warning should be in merged warnings"
        );
    }

    #[test]
    fn cases_warning_plus_profile_warning_both_appear() {
        let cases_warn = check_cases_query_rules(CASES_QUERY, CASES_START, CASES_END);
        assert!(cases_warn.is_some());

        let mut resp = make_generic_response(vec![], false);
        resp.warnings = vec![json!({"compileWarning": {"warningMessage": "too many results"}})];
        let per_profile = vec![("prod".to_string(), Ok(resp))];
        let merged = merge_results(per_profile, true, cases_warn.as_deref()).unwrap();

        assert_eq!(
            merged.warnings.len() + merged.queries[0].warnings.len(),
            2,
            "should have one cases warning and one profile warning"
        );
        assert!(merged.warnings[0].contains("[Cases query warning]"));
        assert_eq!(merged.queries[0].profile, "prod");
        assert_eq!(
            merged.queries[0].warnings[0]["compileWarning"]["warningMessage"],
            "too many results"
        );
    }

    #[test]
    fn cases_warning_present_when_profile_errors() {
        let cases_warn = check_cases_query_rules(CASES_QUERY, CASES_START, CASES_END);
        assert!(cases_warn.is_some());
        let warning_text = cases_warn.clone().unwrap();

        // With a cases warning and a failed profile, the warning is still in
        // merged.warnings (printed by render_results), not embedded in errors.
        let per_profile: Vec<(String, anyhow::Result<QueryGenericResponse>)> = vec![
            (
                "good".to_string(),
                Ok(make_generic_response(vec![json!({"ok": true})], false)),
            ),
            ("bad".to_string(), Err(anyhow::anyhow!("timeout"))),
        ];
        let merged = merge_results(per_profile, true, cases_warn.as_deref()).unwrap();

        // The cases warning appears in merged.warnings regardless of profile errors.
        assert!(
            merged
                .warnings
                .iter()
                .any(|w| w.contains("[Cases query warning]")),
            "cases warning must be present even when a profile errors"
        );
        // The good profile's row is still included.
        assert_eq!(merged.rows.len(), 1);
        // The warning text is non-empty (contains Rule content).
        assert!(warning_text.contains("Rule"));
    }

    #[test]
    fn no_cases_warning_when_query_has_dedup() {
        let warning = check_cases_query_rules(
            "source system/labs.cases.state_updates | dedupeby caseId orderby $m.timestamp desc",
            CASES_START,
            CASES_END,
        );
        let per_profile = vec![("prod".to_string(), Ok(make_generic_response(vec![], false)))];
        let merged = merge_results(per_profile, false, warning.as_deref()).unwrap();

        assert!(
            merged.warnings.is_empty(),
            "no warnings expected for a compliant cases query"
        );
    }

    #[test]
    fn no_cases_warning_for_non_cases_source() {
        let warning = check_cases_query_rules("source logs | limit 10", CASES_START, CASES_END);
        assert!(warning.is_none());

        let per_profile = vec![(
            "prod".to_string(),
            Ok(make_generic_response(vec![json!({"msg": "hi"})], false)),
        )];
        let merged = merge_results(per_profile, false, warning.as_deref()).unwrap();

        assert!(merged.warnings.is_empty());
        assert_eq!(merged.rows.len(), 1);
    }
}