cim-kit 0.6.0

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
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
//! Difference models (IEC 61970-552 `dm:DifferenceModel`).
//!
//! A difference model expresses a change to a previously exchanged model as a set of
//! statements to retract followed by a set to assert. The corpus ships real ones, so the
//! tests below exercise the published form rather than a synthetic approximation.

#![cfg(feature = "cgmes3")]

mod common;

use cim_kit::cgmes3::{SCHEMA, attributes as attrs};
use cim_kit::diff::DiffOptions;
use cim_kit::header::StatementValue;
use cim_kit::prelude::*;

/// Every value of a model, in a form two datasets can be compared by.
fn projection(ds: &Dataset) -> std::collections::BTreeMap<String, Vec<String>> {
    let mut out = std::collections::BTreeMap::new();
    for (_, o) in ds.iter() {
        let mut values: Vec<String> = o
            .values()
            .map(|(a, v)| {
                format!(
                    "{}={}",
                    SCHEMA.attr(a).name,
                    cim_kit::value::display_value(SCHEMA, v)
                )
            })
            .collect();
        values.sort();
        out.insert(
            format!("{} {}", SCHEMA.class(o.class()).name, o.mrid()),
            values,
        );
    }
    out
}

#[test]
fn reads_a_published_difference_model() {
    let dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS-EQ_diff"
    ));
    let files = common::xml_files(&dir);
    let path = files.first().expect("a diff file");

    let file = std::fs::File::open(path).unwrap();
    let diff = cim_kit::reader::read_difference(
        SCHEMA,
        std::io::BufReader::new(file),
        path.file_name().and_then(|n| n.to_str()),
        &ReadOptions::default(),
    )
    .unwrap()
    .expect("document declares a dm:DifferenceModel");

    println!(
        "difference: {} reverse, {} forward statements, {} objects affected",
        diff.reverse.len(),
        diff.forward.len(),
        diff.affected_objects().len()
    );
    assert!(
        !diff.reverse.is_empty() || !diff.forward.is_empty(),
        "difference model carried no statements"
    );

    // The header must survive: it declares what the difference supersedes.
    assert_eq!(diff.header.kind, cim_kit::ModelKind::Difference);
    assert!(
        !diff.header.supersedes.is_empty(),
        "a difference model names the model it supersedes"
    );
    assert!(!diff.header.profiles.is_empty());

    // Every statement must name a resolvable predicate.
    for s in diff.reverse.iter().chain(&diff.forward) {
        assert!(
            SCHEMA.find_attr(&s.predicate_ns, &s.predicate).is_some(),
            "unknown predicate {} in {}",
            s.predicate,
            s.predicate_ns
        );
    }
}

#[test]
fn applying_a_difference_changes_the_model_and_reverses_cleanly() {
    let base_dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS"
    ));
    let diff_dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS-EQ_diff"
    ));

    let mut ds = Dataset::new(SCHEMA);
    ds.load_files(common::xml_files(&base_dir), &ReadOptions::lenient())
        .unwrap();

    let diff_path = common::xml_files(&diff_dir).remove(0);
    let diff = cim_kit::reader::read_difference(
        SCHEMA,
        std::io::BufReader::new(std::fs::File::open(&diff_path).unwrap()),
        None,
        &ReadOptions::default(),
    )
    .unwrap()
    .unwrap();

    // Record the values the difference is going to touch.
    let before: Vec<(Mrid, String, Option<String>)> = diff
        .forward
        .iter()
        .filter_map(|s| {
            let attr = SCHEMA.find_attr(&s.predicate_ns, &s.predicate)?;
            let obj = ds.by_mrid(&s.subject)?;
            Some((
                s.subject.clone(),
                s.predicate.clone(),
                obj.get(attr)
                    .map(|v| cim_kit::value::display_value(SCHEMA, v)),
            ))
        })
        .collect();

    let report = ds.apply_difference(&diff);
    println!(
        "applied difference: {} diagnostics ({} errors)",
        report.len(),
        report.count(Severity::Error)
    );
    assert!(!report.has_errors(), "{report}");

    // Every forward statement must now be reflected in the model.
    let mut changed = 0;
    for s in &diff.forward {
        let Some(attr) = SCHEMA.find_attr(&s.predicate_ns, &s.predicate) else {
            continue;
        };
        let obj = ds
            .by_mrid(&s.subject)
            .unwrap_or_else(|| panic!("{} absent after applying difference", s.subject));
        let stored = obj
            .get(attr)
            .map(|v| cim_kit::value::display_value(SCHEMA, v))
            .expect("forward statement must be asserted");
        // Compare in the same normalized form the library stores: references become
        // canonical mRIDs, enumeration IRIs become their qualified literal name, and
        // numbers are compared numerically since parsing normalizes their lexical form.
        let expected = match &s.value {
            StatementValue::Literal(t) => t.trim().to_owned(),
            StatementValue::Resource(iri) => match SCHEMA.attr(attr).kind {
                cim_kit::schema::AttrKind::Enumeration(_) => iri
                    .rsplit_once('#')
                    .map(|(_, l)| l.to_owned())
                    .unwrap_or_else(|| iri.clone()),
                _ => Mrid::parse(iri).canonical(),
            },
        };
        let matches = stored == expected
            || match (stored.parse::<f64>(), expected.parse::<f64>()) {
                (Ok(a), Ok(b)) => (a - b).abs() < 1e-9,
                _ => false,
            };
        assert!(
            matches,
            "{}.{}: stored {stored:?} != {expected:?}",
            s.subject, s.predicate
        );
        changed += 1;
    }
    assert!(changed > 0, "difference asserted nothing");
    println!("{changed} forward statements verified in the model");

    // At least one value must genuinely differ from the base model, otherwise the test
    // would pass on a no-op difference.
    let differing = before
        .iter()
        .filter(|(mrid, pred, old)| {
            let attr = SCHEMA
                .find_attr("http://iec.ch/TC57/CIM100#", pred)
                .or_else(|| SCHEMA.find_attr("http://iec.ch/TC57/CIM100-European#", pred));
            match (attr, ds.by_mrid(mrid)) {
                (Some(a), Some(o)) => {
                    o.get(a).map(|v| cim_kit::value::display_value(SCHEMA, v)) != *old
                }
                _ => false,
            }
        })
        .count();
    println!("{differing} values actually changed");
    assert!(differing > 0, "difference did not modify any value");
}

#[test]
fn reverse_statements_retract_values() {
    // A synthetic difference exercises retraction precisely, which the published diffs
    // do only incidentally.
    let doc = r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <md:FullModel rdf:about="urn:uuid:11111111-1111-4111-8111-111111111111">
    <md:Model.profile>http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0</md:Model.profile>
  </md:FullModel>
  <cim:ACLineSegment rdf:ID="_22222222-2222-4222-8222-222222222222">
    <cim:IdentifiedObject.name>Line A</cim:IdentifiedObject.name>
    <cim:ACLineSegment.r>1.5</cim:ACLineSegment.r>
  </cim:ACLineSegment>
</rdf:RDF>"##;

    let diff_doc = r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#"
         xmlns:dm="http://iec.ch/TC57/61970-552/DifferenceModel/1#"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#"
         xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <dm:DifferenceModel rdf:about="urn:uuid:33333333-3333-4333-8333-333333333333">
    <md:Model.profile>http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0</md:Model.profile>
    <md:Model.Supersedes rdf:resource="urn:uuid:11111111-1111-4111-8111-111111111111"/>
    <dm:reverseDifferences rdf:parseType="Statements">
      <rdf:Description rdf:about="#_22222222-2222-4222-8222-222222222222">
        <cim:ACLineSegment.r>1.5</cim:ACLineSegment.r>
      </rdf:Description>
    </dm:reverseDifferences>
    <dm:forwardDifferences rdf:parseType="Statements">
      <rdf:Description rdf:about="#_22222222-2222-4222-8222-222222222222">
        <cim:ACLineSegment.r>2.75</cim:ACLineSegment.r>
      </rdf:Description>
    </dm:forwardDifferences>
  </dm:DifferenceModel>
</rdf:RDF>"##;

    let mut ds = Dataset::new(SCHEMA);
    cim_kit::reader::read_into(
        &mut ds,
        doc.as_bytes(),
        Some("base.xml"),
        &ReadOptions::strict(),
    )
    .unwrap();

    let r_attr = SCHEMA
        .find_attr("http://iec.ch/TC57/CIM100#", "ACLineSegment.r")
        .unwrap();
    let subject = Mrid::parse("22222222-2222-4222-8222-222222222222");
    assert_eq!(
        ds.by_mrid(&subject).unwrap().get(r_attr).unwrap().as_f64(),
        Some(1.5)
    );

    let diff = cim_kit::reader::read_difference(
        SCHEMA,
        diff_doc.as_bytes(),
        Some("diff.xml"),
        &ReadOptions::default(),
    )
    .unwrap()
    .unwrap();
    assert_eq!(diff.reverse.len(), 1);
    assert_eq!(diff.forward.len(), 1);

    let report = ds.apply_difference(&diff);
    assert!(!report.has_errors(), "{report}");

    // The old value was retracted and the new one asserted — exactly one remains.
    let obj = ds.by_mrid(&subject).unwrap();
    assert_eq!(obj.count(r_attr), 1, "retraction left a stale value behind");
    assert_eq!(obj.get(r_attr).unwrap().as_f64(), Some(2.75));
}

// ---------------------------------------------------------------------------
// Computing a difference
// ---------------------------------------------------------------------------

/// The property that makes a computed change set worth anything: applying it works.
///
/// `base.difference_to(&target)` is only correct if feeding the result back through
/// `apply_difference` turns the base into the target — every value present, none left over,
/// classes included. Anything less and the change set is a plausible-looking document that
/// silently loses data, which is the failure mode a hand-checked example would not catch.
#[test]
fn a_computed_difference_turns_the_base_into_the_target() {
    let base_dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS"
    ));
    let diff_dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS-EQ_diff"
    ));

    // Build a genuinely different target by applying a published change set to the base.
    let mut base = Dataset::new(SCHEMA);
    base.load_files(common::xml_files(&base_dir), &ReadOptions::lenient())
        .unwrap();
    let mut target = Dataset::new(SCHEMA);
    target
        .load_files(common::xml_files(&base_dir), &ReadOptions::lenient())
        .unwrap();
    let published = cim_kit::reader::read_difference(
        SCHEMA,
        std::io::BufReader::new(std::fs::File::open(&common::xml_files(&diff_dir)[0]).unwrap()),
        None,
        &ReadOptions::default(),
    )
    .unwrap()
    .unwrap();
    assert!(!target.apply_difference(&published).has_errors());
    assert_ne!(
        projection(&base),
        projection(&target),
        "the two models must actually differ"
    );

    // Now recover the change from the two states, and check it reproduces the target.
    let computed = base.difference_to(&target, &DiffOptions::default());
    println!(
        "computed: {} reverse, {} forward ({} added, {} removed, {} changed)",
        computed.model.reverse.len(),
        computed.model.forward.len(),
        computed.added,
        computed.removed,
        computed.changed
    );
    assert!(!computed.is_empty(), "no change was detected");
    assert!(!computed.report.has_errors(), "{}", computed.report);

    let report = base.apply_difference(&computed.model);
    assert!(!report.has_errors(), "{report}");
    assert_eq!(
        projection(&base),
        projection(&target),
        "applying the computed difference did not reproduce the target"
    );

    // And a model differs from itself by nothing at all.
    let none = target.difference_to(&target, &DiffOptions::default());
    assert!(none.is_empty(), "a model differs from itself");
}

/// Additions, removals, edits, repeated values and a class change, each on purpose.
#[test]
fn a_computed_difference_covers_every_kind_of_change() {
    use cim_kit::cgmes3::{attributes as attrs, classes};
    use cim_kit::object::Object;
    use cim_kit::value::Value;

    let a = Mrid::parse("11111111-1111-4111-8111-111111111111");
    let b = Mrid::parse("22222222-2222-4222-8222-222222222222");
    let c = Mrid::parse("33333333-3333-4333-8333-333333333333");

    let mut base = Dataset::new(SCHEMA);
    // `a`: an attribute will change. `b`: the object goes away. `c` is not there yet.
    let mut o = Object::new(classes::ACLineSegment, a.clone());
    o.set(attrs::identified_object::name, Value::Text("L".into()));
    o.set(attrs::ac_line_segment::r, Value::from(1.5));
    base.insert(o);
    let mut o = Object::new(classes::Breaker, b.clone());
    o.set(attrs::identified_object::name, Value::Text("BR".into()));
    base.insert(o);

    let mut target = Dataset::new(SCHEMA);
    let mut o = Object::new(classes::ACLineSegment, a.clone());
    o.set(attrs::identified_object::name, Value::Text("L".into()));
    o.set(attrs::ac_line_segment::r, Value::from(2.75));
    target.insert(o);
    let mut o = Object::new(classes::Disconnector, c.clone());
    o.set(attrs::identified_object::name, Value::Text("DS".into()));
    target.insert(o);

    let d = base.difference_to(&target, &DiffOptions::default());
    assert_eq!((d.added, d.removed, d.changed), (1, 1, 1));

    // The change set must survive a trip through the serialized form, because that is how
    // it is actually delivered.
    let mut xml = Vec::new();
    cim_kit::writer::write_difference(SCHEMA, &d.model, &mut xml, &Default::default()).unwrap();
    let xml = String::from_utf8(xml).unwrap();
    common::assert_well_formed("computed difference", &xml);
    let reread =
        cim_kit::reader::read_difference(SCHEMA, xml.as_bytes(), None, &ReadOptions::default())
            .unwrap()
            .expect("a dm:DifferenceModel");

    let report = base.apply_difference(&reread);
    assert!(!report.has_errors(), "{report}");
    // The removed object is left as an empty shell — 61970-552 has no "delete" statement.
    assert!(base.by_mrid(&b).is_some_and(|o| o.is_empty()));
    assert_eq!(base.prune_empty(), 1);
    assert_eq!(projection(&base), projection(&target));
}

/// A change set restricted to a profile carries that profile's values and no others.
#[test]
fn a_computed_difference_can_be_restricted_to_one_profile() {
    let base_dir = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS"
    ));
    let files = common::xml_files(&base_dir);

    let mut base = Dataset::new(SCHEMA);
    base.load_files(&files, &ReadOptions::lenient()).unwrap();
    let mut target = Dataset::new(SCHEMA);
    target.load_files(&files, &ReadOptions::lenient()).unwrap();

    // Change one Steady State Hypothesis value.
    let ssh = SCHEMA.profile_by_keyword("SSH").unwrap();
    let eq = SCHEMA.profile_by_keyword("EQ").unwrap();
    let attr = SCHEMA
        .find_attr("http://iec.ch/TC57/CIM100#", "RotatingMachine.p")
        .unwrap();
    let victim = target
        .iter()
        .find(|(_, o)| o.has(attr))
        .map(|(id, _)| id)
        .expect("the model sets RotatingMachine.p");
    let old = target
        .get(victim)
        .unwrap()
        .get(attr)
        .unwrap()
        .as_f64()
        .unwrap();
    target
        .get_mut(victim)
        .unwrap()
        .set_in(ssh.mask(), attr, cim_kit::Value::from(old + 1.0));

    let in_ssh = base.difference_to(&target, &DiffOptions::default().profiles(ssh.mask()));
    assert!(
        !in_ssh.is_empty(),
        "the SSH change is missing from an SSH diff"
    );

    let in_eq = base.difference_to(&target, &DiffOptions::default().profiles(eq.mask()));
    assert!(
        in_eq.is_empty(),
        "an SSH-only change leaked into an Equipment change set: {} statements",
        in_eq.model.forward.len()
    );
}

/// A change file re-exported as itself, even when its header carries no identifier.
///
/// `save_as_loaded` reproduces the file set a model was read from, and a change file holds
/// statements rather than objects, so they have to be matched back to the header. The
/// header's identifier is the obvious key and is not enough: `md:DifferenceModel` without an
/// `rdf:about` is a defect the reader tolerates (`CIM0013`), and matching on identifier
/// alone drops such a file from the export.
#[test]
fn a_change_file_without_an_identifier_is_still_re_exported() {
    const NS: &str = "http://iec.ch/TC57/CIM100#";
    const SUBJECT: &str = "22222222-2222-4222-8222-222222222222";
    let change = format!(
        r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cim="{NS}"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#"
         xmlns:dm="http://iec.ch/TC57/61970-552/DifferenceModel/1#">
  <dm:DifferenceModel>
    <md:Model.profile>http://iec.ch/TC57/ns/CIM/SteadyStateHypothesis-EU/3.0</md:Model.profile>
    <dm:forwardDifferences rdf:parseType="Statements">
      <rdf:Description rdf:about="#_{SUBJECT}">
        <cim:Equipment.inService>true</cim:Equipment.inService>
      </rdf:Description>
    </dm:forwardDifferences>
  </dm:DifferenceModel>
</rdf:RDF>
"##
    );
    let dir = std::env::temp_dir().join(format!("cim-diff-export-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("in")).unwrap();
    std::fs::write(dir.join("in/change_DIFF.xml"), change).unwrap();

    let ds = Dataset::load_dir(SCHEMA, dir.join("in")).unwrap();
    assert_eq!(ds.differences().len(), 1);
    assert!(
        ds.headers()[0].id.is_none(),
        "this test is about a header with no identifier"
    );

    let saved = ds.save_as_loaded(&dir.join("out")).unwrap();
    assert!(
        saved.skipped.is_empty(),
        "the change file was dropped: {:?}",
        saved.skipped
    );
    assert_eq!(saved.written.len(), 1, "{saved:?}");

    let text = std::fs::read_to_string(&saved.written[0]).unwrap();
    common::assert_well_formed("re-exported change file", &text);
    assert!(text.contains("dm:forwardDifferences"), "{text}");
    assert!(text.contains("Equipment.inService"), "{text}");
    // Re-reading it gives the statement back.
    let again = Dataset::load_dir(SCHEMA, dir.join("out")).unwrap();
    assert_eq!(again.differences().len(), 1);
    assert_eq!(again.differences()[0].forward.len(), 1);

    let _ = std::fs::remove_dir_all(&dir);
}

/// Both limits of the statement syntax are reported, not just the one that was.
///
/// A changed compound has always produced a diagnostic. Deletion — the other thing
/// `rdf:parseType="Statements"` cannot express — was only counted, so a caller who applied
/// a computed change set and compared content identifiers found an object that was empty
/// rather than absent, with nothing in the report to say why.
#[test]
fn a_difference_says_that_it_cannot_delete_an_object() {
    let id = Mrid::parse("51515151-5151-4151-8151-515151515151");
    let mut base = Dataset::new(SCHEMA);
    let mut going = Object::new(cim_kit::cgmes3::classes::Substation, id.clone());
    going.set(
        cim_kit::cgmes3::attributes::identified_object::name,
        Value::from("gone"),
    );
    base.insert(going);

    let target = Dataset::new(SCHEMA);
    let change = base.difference_to(&target, &Default::default());

    assert_eq!(change.removed, 1);
    let said: Vec<String> = change.report.iter().map(|d| d.to_string()).collect();
    assert!(
        said.iter().any(|s| s.contains("cannot say so")),
        "the deletion limit went unreported: {said:?}"
    );

    // And the reason it is worth saying: applying leaves a shell behind.
    base.apply_difference(&change.model);
    let left = base.by_mrid(&id).expect("the identifier remains");
    assert!(left.is_empty(), "the object should have been emptied");
    assert_ne!(base.content_id(), target.content_id());
    // Which `prune_empty` is for.
    base.prune_empty();
    assert!(base.by_mrid(&id).is_none());
}

// ---------------------------------------------------------------------------
// A change set knows what it changes
// ---------------------------------------------------------------------------

fn read_change(text: &str) -> cim_kit::header::DifferenceModel {
    cim_kit::reader::read_difference(
        SCHEMA,
        text.as_bytes(),
        Some("change.xml"),
        &ReadOptions::default(),
    )
    .unwrap()
    .expect("a dm:DifferenceModel")
}

fn read_change_file(path: &std::path::Path) -> cim_kit::header::DifferenceModel {
    let file = std::io::BufReader::new(std::fs::File::open(path).unwrap());
    cim_kit::reader::read_difference(SCHEMA, file, None, &ReadOptions::default())
        .unwrap()
        .expect("a dm:DifferenceModel")
}

fn loaded(dir: &std::path::Path) -> Dataset {
    let mut ds = Dataset::new(SCHEMA);
    ds.load_files(common::xml_files(dir), &ReadOptions::lenient())
        .unwrap();
    ds
}

fn refused(report: &cim_kit::Report) -> bool {
    report.by_rule(cim_kit::Rule::UnsatisfiedDependency).count() == 1 && report.len() == 1
}

/// A one-object EQ document whose header has identifier `model`.
fn model_doc(model: &str, r: &str) -> String {
    format!(
        r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#">
  <md:FullModel rdf:about="urn:uuid:{model}">
    <md:Model.profile>http://iec.ch/TC57/ns/CIM/CoreEquipment-EU/3.0</md:Model.profile>
  </md:FullModel>
  <cim:ACLineSegment rdf:ID="_aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa">
    <cim:ACLineSegment.r>{r}</cim:ACLineSegment.r>
  </cim:ACLineSegment>
</rdf:RDF>"##
    )
}

fn model(model: &str, r: &str) -> Dataset {
    let mut ds = Dataset::new(SCHEMA);
    cim_kit::reader::read_into(
        &mut ds,
        model_doc(model, r).as_bytes(),
        Some("EQ.xml"),
        &ReadOptions::default(),
    )
    .unwrap();
    ds
}

/// A change set setting `r` from `from` to `to`, superseding `base`, with `precondition`
/// (a value of `r` that must hold) if given.
fn change(base: &str, from: &str, to: &str, precondition: Option<&str>) -> String {
    let pre = precondition.map_or(String::new(), |p| {
        format!(
            r##"<rdf:Description rdf:about="#_aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"><cim:ACLineSegment.r>{p}</cim:ACLineSegment.r></rdf:Description>"##
        )
    });
    format!(
        r##"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#" xmlns:dm="http://iec.ch/TC57/61970-552/DifferenceModel/1#">
  <dm:DifferenceModel rdf:about="urn:uuid:cccccccc-cccc-4ccc-8ccc-cccccccccccc">
    <md:Model.Supersedes rdf:resource="urn:uuid:{base}"/>
    <dm:preconditions rdf:parseType="Statements">{pre}</dm:preconditions>
    <dm:reverseDifferences rdf:parseType="Statements">
      <rdf:Description rdf:about="#_aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"><cim:ACLineSegment.r>{from}</cim:ACLineSegment.r></rdf:Description>
    </dm:reverseDifferences>
    <dm:forwardDifferences rdf:parseType="Statements">
      <rdf:Description rdf:about="#_aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"><cim:ACLineSegment.r>{to}</cim:ACLineSegment.r></rdf:Description>
    </dm:forwardDifferences>
  </dm:DifferenceModel>
</rdf:RDF>"##
    )
}

const BASE: &str = "11111111-1111-4111-8111-111111111111";
const OTHER: &str = "22222222-2222-4222-8222-222222222222";

/// The published NL Equipment change set, applied to the BE model set by mistake, used to be
/// applied anyway — retractions failing as warnings, assertions making objects from nothing.
/// It is refused before anything changes; against its own base it applies, and once
/// applied, its base is no longer the state the dataset holds, so it cannot apply twice.
#[test]
fn a_published_change_set_applies_to_its_base_and_to_nothing_else() {
    let nl = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS"
    ));
    let be = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-BE-MAS"
    ));
    let change = require_corpus!(common::cgmes3_model(
        "MicroGrid/MicroGid-BaseCase/MicroGrid-NL-MAS-EQ_diff"
    ));
    let diff = read_change_file(&common::xml_files(&change)[0]);

    let mut wrong = loaded(&be);
    let before = projection(&wrong);
    let report = wrong.apply_difference(&diff);
    assert!(refused(&report), "{report}");
    assert!(
        report.to_string().contains("87da6373"),
        "names what it supersedes: {report}"
    );
    assert_eq!(projection(&wrong), before, "nothing was applied");

    let mut right = loaded(&nl);
    let report = right.apply_difference(&diff);
    assert!(!report.has_errors(), "{report}");
    let again = right.apply_difference(&diff);
    assert!(
        refused(&again),
        "the second application finds its base replaced: {again}"
    );
}

/// Every change set ENTSO-E publishes for CGMES 3.0 names a base that is published beside
/// it, and applies to it without a refusal. A check that refused one of these would be a
/// check nobody could leave on.
#[test]
fn every_published_change_set_applies_to_its_own_base() {
    let root = require_corpus!(common::cgmes3_model("MicroGrid/MicroGid-BaseCase"));
    let dirs: Vec<_> = std::fs::read_dir(&root)
        .unwrap()
        .flatten()
        .map(|e| e.path())
        .filter(|p| p.is_dir())
        .collect();
    let (changes, bases): (Vec<_>, Vec<_>) = dirs
        .iter()
        .partition(|p| p.to_string_lossy().to_ascii_lowercase().contains("diff"));
    assert!(!changes.is_empty());

    for dir in changes {
        let diff = read_change_file(&common::xml_files(dir)[0]);
        assert!(
            !diff.header.supersedes.is_empty(),
            "{} names its base",
            dir.display()
        );
        let home = bases.iter().find(|b| {
            let ds = loaded(b);
            diff.header
                .supersedes
                .iter()
                .all(|id| ds.model_ids().any(|m| m == id))
        });
        let home = home
            .unwrap_or_else(|| panic!("{}: no published model set holds its base", dir.display()));
        let report = loaded(home).apply_difference(&diff);
        assert_eq!(
            report.by_rule(cim_kit::Rule::UnsatisfiedDependency).count(),
            0,
            "{} on {}: {report}",
            dir.display(),
            home.display()
        );
    }
}

#[test]
fn a_change_set_needs_its_base_only_when_both_sides_can_say_what_it_is() {
    // The right base.
    let mut ds = model(BASE, "1");
    assert!(
        !ds.apply_difference(&read_change(&change(BASE, "1", "2", None)))
            .has_errors()
    );

    // A model built in memory has no header identifier: nothing to compare, nothing refused.
    let mut built = Dataset::new(SCHEMA);
    let mut line = cim_kit::object::Object::new(
        cim_kit::cgmes3::names::classes::ACLineSegment,
        Mrid::parse("_aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
    );
    line.set(
        attrs::ac_line_segment::r,
        Value::Float(cim_kit::value::Real::new(1.0)),
    );
    built.insert(line);
    let report = built.apply_difference(&read_change(&change(OTHER, "1", "2", None)));
    assert!(!report.has_errors(), "{report}");

    // A change set naming no base is not checked either.
    let mut unnamed = read_change(&change(OTHER, "1", "2", None));
    unnamed.header.supersedes.clear();
    let mut ds = model(BASE, "1");
    assert!(
        !ds.apply_difference(&unnamed).has_errors(),
        "clearing the base is the bypass"
    );
}

#[test]
fn preconditions_are_kept_and_enforced() {
    let diff = read_change(&change(BASE, "1", "2", Some("1")));
    assert_eq!(diff.preconditions.len(), 1, "read, not dropped");

    // Written and read back.
    let mut out = Vec::new();
    cim_kit::writer::write_difference(SCHEMA, &diff, &mut out, &WriteOptions::default()).unwrap();
    let again = read_change(std::str::from_utf8(&out).unwrap());
    assert_eq!(
        again.preconditions, diff.preconditions,
        "survives a round trip"
    );

    let mut holds = model(BASE, "1");
    assert!(!holds.apply_difference(&diff).has_errors());

    let mut fails = model(BASE, "5");
    let before = projection(&fails);
    let report = fails.apply_difference(&read_change(&change(BASE, "5", "2", Some("1"))));
    assert!(refused(&report), "{report}");
    assert!(report.to_string().contains("precondition"), "{report}");
    assert_eq!(projection(&fails), before);
}

/// Baseline SR-009: a retraction that does not hold is reported, not refused — published
/// change sets reconcile files that disagree, so it is evidence rather than grounds.
#[test]
fn a_retraction_that_does_not_hold_is_reported() {
    let mut ds = model(BASE, "1");
    let report = ds.apply_difference(&read_change(&change(BASE, "9", "2", None)));
    assert!(!report.has_errors(), "a warning, not an error: {report}");
    assert!(
        report.iter().any(|d| d.message.contains("ACLineSegment.r")),
        "the statement is named: {report}"
    );
}

/// `Supersedes` names the base — what the change replaces — as every published change set
/// does. It used to name the target, so each computed change set claimed to replace the
/// state it produced; and its identifier ignored the base, so two changes into one target
/// were one change.
#[test]
fn a_computed_change_set_names_its_base() {
    let base = model(BASE, "1");
    let target = model(OTHER, "2");
    let diff = base.difference_to(&target, &DiffOptions::default()).model;
    assert_eq!(
        diff.header.supersedes,
        vec![Mrid::parse(&format!("urn:uuid:{BASE}"))]
    );

    assert!(!model(BASE, "1").apply_difference(&diff).has_errors());
    assert!(
        refused(&model(OTHER, "2").apply_difference(&diff)),
        "not onto the target"
    );

    let other_base = model("33333333-3333-4333-8333-333333333333", "3");
    let second = other_base
        .difference_to(&target, &DiffOptions::default())
        .model;
    assert_ne!(
        diff.header.id, second.header.id,
        "two bases, two change sets"
    );
}