openehr 0.6.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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
//! The cross-cutting guarantees, tested where they can actually fail.
//!
//! Unit tests inside a module check one type. These check a **property that
//! must hold across the crate**, which is the kind that regresses when someone
//! adds a type and follows the shape of the one next to it without noticing
//! what that shape was for.
//!
//! Each test here has a stated failure mode. A test whose failure mode nobody
//! wrote down is a test nobody will maintain.

use core::cmp::Ordering;
use openehr::aql::AqlQuery;
use openehr::base::{Interval, iso8601};
use openehr::path::Pathable;
use openehr::rm::common::{LocatableAttrs, PartyIdentified};
use openehr::rm::data_structures::{Element, ItemTree};
use openehr::rm::data_types::{
    CodePhrase, DataValue, DvCount, DvDate, DvDateTime, DvIdentifier, DvMultimedia, DvOrdered,
    DvQuantity, DvText,
};
use openehr::rm::ehr::{Composition, EntryAttrs, Evaluation};
use openehr::security::{ChainKey, RedactionRule, Redactor, Sensitive};
use openehr::terminology::{self, composition_category};
use openehr::validation::Validate;

/// A string that will not occur by accident, so that "does this output contain
/// patient data?" is answerable by substring search.
const MARKER: &str = "ZZ-DISTINCTIVE-MARKER-9999";

fn at(name: &str, node: &str) -> LocatableAttrs {
    LocatableAttrs::named(name, node).expect("literal attrs")
}

fn composition_containing(marker: &str) -> Composition {
    let data = ItemTree::new(
        at("tree", "at0001"),
        vec![
            Element::new(
                at("HIV status", "at0011"),
                DataValue::Text(DvText::new(marker).unwrap()),
            )
            .into(),
        ],
    );
    let evaluation = Evaluation::new(
        // An ENTRY is the root of an entry archetype (`ENTRY.Is_archetype_root`),
        // and this fixture said `at0000` — an interior node id — until that rule
        // was enforced.
        at("Problem", "openEHR-EHR-EVALUATION.problem.v1").with_archetype_details(
            openehr::rm::common::Archetyped::new("openEHR-EHR-EVALUATION.problem.v1", "1.1.0")
                .unwrap(),
        ),
        EntryAttrs::about_subject(
            CodePhrase::new("ISO_639-1", "en").unwrap(),
            CodePhrase::new("IANA_character-sets", "UTF-8").unwrap(),
        ),
        data.into(),
    );
    Composition::new(
        at("Encounter", "openEHR-EHR-COMPOSITION.encounter.v1").with_archetype_details(
            openehr::rm::common::Archetyped::new("openEHR-EHR-COMPOSITION.encounter.v1", "1.1.0")
                .unwrap(),
        ),
        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()
    .with_content(evaluation.into())
}

// ---------------------------------------------------------------------------
// Nothing prints protected health information
// ---------------------------------------------------------------------------

/// Fails if any `Display` implementation on a PHI-bearing type starts printing
/// its content — the change that turns one `tracing::info!("{id}")` into a
/// disclosure.
#[test]
fn display_never_reveals_an_identifier_or_a_media_blob() {
    let id = DvIdentifier::new(MARKER)
        .unwrap()
        .with_type("NHS number")
        .with_issuer("NHS England");
    assert!(!format!("{id}").contains(MARKER));
    assert_eq!(format!("{id}"), "NHS number issued by NHS England");

    let media = DvMultimedia::inline(
        CodePhrase::new("IANA_media-types", "image/png").unwrap(),
        MARKER.as_bytes().to_vec(),
    );
    // Multimedia has no Display at all — deliberately — so the reachable
    // rendering is Debug, which prints shape.
    assert!(!format!("{media:?}").contains(MARKER));

    let wrapped = Sensitive::new(MARKER.to_owned());
    assert!(!format!("{wrapped}").contains(MARKER));
    assert!(!format!("{wrapped:?}").contains(MARKER));
    // …and it is still there for storage and for an authorised recipient.
    assert_eq!(wrapped.expose(), MARKER);
}

/// Fails if a constructor starts echoing the value that broke an invariant.
///
/// The failure this prevents is specific: an error message is the one place a
/// value reaches a log, an HTTP response, and a support ticket at once.
#[test]
fn no_construction_error_echoes_a_submitted_value() {
    let failures: Vec<String> = vec![
        DvText::new("").unwrap_err().to_string(),
        DvQuantity::new(f64::NAN, "mg").unwrap_err().to_string(),
        DvQuantity::new(1.0, "").unwrap_err().to_string(),
        DvIdentifier::new("").unwrap_err().to_string(),
        Element::new_null(at("x", "at0001"), "999")
            .unwrap_err()
            .to_string(),
        DvDate::new(MARKER).unwrap_err().to_string(),
    ];
    // The one deliberate exception is a *lexical* rejection of design-time
    // vocabulary, which does echo — an identifier error that will not say which
    // identifier is unactionable. So the date failure above is expected to
    // repeat its input, and the invariant failures are not.
    for message in &failures[..5] {
        assert!(!message.contains(MARKER), "{message}");
        assert!(message.contains("invalid"), "{message}");
    }
    assert!(
        failures[5].contains(MARKER),
        "lexical errors do name their input"
    );
}

/// Fails if a validation report starts carrying node content.
#[test]
fn a_validation_report_names_paths_and_never_values() {
    let json = format!(r#"{{"name": {{"value": "{MARKER}"}}, "archetype_node_id": "at0004"}}"#);
    let element: Element = serde_json::from_str(&json).unwrap();
    let report = element.validate();
    assert!(!report.is_empty());
    assert!(!report.to_string().contains(MARKER), "{report}");
}

/// Fails if a chain checkpoint starts including anything from the versions it
/// covers. The whole value of a checkpoint is that it can be shipped to a
/// long-retention log where clinical data must not go.
#[test]
fn a_chain_checkpoint_carries_no_patient_data() {
    let key = ChainKey::new("k1", vec![3u8; 32]).unwrap();
    let mut chain = openehr::security::Chain::new();
    chain
        .append("uid::sys::1", &composition_containing(MARKER), Some(&key))
        .unwrap();
    let checkpoint = chain.checkpoint();
    assert!(!checkpoint.contains(MARKER), "{checkpoint}");
    assert!(checkpoint.contains("entries=1"));
}

/// Fails if redaction starts deleting rather than masking, or starts naming
/// what it withheld.
#[test]
fn redaction_masks_and_reports_a_count_not_a_category() {
    let (redacted, count) = Redactor::new()
        .with_rule(RedactionRule::node_id("at0011"))
        .redact_counting(&composition_containing(MARKER))
        .unwrap();
    let json = serde_json::to_string(&redacted).unwrap();

    assert!(!json.contains(MARKER), "the value survived redaction");
    assert!(json.contains(terminology::null_flavour::MASKED));
    // The boundary, stated: redaction rules address ELEMENTs. The composer,
    // the participations, and the audit trail are *not* clinical content and
    // are not withheld by an element rule — a deployment that must also strip
    // those is doing de-identification, which is a different operation with
    // different rules.
    assert!(json.contains("Dr A Nurse"));
    // Masked, not deleted: the reader must be able to tell "withheld" from
    // "never recorded".
    let element = redacted
        .item_at_path("/content/data/items[at0011]")
        .expect("the element is still there");
    assert_eq!(element.type_name(), "ELEMENT");
    // And the count says how much without saying what.
    assert_eq!(count.masked, 1);
    assert!(!count.to_string().contains("HIV"));

    // The result is still a valid composition, so the receiving system can
    // read it.
    assert!(redacted.validate().is_empty());
}

// ---------------------------------------------------------------------------
// Refuse rather than guess
// ---------------------------------------------------------------------------

/// Fails if any of the partial orders quietly becomes total.
///
/// Each pair below has a plausible wrong answer that nothing downstream could
/// detect: a month ordered before a day inside it, five milligrams equal to
/// five millilitres, a local time compared with a UTC one.
#[test]
fn every_undecidable_comparison_answers_none() {
    let month: iso8601::Date = "2024-05".parse().unwrap();
    let day: iso8601::Date = "2024-05-17".parse().unwrap();
    assert_eq!(month.semantic_cmp(&day), None);

    let local: iso8601::Time = "11:00:00".parse().unwrap();
    let utc: iso8601::Time = "11:00:00Z".parse().unwrap();
    assert_eq!(local.semantic_cmp(&utc), None);

    let twelve_months: iso8601::Duration = "P12M".parse().unwrap();
    let one_year: iso8601::Duration = "P1Y".parse().unwrap();
    assert_eq!(twelve_months.semantic_cmp(&one_year), None);

    let mg = DataValue::Quantity(DvQuantity::new(5.0, "mg").unwrap());
    let ml = DataValue::Quantity(DvQuantity::new(5.0, "mL").unwrap());
    assert_eq!(mg.semantic_cmp(&ml), None);
    assert!(!mg.is_strictly_comparable_to(&ml));

    let count = DataValue::Count(openehr::rm::data_types::DvCount::new(5));
    assert_eq!(mg.semantic_cmp(&count), None);

    // And the decidable cases are still decided, so the refusals above are not
    // just "comparison is broken".
    let april: iso8601::Date = "2024-04".parse().unwrap();
    assert_eq!(april.semantic_cmp(&day), Some(Ordering::Less));
    let more = DataValue::Quantity(DvQuantity::new(6.0, "mg").unwrap());
    assert_eq!(mg.semantic_cmp(&more), Some(Ordering::Less));
}

/// Fails if an ambiguous path starts resolving to its first match.
#[test]
fn an_ambiguous_path_refuses_instead_of_choosing() {
    let data = ItemTree::new(
        at("tree", "at0001"),
        vec![
            Element::new(
                at("Systolic", "at0004"),
                DataValue::Quantity(DvQuantity::new(184.0, "mm[Hg]").unwrap()),
            )
            .into(),
            Element::new(
                at("Diastolic", "at0005"),
                DataValue::Quantity(DvQuantity::new(96.0, "mm[Hg]").unwrap()),
            )
            .into(),
        ],
    );
    // Rooted at `ItemStructure`, which is the type a path addresses; the four
    // concrete structures convert into it.
    let data: openehr::rm::data_structures::ItemStructure = data.into();
    assert!(data.path_exists("/items/value/magnitude").unwrap());
    assert!(!data.path_unique("/items/value/magnitude").unwrap());
    assert_eq!(
        data.items_at_path("/items/value/magnitude").unwrap().len(),
        2
    );
    assert!(data.item_at_path("/items/value/magnitude").is_err());
    // With a predicate it resolves, and to the right one.
    assert!(
        data.item_at_path("/items['Diastolic']/value/magnitude")
            .is_ok()
    );
}

/// Fails if an interval starts accepting bounds whose order is not established.
#[test]
fn an_interval_refuses_bounds_it_cannot_order() {
    // Two dates of different precision whose known components agree: nothing
    // establishes which is earlier, so this is not a usable range.
    let month = DvDate::new("2024-05").unwrap();
    let day = DvDate::new("2024-05-17").unwrap();
    assert!(Interval::closed(month, day).is_err());

    let ok = Interval::closed(
        DvDate::new("2024-04").unwrap(),
        DvDate::new("2024-05-17").unwrap(),
    );
    assert!(ok.is_ok());
}

/// Fails if an unimplemented openEHR operation starts returning a plausible
/// value instead of refusing.
#[test]
fn unimplemented_operations_refuse_and_cite_the_spec() {
    use openehr::rm::data_structures::{IntervalEvent, ItemSingle};

    let data = ItemSingle::new(
        at("d", "at0001"),
        Element::new(
            at("v", "at0002"),
            DataValue::Count(openehr::rm::data_types::DvCount::new(1)),
        ),
    );
    // A calendar-month width has no fixed length in seconds; a month before
    // 31 March is 28 February, which no number of seconds produces.
    let event = IntervalEvent::new(
        at("monthly", "at0006"),
        DvDateTime::new("2026-03-31T08:00:00Z").unwrap(),
        data.into(),
        openehr::rm::data_types::DvDuration::new("P1M").unwrap(),
        terminology::event_math_function::TOTAL,
    )
    .unwrap();
    let err = event.interval_start_time().unwrap_err();
    assert!(matches!(err, openehr::Error::Unsupported { .. }));
    assert!(err.to_string().contains("spec/"), "{err}");
}

// ---------------------------------------------------------------------------
// Absence stays structured
// ---------------------------------------------------------------------------

/// Fails if the four null flavours ever become interchangeable.
#[test]
fn the_four_null_flavours_remain_four() {
    let flavours = [
        terminology::null_flavour::NO_INFORMATION,
        terminology::null_flavour::UNKNOWN,
        terminology::null_flavour::MASKED,
        terminology::null_flavour::NOT_APPLICABLE,
    ];
    let mut codes = std::collections::HashSet::new();
    for code in flavours {
        let element = Element::new_null(at("x", "at0001"), code).unwrap();
        assert!(element.is_null());
        assert_eq!(element.null_flavour_code(), Some(code));
        assert_eq!(
            element.is_masked(),
            code == terminology::null_flavour::MASKED
        );
        codes.insert(code);

        // Each survives a round trip as itself.
        let json = serde_json::to_string(&element).unwrap();
        let back: Element = serde_json::from_str(&json).unwrap();
        assert_eq!(back.null_flavour_code(), Some(code));
    }
    assert_eq!(codes.len(), 4);

    // A fifth cannot be invented.
    assert!(Element::new_null(at("x", "at0001"), "999").is_err());
}

// ---------------------------------------------------------------------------
// The AQL front end tells the truth about itself
// ---------------------------------------------------------------------------

/// Fails if AQL parsing starts accepting a construct it cannot represent, which
/// would make a partially-understood query look fully understood.
#[test]
fn aql_refuses_what_it_does_not_model_and_says_where_that_is_recorded() {
    for text in ["SELECT * FROM COMPOSITION c", "SELECT c/uid FROM VERSION v"] {
        let err = text.parse::<AqlQuery>().unwrap_err();
        assert!(err.reason.contains("Q12.9"), "{err}");
    }
}

/// Fails if the alias check stops catching the rename bug — a query that parses,
/// executes, and returns nothing.
#[test]
fn aql_catches_a_path_rooted_at_an_unbound_alias() {
    let query: AqlQuery = "SELECT o/value FROM COMPOSITION c CONTAINS OBSERVATION obs"
        .parse()
        .unwrap();
    assert!(query.check().is_err());
    let fixed: AqlQuery = "SELECT obs/value FROM COMPOSITION c CONTAINS OBSERVATION obs"
        .parse()
        .unwrap();
    assert!(fixed.check().is_ok());
}

// ---------------------------------------------------------------------------
// The premise `X11.24` rests on

/// `A-10` says redaction's fail-closed path cannot be provoked, because "every
/// `Composition` this crate can construct serializes". That is the reason
/// `X11.24` is recorded as **?** rather than **•**, so it is worth more than a
/// belief.
///
/// The reason is sharper than "documents are well formed", and worse.
/// `serde_json` does **not** refuse a non-finite float: it writes `null`. So a
/// `NaN` magnitude that ever reached serialization would not fail — it would
/// silently become an absent value, in the canonical form the content digest
/// is taken over.
///
/// Every `f64` a document can carry is therefore refused **at construction**,
/// and those constructors are the only barrier. This asserts each one holds.
/// If somebody relaxes one — an `Accuracy_finite` that starts accepting `NaN` —
/// this test fails and names it, and what follows is silent data loss rather
/// than an error anybody sees.
#[test]
fn no_document_this_crate_can_build_carries_a_non_finite_float() {
    use openehr::rm::data_types::{DvCodedText, DvProportion, DvScale, ProportionKind};

    let symbol = || {
        DvCodedText::new("symbol", CodePhrase::new("local", "at0001").unwrap()).unwrap()
    };
    for (name, value) in [
        ("NaN", f64::NAN),
        ("+inf", f64::INFINITY),
        ("-inf", f64::NEG_INFINITY),
    ] {
        assert!(
            DvQuantity::new(value, "mm[Hg]").is_err(),
            "DV_QUANTITY accepted a magnitude of {name}"
        );
        assert!(
            DvScale::new(value, symbol()).is_err(),
            "DV_SCALE accepted a value of {name}"
        );
        assert!(
            DvQuantity::new(1.0, "mm[Hg]")
                .unwrap()
                .with_accuracy(value, false)
                .is_err(),
            "DV_AMOUNT accepted an accuracy of {name}"
        );
        assert!(
            DvProportion::new(value, 1.0, ProportionKind::Ratio).is_err(),
            "DV_PROPORTION accepted a numerator of {name}"
        );
        assert!(
            DvProportion::new(1.0, value, ProportionKind::Ratio).is_err(),
            "DV_PROPORTION accepted a denominator of {name}"
        );
    }

    // The fact that makes the above load-bearing, asserted rather than
    // assumed. Serialization does not fail here; it loses the value.
    assert_eq!(serde_json::to_string(&f64::NAN).unwrap(), "null");
    assert_eq!(
        openehr::security::to_canonical_string(&f64::INFINITY).unwrap(),
        "null"
    );
}

/// `X11.12`: tag comparison is constant-time, and the *natural* wrong way to
/// write it does not compile.
///
/// Timing is not measured — a timing assertion in a unit test is a flake
/// generator, and the matrix records `X11.12` as **?** for that reason. The
/// The structural half is not pinned by a test either, and `Mac`'s own
/// documentation says why: a `compile_fail` doctest for it passes whether or
/// not the derive is there, because the constructor it would need is private.
/// What this test pins is the behaviour that matters — a tag from the wrong
/// key is refused, and refused *as a tag mismatch* rather than as a missing or
/// unknown key (`X11.13`).
///
/// The rule was previously kept by one `ct_eq` call and the discipline not to
/// replace it, and `==` is what anyone simplifying that line would reach for.
#[test]
fn a_forged_tag_is_refused() {
    let key = ChainKey::new("k1", vec![7u8; 32]).unwrap();
    let other = ChainKey::new("k1", vec![9u8; 32]).unwrap();

    let mut chain = openehr::security::Chain::new();
    chain.append("v1", &"content", Some(&key)).unwrap();
    assert!(matches!(
        chain.verify(&[&key]),
        openehr::security::ChainStatus::Verified
    ));

    // A key with the same id and different material is the forgery this is
    // for: the entry names `k1`, so verification finds a key and the tag has
    // to do the work.
    assert!(matches!(
        chain.verify(&[&other]),
        openehr::security::ChainStatus::Broken {
            reason: openehr::security::BreakReason::TagMismatch,
            ..
        }
    ));
}

/// Redaction has three rule kinds. Two of them had no test at all.
///
/// Every existing redaction test used `RedactionRule::node_id`, so the arms
/// matching by **name** and by **archetype root** could each be inverted with
/// the suite green (`lib:A-09`). Redaction is the PHI-withholding mechanism
/// (`X11.24`, `X11.25`); two thirds of its vocabulary being unexercised is not
/// a coverage statistic, it is a rule nobody has watched work.
#[test]
fn every_redaction_rule_kind_withholds_what_it_names() {
    let masked = |rule: RedactionRule| {
        let (redacted, count) = Redactor::new()
            .with_rule(rule)
            .redact_counting(&composition_containing(MARKER))
            .unwrap();
        let json = serde_json::to_string(&redacted).unwrap();
        (json.contains(MARKER), count.masked)
    };

    // By node id — the one that was covered.
    assert_eq!(masked(RedactionRule::node_id("at0011")), (false, 1));

    // By runtime name. The fixture's element is named "HIV status", and a
    // deployment withholding by name is withholding what a clinician sees.
    assert_eq!(masked(RedactionRule::name("HIV status")), (false, 1));

    // By archetype root: everything under the entry, not one element.
    assert_eq!(
        masked(RedactionRule::archetype_root(
            "openEHR-EHR-EVALUATION.problem.v1"
        )),
        (false, 1)
    );

    // And a rule that names nothing withholds nothing — the direction that
    // catches an inverted comparison, which would mask every element *except*
    // the one asked for.
    assert_eq!(masked(RedactionRule::node_id("at9999")), (true, 0));
    assert_eq!(masked(RedactionRule::name("Blood pressure")), (true, 0));
    assert_eq!(
        masked(RedactionRule::archetype_root("openEHR-EHR-OBSERVATION.other.v1")),
        (true, 0)
    );
}

/// The count says how much, and the rules are the ones that were given.
#[test]
fn a_redaction_count_reports_numbers_and_the_rules_are_kept() {
    let redactor = Redactor::new()
        .with_rule(RedactionRule::node_id("at0011"))
        .with_rule(RedactionRule::name("something else"));
    assert_eq!(redactor.rules().len(), 2, "a rule was dropped");

    let (_, count) = redactor
        .redact_counting(&composition_containing(MARKER))
        .unwrap();
    assert_eq!(count.masked, 1);
    assert!(count.examined >= count.masked);

    // `Display` could render nothing at all: a report saying how much was
    // withheld is the point of counting, and an empty one reads as "none".
    let shown = count.to_string();
    assert!(shown.contains('1'), "no number in {shown:?}");
    assert!(!shown.contains("HIV"), "a count must not name what it withheld");
}

/// Redaction tells an ELEMENT from a CLUSTER by **shape**, not by `_type`.
///
/// This crate does not emit `_type` on an `ELEMENT` — measured, not assumed —
/// so the structural fallback in `is_element` is not a corner case for foreign
/// documents. It is the path every composition here takes.
///
/// Its three negative conditions were untested: a node with `items`, `rows` or
/// `content` is a container and not a leaf. Deleting any of them lets a
/// `CLUSTER` be treated as an element, which for a redactor means masking a
/// whole branch as though it were one value — or counting it as examined when
/// nothing looked inside (`lib:A-09`).
#[test]
fn redaction_distinguishes_a_leaf_from_a_branch_by_shape() {
    use openehr::rm::data_structures::{Cluster, Item, ItemTree};

    let leaf = |name: &str, node: &str, text: &str| {
        Item::Element(Element::new(
            at(name, node),
            DataValue::Text(DvText::new(text).unwrap()),
        ))
    };
    // A tree holding one element and one cluster of two elements: three leaves
    // and two branches.
    let tree = ItemTree::new(
        at("tree", "at0001"),
        vec![
            leaf("Top", "at0020", "top"),
            Item::Cluster(
                Cluster::new(
                    at("Group", "at0021"),
                    vec![leaf("Inner A", "at0022", "a"), leaf("Inner B", "at0023", "b")],
                )
                .unwrap(),
            ),
        ],
    );
    let evaluation = Evaluation::new(
        at("Problem", "openEHR-EHR-EVALUATION.problem.v1").with_archetype_details(
            openehr::rm::common::Archetyped::new("openEHR-EHR-EVALUATION.problem.v1", "1.1.0")
                .unwrap(),
        ),
        EntryAttrs::about_subject(
            CodePhrase::new("ISO_639-1", "en").unwrap(),
            CodePhrase::new("IANA_character-sets", "UTF-8").unwrap(),
        ),
        tree.into(),
    );
    let composition = Composition::new(
        at("Encounter", "openEHR-EHR-COMPOSITION.encounter.v1").with_archetype_details(
            openehr::rm::common::Archetyped::new("openEHR-EHR-COMPOSITION.encounter.v1", "1.1.0")
                .unwrap(),
        ),
        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()
    .with_content(evaluation.into());

    // Three leaves, and only three. A cluster counted as examined means the
    // shape test let a branch through.
    let (_, count) = Redactor::new()
        .with_rule(RedactionRule::node_id("at9999"))
        .redact_counting(&composition)
        .unwrap();
    assert_eq!(count.examined, 3, "a branch was counted as a leaf");
    assert_eq!(count.masked, 0);

    // And a rule naming the cluster masks nothing: it is not an element, so
    // there is no value to withhold and no branch to flatten.
    let (redacted, count) = Redactor::new()
        .with_rule(RedactionRule::node_id("at0021"))
        .redact_counting(&composition)
        .unwrap();
    assert_eq!(count.masked, 0, "a cluster was masked as though it were a value");
    let json = serde_json::to_string(&redacted).unwrap();
    assert!(json.contains('a') && json.contains('b'), "the branch survived");

    // A rule naming a leaf inside the cluster masks exactly that one.
    let (_, count) = Redactor::new()
        .with_rule(RedactionRule::node_id("at0022"))
        .redact_counting(&composition)
        .unwrap();
    assert_eq!(count.masked, 1);
}

/// The shape test is reached for an `ITEM_SINGLE`, whose element is a bare
/// field and carries no `_type`.
///
/// `is_element` checks `_type` first and falls back to shape. Inside an
/// `Item` enum an element is tagged, so the fallback never runs; as
/// `ITEM_SINGLE`'s `item` field it is untagged, and the fallback is the only
/// thing that recognises it.
///
/// The condition tested here is `value` **or** `null_flavour`: an element
/// carrying a value and no null flavour is still an element. Turning that into
/// `and` makes redaction stop recognising ordinary values — it would withhold
/// nothing and report nothing, which is the worst failure a redactor has
/// (`lib:A-09`, `X11.24`).
#[test]
fn an_untagged_element_is_still_recognised_and_withheld() {
    use openehr::rm::data_structures::ItemSingle;

    let composition = Composition::new(
        at("Encounter", "openEHR-EHR-COMPOSITION.encounter.v1").with_archetype_details(
            openehr::rm::common::Archetyped::new("openEHR-EHR-COMPOSITION.encounter.v1", "1.1.0")
                .unwrap(),
        ),
        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()
    .with_content(
        Evaluation::new(
            at("Problem", "openEHR-EHR-EVALUATION.problem.v1").with_archetype_details(
                openehr::rm::common::Archetyped::new("openEHR-EHR-EVALUATION.problem.v1", "1.1.0")
                    .unwrap(),
            ),
            EntryAttrs::about_subject(
                CodePhrase::new("ISO_639-1", "en").unwrap(),
                CodePhrase::new("IANA_character-sets", "UTF-8").unwrap(),
            ),
            ItemSingle::new(
                at("single", "at0030"),
                Element::new(
                    at("HIV status", "at0031"),
                    DataValue::Text(DvText::new(MARKER).unwrap()),
                ),
            )
            .into(),
        )
        .into(),
    );

    // Untagged in the JSON, so only the shape test can find it.
    let raw = serde_json::to_string(&composition).unwrap();
    assert!(raw.contains(MARKER));
    assert!(
        !raw.contains(r#""at0031","_type":"ELEMENT""#),
        "the element is expected to be untagged here"
    );

    let (redacted, count) = Redactor::new()
        .with_rule(RedactionRule::node_id("at0031"))
        .redact_counting(&composition)
        .unwrap();
    assert_eq!(count.masked, 1, "an untagged element was not recognised");
    assert!(!serde_json::to_string(&redacted).unwrap().contains(MARKER));
}


/// A `DV_URI` that arrived as JSON is checked, and reading it does not panic.
///
/// **Failure mode.** `Deserialize` is derived on `DvUri` and writes `value`
/// straight in, so a URI read from a wire passes no constructor (`L10.1a`).
/// `scheme()` then split on `':'` and `expect`ed a colon its rustdoc claimed
/// the constructor guaranteed — true of a URI this program builds, false of one
/// it is sent. `{"value":"nocolon"}` deserialized cleanly and panicked on the
/// next line. `DataValue`'s validation match had a `_ => {}` arm, so nothing
/// reported it either. See `A-36`.
#[test]
fn a_uri_that_never_saw_a_constructor_is_reported_rather_than_panicking() {
    let uri: openehr::rm::data_types::DvUri =
        serde_json::from_str(r#"{"value":"nocolon"}"#).expect("serde writes the field in");

    // Total, and fails closed: no colon means no scheme, and "" matches none.
    assert_eq!(uri.scheme(), "");
    assert_eq!(uri.rest(), "");

    let report = DataValue::Uri(uri).validate();
    let named: Vec<_> = report
        .violations()
        .iter()
        .map(|v| (v.class, v.invariant))
        .collect();
    assert!(
        named.contains(&("DV_URI", "Uri_well_formed")),
        "a malformed URI must be reported, got {named:?}"
    );
}

/// An empty `DV_URI` is openEHR's own `Value_valid`, not the crate's addition.
///
/// **Failure mode.** `L10.4` requires openEHR's own invariant name wherever
/// openEHR states the rule. openEHR's `DV_URI.Value_valid` is exactly
/// `not value.is_empty` and nothing more; reporting emptiness under the added
/// name `Uri_well_formed` would send a reader looking for a rule openEHR does
/// not have.
#[test]
fn an_empty_uri_is_reported_under_openehrs_own_invariant_name() {
    let uri: openehr::rm::data_types::DvUri =
        serde_json::from_str(r#"{"value":""}"#).expect("serde writes the field in");
    let report = DataValue::Uri(uri).validate();
    let named: Vec<_> = report
        .violations()
        .iter()
        .map(|v| (v.class, v.invariant))
        .collect();
    assert_eq!(named, vec![("DV_URI", "Value_valid")], "got {named:?}");
}

/// A `DV_EHR_URI` deserialized with a foreign scheme is reported.
///
/// **Failure mode.** The type exists so that `LINK.target` cannot point out of
/// the record without saying so (`D3.31`, `M5.9`), and its own doctest asserts
/// that `"https://example.org/x"` fails to **parse**. The JSON path accepted
/// it: `DvEhrUri` is `#[serde(transparent)]` over `DvUri`, whose derived
/// `Deserialize` runs no scheme check. The guarantee held for links this
/// program builds and not for links it is sent, which is the half that matters.
#[test]
fn an_ehr_uri_deserialized_with_a_foreign_scheme_is_reported() {
    let uri: openehr::rm::data_types::DvEhrUri =
        serde_json::from_str(r#"{"value":"https://example.org/x"}"#)
            .expect("serde writes the field in");
    assert_eq!(uri.scheme(), "https", "the parse gate is the one it skipped");

    let report = DataValue::EhrUri(uri).validate();
    let named: Vec<_> = report
        .violations()
        .iter()
        .map(|v| (v.class, v.invariant))
        .collect();
    assert_eq!(named, vec![("DV_EHR_URI", "Scheme_valid")], "got {named:?}");
}

/// Every `LOCATABLE`'s links are validated, at a path that names the link.
///
/// **Failure mode.** Checking a `DV_EHR_URI` only where it appears as a
/// `DataValue` would miss the place it actually arrives: `LINK.target`, on any
/// node in any structure. `LOCATABLE` is the one place that covers all of them
/// — a per-class rule would be fourteen copies, and the fourteenth would be
/// forgotten (`W0.1`).
#[test]
fn a_link_target_is_validated_on_every_locatable_that_carries_it() {
    let element: Element = serde_json::from_str(
        r#"{
            "name": {"value": "Problem"},
            "archetype_node_id": "at0002",
            "links": [{
                "meaning": {"value": "because of"},
                "type": {"value": "issue"},
                "target": {"value": "https://example.org/elsewhere"}
            }],
            "value": {"_type": "DV_TEXT", "value": "hypertension"}
        }"#,
    )
    .expect("serde writes the fields in");

    let report = element.validate();
    let found = report
        .violations()
        .iter()
        .find(|v| v.class == "DV_EHR_URI")
        .expect("the link target must be reported");
    assert_eq!(found.invariant, "Scheme_valid");
    assert_eq!(
        found.path, "/links[0]/target",
        "a violation must name the path to the offending node (`L10.4`)"
    );
}

/// No `DV_ORDERED` implements `PartialOrd`, and none may start.
///
/// **Failure mode.** Every `DV_ORDERED` derives `PartialEq` over all its
/// fields — including the `OrderedAttrs` all of them carry, and
/// `DV_QUANTITY`'s `precision` and `units_display_name` — while comparison
/// looks only at the magnitude. Implementing both traits therefore breaks
/// Rust's contract that `a == b` if and only if `partial_cmp` reports
/// `Some(Equal)`: each pair below was `!=` while `a <= b` and `a >= b` were
/// both true. Nothing in this crate depended on it, which is why it survived
/// as `A-35`; a caller's `binary_search` or `dedup_by` is where it surfaces.
///
/// This test is the guard against the fix being undone. `semantic_cmp` says
/// `Equal` for every pair, and `==` says false — which is correct, and is
/// exactly why neither may be a `PartialOrd` impl (`D3.18b`).
#[test]
fn equality_and_order_disagree_by_design_and_neither_is_partial_ord() {
    fn distinct_but_ordered_equal<T>(what: &str, a: &T, b: &T)
    where
        T: PartialEq + core::fmt::Debug + DvOrdered,
    {
        assert_ne!(a, b, "{what}: these are different stored values");
        assert_eq!(
            a.semantic_cmp(b),
            Some(Ordering::Equal),
            "{what}: they denote the same point and must order equal"
        );
    }

    let range = openehr::base::Interval::closed(
        DataValue::Count(DvCount::new(0)),
        DataValue::Count(DvCount::new(10)),
    )
    .unwrap();

    distinct_but_ordered_equal(
        "DV_DATE_TIME written two ways",
        &DvDateTime::new("2026-08-01T11:00:00Z").unwrap(),
        &DvDateTime::new("2026-08-01T12:00:00+01:00").unwrap(),
    );
    distinct_but_ordered_equal(
        "DV_QUANTITY differing only in precision",
        &DvQuantity::new(5.0, "mg").unwrap().with_precision(1).unwrap(),
        &DvQuantity::new(5.0, "mg").unwrap().with_precision(2).unwrap(),
    );
    distinct_but_ordered_equal(
        "DV_QUANTITY differing only in units_display_name",
        &DvQuantity::new(5.0, "mg").unwrap().with_units_display_name("mg"),
        &DvQuantity::new(5.0, "mg").unwrap(),
    );
    distinct_but_ordered_equal(
        "DV_COUNT differing only in its normal range",
        &DvCount::new(5).with_normal_range(range),
        &DvCount::new(5),
    );

    // The enum has the same shape and the same answer.
    let utc = DataValue::DateTime(DvDateTime::new("2026-08-01T11:00:00Z").unwrap());
    let offset = DataValue::DateTime(DvDateTime::new("2026-08-01T12:00:00+01:00").unwrap());
    assert_ne!(utc, offset);
    assert_eq!(utc.semantic_cmp(&offset), Some(Ordering::Equal));
}

/// A reference range still answers correctly for the same point spelled two ways.
///
/// **Failure mode.** `Interval::contains` was written with `>=` and `<=`, which
/// need `PartialOrd`. Rewriting it against `semantic_cmp` (`D3.18c`) could
/// silently change what an interval contains — and an interval here is a
/// clinical reference range, so "is this result normal?" is the question that
/// would change its answer. The operators also read "not comparable" as "not
/// greater, therefore below", which is a wrong answer rather than a missing one.
#[test]
fn a_reference_range_is_unmoved_by_how_an_instant_is_spelled() {
    let range = openehr::base::Interval::closed(
        DvDateTime::new("2026-08-01T11:00:00Z").unwrap(),
        DvDateTime::new("2026-08-01T13:00:00Z").unwrap(),
    )
    .unwrap();
    assert!(range.contains(&DvDateTime::new("2026-08-01T11:00:00Z").unwrap()));
    assert!(range.contains(&DvDateTime::new("2026-08-01T12:00:00+01:00").unwrap()));
    assert!(!range.contains(&DvDateTime::new("2026-08-01T14:00:00Z").unwrap()));

    // A bound that is not comparable is excluded, not silently admitted.
    let month = DvDateTime::new("2026-08").unwrap();
    assert_eq!(month.semantic_cmp(&DvDateTime::new("2026-08-01T11:00:00Z").unwrap()), None);
    assert!(!range.contains(&month), "an incomparable value was admitted");

    // An excluded bound is still excluded.
    let open = openehr::base::Interval::open(
        DvDateTime::new("2026-08-01T11:00:00Z").unwrap(),
        DvDateTime::new("2026-08-01T13:00:00Z").unwrap(),
    )
    .unwrap();
    assert!(!open.contains(&DvDateTime::new("2026-08-01T11:00:00Z").unwrap()));
    assert!(!open.contains(&DvDateTime::new("2026-08-01T12:00:00+01:00").unwrap()));
    assert!(open.contains(&DvDateTime::new("2026-08-01T12:00:00Z").unwrap()));
}

/// A non-ASCII string literal survives AQL lexing.
///
/// **Failure mode.** The lexer scanned the input as bytes — correct, since the
/// only bytes it examines are ASCII delimiters — but *copied* them one at a
/// time with `value.push(bytes[i] as char)`. That widens each UTF-8 byte into
/// its own `char`, so every non-ASCII character became Latin-1 mojibake:
/// `'Müller'` lexed to `'Müller'`. A `WHERE name = 'Müller'` then matched
/// nobody, and nothing reported it — the query parsed, checked clean, and was
/// simply about a different string. Found by the `aql` fuzz target as a
/// non-idempotent render; the corruption is the larger half. `A-37`.
#[test]
fn an_aql_string_literal_is_not_mangled_by_the_lexer() {
    for text in ["Müller", "日本語", "Ω", "naïve café", "\u{59a}\u{7fc}"] {
        let query: AqlQuery = format!("SELECT c FROM EHR e WHERE c/name/value = '{text}'")
            .parse()
            .unwrap_or_else(|e| panic!("{text:?} must parse: {e}"));
        assert!(
            query.to_string().contains(text),
            "{text:?} was corrupted to {:?}",
            query.to_string()
        );
    }
}

/// Rendering an AQL query and reparsing it yields the same query.
///
/// **Failure mode, twice over.** A renderer that is not idempotent silently
/// rewrites a caller's query into a different one, and both defects here did
/// exactly that:
///
/// * `FROM` puts `CONTAINS`, `AND` and `OR` at one precedence level, and
///   `CONTAINS` takes the whole remainder as its right operand. So
///   `Or(Contains(a, b), c)` rendered as `(a CONTAINS b OR c)` and reparsed as
///   `Contains(a, Or(b, c))` — *a containing either b or c*, where the caller
///   asked for *either (a containing b) or c*. Different records.
/// * A string literal containing a quote rendered unescaped, so `it's` came
///   back as `'it's'`.
///
/// This is `Q12.7`'s round-trip property, driven over the shapes that broke it
/// rather than over the shapes that already worked.
#[test]
fn aql_rendering_round_trips_through_the_parser() {
    for text in [
        "SELECT c FROM (EHR e CONTAINS COMPOSITION c) OR EHR x",
        "SELECT c FROM EHR e CONTAINS (COMPOSITION c OR EHR x)",
        "SELECT c FROM (EHR e CONTAINS COMPOSITION c) CONTAINS OBSERVATION o",
        "SELECT c FROM EHR e CONTAINS COMPOSITION c",
        r"SELECT c FROM EHR e WHERE c/name/value = 'it\'s'",
        r"SELECT c FROM EHR e WHERE c/name/value = 'back\\slash'",
        "SELECT c FROM EHR e WHERE c/name/value = 'Müller'",
    ] {
        let once: AqlQuery = text.parse().unwrap_or_else(|e| panic!("{text:?}: {e}"));
        let rendered = once.to_string();
        let twice: AqlQuery = rendered
            .parse()
            .unwrap_or_else(|e| panic!("{text:?} rendered to {rendered:?}, which will not reparse: {e}"));
        assert_eq!(
            twice.to_string(),
            rendered,
            "rendering {text:?} is not idempotent"
        );
        // Stronger than string equality of the render: the *tree* is the same,
        // so the second query selects the same records as the first.
        assert_eq!(twice, once, "reparsing {text:?} produced a different query");
    }
}

/// A high-precision magnitude survives repeated canonical round trips.
///
/// **This test asserted the opposite until 2026-08-22.** `serde_json`'s float
/// parser was not the inverse of its own serializer, so a magnitude *drifted*:
///
/// ```text
/// 4.4444444444444444e-7 → 4.4444444444444454e-7 → 4.444444444444446e-7 → stable
/// ```
///
/// That was `A-38`, reported as <https://github.com/serde-rs/json/issues/1336>
/// and recorded here as open and upstream. It was neither: `serde_json` has a
/// **`float_roundtrip`** feature that makes `f64 → JSON → f64` exact, and this
/// crate had not enabled it. The fix was one word in thirteen manifests.
///
/// The test is kept rather than deleted, pointed the other way. The property is
/// still not this crate's to guarantee — it now rests on a cargo feature
/// staying enabled, which is one careless edit away from silently reverting to
/// drift that nothing else would notice.
#[test]
fn a_high_precision_magnitude_survives_repeated_canonical_round_trips() {
    let source = r#"{"_type":"DV_QUANTITY","magnitude":0.000000444444444444444444444444444444444444444444441569995,"units":"m"}"#;
    let mut value: DataValue = serde_json::from_str(source).expect("parses");

    let mut seen = Vec::new();
    for _ in 0..4 {
        let canonical = openehr::security::to_canonical_string(&value).expect("canonicalises");
        seen.push(canonical.clone());
        value = serde_json::from_str(&canonical).expect("re-parses");
    }

    assert_eq!(
        seen[0], seen[1],
        "the magnitude moved between the first and second canonicalisation — \
         `float_roundtrip` may have been dropped from serde_json's features (A-38)"
    );
    assert!(
        seen.iter().all(|s| *s == seen[0]),
        "canonical form is not a fixed point: {seen:?}"
    );

    // The parser and the serializer agree, which is the property underneath.
    let text = "1.5777777777770001";
    assert_eq!(
        serde_json::from_str::<f64>(text).expect("parses").to_bits(),
        text.parse::<f64>().expect("parses").to_bits(),
        "serde_json and core disagree about a float by one ULP (A-38)"
    );
}

/// Every code the crate declines to validate is reachable through its API.
///
/// **This pins the premise of a departure, not a behaviour.** `lib:S1.18` and
/// its neighbours decline to check ten openEHR invariants — `COMPOSITION`'s
/// language and territory, `DV_TEXT`'s and `ENTRY`'s encoding and language,
/// `DV_ENCAPSULATED`'s charset and language, `DV_MULTIMEDIA`'s media type —
/// because the code sets are mutable and a table compiled into a library is
/// wrong from the day a country changes. Rejecting conformant data is the worse
/// failure (`D3.5`).
///
/// The departure ends with: *"A deployment that needs the check should do it
/// where the tables can be updated."* That sentence is only true while a caller
/// can **reach** each code, and reachability is not free — `lib:A-34` is the
/// finding where `DV_ENCAPSULATED`'s charset and language round-tripped
/// perfectly and could not be read, because `EncapsulatedAttrs` was exported and
/// no type returned one. The accessors this test uses were *added* by that
/// finding.
///
/// **Failure mode.** An accessor with no caller can be deleted, or quietly
/// narrowed, and every test still passes — at which point the departure is
/// silently worse than declared: the crate does not do the check and the caller
/// can no longer do it either.
#[test]
fn a_caller_can_read_every_code_the_crate_declines_to_check() {
    // COMPOSITION.language, COMPOSITION.territory — `S1.18`.
    let composition = composition_containing("irrelevant");
    assert_eq!(composition.language().code_string(), "en");
    assert_eq!(composition.territory().code_string(), "GB");

    // ENTRY.language, ENTRY.encoding.
    let entry = composition
        .entries()
        .next()
        .expect("the fixture holds one entry");
    // Reached through `Entry::entry_attrs`, because `Entry` is the enum over
    // the five entry classes and the codes live on the attributes they share.
    // That indirection is the part worth pinning: it is one accessor away from
    // the `A-34` shape, where the data was present and unreachable.
    assert_eq!(entry.entry_attrs().language().code_string(), "en");
    assert_eq!(entry.entry_attrs().encoding().code_string(), "UTF-8");

    // DV_TEXT.language, DV_TEXT.encoding. Optional, so both answers matter:
    // absent is a fact, and present must be readable.
    let plain = DvText::new("x").unwrap();
    assert!(plain.language().is_none() && plain.encoding().is_none());
    let tagged = DvText::new("x")
        .unwrap()
        .with_language(CodePhrase::new("ISO_639-1", "fr").unwrap())
        .with_encoding(CodePhrase::new("IANA_character-sets", "UTF-8").unwrap());
    assert_eq!(tagged.language().expect("set above").code_string(), "fr");
    assert_eq!(tagged.encoding().expect("set above").code_string(), "UTF-8");

    // DV_ENCAPSULATED.charset and .language, and DV_MULTIMEDIA.media_type.
    //
    // These have no builder: they arrive by deserialization, which is the path
    // that matters — a code the crate will not check is a code that came from
    // outside it.
    let multimedia: DvMultimedia = serde_json::from_str(
        r#"{
            "media_type": {"terminology_id": {"value": "IANA_media-types"},
                           "code_string": "image/png"},
            "charset": {"terminology_id": {"value": "IANA_character-sets"},
                        "code_string": "UTF-8"},
            "language": {"terminology_id": {"value": "ISO_639-1"}, "code_string": "de"}
        }"#,
    )
    .expect("a multimedia value with all three codes");
    assert_eq!(multimedia.media_type().code_string(), "image/png");
    let encapsulated = multimedia.encapsulated();
    assert_eq!(
        encapsulated.charset().expect("set above").code_string(),
        "UTF-8"
    );
    assert_eq!(
        encapsulated.language().expect("set above").code_string(),
        "de"
    );
}