openehr 0.1.0

openEHR Reference Model types, validation, paths, AQL parsing, and change-control security primitives
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
//! Reference Model invariant checking.
//!
//! # Why this exists when the constructors already check
//!
//! Every builder in this crate enforces the invariants of the class it builds.
//! **Deserialization does not.** `serde` writes fields directly, so a
//! `COMPOSITION` read from JSON has never passed through `Composition::new`,
//! and an `ELEMENT` read from JSON can carry a `value` *and* a `null_flavour`
//! — a combination no constructor here will produce and every openEHR
//! implementation must be prepared to receive.
//!
//! So there are two gates, and they are not redundant:
//!
//! | Gate | Covers | Enforced by |
//! | --- | --- | --- |
//! | construction | data this program builds | `Result`-returning builders |
//! | validation | data this program **receives** | this module |
//!
//! A service that deserializes a composition and stores it without calling
//! [`Validate::validate`] has no invariant checking at all, whatever its
//! constructors do.
//!
//! # What it reports, and what it cannot
//!
//! Validation here is **RM-level**: the invariants stated in the openEHR class
//! definitions. It is not archetype validation. Checking that
//! `openEHR-EHR-OBSERVATION.blood_pressure.v2` permits exactly these elements
//! at these node ids requires the archetype, and archetypes are out of scope
//! (`S1.4`). A composition that passes here can still violate its archetype,
//! and the documentation says so rather than letting "valid" be read as more
//! than it is.
//!
//! ```
//! use openehr::validation::Validate;
//! use openehr::rm::data_structures::Element;
//!
//! // An ELEMENT that serde built with both a value and a null flavour: no
//! // constructor produces it, and a sender can still send it.
//! let json = r#"{
//!   "name": {"value": "Systolic"},
//!   "archetype_node_id": "at0004",
//!   "value": {"_type": "DV_COUNT", "magnitude": 1},
//!   "null_flavour": {"value": "unknown", "defining_code":
//!     {"terminology_id": {"value": "openehr"}, "code_string": "253"}}
//! }"#;
//! let element: Element = serde_json::from_str(json).unwrap();
//! let report = element.validate();
//! assert!(!report.is_empty());
//! assert_eq!(report.violations()[0].invariant, "Value_null_flavour_valid");
//! ```

use crate::error::{ValidationReport, Violation};
use crate::rm::common::PartyProxy;
use crate::rm::data_structures::{Cluster, Element, Event, History, Item, ItemStructure};
use crate::rm::data_types::{DataValue, DvCodedText};
use crate::rm::ehr::{Composition, ContentItem, Entry, EventContext, Section};

/// Accumulates violations while walking a structure, tracking where it is.
#[derive(Debug, Default)]
pub struct Context {
    path: Vec<String>,
    report: ValidationReport,
}

impl Context {
    /// A fresh context rooted at the object being validated.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Records a violation at the current path.
    pub fn violation(
        &mut self,
        class: &'static str,
        invariant: &'static str,
        detail: &'static str,
    ) {
        self.report.push(Violation {
            path: self.path.join(""),
            class,
            invariant,
            detail,
        });
    }

    /// Runs `f` with one more path segment pushed.
    fn nested<F: FnOnce(&mut Self)>(&mut self, segment: String, f: F) {
        self.path.push(segment);
        f(self);
        self.path.pop();
    }

    /// The accumulated report.
    #[must_use]
    pub fn finish(self) -> ValidationReport {
        self.report
    }
}

/// Checks a structure's Reference Model invariants.
pub trait Validate {
    /// Walks the structure, recording every violation found.
    fn visit(&self, ctx: &mut Context);

    /// Validates the structure and returns everything that failed.
    fn validate(&self) -> ValidationReport {
        let mut ctx = Context::new();
        self.visit(&mut ctx);
        ctx.finish()
    }

    /// Validates and converts to a `Result`.
    ///
    /// # Errors
    ///
    /// Returns the [`ValidationReport`] if any invariant failed.
    fn validate_ok(&self) -> Result<(), ValidationReport> {
        self.validate().into_result()
    }
}

/// Checks the invariants shared by every `LOCATABLE`.
fn check_locatable<L: crate::rm::common::Locatable>(node: &L, ctx: &mut Context) {
    if node.archetype_node_id().is_empty() {
        ctx.violation(
            "LOCATABLE",
            "Archetype_node_id_valid",
            "archetype_node_id is empty, so the node cannot be reached by any path",
        );
    }
    if node.name().value().is_empty() {
        ctx.violation("LOCATABLE", "Name_valid", "name is empty");
    }
    // An archetype root whose archetype id constrains a different RM class is
    // the single most common structural error in hand-built or
    // transform-produced instances: an OBSERVATION archetype id on an
    // EVALUATION node. Nothing downstream detects it, and the data looks fine.
    if let Some(details) = node.archetype_details() {
        let entity = details.archetype_id().rm_entity();
        if entity != node.rm_type_name() {
            ctx.violation(
                "ARCHETYPED",
                "Archetype_id_rm_entity_matches",
                "archetype id constrains a different RM class than the node it annotates",
            );
        }
        if details.rm_version().is_empty() {
            ctx.violation("ARCHETYPED", "Rm_version_valid", "rm_version is empty");
        }
    }
}

/// Checks a `DV_CODED_TEXT` against the openEHR support terminology.
fn check_coded_text(coded: &DvCodedText, ctx: &mut Context) {
    if coded.check_openehr_rubric() == Some(false) {
        ctx.violation(
            "DV_CODED_TEXT",
            "Value_is_rubric",
            "value does not match the openEHR rubric for defining_code",
        );
    }
}

impl Validate for DataValue {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::CodedText(t) => check_coded_text(t, ctx),
            Self::Ordinal(o) => check_coded_text(o.symbol(), ctx),
            Self::Scale(s) => check_coded_text(s.symbol(), ctx),
            Self::Quantity(q) => {
                if !q.magnitude().is_finite() {
                    ctx.violation(
                        "DV_QUANTITY",
                        "Magnitude_finite",
                        "magnitude is not a finite number",
                    );
                }
                if q.units().is_empty() {
                    ctx.violation("DV_QUANTITY", "Units_valid", "units is empty");
                }
                if q.precision().is_some_and(|p| p < 0) {
                    ctx.violation("DV_QUANTITY", "Precision_valid", "precision is negative");
                }
            }
            Self::Proportion(p) => {
                if p.denominator() == 0.0 {
                    ctx.violation("DV_PROPORTION", "Denominator_valid", "denominator is zero");
                }
                if p.kind().requires_integral()
                    && (p.numerator().fract() != 0.0 || p.denominator().fract() != 0.0)
                {
                    ctx.violation(
                        "DV_PROPORTION",
                        "Is_integral_validity",
                        "a fractional kind has a non-integral numerator or denominator",
                    );
                }
            }
            Self::Multimedia(m) => {
                if !m.has_content() {
                    ctx.violation(
                        "DV_MULTIMEDIA",
                        "Data_or_uri_valid",
                        "neither inline data nor a uri is present",
                    );
                }
                if m.verify_integrity() == crate::rm::data_types::IntegrityCheck::Failed {
                    ctx.violation(
                        "DV_MULTIMEDIA",
                        "Integrity_check_valid",
                        "the recorded digest does not match the inline data",
                    );
                }
            }
            Self::Text(t) if t.value().is_empty() => {
                ctx.violation("DV_TEXT", "Value_valid", "value is empty");
            }
            _ => {}
        }
    }
}

impl Validate for Element {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        // openEHR: `is_null xor null_flavour = Void`. Both present and both
        // absent are each a violation, and they fail differently: both present
        // is a contradiction, both absent is an element that says nothing.
        match (self.value().is_some(), self.null_flavour().is_some()) {
            (true, true) => ctx.violation(
                "ELEMENT",
                "Value_null_flavour_valid",
                "an element has both a value and a null_flavour",
            ),
            (false, false) => ctx.violation(
                "ELEMENT",
                "Value_null_flavour_valid",
                "an element has neither a value nor a null_flavour",
            ),
            _ => {}
        }
        if self.null_reason().is_some() && self.value().is_some() {
            ctx.violation(
                "ELEMENT",
                "Null_reason_valid",
                "a reason for absence is recorded on an element that has a value",
            );
        }
        if let Some(flavour) = self.null_flavour() {
            if !flavour.defining_code().is_openehr()
                || !crate::terminology::null_flavour::GROUP
                    .contains(flavour.defining_code().code_string())
            {
                ctx.violation(
                    "ELEMENT",
                    "Null_flavour_valid",
                    "null_flavour is not one of the four openEHR null flavours",
                );
            }
            check_coded_text(flavour, ctx);
        }
        if let Some(value) = self.value() {
            ctx.nested("/value".to_owned(), |c| value.visit(c));
        }
    }
}

impl Validate for Cluster {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        if self.items().is_empty() {
            ctx.violation("CLUSTER", "Items_valid", "a cluster has no items");
        }
        for (i, item) in self.items().iter().enumerate() {
            ctx.nested(format!("/items[{i}]"), |c| item.visit(c));
        }
    }
}

impl Validate for Item {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Cluster(v) => v.visit(ctx),
            Self::Element(v) => v.visit(ctx),
        }
    }
}

impl Validate for ItemStructure {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Single(s) => {
                check_locatable(s, ctx);
                ctx.nested("/item".to_owned(), |c| s.item().visit(c));
            }
            Self::List(s) => {
                check_locatable(s, ctx);
                for (i, e) in s.items().iter().enumerate() {
                    ctx.nested(format!("/items[{i}]"), |c| e.visit(c));
                }
            }
            Self::Table(s) => {
                check_locatable(s, ctx);
                if !s.is_regular() {
                    ctx.violation(
                        "ITEM_TABLE",
                        "Rows_regular",
                        "rows do not all have the same number of columns",
                    );
                }
                for (i, r) in s.rows().iter().enumerate() {
                    ctx.nested(format!("/rows[{i}]"), |c| r.visit(c));
                }
            }
            Self::Tree(s) => {
                check_locatable(s, ctx);
                for (i, item) in s.items().iter().enumerate() {
                    ctx.nested(format!("/items[{i}]"), |c| item.visit(c));
                }
            }
        }
    }
}

impl Validate for Event {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Point(e) => {
                check_locatable(e, ctx);
                ctx.nested("/data".to_owned(), |c| e.data().visit(c));
                if let Some(state) = e.state() {
                    ctx.nested("/state".to_owned(), |c| state.visit(c));
                }
            }
            Self::Interval(e) => {
                check_locatable(e, ctx);
                if e.width().value().is_negative() {
                    ctx.violation(
                        "INTERVAL_EVENT",
                        "Width_valid",
                        "width is negative, so the interval ends before it starts",
                    );
                }
                check_coded_text(e.math_function(), ctx);
                ctx.nested("/data".to_owned(), |c| e.data().visit(c));
                if let Some(state) = e.state() {
                    ctx.nested("/state".to_owned(), |c| state.visit(c));
                }
            }
        }
    }
}

impl Validate for History {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        if self.events().is_empty() && self.summary().is_none() {
            ctx.violation(
                "HISTORY",
                "Items_valid",
                "a history has neither events nor a summary",
            );
        }
        if self
            .period()
            .is_some_and(|p| p.value().is_zero() || p.value().is_negative())
        {
            ctx.violation(
                "HISTORY",
                "Period_valid",
                "a periodic history declares a zero or negative period",
            );
        }
        for (i, event) in self.events().iter().enumerate() {
            // Every event must be at or after the history's origin: an event
            // before the zero point has a negative offset, and `EVENT.offset`
            // is defined as `time - origin` with no provision for one.
            if matches!(
                event.time().partial_cmp(self.origin()),
                Some(core::cmp::Ordering::Less)
            ) {
                ctx.nested(format!("/events[{i}]"), |c| {
                    c.violation(
                        "EVENT",
                        "Time_after_origin",
                        "event time is before the history origin",
                    );
                });
            }
            ctx.nested(format!("/events[{i}]"), |c| event.visit(c));
        }
        if let Some(summary) = self.summary() {
            ctx.nested("/summary".to_owned(), |c| summary.visit(c));
        }
    }
}

impl Validate for EventContext {
    fn visit(&self, ctx: &mut Context) {
        check_coded_text(self.setting(), ctx);
        if !self.setting().defining_code().is_openehr()
            || !crate::terminology::setting::GROUP
                .contains(self.setting().defining_code().code_string())
        {
            ctx.violation(
                "EVENT_CONTEXT",
                "Setting_valid",
                "setting is not from the openEHR setting group",
            );
        }
        if let Some(end) = self.end_time()
            && matches!(
                end.partial_cmp(self.start_time()),
                Some(core::cmp::Ordering::Less)
            )
        {
            ctx.violation(
                "EVENT_CONTEXT",
                "End_time_valid",
                "end_time is before start_time",
            );
        }
        if let Some(other) = self.other_context() {
            ctx.nested("/other_context".to_owned(), |c| other.visit(c));
        }
    }
}

impl Validate for Entry {
    fn visit(&self, ctx: &mut Context) {
        check_locatable_entry(self, ctx);
        check_party(self.subject(), "ENTRY", "Subject_valid", ctx);
        match self {
            Self::Observation(o) => {
                ctx.nested("/data".to_owned(), |c| o.data().visit(c));
                if let Some(state) = o.state() {
                    ctx.nested("/state".to_owned(), |c| state.visit(c));
                }
                if let Some(protocol) = o.care_entry().protocol() {
                    ctx.nested("/protocol".to_owned(), |c| protocol.visit(c));
                }
            }
            Self::Evaluation(e) => ctx.nested("/data".to_owned(), |c| e.data().visit(c)),
            Self::AdminEntry(a) => ctx.nested("/data".to_owned(), |c| a.data().visit(c)),
            Self::Instruction(i) => {
                if i.activities().is_empty() {
                    ctx.violation(
                        "INSTRUCTION",
                        "Activities_valid",
                        "an instruction has no activities",
                    );
                }
                if i.narrative().value().is_empty() {
                    ctx.violation(
                        "INSTRUCTION",
                        "Narrative_valid",
                        "an instruction has an empty narrative",
                    );
                }
                for (n, activity) in i.activities().iter().enumerate() {
                    ctx.nested(format!("/activities[{n}]/description"), |c| {
                        activity.description().visit(c);
                    });
                }
            }
            Self::Action(a) => {
                check_coded_text(a.ism_transition().current_state(), ctx);
                if !crate::terminology::instruction_state::GROUP.contains(
                    a.ism_transition()
                        .current_state()
                        .defining_code()
                        .code_string(),
                ) {
                    ctx.violation(
                        "ISM_TRANSITION",
                        "Current_state_valid",
                        "current_state is not an Instruction State Machine state",
                    );
                }
                ctx.nested("/description".to_owned(), |c| a.description().visit(c));
            }
        }
    }
}

fn check_locatable_entry(entry: &Entry, ctx: &mut Context) {
    match entry {
        Entry::Observation(e) => check_locatable(e, ctx),
        Entry::Evaluation(e) => check_locatable(e, ctx),
        Entry::Instruction(e) => check_locatable(e, ctx),
        Entry::Action(e) => check_locatable(e, ctx),
        Entry::AdminEntry(e) => check_locatable(e, ctx),
    }
}

fn check_party(
    party: &PartyProxy,
    class: &'static str,
    invariant: &'static str,
    ctx: &mut Context,
) {
    let identified = match party {
        PartyProxy::SelfParty(_) => return,
        PartyProxy::Identified(p) => p,
        PartyProxy::Related(p) => {
            check_coded_text(p.relationship(), ctx);
            p.as_identified()
        }
    };
    if identified.name().is_none()
        && identified.identifiers().is_empty()
        && identified.external_ref().is_none()
    {
        ctx.violation(
            class,
            invariant,
            "an identified party has no name, no identifiers, and no external reference",
        );
    }
}

impl Validate for Section {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        for (i, item) in self.items().iter().enumerate() {
            ctx.nested(format!("/items[{i}]"), |c| item.visit(c));
        }
    }
}

impl Validate for ContentItem {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Section(s) => s.visit(ctx),
            Self::Entry(e) => e.visit(ctx),
        }
    }
}

impl Validate for Composition {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        check_coded_text(self.category(), ctx);
        if !crate::terminology::composition_category::GROUP.contains(self.category_code()) {
            ctx.violation(
                "COMPOSITION",
                "Category_validity",
                "category is not from the openEHR composition_category group",
            );
        }
        check_party(self.composer(), "COMPOSITION", "Composer_valid", ctx);
        if let Some(context) = self.context() {
            ctx.nested("/context".to_owned(), |c| context.visit(c));
        }
        for (i, item) in self.content().iter().enumerate() {
            ctx.nested(format!("/content[{i}]"), |c| item.visit(c));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rm::common::{Archetyped, LocatableAttrs, PartyIdentified};
    use crate::rm::data_structures::{ItemSingle, PointEvent};
    use crate::rm::data_types::{CodePhrase, DvCount, DvDateTime, DvQuantity, DvText};
    use crate::rm::ehr::{EntryAttrs, Evaluation, Observation};
    use crate::terminology;

    fn attrs(name: &str, node: &str) -> LocatableAttrs {
        LocatableAttrs::named(name, node).unwrap()
    }

    fn structure() -> ItemStructure {
        ItemSingle::new(
            attrs("d", "at0001"),
            Element::new(attrs("v", "at0002"), DataValue::Count(DvCount::new(1))),
        )
        .into()
    }

    fn entry_attrs() -> EntryAttrs {
        EntryAttrs::about_subject(
            CodePhrase::new("ISO_639-1", "en").unwrap(),
            CodePhrase::new("IANA_character-sets", "UTF-8").unwrap(),
        )
    }

    fn composition() -> Composition {
        Composition::new(
            attrs("Encounter", "openEHR-EHR-COMPOSITION.encounter.v1"),
            terminology::composition_category::EVENT,
            PartyIdentified::named("Dr A Nurse").unwrap().into(),
            CodePhrase::new("ISO_639-1", "en").unwrap(),
            CodePhrase::new("ISO_3166-1", "GB").unwrap(),
        )
        .unwrap()
    }

    #[test]
    fn a_well_formed_composition_has_no_violations() {
        let c = composition().with_content(
            Evaluation::new(attrs("Problem", "at0000"), entry_attrs(), structure()).into(),
        );
        let report = c.validate();
        assert!(report.is_empty(), "{report}");
    }

    #[test]
    fn deserialization_bypasses_constructors_and_validation_catches_it() {
        // The mutation check for this whole module: if `visit` stopped
        // checking the null invariant, this element would validate clean.
        let json = r#"{
          "name": {"value": "Systolic"},
          "archetype_node_id": "at0004",
          "value": {"_type": "DV_COUNT", "magnitude": 1},
          "null_flavour": {"value": "unknown", "defining_code":
            {"terminology_id": {"value": "openehr"}, "code_string": "253"}}
        }"#;
        let element: Element = serde_json::from_str(json).unwrap();
        let report = element.validate();
        assert_eq!(report.len(), 1);
        assert_eq!(report.violations()[0].invariant, "Value_null_flavour_valid");
    }

    #[test]
    fn an_element_with_nothing_at_all_is_also_a_violation() {
        let json = r#"{"name": {"value": "Systolic"}, "archetype_node_id": "at0004"}"#;
        let element: Element = serde_json::from_str(json).unwrap();
        assert_eq!(element.validate().len(), 1);
    }

    #[test]
    fn an_archetype_id_on_the_wrong_class_is_reported() {
        let wrong = Evaluation::new(
            attrs("Problem", "openEHR-EHR-OBSERVATION.blood_pressure.v2").with_archetype_details(
                Archetyped::new("openEHR-EHR-OBSERVATION.blood_pressure.v2", "1.1.0").unwrap(),
            ),
            entry_attrs(),
            structure(),
        );
        let report = Entry::from(wrong).validate();
        assert_eq!(report.len(), 1);
        assert_eq!(
            report.violations()[0].invariant,
            "Archetype_id_rm_entity_matches"
        );
    }

    #[test]
    fn a_coded_text_that_contradicts_its_own_code_is_reported() {
        let json = r#"{
          "name": {"value": "Category"},
          "archetype_node_id": "at0001",
          "value": {"_type": "DV_CODED_TEXT", "value": "deletion",
            "defining_code": {"terminology_id": {"value": "openehr"}, "code_string": "249"}}
        }"#;
        let element: Element = serde_json::from_str(json).unwrap();
        let report = element.validate();
        assert_eq!(report.len(), 1);
        assert_eq!(report.violations()[0].invariant, "Value_is_rubric");
        // The path locates the offending node without repeating its content.
        assert_eq!(report.violations()[0].path, "/value");
    }

    #[test]
    fn violation_paths_locate_the_node_and_never_the_value() {
        let marker = "ZZ-DISTINCTIVE-9999";
        let bad_element: Element = serde_json::from_str(&format!(
            r#"{{"name": {{"value": "{marker}"}}, "archetype_node_id": "at0004"}}"#
        ))
        .unwrap();
        let structure: ItemStructure = ItemSingle::new(attrs("d", "at0001"), bad_element).into();
        let report = structure.validate();
        assert_eq!(report.violations()[0].path, "/item");
        assert!(!report.to_string().contains(marker), "{report}");
    }

    #[test]
    fn an_event_before_its_history_origin_is_reported() {
        let event = PointEvent::new(
            attrs("early", "at0006"),
            DvDateTime::new("2026-07-31T08:00:00Z").unwrap(),
            structure(),
        );
        let history = History::new(
            attrs("Event Series", "at0001"),
            DvDateTime::new("2026-07-31T09:00:00Z").unwrap(),
            vec![event.into()],
            None,
        )
        .unwrap();
        let observation = Observation::new(attrs("Obs", "at0000"), entry_attrs(), history);
        let report = Entry::from(observation).validate();
        assert_eq!(report.len(), 1);
        assert_eq!(report.violations()[0].invariant, "Time_after_origin");
        assert_eq!(report.violations()[0].path, "/data/events[0]");
    }

    #[test]
    fn every_violation_is_reported_not_just_the_first() {
        let json = r#"{
          "name": {"value": ""},
          "archetype_node_id": "",
          "value": {"_type": "DV_QUANTITY", "magnitude": 1.0, "units": "", "precision": -3}
        }"#;
        let element: Element = serde_json::from_str(json).unwrap();
        let report = element.validate();
        // empty node id, empty name, empty units, negative precision.
        assert_eq!(report.len(), 4, "{report}");
    }

    #[test]
    fn a_valid_quantity_with_a_normal_range_still_validates() {
        let q = DvQuantity::new(4.2, "mmol/l").unwrap();
        let element = Element::new(attrs("Glucose", "at0004"), DataValue::Quantity(q));
        assert!(element.validate().is_empty());
        let _ = DvText::new("unused");
    }
}