cadmpeg-codec-step 0.6.8

Read and write ISO 10303-21 STEP Part 21 files for AP203, AP214, and AP242.
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
// SPDX-License-Identifier: Apache-2.0
//! Nesting follows the session depth; value-node limits omit the bounded item.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;

use cadmpeg_core::decode::{DecodePolicy, ResourceDimension};
use cadmpeg_core::CodecError;

use crate::parse::{
    AnchorResolver, ParseDiagnosticKind, ReferenceEntry, ReferenceName, ReferenceResolver,
    ResolveError, Value, EXPANDED_PAYLOAD_BASE,
};
use crate::test_support::{with_policy_context, with_service_context};

const ANCHOR_BOUND: &str = "anchor expansion exceeds 1000000 value nodes";
const REFERENCE_BOUND: &str = "external reference expansion exceeds 1000000 value nodes";

fn assert_bounded(error: &ResolveError, expected: &str) {
    assert!(
        matches!(error, ResolveError::Bounded(message) if message == expected),
        "{expected}: {error:?}"
    );
}

fn assert_depth_refusal(error: &ResolveError) {
    assert!(
        matches!(error, ResolveError::Resource(CodecError::ResourceLimit(refusal))
            if refusal.dimension == ResourceDimension::RecursionDepth),
        "{error:?}"
    );
}

fn depth_policy(depth: u64) -> DecodePolicy {
    let mut policy = DecodePolicy::service();
    policy.limits.max_recursion_depth = depth;
    policy
}

fn on_large_stack(run: impl FnOnce() + Send + 'static) {
    std::thread::Builder::new()
        .stack_size(16 * 1024 * 1024)
        .spawn(run)
        .expect("fixture thread starts")
        .join()
        .expect("fixture thread completes");
}

/// Anchors `a0` to `a{last}`; each holds ten copies of the one before, so
/// `a{k}` expands to `(10^(k+2) - 1) / 9` value nodes.
fn fan_out_anchors(last: usize) -> String {
    let mut anchors = String::from("<a0>=(1,1,1,1,1,1,1,1,1,1);");
    for index in 1..=last {
        let copy = format!("<#a{}>", index - 1);
        write!(anchors, "<a{index}>=({});", vec![copy; 10].join(","))
            .expect("write anchor fixture");
    }
    anchors
}

fn exchange_source(anchors: &str, references: &str, data: &str) -> String {
    let references = if references.is_empty() {
        String::new()
    } else {
        format!("REFERENCE;{references}ENDSEC;")
    };
    format!(
        "ISO-10303-21;HEADER;FILE_DESCRIPTION(('test'),'4;3');FILE_NAME('','',(''),(''),'','','');FILE_SCHEMA(('AP242'));ENDSEC;ANCHOR;{anchors}ENDSEC;{references}DATA;{data}ENDSEC;END-ISO-10303-21;"
    )
}

fn parse_with_service(
    source: &str,
) -> (crate::parse::Exchange, Vec<crate::parse::ParseDiagnostic>) {
    with_service_context(source.as_bytes(), crate::parse::parse)
        .expect("a bounded expansion omits items instead of refusing the decode")
}

fn has_diagnostic(
    diagnostics: &[crate::parse::ParseDiagnostic],
    kind: ParseDiagnosticKind,
    message: &str,
) -> bool {
    diagnostics
        .iter()
        .any(|diagnostic| diagnostic.kind == kind && diagnostic.message == message)
}

#[test]
fn parameter_nesting_follows_the_session_depth() {
    on_large_stack(|| {
        let nested = format!("{}1{}", "(".repeat(300), ")".repeat(300));
        let source = format!("ISO-10303-21;HEADER;FILE_DESCRIPTION(('test'),'2;1');FILE_NAME('','',(''),(''),'','','');FILE_SCHEMA(('AP242'));ENDSEC;DATA;#1=ITEM({nested});ENDSEC;END-ISO-10303-21;");
        with_policy_context(source.as_bytes(), &depth_policy(1024), |source, ctx| {
            let (exchange, _) =
                crate::parse::parse(source, ctx).expect("the session admits 300 levels");
            assert!(exchange.records().contains_key(&1));
        });
        with_policy_context(source.as_bytes(), &depth_policy(200), |source, ctx| {
            let error = crate::parse::parse(source, ctx).expect_err("the session refuses");
            assert!(matches!(error, CodecError::ResourceLimit(refusal)
                if refusal.dimension == ResourceDimension::RecursionDepth
                    && refusal.operation == "step_parse_parameter_nesting"));
        });
    });
}

#[test]
fn anchor_reference_depth_follows_the_session_depth() {
    on_large_stack(|| {
        let mut anchors = BTreeMap::from([("a0".to_owned(), Value::Integer(1))]);
        for index in 1..300 {
            anchors.insert(
                format!("a{index}"),
                Value::List(vec![Value::Resource(format!("#a{}", index - 1))]),
            );
        }
        let root = Value::Resource("#a299".into());
        with_policy_context(b"", &depth_policy(4096), |_, ctx| {
            let mut resolver = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx);
            let mut value = resolver.resolve_root(&root).expect("the session admits");
            let mut levels = 0;
            while let Value::List(mut values) = value {
                value = values.pop().expect("one nested value");
                levels += 1;
            }
            assert_eq!(levels, 299);
        });
        with_policy_context(b"", &depth_policy(64), |_, ctx| {
            let error = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx)
                .resolve_root(&root)
                .expect_err("the session refuses");
            assert_depth_refusal(&error);
        });
    });
}

#[test]
fn reference_expansion_depth_follows_the_session_depth() {
    on_large_stack(|| {
        let mut anchors = BTreeMap::from([("r0".to_owned(), Value::List(vec![Value::Integer(1)]))]);
        let mut references = vec![ReferenceEntry {
            name: ReferenceName::Value(1),
            uri: "#r0".into(),
        }];
        for index in 1..300 {
            anchors.insert(
                format!("r{index}"),
                Value::List(vec![Value::ExternalReference(index)]),
            );
            references.push(ReferenceEntry {
                name: ReferenceName::Value(index + 1),
                uri: format!("#r{index}"),
            });
        }
        let omitted = BTreeSet::new();
        let root = Value::ExternalReference(300);
        with_policy_context(b"", &depth_policy(4096), |_, ctx| {
            let mut value =
                ReferenceResolver::new(&references, &anchors, &omitted, EXPANDED_PAYLOAD_BASE, ctx)
                    .resolve_value(&root)
                    .expect("the session admits");
            let mut levels = 0;
            while let Value::List(mut values) = value {
                value = values.pop().expect("one nested value");
                levels += 1;
            }
            assert_eq!(levels, 300);
        });
        with_policy_context(b"", &depth_policy(64), |_, ctx| {
            let error =
                ReferenceResolver::new(&references, &anchors, &omitted, EXPANDED_PAYLOAD_BASE, ctx)
                    .resolve_value(&root)
                    .expect_err("the session refuses");
            assert_depth_refusal(&error);
        });
    });
}

#[test]
fn anchor_memo_output_node_slice_is_bounded() {
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([(
            "a".into(),
            Value::List(vec![Value::Integer(1), Value::Integer(2)]),
        )]);
        let mut resolver = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx);
        let value = Value::Resource("#a".into());
        resolver
            .resolve_root(&value)
            .expect("fixture operation succeeds");
        resolver.remaining_nodes = 2;
        assert_bounded(
            &resolver
                .resolve_root(&value)
                .expect_err("the node limit stops the expansion"),
            ANCHOR_BOUND,
        );
    });
}

#[test]
fn anchor_first_expansion_output_node_slice_is_bounded() {
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([(
            "a".into(),
            Value::List(vec![Value::Integer(1), Value::Integer(2)]),
        )]);
        let mut resolver = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 2;
        assert_bounded(
            &resolver
                .resolve_root(&Value::Resource("#a".into()))
                .expect_err("the node limit stops the expansion"),
            ANCHOR_BOUND,
        );
    });
}

#[test]
fn bounded_anchor_item_gives_back_its_nodes() {
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([(
            "a".into(),
            Value::List(vec![Value::Integer(1), Value::Integer(2)]),
        )]);
        let mut resolver = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 4;
        let mut item = [Value::Resource("#a".into()), Value::Resource("#a".into())];
        assert_eq!(
            resolver
                .resolve_item(item.iter_mut())
                .expect("a node limit is not an error")
                .as_deref(),
            Some(ANCHOR_BOUND)
        );
        assert_eq!(resolver.remaining_nodes, 4);

        let mut item = [Value::Resource("#a".into())];
        assert_eq!(
            resolver
                .resolve_item(item.iter_mut())
                .expect("the item fits"),
            None
        );
        assert_eq!(resolver.remaining_nodes, 1);
        assert_eq!(item[0], anchors["a"]);
    });
}

/// Anchors `a0` to `a{last}`; each holds two copies of the one before, so
/// `a{k}` expands to `2^(k+2) - 1` value nodes.
fn doubling_anchor_values(last: usize) -> BTreeMap<String, Value> {
    let mut anchors = BTreeMap::from([(
        "a0".to_owned(),
        Value::List(vec![Value::Integer(1), Value::Integer(1)]),
    )]);
    for index in 1..=last {
        let previous = Value::Resource(format!("#a{}", index - 1));
        anchors.insert(
            format!("a{index}"),
            Value::List(vec![previous.clone(), previous]),
        );
    }
    anchors
}

#[test]
fn repeated_bounded_anchor_items_stop_before_copying() {
    with_service_context(b"", |_, ctx| {
        let anchors = doubling_anchor_values(12);
        let mut resolver = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 10_000;
        let mut first = [Value::Resource("#a12".into())];
        assert_eq!(
            resolver
                .resolve_item(first.iter_mut())
                .expect("a node limit is not an error")
                .as_deref(),
            Some(ANCHOR_BOUND)
        );
        let allowance = resolver.discard_allowance;

        for _ in 0..10_000 {
            let mut item = [
                Value::Resource("#a11".into()),
                Value::Resource("#a12".into()),
            ];
            assert_eq!(
                resolver
                    .resolve_item(item.iter_mut())
                    .expect("a node limit is not an error")
                    .as_deref(),
                Some(ANCHOR_BOUND)
            );
            assert_eq!(item[0], Value::Resource("#a11".into()));
        }
        assert_eq!(resolver.discard_allowance, allowance);
        assert_eq!(resolver.remaining_nodes, 10_000);

        let mut item = [Value::Resource("#a11".into())];
        assert_eq!(
            resolver
                .resolve_item(item.iter_mut())
                .expect("the item fits"),
            None
        );
        assert_eq!(resolver.remaining_nodes, 10_000 - 8_191);
    });
}

#[test]
fn omitted_anchor_items_past_the_discard_allowance_are_skipped() {
    const DISCARD_BOUND: &str =
        "anchor expansions omitted at the node limit already copied 16000000 value nodes";
    with_service_context(b"", |_, ctx| {
        let mut anchors = doubling_anchor_values(4);
        for name in ["f", "g"] {
            anchors.insert(
                name.into(),
                Value::List(vec![
                    Value::Resource("#a4".into()),
                    Value::Resource("#a4".into()),
                ]),
            );
        }
        let mut resolver = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 100;
        resolver.discard_allowance = Some(1);
        let mut resolve = |value: Value| {
            let mut item = [value];
            resolver
                .resolve_item(item.iter_mut())
                .expect("a node limit is not an error")
        };

        assert_eq!(
            resolve(Value::Resource("#f".into())).as_deref(),
            Some(ANCHOR_BOUND)
        );
        assert_eq!(
            resolve(Value::Resource("#g".into())).as_deref(),
            Some(DISCARD_BOUND)
        );
        assert_eq!(
            resolve(Value::Resource("#f".into())).as_deref(),
            Some(ANCHOR_BOUND)
        );
        assert_eq!(resolve(Value::Resource("#a4".into())), None);
        assert_eq!(resolve(Value::Integer(1)), None);
        assert_eq!(resolver.discard_allowance, None);
        assert_eq!(resolver.remaining_nodes, 100 - 63);
    });
}

#[test]
fn repeated_bounded_reference_items_stop_before_copying() {
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([(
            "a".into(),
            Value::List(vec![
                Value::Integer(1),
                Value::Integer(2),
                Value::Integer(3),
            ]),
        )]);
        let references = [ReferenceEntry {
            name: ReferenceName::Value(2),
            uri: "#a".into(),
        }];
        let omitted = BTreeSet::new();
        let mut resolver =
            ReferenceResolver::new(&references, &anchors, &omitted, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 10;
        let allowance = resolver.discard_allowance;
        let mut first = [Value::ExternalReference(2), Value::ExternalReference(2)];
        assert_eq!(
            resolver
                .resolve_item(first.iter_mut())
                .expect("the item fits"),
            None
        );
        assert_eq!(resolver.remaining_nodes, 2);
        assert_eq!(resolver.discard_allowance, allowance);

        for _ in 0..10_000 {
            let mut item = [Value::Integer(7), Value::ExternalReference(2)];
            assert_eq!(
                resolver
                    .resolve_item(item.iter_mut())
                    .expect("a node limit is not an error")
                    .as_deref(),
                Some(REFERENCE_BOUND)
            );
            assert_eq!(item[1], Value::ExternalReference(2));
        }
        assert_eq!(resolver.discard_allowance, allowance);
        assert_eq!(resolver.remaining_nodes, 2);
    });
}

#[test]
fn omitted_reference_items_past_the_discard_allowance_are_skipped() {
    const DISCARD_BOUND: &str = "external reference expansions omitted at the node limit already copied 16000000 value nodes";
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([
            ("big".into(), Value::List(vec![Value::Integer(1); 20])),
            ("small".into(), Value::Integer(1)),
        ]);
        let references = [
            ReferenceEntry {
                name: ReferenceName::Value(1),
                uri: "#big".into(),
            },
            ReferenceEntry {
                name: ReferenceName::Value(2),
                uri: "#big".into(),
            },
            ReferenceEntry {
                name: ReferenceName::Value(3),
                uri: "#small".into(),
            },
        ];
        let omitted = BTreeSet::new();
        let mut resolver =
            ReferenceResolver::new(&references, &anchors, &omitted, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 10;
        resolver.discard_allowance = Some(1);
        let mut resolve = |value: Value| {
            let mut item = [value];
            resolver
                .resolve_item(item.iter_mut())
                .expect("a node limit is not an error")
        };

        assert_eq!(
            resolve(Value::ExternalReference(1)).as_deref(),
            Some(REFERENCE_BOUND)
        );
        assert_eq!(
            resolve(Value::ExternalReference(2)).as_deref(),
            Some(DISCARD_BOUND)
        );
        assert_eq!(
            resolve(Value::ExternalReference(1)).as_deref(),
            Some(REFERENCE_BOUND)
        );
        assert_eq!(
            resolve(Value::ExternalReference(3)).as_deref(),
            Some(DISCARD_BOUND)
        );
        assert_eq!(resolve(Value::Integer(1)), None);
        assert_eq!(resolver.discard_allowance, None);
        assert_eq!(resolver.remaining_nodes, 10);
    });
}

#[test]
fn reference_output_node_slice_bounds_before_leaf_copy() {
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([("a".into(), Value::Enumeration("TEXT".into()))]);
        let references = [ReferenceEntry {
            name: ReferenceName::Value(2),
            uri: "#a".into(),
        }];
        let omitted = BTreeSet::new();
        let mut resolver =
            ReferenceResolver::new(&references, &anchors, &omitted, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 1;
        assert_eq!(
            resolver
                .resolve_value(&Value::ExternalReference(2))
                .expect("fixture operation succeeds"),
            anchors["a"]
        );
        assert_bounded(
            &resolver
                .resolve_value(&Value::ExternalReference(2))
                .expect_err("the node limit stops the expansion"),
            REFERENCE_BOUND,
        );
    });
}

#[test]
fn reference_output_node_slice_bounds_before_list_storage() {
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([(
            "a".into(),
            Value::List(vec![Value::Integer(1), Value::Integer(2)]),
        )]);
        let references = [ReferenceEntry {
            name: ReferenceName::Value(2),
            uri: "#a".into(),
        }];
        let omitted = BTreeSet::new();
        let mut resolver =
            ReferenceResolver::new(&references, &anchors, &omitted, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 2;
        assert_bounded(
            &resolver
                .resolve_value(&Value::ExternalReference(2))
                .expect_err("the node limit stops the expansion"),
            REFERENCE_BOUND,
        );
    });
}

#[test]
fn bounded_reference_item_gives_back_its_nodes() {
    with_service_context(b"", |_, ctx| {
        let anchors = BTreeMap::from([("a".into(), Value::Enumeration("TEXT".into()))]);
        let references = [ReferenceEntry {
            name: ReferenceName::Value(2),
            uri: "#a".into(),
        }];
        let omitted = BTreeSet::new();
        let mut resolver =
            ReferenceResolver::new(&references, &anchors, &omitted, EXPANDED_PAYLOAD_BASE, ctx);
        resolver.remaining_nodes = 1;
        let mut item = [Value::ExternalReference(2), Value::ExternalReference(2)];
        assert_eq!(
            resolver
                .resolve_item(item.iter_mut())
                .expect("a node limit is not an error")
                .as_deref(),
            Some(REFERENCE_BOUND)
        );
        assert_eq!(resolver.remaining_nodes, 1);
    });
}

#[test]
fn value_node_count_depth_follows_the_session_depth() {
    let mut value = Value::Integer(1);
    for _ in 0..300 {
        value = Value::List(vec![value]);
    }
    with_policy_context(b"", &depth_policy(1024), |_, ctx| {
        assert_eq!(
            crate::parse::value_node_count(&value, 1_000_000, ctx).expect("the session admits"),
            301
        );
    });
}

#[test]
fn value_node_count_nodes_are_bounded() {
    with_service_context(b"", |_, ctx| {
        assert_bounded(
            &crate::parse::value_node_count(&Value::Integer(1), 0, ctx)
                .expect_err("the node limit stops the count"),
            "anchor value exceeds 0 value nodes",
        );
    });
}

#[test]
fn reference_expansion_limit_omits_the_record_and_its_dependents() {
    let source = exchange_source(
        &fan_out_anchors(4),
        "@10=<#a4>;",
        "#1=ITEM((@10,@10,@10,@10,@10,@10,@10,@10,@10,@10));#2=ITEM(@10);#3=ITEM(#1);",
    );
    let (exchange, diagnostics) = parse_with_service(&source);

    assert!(has_diagnostic(
        &diagnostics,
        ParseDiagnosticKind::ExpansionBounded,
        &format!("instance #1 omitted: {REFERENCE_BOUND}; exact source retained"),
    ));
    assert!(exchange
        .omitted_spans()
        .iter()
        .any(|span| source[span.clone()].starts_with("#1=ITEM((@10,")));
    assert!(exchange.records().contains_key(&2));
    assert!(has_diagnostic(
        &diagnostics,
        ParseDiagnosticKind::RecordOmitted,
        "instance #3 omitted: unresolved instance reference #1; exact source retained",
    ));
    assert!(!exchange.records().contains_key(&3));
}

#[test]
fn reference_to_a_bounded_anchor_omits_the_record() {
    let source = exchange_source(
        &fan_out_anchors(5),
        "@10=<#a5>;",
        "#1=ITEM(@10);#2=ITEM(1);",
    );
    let (exchange, diagnostics) = parse_with_service(&source);

    assert!(has_diagnostic(
        &diagnostics,
        ParseDiagnosticKind::ExpansionBounded,
        &format!("anchor <a5> omitted: {ANCHOR_BOUND}; exact source retained"),
    ));
    assert!(has_diagnostic(
        &diagnostics,
        ParseDiagnosticKind::ExpansionBounded,
        "instance #1 omitted: REFERENCE @10 names anchor <a5>, omitted at its expansion limit; exact source retained",
    ));
    assert!(!exchange.records().contains_key(&1));
    assert!(exchange.records().contains_key(&2));
}

#[test]
fn anchor_naming_a_bounded_instance_is_omitted_not_refused() {
    let source = exchange_source(
        &format!("{}<b>=#1;", fan_out_anchors(5)),
        "",
        "#1=ITEM(<#a5>);#2=ITEM(1);",
    );
    let (exchange, diagnostics) = parse_with_service(&source);

    assert!(has_diagnostic(
        &diagnostics,
        ParseDiagnosticKind::ExpansionBounded,
        &format!("instance #1 omitted: {ANCHOR_BOUND}; exact source retained"),
    ));
    assert!(has_diagnostic(
        &diagnostics,
        ParseDiagnosticKind::ExpansionBounded,
        "anchor <b> omitted: depends on instance #1, omitted at its expansion limit; exact source retained",
    ));
    assert!(exchange
        .omitted_spans()
        .iter()
        .any(|span| &source[span.clone()] == "<b>=#1;"));
    assert!(exchange.anchors().iter().all(|anchor| anchor.name != "b"));
    assert!(exchange.records().contains_key(&2));
}

const LARGE_STRING_OCTETS: usize = 32_000;
const LARGE_STRING_RECORDS: usize = 4_000;

/// Anchor `big` holds one large string that every DATA record copies through
/// `occurrence`. Returns the source and the payload allowance it receives.
fn large_string_exchange(references: &str, occurrence: &str) -> (String, usize) {
    let records = (1..=LARGE_STRING_RECORDS).fold(String::new(), |mut records, id| {
        write!(records, "#{id}=ITEM({occurrence});").expect("write record fixture");
        records
    });
    let anchors = format!("<big>='{}';", "A".repeat(LARGE_STRING_OCTETS));
    let source = exchange_source(&anchors, references, &records);
    let allowance = 16 * source.len() + 16 * 1024 * 1024;
    assert!(
        LARGE_STRING_RECORDS * LARGE_STRING_OCTETS > 6 * allowance,
        "unbounded copies must pass the allowance several times over"
    );
    (source, allowance)
}

fn assert_payload_bounded(source: &str, allowance: usize, expansion: &str, occurrence: &str) {
    let (exchange, diagnostics) = parse_with_service(source);
    let kept = allowance / LARGE_STRING_OCTETS;
    assert_eq!(
        exchange.records().keys().copied().collect::<Vec<_>>(),
        (1..=u64::try_from(kept).expect("small count")).collect::<Vec<_>>()
    );
    let bound = format!(
        "{expansion} expansion exceeds {allowance} payload bytes (MAX_EXPANDED_PAYLOAD_PER_INPUT_BYTE)"
    );
    for id in kept + 1..=LARGE_STRING_RECORDS {
        assert!(
            has_diagnostic(
                &diagnostics,
                ParseDiagnosticKind::ExpansionBounded,
                &format!("instance #{id} omitted: {bound}; exact source retained"),
            ),
            "#{id}"
        );
    }
    let last = format!("#{LARGE_STRING_RECORDS}=ITEM({occurrence});");
    assert!(exchange
        .omitted_spans()
        .iter()
        .any(|span| source[span.clone()] == last));
}

#[test]
fn payload_copied_by_an_omitted_item_stays_charged() {
    with_service_context(b"", |_, ctx| {
        let mut anchors = doubling_anchor_values(4);
        anchors.insert("s".into(), Value::String(b"ABCD".to_vec()));
        let mut resolver = AnchorResolver::new(&anchors, EXPANDED_PAYLOAD_BASE, ctx);
        let allowance = resolver.payload.remaining;
        resolver.remaining_nodes = 10;
        let mut item = [Value::Resource("#s".into()), Value::Resource("#a4".into())];

        assert_eq!(
            resolver
                .resolve_item(item.iter_mut())
                .expect("a node limit is not an error")
                .as_deref(),
            Some(ANCHOR_BOUND)
        );
        assert_eq!(resolver.remaining_nodes, 10);
        assert_eq!(resolver.payload.remaining, allowance - 4);
    });
}

#[test]
fn repeated_large_anchor_string_stops_at_the_payload_allowance() {
    let (source, allowance) = large_string_exchange("", "<#big>");
    assert_payload_bounded(&source, allowance, "anchor", "<#big>");
}

#[test]
fn repeated_large_reference_string_stops_at_the_payload_allowance() {
    let (source, allowance) = large_string_exchange("@9000=<#big>;", "@9000");
    assert_payload_bounded(&source, allowance, "external reference", "@9000");
}

#[test]
fn unknown_record_omits_non_finite_real_at_lex_admission() {
    const SOURCE: &[u8] = b"ISO-10303-21;HEADER;FILE_DESCRIPTION(('test'),'2;1');FILE_NAME('','',(''),(''),'','','');FILE_SCHEMA(('AP242'));ENDSEC;DATA;#1=UNKNOWN_ITEM(1.E9999);ENDSEC;END-ISO-10303-21;";
    with_service_context(SOURCE, |source, ctx| {
        let (exchange, diagnostics) =
            crate::parse::parse(source, ctx).expect("literal failure has a bounded record");
        assert!(exchange.records().is_empty());
        assert!(diagnostics.iter().any(|diagnostic| {
            diagnostic.kind == crate::parse::ParseDiagnosticKind::RecordOmitted
                && diagnostic.message.contains("finite binary64 range")
        }));
    });
}