warble 0.8.0

Warble front-end compiler: parse/resolve/validate a behavior profile into language-neutral IR (sans-IO).
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
//! The `ContextLoader` trait and its narrow Info projections — the host I/O interface for
//! semantic-layer access.
//!
//! **Sans-IO, by design.** The trait lives in core and performs no filesystem or network access:
//! a host (the CLI, or a WASM/py/napi binding) reads the bound semantic layer, builds an adapter
//! that implements this trait, and injects it into [`crate::compile`]. This is the fine-grained
//! successor to the old `project_precondition_ok: bool` — instead of "the host already decided
//! pass/fail", the host now hands in an object the compiler can *probe*.
//!
//! **Warble's own narrow projection.** The Info types here are deliberately Warble's own shapes,
//! not re-exports of any semantic-format's structs (e.g. `wren-core-base`'s `Model`/`Measure`).
//! That is what keeps `context_precondition` evaluation format-agnostic: the MDL adapter is
//! adapter #1, and a future OSI (or any other) adapter implements the same trait without touching
//! core (architecture invariant #2).

/// Whether a metric's aggregation is additive across the dimensions a decomposition would drill
/// along. Inferred by an adapter from the metric's underlying aggregation; it is *not* a field any
/// current MDL carries.
///
/// - `Additive` — a sum-of-parts equals the whole (`SUM`, non-distinct `COUNT`).
/// - `NonAdditive` — parts do not sum to the whole (`AVG`, `MIN`, `MAX`, ratios, `COUNT(DISTINCT …)`).
/// - `SemiAdditive` — additive across some dimensions but not others (classically, not across
///   time — balances, inventory levels). Forward-declared: the expression heuristic in adapter #1
///   only distinguishes additive vs non-additive; producing `SemiAdditive` needs knowledge-layer
///   input (a later vocabulary batch), so it is defined but not yet emitted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Additivity {
    Additive,
    SemiAdditive,
    NonAdditive,
}

/// A queryable metric — either a *declared* cube measure (whose additivity is determinable) or an
/// *implicit* numeric column projected as a metric so that `has_metric` holds on cube-less
/// projects. `declared` is the line between the two; `additivity` is `Some` only when `declared`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetricInfo {
    pub name: String,
    /// The model or cube this metric is anchored to (used to seed lineage).
    pub owner: String,
    /// `true` for a declared cube measure (a known aggregation ⇒ additivity is expressible);
    /// `false` for an implicit numeric column surfaced as a queryable quantity.
    pub declared: bool,
    /// Inferred additivity. `Some` only when `declared` (an aggregation is known); `None` means
    /// additivity is not expressible for this metric — the source of a `can_answer = false`
    /// loud-fail for `metric_additive`, as distinct from evaluating it `false`.
    pub additivity: Option<Additivity>,
}

/// A dimension the semantic layer can group/slice by — a cube dimension or a selectable model
/// column. `is_temporal` marks a DATE/TIMESTAMP-typed dimension (satisfies `has_time_dimension`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DimensionInfo {
    pub name: String,
    /// The model or cube this dimension belongs to.
    pub owner: String,
    /// Whether this dimension is time-typed (DATE / TIMESTAMP / DATETIME).
    pub is_temporal: bool,
}

/// A model in the semantic layer, narrowed to what the precondition vocabulary needs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelInfo {
    pub name: String,
    /// Whether the model has at least one DATE/TIMESTAMP column (satisfies `model_has_timestamp`).
    pub has_timestamp: bool,
    /// Column names, for discoverability and lineage anchoring.
    pub columns: Vec<String>,
}

// --- lineage ------------------------------------------------------------------------------------

/// The kind of a node in the semantic lineage DAG. Ordered coarse→fine along the dependency flow
/// `raw → models → relationships → metrics/dimensions → views → consumers` (capability-model §7.1).
/// `Query` and `Dashboard` are *consumer* nodes — artifacts outside the semantic layer (a confirmed
/// saved query, a dashboard spec) that depend on it; they are always sinks, never upstream of a
/// semantic node.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineageKind {
    Model,
    Column,
    Relationship,
    Cube,
    Metric,
    Dimension,
    View,
    Query,
    Dashboard,
}

/// A node in the lineage DAG. `id` is a stable, adapter-assigned identifier (e.g. `model:orders`,
/// `column:orders.amount`, `metric:revenue.total_revenue`); it is what `blast_radius` is queried by.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LineageNode {
    pub id: String,
    pub kind: LineageKind,
}

/// A directed dependency edge, oriented **upstream → downstream**: `from` is the thing depended on,
/// `to` is the dependent that would break if `from` changed. `blast_radius` follows edges forward.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LineageEdge {
    pub from: String,
    pub to: String,
}

/// The worst class of downstream impact in a blast radius (capability-model §7.1). Ordered least →
/// most dangerous so the overall severity of an impact set is the max over its members.
/// - `Compatibility` — a type/grain mismatch downstream.
/// - `Structural` — a downstream model/view/column breaks (loud: queries error).
/// - `Semantic` — a downstream **metric** silently shifts its numbers for every consumer (the most
///   dangerous, because it does not error).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    None,
    Compatibility,
    Structural,
    Semantic,
}

/// The read-only result of a blast-radius query: the transitive downstream closure of a node plus
/// the worst severity across it. Computed at dry-run in Phase 2 (analysis only); Phase 4 uses it to
/// gate a mutating apply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlastRadius {
    /// The node whose downstream impact was computed.
    pub seed: String,
    /// Every node transitively downstream of `seed` (sorted, excludes `seed`).
    pub downstream: Vec<String>,
    /// The worst impact class over `downstream` (`None` when nothing is downstream).
    pub severity: Severity,
}

/// The semantic lineage DAG. Built by an adapter from the bound semantic layer (structural refs:
/// relationships, cube base objects, column expressions, view statements); traversed by core.
/// `blast_radius` is a pure query over this Warble-owned type, reusable by any adapter.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LineageGraph {
    pub nodes: Vec<LineageNode>,
    pub edges: Vec<LineageEdge>,
}

impl LineageGraph {
    /// Whether every edge endpoint refers to a declared node — the structural condition behind the
    /// `lineage_resolvable` predicate (no dangling relationship/base-object/view reference).
    pub fn is_resolvable(&self) -> bool {
        self.edges
            .iter()
            .all(|e| self.contains(&e.from) && self.contains(&e.to))
    }

    /// Whether a node with the given id exists in the graph.
    pub fn contains(&self, id: &str) -> bool {
        self.nodes.iter().any(|n| n.id == id)
    }

    /// Look up a node by id.
    pub fn node(&self, id: &str) -> Option<&LineageNode> {
        self.nodes.iter().find(|n| n.id == id)
    }

    /// The blast radius of `seed`: its transitive downstream closure (forward along `from → to`
    /// edges) plus the worst downstream [`Severity`]. Read-only; cycle-safe (a visited set bounds
    /// the walk even on a malformed cyclic graph). An unknown or leaf `seed` yields an empty radius.
    pub fn blast_radius(&self, seed: &str) -> BlastRadius {
        let mut downstream: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        let mut stack = vec![seed.to_string()];
        while let Some(current) = stack.pop() {
            for edge in self.edges.iter().filter(|e| e.from == current) {
                if edge.to != seed && downstream.insert(edge.to.clone()) {
                    stack.push(edge.to.clone());
                }
            }
        }
        let severity = downstream
            .iter()
            .map(|id| self.node_severity(id))
            .max()
            .unwrap_or(Severity::None);
        BlastRadius {
            seed: seed.to_string(),
            downstream: downstream.into_iter().collect(),
            severity,
        }
    }

    /// The impact class of a single downstream node, by kind. A metric is semantic (silent number
    /// shift); a consumer (query/dashboard) is likewise semantic — the end user sees silently
    /// shifted numbers, not an error; a model/view/column is structural (breaks queries);
    /// relationship/cube/dimension is a compatibility concern.
    fn node_severity(&self, id: &str) -> Severity {
        match self.node(id).map(|n| n.kind) {
            Some(LineageKind::Metric | LineageKind::Query | LineageKind::Dashboard) => {
                Severity::Semantic
            }
            Some(LineageKind::Model | LineageKind::View | LineageKind::Column) => {
                Severity::Structural
            }
            Some(LineageKind::Relationship | LineageKind::Cube | LineageKind::Dimension) => {
                Severity::Compatibility
            }
            None => Severity::None,
        }
    }
}

// --- the trait ----------------------------------------------------------------------------------

/// Host-injected semantic-layer access. Pure on the core side (operates over an already-loaded
/// adapter); the host owns all I/O. One accessor per capability the compiler needs to *probe* the
/// bound Context for, plus `lineage` for `blast_radius`.
///
/// The two lookup methods (`metric_additivity`, `can_answer`) are provided defaults derived from
/// the Info data + the closed predicate vocabulary, so an adapter only has to fill the data; a
/// non-MDL adapter with a different answerable set may still override them.
pub trait ContextLoader {
    /// Whether the bound semantic layer assembled and parsed. Backs `mdl_parseable` /
    /// `wren_project_exists`.
    fn is_parseable(&self) -> bool;

    /// The underlying parse/assembly failure text, when [`Self::is_parseable`] is `false` and the
    /// adapter has one to offer (e.g. a serde error from the bound project's manifest). Message-only
    /// enrichment for the `mdl_parseable` precondition failure — never used for control flow.
    /// Defaults to `None` (no detail beyond the generic floor message); an adapter that keeps the
    /// real error around overrides it.
    fn parse_error(&self) -> Option<&str> {
        None
    }

    /// All queryable metrics (declared cube measures + implicit numeric columns).
    fn metrics(&self) -> &[MetricInfo];

    /// All groupable / queryable dimensions (cube dimensions + selectable columns).
    fn dimensions(&self) -> &[DimensionInfo];

    /// Time dimensions — the temporal subset that satisfies `has_time_dimension`.
    fn time_dimensions(&self) -> &[DimensionInfo];

    /// All models in the layer.
    fn models(&self) -> &[ModelInfo];

    /// A single model by name.
    fn model(&self, name: &str) -> Option<&ModelInfo> {
        self.models().iter().find(|m| m.name == name)
    }

    /// The semantic lineage DAG (for `lineage_resolvable` + `blast_radius`).
    fn lineage(&self) -> &LineageGraph;

    /// Raw-shape probe (constitutive family): whether the bound **raw** source can have its schema
    /// introspected (the precondition `source_introspectable`). This *inverts* the consumer probes
    /// above: a constitutive component's input is a raw source that has no MDL yet — the component's
    /// output *is* the MDL. `Some(true)` = introspectable, `Some(false)` = a raw source is bound but
    /// not introspectable, `None` = this Context cannot answer raw-shape at all (an MDL-only adapter),
    /// which the compiler turns into an *unanswerable* loud-fail rather than guessing (the same
    /// distinction `metric_additive` draws). Defaults to `None` so existing MDL adapters are unaffected;
    /// a raw-source adapter overrides it (schema introspection is borrowed — dlt/wren — never built).
    fn source_introspectable(&self) -> Option<bool> {
        None
    }

    /// Raw-shape probe (constitutive family): whether readable raw business docs back a knowledge
    /// enrichment (the precondition `raw_docs_readable`). Same `Some`/`None` semantics as
    /// [`Self::source_introspectable`]; defaults to `None` (MDL-only adapters cannot answer it).
    fn raw_docs_readable(&self) -> Option<bool> {
        None
    }

    /// Human-readable notes about where lineage construction had to degrade (e.g. a consumer's SQL
    /// failed to parse and a cruder text scan was used, or a malformed consumer file was skipped).
    /// Surfaced into the IR's resolved binding so a thinner-than-authored graph is never silent
    /// (no silent caps). Defaults to empty: an adapter with nothing to confess reports nothing.
    fn lineage_diagnostics(&self) -> &[String] {
        &[]
    }

    /// Additivity of a *declared* metric, or `None` when the metric is not declared or its
    /// additivity is not expressible (⇒ `can_answer("metric_additive")` is `false` for it).
    fn metric_additivity(&self, metric: &str) -> Option<Additivity> {
        self.metrics()
            .iter()
            .find(|m| m.name == metric)
            .and_then(|m| m.additivity)
    }

    /// Capability probe: can this Context answer `predicate` *at all*? A `false` here is a
    /// different loud-fail from evaluating the predicate `false` — it means the semantic format
    /// cannot carry the answer, so the compiler must refuse rather than guess.
    ///
    /// In the current vocabulary `metric_additive` (needs a declared metric) and the constitutive
    /// raw-shape predicates (`source_introspectable` / `raw_docs_readable`, answerable only by a
    /// raw-source adapter) can be unanswerable. Every other predicate is answerable by inspection
    /// (it evaluates true or false).
    fn can_answer(&self, predicate: &str) -> bool {
        match predicate {
            "metric_additive" => self.metrics().iter().any(|m| m.declared),
            // Constitutive raw-shape: answerable iff this Context actually probes a raw source
            // (`Some(_)`); an MDL-only adapter returns `None` ⇒ unanswerable.
            "source_introspectable" => self.source_introspectable().is_some(),
            "raw_docs_readable" => self.raw_docs_readable().is_some(),
            "mdl_parseable"
            | "wren_project_exists"
            | "has_metric"
            | "has_queryable_dimension"
            | "has_time_dimension"
            | "has_groupable_dimension"
            | "model_has_timestamp"
            | "lineage_resolvable" => true,
            // Unknown predicates are rejected earlier by the closed-vocabulary check; treating an
            // unknown here as unanswerable is defense-in-depth.
            _ => false,
        }
    }
}

/// A binding whose semantic layer is **not reachable from here** — held by a service that answers
/// the questions itself, or simply not pulled onto this machine.
///
/// It is well-formed, so [`ContextLoader::is_parseable`] holds and the compiler's coarse floor
/// passes: the binding resolved, there is just no local MDL behind it. Beyond that it answers
/// nothing. Every precondition against it comes back *unanswerable* rather than false, which is the
/// point — a profile bound this way cannot quietly gate on schema facts nobody checked, and an
/// author who wants such a gate is told to bind a context that can answer it instead.
///
/// This is what makes an offline delegating profile honest. Reporting empty collections *without*
/// declining the probes would be worse than useless: `has_metric` would evaluate to a confident
/// `false` about a layer this process has never seen.
#[derive(Debug, Default)]
pub struct ExternalContext {
    lineage: LineageGraph,
}

impl ExternalContext {
    pub fn new() -> Self {
        Self::default()
    }
}

impl ContextLoader for ExternalContext {
    fn is_parseable(&self) -> bool {
        true
    }
    fn metrics(&self) -> &[MetricInfo] {
        &[]
    }
    fn dimensions(&self) -> &[DimensionInfo] {
        &[]
    }
    fn time_dimensions(&self) -> &[DimensionInfo] {
        &[]
    }
    fn models(&self) -> &[ModelInfo] {
        &[]
    }
    fn lineage(&self) -> &LineageGraph {
        &self.lineage
    }
    fn can_answer(&self, _predicate: &str) -> bool {
        false
    }
}

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

    /// A minimal in-test adapter so the trait's provided methods can be exercised without the MDL
    /// adapter crate (which lives in the binding layer).
    struct FakeContext {
        metrics: Vec<MetricInfo>,
        dimensions: Vec<DimensionInfo>,
        models: Vec<ModelInfo>,
        lineage: LineageGraph,
        parseable: bool,
    }

    impl ContextLoader for FakeContext {
        fn is_parseable(&self) -> bool {
            self.parseable
        }
        fn metrics(&self) -> &[MetricInfo] {
            &self.metrics
        }
        fn dimensions(&self) -> &[DimensionInfo] {
            &self.dimensions
        }
        fn time_dimensions(&self) -> &[DimensionInfo] {
            // The temporal subset; adapters cache this, but deriving it here keeps the fake small.
            // (Provided methods don't call this, so an empty slice would also do.)
            &self.dimensions
        }
        fn models(&self) -> &[ModelInfo] {
            &self.models
        }
        fn lineage(&self) -> &LineageGraph {
            &self.lineage
        }
    }

    fn metric(name: &str, declared: bool, additivity: Option<Additivity>) -> MetricInfo {
        MetricInfo {
            name: name.to_string(),
            owner: "m".to_string(),
            declared,
            additivity,
        }
    }

    #[test]
    fn metric_additivity_looks_up_declared_metric() {
        let ctx = FakeContext {
            metrics: vec![
                metric("total_revenue", true, Some(Additivity::Additive)),
                metric("avg_order", true, Some(Additivity::NonAdditive)),
                metric("amount", false, None),
            ],
            dimensions: vec![],
            models: vec![],
            lineage: LineageGraph::default(),
            parseable: true,
        };
        assert_eq!(
            ctx.metric_additivity("total_revenue"),
            Some(Additivity::Additive)
        );
        assert_eq!(
            ctx.metric_additivity("avg_order"),
            Some(Additivity::NonAdditive)
        );
        // implicit column: not expressible
        assert_eq!(ctx.metric_additivity("amount"), None);
        // absent metric
        assert_eq!(ctx.metric_additivity("nope"), None);
    }

    #[test]
    fn can_answer_metric_additive_needs_a_declared_metric() {
        // No declared metric (cube-less project) → metric_additive is unanswerable.
        let cubeless = FakeContext {
            metrics: vec![metric("amount", false, None)],
            dimensions: vec![],
            models: vec![],
            lineage: LineageGraph::default(),
            parseable: true,
        };
        assert!(!cubeless.can_answer("metric_additive"));
        // A declared metric exists → answerable (then it evaluates true/false separately).
        let with_cube = FakeContext {
            metrics: vec![metric("total_revenue", true, Some(Additivity::Additive))],
            dimensions: vec![],
            models: vec![],
            lineage: LineageGraph::default(),
            parseable: true,
        };
        assert!(with_cube.can_answer("metric_additive"));
    }

    #[test]
    fn can_answer_existence_predicates_always_true() {
        let ctx = FakeContext {
            metrics: vec![],
            dimensions: vec![],
            models: vec![],
            lineage: LineageGraph::default(),
            parseable: false,
        };
        for p in [
            "mdl_parseable",
            "wren_project_exists",
            "has_metric",
            "has_queryable_dimension",
            "has_time_dimension",
            "has_groupable_dimension",
            "model_has_timestamp",
            "lineage_resolvable",
        ] {
            assert!(ctx.can_answer(p), "{p} should be answerable");
        }
        assert!(!ctx.can_answer("some_future_unknown_predicate"));
    }

    #[test]
    fn mdl_only_adapter_cannot_answer_constitutive_raw_shape() {
        // The default trait probes return `None` — an MDL-only adapter (FakeContext doesn't override
        // them) cannot answer the constitutive raw-shape predicates, so they are *unanswerable*
        // (a loud-fail at compile), never silently `false`.
        let ctx = FakeContext {
            metrics: vec![],
            dimensions: vec![],
            models: vec![],
            lineage: LineageGraph::default(),
            parseable: true,
        };
        assert_eq!(ctx.source_introspectable(), None);
        assert_eq!(ctx.raw_docs_readable(), None);
        assert!(!ctx.can_answer("source_introspectable"));
        assert!(!ctx.can_answer("raw_docs_readable"));
    }

    #[test]
    fn raw_source_adapter_answers_constitutive_raw_shape() {
        // An adapter that DOES probe a raw source (overriding the defaults) makes the constitutive
        // predicates answerable — the inversion the constitutive family depends on.
        struct RawFake;
        impl ContextLoader for RawFake {
            fn is_parseable(&self) -> bool {
                true
            }
            fn metrics(&self) -> &[MetricInfo] {
                &[]
            }
            fn dimensions(&self) -> &[DimensionInfo] {
                &[]
            }
            fn time_dimensions(&self) -> &[DimensionInfo] {
                &[]
            }
            fn models(&self) -> &[ModelInfo] {
                &[]
            }
            fn lineage(&self) -> &LineageGraph {
                // A raw source has no MDL lineage yet; a leaked-static empty graph keeps the
                // signature borrow-clean for this test-only adapter.
                static EMPTY: std::sync::OnceLock<LineageGraph> = std::sync::OnceLock::new();
                EMPTY.get_or_init(LineageGraph::default)
            }
            fn source_introspectable(&self) -> Option<bool> {
                Some(true)
            }
            fn raw_docs_readable(&self) -> Option<bool> {
                Some(false)
            }
        }
        let ctx = RawFake;
        assert!(ctx.can_answer("source_introspectable"));
        assert!(ctx.can_answer("raw_docs_readable"));
        assert_eq!(ctx.source_introspectable(), Some(true));
        assert_eq!(ctx.raw_docs_readable(), Some(false));
    }

    #[test]
    fn lineage_resolvable_detects_dangling_edges() {
        let good = LineageGraph {
            nodes: vec![
                LineageNode {
                    id: "model:orders".into(),
                    kind: LineageKind::Model,
                },
                LineageNode {
                    id: "metric:revenue".into(),
                    kind: LineageKind::Metric,
                },
            ],
            edges: vec![LineageEdge {
                from: "model:orders".into(),
                to: "metric:revenue".into(),
            }],
        };
        assert!(good.is_resolvable());

        let dangling = LineageGraph {
            nodes: vec![LineageNode {
                id: "model:orders".into(),
                kind: LineageKind::Model,
            }],
            edges: vec![LineageEdge {
                from: "model:orders".into(),
                to: "metric:missing".into(),
            }],
        };
        assert!(!dangling.is_resolvable());
    }

    fn node(id: &str, kind: LineageKind) -> LineageNode {
        LineageNode {
            id: id.into(),
            kind,
        }
    }
    fn edge(from: &str, to: &str) -> LineageEdge {
        LineageEdge {
            from: from.into(),
            to: to.into(),
        }
    }

    /// `model → cube → {metric, dim}`, plus a view off the model — the jaffle-shaped chain.
    fn sample_graph() -> LineageGraph {
        LineageGraph {
            nodes: vec![
                node("model:orders", LineageKind::Model),
                node("cube:revenue", LineageKind::Cube),
                node("metric:revenue.total", LineageKind::Metric),
                node("dim:revenue.status", LineageKind::Dimension),
                node("view:orders_view", LineageKind::View),
            ],
            edges: vec![
                edge("model:orders", "cube:revenue"),
                edge("cube:revenue", "metric:revenue.total"),
                edge("cube:revenue", "dim:revenue.status"),
                edge("model:orders", "view:orders_view"),
            ],
        }
    }

    #[test]
    fn blast_radius_is_the_transitive_downstream_closure() {
        let graph = sample_graph();
        let radius = graph.blast_radius("model:orders");
        assert_eq!(
            radius.downstream,
            vec![
                "cube:revenue".to_string(),
                "dim:revenue.status".to_string(),
                "metric:revenue.total".to_string(),
                "view:orders_view".to_string(),
            ],
            "changing the base model reaches the cube, its members, and the view"
        );
        // A downstream metric makes the worst impact semantic (silent number shift).
        assert_eq!(radius.severity, Severity::Semantic);
    }

    #[test]
    fn blast_radius_of_a_leaf_is_empty() {
        let graph = sample_graph();
        let radius = graph.blast_radius("metric:revenue.total");
        assert!(radius.downstream.is_empty());
        assert_eq!(radius.severity, Severity::None);
    }

    #[test]
    fn blast_radius_severity_is_the_max_over_downstream() {
        let graph = sample_graph();
        // The cube's downstream is a metric (semantic) + a dimension (compatibility) → semantic.
        assert_eq!(
            graph.blast_radius("cube:revenue").severity,
            Severity::Semantic
        );
        // A model whose only downstream is a view → structural (no metric reached).
        let structural = LineageGraph {
            nodes: vec![
                node("model:m", LineageKind::Model),
                node("view:v", LineageKind::View),
            ],
            edges: vec![edge("model:m", "view:v")],
        };
        assert_eq!(
            structural.blast_radius("model:m").severity,
            Severity::Structural
        );
    }

    #[test]
    fn consumer_nodes_are_semantic_severity() {
        // metric → query and metric → dashboard: hitting a consumer is a silent number shift for
        // the end user, so it classifies Semantic even with no further metric downstream.
        let graph = LineageGraph {
            nodes: vec![
                node("metric:revenue.total", LineageKind::Metric),
                node("query:monthly-revenue", LineageKind::Query),
                node("dashboard:exec-weekly", LineageKind::Dashboard),
            ],
            edges: vec![
                edge("metric:revenue.total", "query:monthly-revenue"),
                edge("metric:revenue.total", "dashboard:exec-weekly"),
            ],
        };
        let radius = graph.blast_radius("metric:revenue.total");
        assert_eq!(
            radius.downstream,
            vec![
                "dashboard:exec-weekly".to_string(),
                "query:monthly-revenue".to_string(),
            ],
            "a metric with consumers is no longer a leaf"
        );
        assert_eq!(radius.severity, Severity::Semantic);
    }

    #[test]
    fn lineage_diagnostics_default_to_empty() {
        let ctx = FakeContext {
            metrics: vec![],
            dimensions: vec![],
            models: vec![],
            lineage: LineageGraph::default(),
            parseable: true,
        };
        assert!(ctx.lineage_diagnostics().is_empty());
    }

    #[test]
    fn blast_radius_is_cycle_safe() {
        // A pathological cyclic graph must still terminate.
        let cyclic = LineageGraph {
            nodes: vec![node("a", LineageKind::Model), node("b", LineageKind::Model)],
            edges: vec![edge("a", "b"), edge("b", "a")],
        };
        let radius = cyclic.blast_radius("a");
        assert_eq!(radius.downstream, vec!["b".to_string()]);
    }

    #[test]
    fn severity_ordering() {
        assert!(Severity::Semantic > Severity::Structural);
        assert!(Severity::Structural > Severity::Compatibility);
        assert!(Severity::Compatibility > Severity::None);
    }
}