lemma-engine 0.9.0

A pure, declarative language for business rules.
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
//! Planning module integration tests (formerly `internal_tests` in `planning/mod.rs`).

use crate::engine::Context;
use crate::limits::ResourceLimits;
use crate::literals::DateGranularity;
use crate::parsing::ast::{
    DataValue, LemmaData, LemmaRepository, LemmaSpec, ParentType, Reference, Span,
};
use crate::parsing::parse;
use crate::parsing::source::Source;
use crate::planning::execution_plan::ExecutionPlan;
use crate::planning::plan;
use crate::planning::semantics::{DataPath, PathSegment, TypeDefiningSpec, TypeExtends};
use crate::Error;
use std::collections::HashMap;
use std::sync::Arc;

/// Test helper: plan a single spec and return its execution plan.
fn plan_single(
    main_spec: &LemmaSpec,
    all_specs: &[LemmaSpec],
) -> Result<ExecutionPlan, Vec<Error>> {
    let mut ctx = Context::new();
    let repository = ctx.workspace();
    for spec in all_specs {
        if let Err(e) = ctx.insert_spec(Arc::clone(&repository), spec.clone()) {
            return Err(vec![e]);
        }
    }
    let main_spec_arc = ctx
        .spec_set(&repository, main_spec.name.as_str())
        .and_then(|ss| ss.get_exact(main_spec.effective_from()).cloned())
        .expect("main_spec must be in all_specs");
    let result = plan(&ctx, &ResourceLimits::default());
    if !result.errors.is_empty() {
        return Err(result.errors);
    }
    let Some(plans) = result
        .plans
        .get_plans(repository.name.as_deref(), &main_spec_arc.name)
    else {
        return Err(vec![Error::validation(
            format!("No execution plan produced for spec '{}'", main_spec.name),
            Some(crate::planning::semantics::Source::new(
                crate::parsing::source::SourceType::Volatile,
                crate::planning::semantics::Span {
                    start: 0,
                    end: 0,
                    line: 1,
                    col: 0,
                },
            )),
            None::<String>,
        )]);
    };
    if plans.is_empty() {
        Err(vec![Error::validation(
            format!("No execution plan produced for spec '{}'", main_spec.name),
            Some(crate::planning::semantics::Source::new(
                crate::parsing::source::SourceType::Volatile,
                crate::planning::semantics::Span {
                    start: 0,
                    end: 0,
                    line: 1,
                    col: 0,
                },
            )),
            None::<String>,
        )])
    } else {
        Ok(plans.values().next().expect("plan").clone())
    }
}

#[test]
fn test_basic_validation() {
    let input = r#"spec person
data name: "John"
data age: 25
rule is_adult: age >= 18"#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        input.to_string(),
    );

    for spec in &specs {
        let result = plan_single(spec, &specs);
        assert!(
            result.is_ok(),
            "Basic validation should pass: {:?}",
            result.err()
        );
    }
}

#[test]
fn test_duplicate_data() {
    let input = r#"spec person
data name: "John"
data name: "Jane""#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        input.to_string(),
    );

    let result = plan_single(&specs[0], &specs);

    assert!(
        result.is_err(),
        "Duplicate data should cause validation error"
    );
    let errors = result.unwrap_err();
    let error_string = errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    assert!(
        error_string.contains("already used"),
        "Error should mention duplicate data: {}",
        error_string
    );
    assert!(error_string.contains("name"));
}

#[test]
fn mixed_type_range_literal_is_planning_error_not_panic() {
    let input = r#"spec demo
data x: 1 ... yes"#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let result = plan_single(&specs[0], &specs);

    let errors = result.expect_err("mixed-type range literal must be a planning error");
    assert_eq!(
        errors.len(),
        1,
        "expected exactly one planning error, got: {:?}",
        errors.iter().map(|e| e.to_string()).collect::<Vec<_>>()
    );
    let error_string = errors[0].to_string();
    assert!(
        error_string.contains(
            "range endpoints must have the same supported base type, got number and boolean"
        ),
        "unexpected error message: {}",
        error_string
    );
}

#[test]
fn text_range_literal_is_planning_error_not_panic() {
    let input = r#"spec demo
data x: "a" ... "b""#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let result = plan_single(&specs[0], &specs);

    let errors = result.expect_err("text range literal must be a planning error");
    assert_eq!(
        errors.len(),
        1,
        "expected exactly one planning error, got: {:?}",
        errors.iter().map(|e| e.to_string()).collect::<Vec<_>>()
    );
    let error_string = errors[0].to_string();
    assert!(
        error_string
            .contains("range endpoints must have the same supported base type, got text and text"),
        "unexpected error message: {}",
        error_string
    );
}

#[test]
fn qualified_type_from_spec_with_type_errors_is_planning_error_not_panic() {
    let input = r#"spec b
data money: number -> minimum 10 -> maximum 5

spec a
uses b
data x: b.money"#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let result = plan_single(&specs[0], &specs);

    let errors = result.expect_err("failing import target must be a planning error");
    let error_string = errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    assert!(
        error_string.contains("minimum"),
        "expected the import target's own type error to be reported: {}",
        error_string
    );
    assert!(
        error_string.contains(
            "Cannot resolve type 'money' from spec 'b' (via import 'b'): spec 'b' failed type resolution"
        ),
        "expected the consumer's qualified type resolution error to be reported: {}",
        error_string
    );
}

#[test]
fn test_duplicate_rules() {
    let input = r#"spec person
data age: 25
rule is_adult: age >= 18
rule is_adult: age >= 21"#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        input.to_string(),
    );

    let result = plan_single(&specs[0], &specs);

    assert!(
        result.is_err(),
        "Duplicate rules should cause validation error"
    );
    let errors = result.unwrap_err();
    let error_string = errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    assert!(
        error_string.contains("Duplicate rule"),
        "Error should mention duplicate rule: {}",
        error_string
    );
    assert!(error_string.contains("is_adult"));
}

#[test]
fn test_circular_dependency() {
    let input = r#"spec test
rule a: b
rule b: a"#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        input.to_string(),
    );

    let result = plan_single(&specs[0], &specs);

    assert!(
        result.is_err(),
        "Circular dependency should cause validation error"
    );
    let errors = result.unwrap_err();
    let error_string = errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    assert!(error_string.contains("Circular dependency") || error_string.contains("circular"));
}

#[test]
fn test_multiple_specs() {
    let input = r#"spec person
data name: "John"
data age: 25

spec company
data name: "Acme Corp"
uses employee: person"#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        input.to_string(),
    );

    let result = plan_single(&specs[0], &specs);

    assert!(
        result.is_ok(),
        "Multiple specs should validate successfully: {:?}",
        result.err()
    );
}

#[test]
fn test_invalid_spec_reference() {
    let input = r#"spec person
data name: "John"
uses contract: nonexistent"#;

    let specs: Vec<_> = parse(
        input,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        input.to_string(),
    );

    let result = plan_single(&specs[0], &specs);

    assert!(
        result.is_err(),
        "Invalid spec reference should cause validation error"
    );
    let errors = result.unwrap_err();
    let error_string = errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    assert!(
        error_string.contains("not found")
            || error_string.contains("Spec")
            || (error_string.contains("nonexistent") && error_string.contains("depends")),
        "Error should mention spec reference issue: {}",
        error_string
    );
    assert!(error_string.contains("nonexistent"));
}

#[test]
fn test_definition_empty_base_returns_lemma_error() {
    let mut spec = LemmaSpec::new("test".to_string());
    let source = Source::new(
        crate::parsing::source::SourceType::Volatile,
        Span {
            start: 0,
            end: 10,
            line: 1,
            col: 0,
        },
    );
    spec.data.push(LemmaData::new(
        Reference {
            segments: vec![],
            name: "x".to_string(),
        },
        DataValue::Definition {
            base: Some(ParentType::Custom {
                name: String::new(),
            }),
            constraints: None,
            value: None,
        },
        source,
    ));

    let specs = vec![spec.clone()];
    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        "spec test\ndata x:".to_string(),
    );

    let result = plan_single(&spec, &specs);
    assert!(
        result.is_err(),
        "Definition with empty base should fail planning"
    );
    let errors = result.unwrap_err();
    let combined = errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        combined.contains("Unknown parent ''"),
        "Error should mention empty/unknown type; got: {}",
        combined
    );
}

#[test]
fn test_data_binding_with_custom_type_resolves_in_correct_spec_context() {
    // This is a planning-level test: ensure data bindings resolve custom types correctly
    // when the type is defined in a different spec than the binding.
    //
    // spec one:
    //   data money: number
    //   data x: money
    // spec two:
    //   with one
    //   with one.x: 7
    //   rule getx: one.x
    let code = r#"
spec one
data money: number
data x: money

spec two
uses one
with one.x: 7
rule getx: one.x
"#;

    let specs = parse(
        code,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();
    let spec_two = specs.iter().find(|d| d.name == "two").unwrap();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        code.to_string(),
    );
    let execution_plan = plan_single(spec_two, &specs).expect("planning should succeed");

    // Verify that one.x keeps its declared custom type name while resolving in spec one.
    let one_x_path = DataPath {
        segments: vec![PathSegment {
            data: "one".to_string(),
            spec: "one".to_string(),
        }],
        data: "x".to_string(),
    };

    let one_x_type = execution_plan
        .data
        .get(&one_x_path)
        .and_then(|d| d.schema_type())
        .expect("one.x should have a resolved type");

    assert_eq!(
        one_x_type.name(),
        "x",
        "one.x should have declared type 'x', got: {}",
        one_x_type.name()
    );
    assert!(one_x_type.is_number(), "money should be number-based");
}

#[test]
fn test_data_definition_from_spec_has_import_defining_spec() {
    let code = r#"
spec examples
data money: measure
  -> unit eur 1.00

spec checkout
uses examples
data money: measure
  -> unit eur 1.00
data local_price: money
data imported_price: examples.money
"#;

    let specs = parse(
        code,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut ctx = Context::new();
    let repository = ctx.workspace();
    for spec in &specs {
        ctx.insert_spec(Arc::clone(&repository), spec.clone())
            .expect("insert spec");
    }

    let checkout_arc = ctx
        .spec_set(&repository, "checkout")
        .and_then(|ss| ss.get_exact(None).cloned())
        .expect("checkout spec should be present");

    let result = plan(&ctx, &ResourceLimits::default());
    assert!(
        result.errors.is_empty(),
        "No checkout planning errors expected, got: {:?}",
        result.errors
    );
    let checkout_plans = result
        .plans
        .get_plans(repository.name.as_deref(), &checkout_arc.name)
        .expect("checkout result should exist");
    assert!(
        !checkout_plans.is_empty(),
        "checkout should produce at least one plan"
    );
    let execution_plan = checkout_plans.values().next().expect("checkout plan");

    let local_type = execution_plan
        .data
        .get(&DataPath::new(vec![], "local_price".to_string()))
        .and_then(|d| d.schema_type())
        .expect("local_price should have schema type");
    let imported_type = execution_plan
        .data
        .get(&DataPath::new(vec![], "imported_price".to_string()))
        .and_then(|d| d.schema_type())
        .expect("imported_price should have schema type");

    match &local_type.extends {
        TypeExtends::Custom {
            defining_spec: TypeDefiningSpec::Local,
            ..
        } => {}
        other => panic!(
            "local_price should resolve as local defining_spec, got {:?}",
            other
        ),
    }

    match &imported_type.extends {
        TypeExtends::Custom {
            defining_spec: TypeDefiningSpec::Import,
            ..
        } => {}
        other => panic!(
            "imported_price should resolve as import defining_spec, got {:?}",
            other
        ),
    }
}

#[test]
fn test_plan_with_registry_grouped_specs() {
    let source = r#"spec somespec
data quantity: 10

spec example
uses inventory: somespec
rule total_measure: inventory.quantity"#;

    let parsed = parse(
        source,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap();
    assert_eq!(parsed.flatten_specs().len(), 2);

    let mut ctx = Context::new();
    let repository = Arc::new(
        LemmaRepository::new(Some("@user/workspace".to_string()))
            .with_dependency("@user/workspace")
            .with_start_line(1)
            .with_source_type(crate::parsing::source::SourceType::Volatile),
    );
    for spec in parsed.flatten_specs() {
        ctx.insert_spec(Arc::clone(&repository), spec.clone())
            .expect("insert spec");
    }

    let result = plan(&ctx, &ResourceLimits::default());
    assert!(
        result.errors.is_empty(),
        "Planning under registry-scoped specs should succeed: {:?}",
        result.errors
    );
    let example_set = result
        .plans
        .get_plans(repository.name.as_deref(), "example")
        .expect("example result must exist");
    assert!(
        !example_set.is_empty(),
        "expected at least one plan for registry-grouped example"
    );
}

#[test]
fn test_multiple_independent_errors_are_all_reported() {
    // A spec referencing a non-existing import AND a non-existing
    // spec should report errors for BOTH, not just stop at the first.
    let source = r#"spec demo
uses type_src: nonexistent_type_source
with type_src.amount: 10
uses helper: nonexistent_spec
data price: 10
rule total: helper.value + price"#;

    let specs = parse(
        source,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        source.to_string(),
    );

    let result = plan_single(&specs[0], &specs);
    assert!(result.is_err(), "Planning should fail with multiple errors");

    let errors = result.unwrap_err();
    let all_messages: Vec<String> = errors.iter().map(|e| e.to_string()).collect();
    let combined = all_messages.join("\n");

    assert!(
        combined.contains("nonexistent_type_source"),
        "Should report import error for 'nonexistent_type_source'. Got:\n{}",
        combined
    );

    // Must also report the spec reference error (not just the import error)
    assert!(
        combined.contains("nonexistent_spec"),
        "Should report spec reference error for 'nonexistent_spec'. Got:\n{}",
        combined
    );

    // Should have at least 2 distinct kinds of errors (import + spec ref)
    assert!(
        errors.len() >= 2,
        "Expected at least 2 errors, got {}: {}",
        errors.len(),
        combined
    );

    let data_import_err = errors
        .iter()
        .find(|e| e.to_string().contains("nonexistent_type_source"))
        .expect("import error");
    let loc = data_import_err
        .location()
        .expect("import error should carry source location");
    assert_eq!(
        loc.source_type,
        crate::parsing::source::SourceType::Volatile
    );
    assert_ne!(
        (loc.span.start, loc.span.end),
        (0, 0),
        "import error span should not be empty"
    );
}

#[test]
fn test_type_error_does_not_suppress_cross_spec_data_error() {
    // When a import fails, errors about cross-spec data references
    // (e.g. ext.some_data where ext is a spec ref to a non-existing spec)
    // must still be reported.
    let source = r#"spec demo
uses cur: missing_spec
with cur.currency: 10
uses ext: also_missing
rule val: ext.some_data"#;

    let specs = parse(
        source,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut sources = HashMap::new();
    sources.insert(
        crate::parsing::source::SourceType::Volatile,
        source.to_string(),
    );

    let result = plan_single(&specs[0], &specs);
    assert!(result.is_err());

    let errors = result.unwrap_err();
    let combined: String = errors
        .iter()
        .map(|e| e.to_string())
        .collect::<Vec<_>>()
        .join("\n");

    assert!(
        combined.contains("missing_spec"),
        "Should report import error about 'missing_spec'. Got:\n{}",
        combined
    );

    // The spec reference error about 'also_missing' should ALSO be reported
    assert!(
        combined.contains("also_missing"),
        "Should report error about 'also_missing'. Got:\n{}",
        combined
    );
}

#[test]
fn test_spec_dag_orders_dep_before_consumer() {
    let source = r#"spec dep 2025-01-01
data money: number
data x: money

spec consumer 2025-01-01
uses dep
data imported_amount: dep.money
rule passthrough: imported_amount"#;
    let specs = parse(
        source,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut ctx = Context::new();
    let repository = ctx.workspace();
    for spec in &specs {
        ctx.insert_spec(Arc::clone(&repository), spec.clone())
            .expect("insert spec");
    }

    let dt = crate::DateTimeValue {
        year: 2025,
        month: 1,
        day: 1,
        hour: 0,
        minute: 0,
        second: 0,
        microsecond: 0,
        timezone: None,
        granularity: DateGranularity::Full,
    };
    let effective = crate::parsing::ast::EffectiveDate::DateTimeValue(dt);
    let consumer_arc = ctx
        .spec_set(&repository, "consumer")
        .and_then(|ss| ss.spec_at(&effective))
        .expect("consumer spec");
    let ordered_dependencies = crate::planning::discovery::discover_dependency_order(
        &ctx,
        consumer_arc,
        &effective,
        &crate::ResourceLimits::default(),
    )
    .expect("dependency order should succeed");
    let ordered_names: Vec<String> = ordered_dependencies
        .iter()
        .map(|s| s.spec.name.clone())
        .collect();
    let dep_idx = ordered_names
        .iter()
        .position(|n| n == "dep")
        .expect("dep must exist");
    let consumer_idx = ordered_names
        .iter()
        .position(|n| n == "consumer")
        .expect("consumer must exist");
    assert!(
        dep_idx < consumer_idx,
        "dependency must be planned before dependent. order={:?}",
        ordered_names
    );
}

#[test]
fn test_spec_dependency_cycle_surfaces_as_spec_error_and_populates_results() {
    let source = r#"spec a 2025-01-01
uses dep_b: b
data amount: number

spec b 2025-01-01
uses src_a: a
data imported_value: src_a.amount
"#;
    let specs = parse(
        source,
        crate::parsing::source::SourceType::Volatile,
        &ResourceLimits::default(),
    )
    .unwrap()
    .into_flattened_specs();

    let mut ctx = Context::new();
    let repository = ctx.workspace();
    for spec in &specs {
        ctx.insert_spec(Arc::clone(&repository), spec.clone())
            .expect("insert spec");
    }

    let result = plan(&ctx, &ResourceLimits::default());

    let spec_errors: Vec<String> = result.errors.iter().map(|e| e.to_string()).collect();
    assert!(
        spec_errors
            .iter()
            .any(|e| e.contains("Spec dependency cycle")),
        "expected cycle error on spec, got: {spec_errors:?}",
    );

    assert!(
        result
            .plans
            .get_plans(repository.name.as_deref(), "b")
            .is_none_or(|plans| plans.is_empty()),
        "cyclic spec 'b' must not install compiled plans"
    );
}