type-bridge-schema 2.2.3

Canonical schema resolution and projection engine for type-bridge
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
use std::collections::BTreeSet;

use type_bridge_contract::id::{AttributeId, FunctionId, RoleId, StructId, TypeId, TypeKind};
use type_bridge_contract::limits::MAX_CANONICAL_STRING_BYTES;
use type_bridge_contract::schema::DocumentId;
use type_bridge_contract::schema::{
    AnnotationKindId, AnnotationSubjectId, CollectionMode, FunctionReturnMode, OwnsFactId,
    RelatesFactId, SchemaFact, SchemaFactId,
};
use type_bridge_contract::value::ValueTypeTag;
use type_bridge_schema::{SchemaDocumentSet, normalize_documents};

fn documents(source: &str) -> SchemaDocumentSet {
    SchemaDocumentSet::parse([(
        DocumentId::new("schema.yaml").expect("fixture document identifier is valid"),
        source,
    )])
    .expect("fixture YAML parses")
}

#[test]
fn ordered_and_distinct_owns_and_relates_normalize_as_independent_facts() {
    let declared = normalize_documents(&documents(
        r#"format: typebridge.schema/v2
attributes:
  tag: { value: string }
entities:
  article:
    owns:
      tag: { ordered: true, distinct: true }
relations:
  collection:
    relates:
      member: { ordered: true, distinct: true }
"#,
    ))
    .expect("ordered collections normalize");

    let owns_id = OwnsFactId::new(
        TypeId::new(TypeKind::Entity, "article").unwrap(),
        AttributeId::new("tag").unwrap(),
    )
    .unwrap();
    let relates_id = RelatesFactId::new(
        TypeId::new(TypeKind::Relation, "collection").unwrap(),
        RoleId::new("collection", "member").unwrap(),
    )
    .unwrap();
    let Some(SchemaFact::Owns(owns)) = declared.fact(&SchemaFactId::Owns(owns_id.clone())) else {
        panic!("ordered owns fact exists");
    };
    let Some(SchemaFact::Relates(relates)) =
        declared.fact(&SchemaFactId::Relates(relates_id.clone()))
    else {
        panic!("ordered relates fact exists");
    };
    assert_eq!(owns.collection_mode(), CollectionMode::OrderedList);
    assert_eq!(relates.collection_mode(), CollectionMode::OrderedList);

    for subject in [
        AnnotationSubjectId::Owns(owns_id),
        AnnotationSubjectId::Relates(relates_id),
    ] {
        assert!(declared.facts().any(|fact| matches!(
            fact,
            SchemaFact::Annotation(annotation)
                if annotation.id().subject() == &subject
                    && annotation.id().kind() == &AnnotationKindId::Distinct
        )));
    }
}

#[test]
fn omitted_collection_flags_preserve_the_unordered_compatibility_default() {
    let declared = normalize_documents(&documents(
        r#"format: typebridge.schema/v2
attributes:
  tag: { value: string }
entities:
  article: { owns: [tag] }
relations:
  collection: { relates: [member] }
"#,
    ))
    .expect("unordered collections normalize");

    for fact in declared.facts() {
        match fact {
            SchemaFact::Owns(fact) => {
                assert_eq!(fact.collection_mode(), CollectionMode::Unordered)
            }
            SchemaFact::Relates(fact) => {
                assert_eq!(fact.collection_mode(), CollectionMode::Unordered)
            }
            _ => {}
        }
    }
}

#[test]
fn collection_flags_reject_false_string_non_boolean_and_plays_forms() {
    for (fragment, expected) in [
        (
            "entities:\n  article:\n    owns:\n      tag: { ordered: false }\n",
            "false_presence_annotation",
        ),
        (
            "entities:\n  article:\n    owns:\n      tag: { distinct: false }\n",
            "false_presence_annotation",
        ),
        (
            "entities:\n  article:\n    owns:\n      tag: { ordered: \"true\" }\n",
            "invalid_schema_boolean",
        ),
        (
            "entities:\n  article:\n    owns:\n      tag: { ordered: 1 }\n",
            "invalid_schema_boolean",
        ),
        (
            "entities:\n  article: {}\nrelations:\n  collection: { relates: [member] }\nplays:\n  article:\n    collection:\n      member: { ordered: true }\n",
            "unknown_schema_document_key",
        ),
    ] {
        let source = format!(
            "format: typebridge.schema/v2\nattributes:\n  tag: {{ value: string }}\n{fragment}"
        );
        let error = normalize_documents(&documents(&source)).expect_err("invalid flag rejects");
        let diagnostic = error.iter().next().expect("one diagnostic");
        assert_eq!(diagnostic.diagnostic().code().as_str(), expected);
        assert!(diagnostic.primary().is_some());
    }
}

#[test]
fn distinct_requires_an_explicit_ordered_collection() {
    for fragment in [
        "entities:\n  article:\n    owns:\n      tag: { distinct: true }\n",
        "relations:\n  collection:\n    relates:\n      member: { distinct: true }\n",
    ] {
        let source = format!(
            "format: typebridge.schema/v2\nattributes:\n  tag: {{ value: string }}\n{fragment}"
        );
        let error = normalize_documents(&documents(&source))
            .expect_err("distinct unordered collection rejects");
        let diagnostic = error.iter().next().expect("one diagnostic");
        assert_eq!(
            diagnostic.diagnostic().code().as_str(),
            "distinct_requires_ordered_collection"
        );
        assert!(diagnostic.primary().is_some());
        assert_eq!(diagnostic.related().len(), 1);
    }
}

#[test]
fn normalizes_types_interfaces_annotations_and_relation_players() {
    let source = r#"format: typebridge.schema/v2
attributes:
  name:
    value:
      type: string
      regex: "^.+$"
entities:
  person:
    abstract: true
    owns:
      - name:
          card: { min: 1, max: 1 }
          doc: "Primary name"
relations:
  friendship:
    relates:
      friend:
        card: 2
plays:
  person:
    friendship:
      - friend:
          card: { min: 0, max: 1 }
"#;

    let declared = normalize_documents(&documents(source)).expect("schema normalizes");
    let person = TypeId::new(TypeKind::Entity, "person").expect("type identifier is valid");
    assert!(declared.fact(&SchemaFactId::Type(person)).is_some());
    assert_eq!(declared.facts().len(), 13);
}

#[test]
fn removing_independent_annotations_preserves_every_structural_subject() {
    let annotated = r#"format: typebridge.schema/v2
attributes:
  name:
    value:
      type: string
      regex: "^.+$"
entities:
  person:
    abstract: true
    owns:
      name:
        doc: "Primary name"
relations:
  friendship:
    relates:
      friend:
        card: { min: 0, max: 1 }
plays:
  person:
    friendship:
      friend:
        meta: { edge: "person-friend" }
"#;
    let plain = r#"format: typebridge.schema/v2
attributes:
  name:
    value: string
entities:
  person:
    owns: [name]
relations:
  friendship:
    relates: [friend]
plays:
  person:
    friendship: [friend]
"#;

    let annotated =
        normalize_documents(&documents(annotated)).expect("annotated schema normalizes");
    let plain = normalize_documents(&documents(plain)).expect("plain schema normalizes");
    let annotated_structural = annotated
        .facts()
        .filter(|fact| !matches!(fact, SchemaFact::Annotation(_)))
        .cloned()
        .collect::<Vec<_>>();
    let plain_structural = plain
        .facts()
        .filter(|fact| !matches!(fact, SchemaFact::Annotation(_)))
        .cloned()
        .collect::<Vec<_>>();
    assert_eq!(annotated_structural, plain_structural);

    let subjects = annotated
        .facts()
        .filter_map(|fact| {
            let SchemaFact::Annotation(annotation) = fact else {
                return None;
            };
            Some(match annotation.id().subject() {
                AnnotationSubjectId::Type(_) => "type",
                AnnotationSubjectId::Value(_) => "value",
                AnnotationSubjectId::Owns(_) => "owns",
                AnnotationSubjectId::Relates(_) => "relates",
                AnnotationSubjectId::Plays(_) => "plays",
                AnnotationSubjectId::Sub(_) => "sub",
                AnnotationSubjectId::Function(_) => "function",
            })
        })
        .collect::<BTreeSet<_>>();
    assert_eq!(
        subjects,
        BTreeSet::from(["type", "value", "owns", "relates", "plays"])
    );
    assert_ne!(
        annotated.declared_identity_fingerprint(),
        plain.declared_identity_fingerprint()
    );
}

#[test]
fn compact_and_expanded_facts_have_equal_declared_identity() {
    let compact = r#"format: typebridge.schema/v2
attributes:
  name:
    value: string
entities:
  person:
    owns: [name]
"#;
    let expanded = r#"format: typebridge.schema/v2
attributes:
  name:
    value: { type: string }
entities:
  person:
    owns:
      name: {}
"#;

    let compact = normalize_documents(&documents(compact)).expect("compact schema normalizes");
    let expanded = normalize_documents(&documents(expanded)).expect("expanded schema normalizes");
    assert_eq!(
        compact.declared_identity_fingerprint(),
        expanded.declared_identity_fingerprint()
    );
}

#[test]
fn required_capability_order_is_non_semantic() {
    let first = r#"format: typebridge.schema/v2
capabilities:
  required: [schema.roles, schema.annotations]
"#;
    let second = r#"format: typebridge.schema/v2
capabilities:
  required: [schema.annotations, schema.roles]
"#;

    let first = normalize_documents(&documents(first)).expect("first schema normalizes");
    let second = normalize_documents(&documents(second)).expect("second schema normalizes");
    assert_eq!(
        first.declared_identity_fingerprint(),
        second.declared_identity_fingerprint()
    );
}

#[test]
fn unknown_core_keys_fail_closed() {
    let source = r#"format: typebridge.schema/v2
entities:
  person:
    typo: true
"#;
    assert!(normalize_documents(&documents(source)).is_err());
}

#[test]
fn fragment_level_sources_are_rejected() {
    let source = r#"format: typebridge.schema/v2
sources: [fragments/*.yaml]
"#;
    let error = normalize_documents(&documents(source))
        .expect_err("source discovery belongs to the workspace manifest");
    let diagnostic = error.iter().next().unwrap();
    assert_eq!(
        diagnostic.diagnostic().code().as_str(),
        "unknown_schema_document_key",
    );
    let span = diagnostic
        .primary()
        .expect("unknown key retains its source span");
    let start = source.find("sources").unwrap();
    assert_eq!(span.document().as_str(), "schema.yaml");
    assert_eq!(
        (span.byte_start(), span.byte_end()),
        (start as u64, (start + 7) as u64)
    );
    assert_eq!((span.line(), span.column()), (2, 1));
    assert_eq!((span.end_line(), span.end_column()), (2, 8));
}

#[test]
fn scalar_and_expanded_sub_facts_have_equal_declared_identity() {
    let scalar = r#"format: typebridge.schema/v2
attributes:
  base-name: { value: string }
  display-name: { sub: base-name }
entities:
  actor: {}
  person: { sub: actor }
relations:
  association: {}
  friendship: { sub: association }
"#;
    let expanded = r#"format: typebridge.schema/v2
attributes:
  base-name: { value: string }
  display-name: { sub: { type: base-name } }
entities:
  actor: {}
  person: { sub: { type: actor } }
relations:
  association: {}
  friendship: { sub: { type: association } }
"#;

    let scalar = normalize_documents(&documents(scalar)).expect("scalar sub facts normalize");
    let expanded = normalize_documents(&documents(expanded)).expect("expanded sub facts normalize");
    assert_eq!(
        scalar.declared_identity_fingerprint(),
        expanded.declared_identity_fingerprint(),
    );
}

#[test]
fn expanded_sub_facts_attach_doc_and_meta_to_the_edge() {
    let source = r#"format: typebridge.schema/v2
attributes:
  base-name: { value: string }
  display-name:
    sub: { type: base-name, doc: "attribute edge", meta: { owner: "schema" } }
entities:
  actor: {}
  person:
    sub: { type: actor, doc: "entity edge", meta: { owner: "schema" } }
relations:
  association: {}
  friendship:
    sub: { type: association, doc: "relation edge", meta: { owner: "schema" } }
"#;
    let declared = normalize_documents(&documents(source)).expect("expanded sub facts normalize");
    let edge_annotations = declared
        .facts()
        .filter(|fact| {
            matches!(
                fact,
                SchemaFact::Annotation(annotation)
                    if matches!(annotation.id().subject(), AnnotationSubjectId::Sub(_))
            )
        })
        .count();
    assert_eq!(edge_annotations, 6);
}

#[test]
fn expanded_sub_shape_is_closed() {
    for (sub, code) in [
        ("[base]", "invalid_schema_sub_shape"),
        (
            "{ type: base, future: true }",
            "unknown_schema_document_key",
        ),
    ] {
        let source = format!(
            "format: typebridge.schema/v2\nentities:\n  base: {{}}\n  child:\n    sub: {sub}\n"
        );
        let error = normalize_documents(&documents(&source)).expect_err("shape must fail closed");
        assert_eq!(
            error.iter().next().unwrap().diagnostic().code().as_str(),
            code
        );
    }
}

#[test]
fn unknown_expanded_sub_key_reports_the_exact_key_span() {
    let source = r#"format: typebridge.schema/v2
entities:
  base: {}
  child:
    sub:
      type: base
      future: true
"#;
    let error = normalize_documents(&documents(source)).expect_err("unknown key must fail closed");
    let diagnostic = error.iter().next().unwrap();
    assert_eq!(
        diagnostic.diagnostic().code().as_str(),
        "unknown_schema_document_key",
    );
    let span = diagnostic
        .primary()
        .expect("unknown key retains its source span");
    let start = source.find("future").unwrap();
    assert_eq!(span.document().as_str(), "schema.yaml");
    assert_eq!(
        (span.byte_start(), span.byte_end()),
        (start as u64, (start + 6) as u64)
    );
    assert_eq!((span.line(), span.column()), (7, 7));
    assert_eq!((span.end_line(), span.end_column()), (7, 13));
}

#[test]
fn bare_null_named_fact_bodies_are_rejected() {
    let source = r#"format: typebridge.schema/v2
attributes:
  name: { value: string }
entities:
  person:
    owns:
      name:
"#;
    let error = normalize_documents(&documents(source)).expect_err("null is not an empty body");
    assert_eq!(
        error.iter().next().unwrap().diagnostic().code().as_str(),
        "invalid_named_schema_fact_body",
    );
}

#[test]
fn v1_extensions_are_requirement_only_and_never_ignore_payloads() {
    let supported = r#"format: typebridge.schema/v2
extensions:
  acme.schema.audit:
    required: true
"#;
    normalize_documents(&documents(supported)).expect("dotted requirement ID is supported");

    for key in ["payload", "data"] {
        let source = format!(
            "format: typebridge.schema/v2\nextensions:\n  acme.schema.audit:\n    required: true\n    {key}: {{ enabled: true }}\n"
        );
        let error = normalize_documents(&documents(&source))
            .expect_err("unimplemented extension bodies must fail closed");
        assert_eq!(
            error.iter().next().unwrap().diagnostic().code().as_str(),
            "unknown_schema_document_key",
        );
    }
}

#[test]
fn normalizes_ordered_builtin_struct_fields() {
    let source = r#"format: typebridge.schema/v2
structs:
  player-stats:
    fields:
      - name: wins
        type: integer
      - name: losses
        type: integer
      - name: nickname
        type: string
        optional: true
"#;

    let declared = normalize_documents(&documents(source)).expect("schema normalizes");
    let id =
        SchemaFactId::Struct(StructId::new("player-stats").expect("struct identifier is valid"));
    let Some(SchemaFact::Struct(fact)) = declared.fact(&id) else {
        panic!("struct fact exists");
    };

    assert_eq!(fact.fields().len(), 3);
    assert_eq!(fact.fields()[0].name().as_str(), "wins");
    assert_eq!(fact.fields()[1].name().as_str(), "losses");
    assert_eq!(fact.fields()[2].name().as_str(), "nickname");
    assert_eq!(fact.fields()[0].value_type(), ValueTypeTag::Long);
    assert!(!fact.fields()[0].optional());
    assert!(fact.fields()[2].optional());
}

#[test]
fn rejects_non_builtin_and_nested_struct_field_types() {
    let unknown = r#"format: typebridge.schema/v2
structs:
  invalid:
    fields:
      - name: value
        type: custom-value
"#;
    let error = normalize_documents(&documents(unknown)).unwrap_err();
    assert_eq!(
        error.iter().next().unwrap().diagnostic().code().as_str(),
        "unknown_schema_value_type",
    );

    let nested = r#"format: typebridge.schema/v2
structs:
  invalid:
    fields:
      - name: value
        type: { struct: another }
"#;
    let error = normalize_documents(&documents(nested)).unwrap_err();
    assert_eq!(
        error.iter().next().unwrap().diagnostic().code().as_str(),
        "schema_scalar_required",
    );
}

#[test]
fn duplicate_struct_fields_report_both_spans() {
    let source = r#"format: typebridge.schema/v2
structs:
  invalid:
    fields:
      - name: value
        type: string
      - name: value
        type: integer
"#;
    let error = normalize_documents(&documents(source)).unwrap_err();
    let diagnostic = error.iter().next().unwrap();
    assert_eq!(
        diagnostic.diagnostic().code().as_str(),
        "duplicate_struct_field",
    );
    assert_eq!(diagnostic.related().len(), 1);
}

#[test]
fn omitted_and_explicit_false_struct_optionality_normalize_identically() {
    let omitted = r#"format: typebridge.schema/v2
structs:
  sample:
    fields:
      - name: value
        type: string
"#;
    let explicit = r#"format: typebridge.schema/v2
structs:
  sample:
    fields:
      - name: value
        type: string
        optional: false
"#;

    let omitted = normalize_documents(&documents(omitted)).unwrap();
    let explicit = normalize_documents(&documents(explicit)).unwrap();
    assert_eq!(
        omitted.declared_identity_fingerprint(),
        explicit.declared_identity_fingerprint(),
    );
}

#[test]
fn root_plays_can_reference_types_in_a_later_fragment() {
    let set = SchemaDocumentSet::parse([
        (
            DocumentId::new("a-plays.yaml").expect("document identifier is valid"),
            "format: typebridge.schema/v2\nplays:\n  person:\n    friendship: [friend]\n",
        ),
        (
            DocumentId::new("z-types.yaml").expect("document identifier is valid"),
            "format: typebridge.schema/v2\nentities:\n  person: {}\nrelations:\n  friendship:\n    relates: [friend]\n",
        ),
    ])
    .expect("fragment set parses");
    assert!(normalize_documents(&set).is_ok());
}

#[test]
fn role_specialization_resolves_the_declaring_ancestor() {
    let source = r#"format: typebridge.schema/v2
relations:
  root:
    relates: [member]
  middle:
    sub: root
  leaf:
    sub: middle
    relates:
      participant: { as: member }
"#;
    let declared = normalize_documents(&documents(source)).expect("schema normalizes");
    let relation = TypeId::new(TypeKind::Relation, "leaf").expect("type identifier is valid");
    let role = RoleId::new("leaf", "participant").expect("role identifier is valid");
    let id = RelatesFactId::new(relation, role).expect("relates identifier is valid");
    let Some(SchemaFact::Relates(relates)) = declared.fact(&SchemaFactId::Relates(id)) else {
        panic!("specialized role fact exists");
    };
    assert_eq!(
        relates
            .specializes()
            .expect("role specializes an ancestor")
            .declaring_relation()
            .as_str(),
        "root"
    );
}

#[test]
fn function_structural_source_excludes_doc_and_meta() {
    let first = r#"format: typebridge.schema/v2
functions:
  answer:
    returns: { stream: [integer] }
    body: { typeql: "match let $x = 42; return first $x;" }
    doc: "first"
"#;
    let second = r#"format: typebridge.schema/v2
functions:
  answer:
    returns: { stream: [integer] }
    body: { typeql: "match let $x = 42; return first $x;" }
    doc: "second"
"#;
    let first = normalize_documents(&documents(first)).expect("first schema normalizes");
    let second = normalize_documents(&documents(second)).expect("second schema normalizes");
    let id =
        SchemaFactId::Function(FunctionId::new("answer").expect("function identifier is valid"));
    let Some(SchemaFact::Function(first_function)) = first.fact(&id) else {
        panic!("first function exists");
    };
    let Some(SchemaFact::Function(second_function)) = second.fact(&id) else {
        panic!("second function exists");
    };
    assert_eq!(first_function.signature(), second_function.signature());
    assert_eq!(first_function.body(), second_function.body());
    assert_eq!(
        first_function.body().text(),
        "match let $x = 42; return first $x;"
    );
    assert_ne!(
        first.declared_identity_fingerprint(),
        second.declared_identity_fingerprint()
    );
}

#[test]
fn normalizes_every_closed_function_return_shape_and_rejects_ambiguous_shapes() {
    let source = r#"format: typebridge.schema/v2
functions:
  scalar-answer:
    returns: { scalar: integer }
    body: { typeql: "match let $x = 42; return first $x;" }
  tuple-answer:
    returns: { tuple: [integer, string] }
    body: { typeql: "match let $x = 42; let $y = 'answer'; return first $x, $y;" }
  stream-answer:
    returns: { stream: [integer] }
    body: { typeql: "match let $x = 42; return { $x };" }
"#;
    let declared = normalize_documents(&documents(source)).expect("return shapes normalize");
    let function = |name: &str| {
        let id = SchemaFactId::Function(FunctionId::new(name).unwrap());
        let Some(SchemaFact::Function(function)) = declared.fact(&id) else {
            panic!("function {name} exists")
        };
        function
    };
    assert!(matches!(
        function("scalar-answer").signature().returns(),
        FunctionReturnMode::Scalar(_)
    ));
    assert!(matches!(
        function("tuple-answer").signature().returns(),
        FunctionReturnMode::Tuple(elements) if elements.len() == 2
    ));
    assert!(matches!(
        function("stream-answer").signature().returns(),
        FunctionReturnMode::Stream(elements) if elements.len() == 1
    ));

    for returns in [
        "{}",
        "{ scalar: integer, stream: [integer] }",
        "{ tuple: [integer] }",
        "{ stream: [] }",
    ] {
        let source = format!(
            "format: typebridge.schema/v2\nfunctions:\n  answer:\n    returns: {returns}\n    body: {{ typeql: \"match let $x = 42; return first $x;\" }}\n"
        );
        normalize_documents(&documents(&source)).expect_err("invalid return shape rejects");
    }
}

#[test]
fn canonical_string_limits_apply_to_yaml_values_and_metadata() {
    fn value_source(payload: &str) -> String {
        format!(
            "format: typebridge.schema/v2\nattributes:\n  note:\n    value:\n      type: string\n      values:\n        - \"{payload}\"\n"
        )
    }

    fn meta_source(payload: &str) -> String {
        format!(
            "format: typebridge.schema/v2\nentities:\n  person:\n    meta:\n      note: \"{payload}\"\n"
        )
    }

    let escaped_boundary = "\\u0078".repeat(MAX_CANONICAL_STRING_BYTES);
    assert!(escaped_boundary.len() > MAX_CANONICAL_STRING_BYTES);
    normalize_documents(&documents(&value_source(&escaped_boundary)))
        .expect("an escaped boundary-sized string value normalizes");

    let boundary = "x".repeat(MAX_CANONICAL_STRING_BYTES);
    normalize_documents(&documents(&meta_source(&boundary)))
        .expect("a boundary-sized metadata value normalizes");

    let oversized = "x".repeat(MAX_CANONICAL_STRING_BYTES + 1);
    for source in [value_source(&oversized), meta_source(&oversized)] {
        let diagnostics =
            normalize_documents(&documents(&source)).expect_err("oversized text must fail");
        let diagnostic = diagnostics
            .iter()
            .next()
            .expect("one diagnostic is emitted");
        assert_eq!(
            diagnostic.diagnostic().code().as_str(),
            "canonical_string_limit_exceeded"
        );
        assert_eq!(
            diagnostic
                .primary()
                .expect("the offending YAML scalar has provenance")
                .document()
                .as_str(),
            "schema.yaml"
        );
    }
}

#[test]
fn named_timezone_values_use_the_pinned_provider_policy() {
    let valid = r#"format: typebridge.schema/v2
attributes:
  observed:
    value:
      type: datetime-tz
      values: ["2024-07-01T12:00:00[europe/paris]"]
"#;
    normalize_documents(&documents(valid)).expect("ordinary named local datetime resolves");

    for (value, code) in [
        (
            "2024-03-31T01:30:00[Europe/London]",
            "nonexistent_named_timezone_local_datetime",
        ),
        (
            "2024-10-27T01:30:00[Europe/London]",
            "ambiguous_named_timezone_local_datetime",
        ),
    ] {
        let source = format!(
            "format: typebridge.schema/v2\nattributes:\n  observed:\n    value:\n      type: datetime-tz\n      values: [\"{value}\"]\n"
        );
        let diagnostics = normalize_documents(&documents(&source))
            .expect_err("provider-ambiguous local datetime must fail closed");
        assert_eq!(
            diagnostics
                .iter()
                .next()
                .unwrap()
                .diagnostic()
                .code()
                .as_str(),
            code,
        );
    }
}