telltale-types 14.0.0

Core session types for Telltale - matching Lean definitions
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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
//! Contentable Trait for Canonical Serialization
//!
//! This module provides the `Contentable` trait for types that can be
//! serialized to a canonical byte representation suitable for content addressing.
//!
//! # Design
//!
//! The serialization process:
//! 1. Convert to de Bruijn representation (for α-equivalence)
//! 2. Normalize branch ordering (deterministic)
//! 3. Serialize to bytes (JSON by default, DAG-CBOR with feature flag)
//!
//! Canonical serialization for binder-carrying protocol types requires
//! all recursion variables to be bound. Open terms are rejected.
//!
//! # Serialization Formats
//!
//! - **JSON** (default): Simple and human-readable. Uses `to_bytes`/`from_bytes`.
//! - **DAG-CBOR** (with `dag-cbor` feature): Compact binary format compatible
//!   with IPLD/IPFS. Uses `to_cbor_bytes`/`from_cbor_bytes`.
//!
//! # Lean Correspondence
//!
//! This module corresponds to `lean/SessionTypes/ContentIdentityPolicy.lean`.
//! The `toCbor`/`fromCbor` methods in Lean map to `to_cbor_bytes`/`from_cbor_bytes` here.

#[cfg(feature = "sha256")]
use crate::content_id::Sha256Hasher;
use crate::content_id::{Blake3Hasher, ContentId, DefaultContentHasher, Hasher};
use crate::de_bruijn::{GlobalTypeDB, LocalTypeRDB};
use crate::{GlobalType, Label, LocalTypeR, PayloadSort};
use serde::{de::DeserializeOwned, Serialize};

/// Trait for types with canonical serialization.
///
/// Types implementing `Contentable` can be serialized to bytes in a
/// deterministic way, enabling content addressing and structural comparison.
///
/// # Invariants
///
/// - `from_bytes(to_bytes(x)) ≈ x` (modulo α-equivalence for types with binders)
/// - Two α-equivalent values produce identical bytes
/// - Byte order is deterministic (independent of insertion order, etc.)
///
/// For binder-carrying protocol types (`GlobalType`, `LocalTypeR`), canonical
/// serialization requires all recursion variables to be bound.
///
/// # Examples
///
/// ```
/// use telltale_types::{GlobalType, Label};
/// use telltale_types::contentable::Contentable;
///
/// // α-equivalent types produce the same bytes
/// let g1 = GlobalType::mu("x", GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("x")));
/// let g2 = GlobalType::mu("y", GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("y")));
///
/// assert_eq!(g1.to_bytes().unwrap(), g2.to_bytes().unwrap());
/// ```
pub trait Contentable: Sized {
    /// Serialize to canonical byte representation (JSON format).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn to_bytes(&self) -> Result<Vec<u8>, ContentableError>;

    /// Deserialize from JSON bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if deserialization fails.
    fn from_bytes(bytes: &[u8]) -> Result<Self, ContentableError>;

    /// Serialize to template bytes, allowing open terms with explicit
    /// free-variable interfaces when supported by the implementation.
    ///
    /// Default behavior falls back to canonical bytes.
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn to_template_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        self.to_bytes()
    }

    /// Serialize to DAG-CBOR bytes (requires `dag-cbor` feature).
    ///
    /// DAG-CBOR is a deterministic subset of CBOR designed for content addressing.
    /// It produces more compact output than JSON and is compatible with IPLD/IPFS.
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    #[cfg(feature = "dag-cbor")]
    fn to_cbor_bytes(&self) -> Result<Vec<u8>, ContentableError>;

    /// Deserialize from DAG-CBOR bytes (requires `dag-cbor` feature).
    ///
    /// # Errors
    ///
    /// Returns an error if deserialization fails.
    #[cfg(feature = "dag-cbor")]
    fn from_cbor_bytes(bytes: &[u8]) -> Result<Self, ContentableError>;

    /// Compute content ID using the specified hasher (from JSON bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn content_id<H: Hasher>(&self) -> Result<ContentId<H>, ContentableError> {
        let bytes = self.to_bytes()?;
        Ok(ContentId::from_bytes(&bytes))
    }

    /// Compute content ID using the central default content hasher (from JSON bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn content_id_default(&self) -> Result<ContentId<DefaultContentHasher>, ContentableError> {
        self.content_id()
    }

    /// Compute content ID using explicit BLAKE3 (from JSON bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn content_id_blake3(&self) -> Result<ContentId<Blake3Hasher>, ContentableError> {
        self.content_id()
    }

    /// Compute content ID using SHA-256 (from JSON bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    #[cfg(feature = "sha256")]
    fn content_id_sha256(&self) -> Result<ContentId<Sha256Hasher>, ContentableError> {
        self.content_id()
    }

    /// Compute a template ID using the specified hasher (from template bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn template_id<H: Hasher>(&self) -> Result<ContentId<H>, ContentableError> {
        let bytes = self.to_template_bytes()?;
        Ok(ContentId::from_bytes(&bytes))
    }

    /// Compute a template ID using the central default content hasher.
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn template_id_default(&self) -> Result<ContentId<DefaultContentHasher>, ContentableError> {
        self.template_id()
    }

    /// Compute a template ID using explicit BLAKE3.
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    fn template_id_blake3(&self) -> Result<ContentId<Blake3Hasher>, ContentableError> {
        self.template_id()
    }

    /// Compute a template ID using SHA-256.
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    #[cfg(feature = "sha256")]
    fn template_id_sha256(&self) -> Result<ContentId<Sha256Hasher>, ContentableError> {
        self.template_id()
    }

    /// Compute content ID from DAG-CBOR bytes (requires `dag-cbor` feature).
    ///
    /// This produces a different content ID than the JSON-based methods.
    /// Use this for IPLD/IPFS compatibility.
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    #[cfg(feature = "dag-cbor")]
    fn content_id_cbor<H: Hasher>(&self) -> Result<ContentId<H>, ContentableError> {
        let bytes = self.to_cbor_bytes()?;
        Ok(ContentId::from_bytes(&bytes))
    }

    /// Compute content ID from DAG-CBOR using the central default content hasher
    /// (requires `dag-cbor` feature).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    #[cfg(feature = "dag-cbor")]
    fn content_id_cbor_default(&self) -> Result<ContentId<DefaultContentHasher>, ContentableError> {
        self.content_id_cbor()
    }

    /// Compute content ID from DAG-CBOR using explicit BLAKE3 (requires `dag-cbor` feature).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    #[cfg(feature = "dag-cbor")]
    fn content_id_cbor_blake3(&self) -> Result<ContentId<Blake3Hasher>, ContentableError> {
        self.content_id_cbor()
    }

    /// Compute content ID from DAG-CBOR using SHA-256 (requires `dag-cbor` feature).
    ///
    /// # Errors
    ///
    /// Returns [`ContentableError`] if serialization fails.
    #[cfg(all(feature = "dag-cbor", feature = "sha256"))]
    fn content_id_cbor_sha256(&self) -> Result<ContentId<Sha256Hasher>, ContentableError> {
        self.content_id_cbor()
    }
}

/// Errors that can occur during contentable operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContentableError {
    /// Failed to deserialize bytes
    DeserializationFailed(String),
    /// Failed to serialize value
    SerializationFailed(String),
    /// Invalid format or structure
    InvalidFormat(String),
}

impl std::fmt::Display for ContentableError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ContentableError::DeserializationFailed(msg) => {
                write!(f, "deserialization failed: {msg}")
            }
            ContentableError::SerializationFailed(msg) => {
                write!(f, "serialization failed: {msg}")
            }
            ContentableError::InvalidFormat(msg) => {
                write!(f, "invalid format: {msg}")
            }
        }
    }
}

impl std::error::Error for ContentableError {}

// Helper for JSON serialization
fn to_json_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>, ContentableError> {
    // Use compact JSON without pretty printing for determinism
    serde_json::to_vec(value).map_err(|e| ContentableError::SerializationFailed(e.to_string()))
}

fn from_json_bytes<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, ContentableError> {
    serde_json::from_slice(bytes)
        .map_err(|e| ContentableError::DeserializationFailed(e.to_string()))
}

fn sorted_free_vars(mut vars: Vec<String>) -> Vec<String> {
    vars.sort();
    vars.dedup();
    vars
}

#[derive(Serialize)]
struct GlobalTemplateEnvelope {
    free_vars: Vec<String>,
    db: GlobalTypeDB,
}

#[derive(Serialize)]
struct LocalTemplateEnvelope {
    free_vars: Vec<String>,
    db: LocalTypeRDB,
}

// Helper for DAG-CBOR serialization (requires dag-cbor feature)
#[cfg(feature = "dag-cbor")]
fn to_cbor_bytes_impl<T: Serialize>(value: &T) -> Result<Vec<u8>, ContentableError> {
    serde_ipld_dagcbor::to_vec(value)
        .map_err(|e| ContentableError::SerializationFailed(format!("dag-cbor: {e}")))
}

#[cfg(feature = "dag-cbor")]
fn from_cbor_bytes_impl<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, ContentableError> {
    serde_ipld_dagcbor::from_slice(bytes)
        .map_err(|e| ContentableError::DeserializationFailed(format!("dag-cbor: {e}")))
}

// ============================================================================
// Contentable implementations
// ============================================================================

impl Contentable for PayloadSort {
    fn to_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        to_json_bytes(self)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        from_json_bytes(bytes)
    }

    #[cfg(feature = "dag-cbor")]
    fn to_cbor_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        to_cbor_bytes_impl(self)
    }

    #[cfg(feature = "dag-cbor")]
    fn from_cbor_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        from_cbor_bytes_impl(bytes)
    }
}

impl Contentable for Label {
    fn to_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        to_json_bytes(self)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        from_json_bytes(bytes)
    }

    #[cfg(feature = "dag-cbor")]
    fn to_cbor_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        to_cbor_bytes_impl(self)
    }

    #[cfg(feature = "dag-cbor")]
    fn from_cbor_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        from_cbor_bytes_impl(bytes)
    }
}

impl Contentable for GlobalType {
    fn to_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        if !self.all_vars_bound() {
            return Err(ContentableError::InvalidFormat(
                "canonical serialization requires all recursion variables to be bound".to_string(),
            ));
        }
        // Convert to de Bruijn, normalize, then serialize
        let db = GlobalTypeDB::from(self).normalize();
        to_json_bytes(&db)
    }

    fn to_template_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        let free_vars = sorted_free_vars(self.free_vars());
        let env: Vec<&str> = free_vars.iter().map(String::as_str).collect();
        let db = GlobalTypeDB::from_global_type_with_env(self, &env).normalize();
        let envelope = GlobalTemplateEnvelope { free_vars, db };
        to_json_bytes(&envelope)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        // Note: This returns a type with generated variable names,
        // since de Bruijn indices don't preserve names.
        let db: GlobalTypeDB = from_json_bytes(bytes)?;
        Ok(global_from_de_bruijn(&db, &mut vec![]))
    }

    #[cfg(feature = "dag-cbor")]
    fn to_cbor_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        if !self.all_vars_bound() {
            return Err(ContentableError::InvalidFormat(
                "canonical serialization requires all recursion variables to be bound".to_string(),
            ));
        }
        let db = GlobalTypeDB::from(self).normalize();
        to_cbor_bytes_impl(&db)
    }

    #[cfg(feature = "dag-cbor")]
    fn from_cbor_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        let db: GlobalTypeDB = from_cbor_bytes_impl(bytes)?;
        Ok(global_from_de_bruijn(&db, &mut vec![]))
    }
}

impl Contentable for LocalTypeR {
    fn to_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        if !self.all_vars_bound() {
            return Err(ContentableError::InvalidFormat(
                "canonical serialization requires all recursion variables to be bound".to_string(),
            ));
        }
        // Convert to de Bruijn, normalize, then serialize.
        // Payload annotations on local branches are preserved.
        let db = LocalTypeRDB::from(self).normalize();
        to_json_bytes(&db)
    }

    fn to_template_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        let free_vars = sorted_free_vars(self.free_vars());
        let env: Vec<&str> = free_vars.iter().map(String::as_str).collect();
        let db = LocalTypeRDB::from_local_type_with_env(self, &env).normalize();
        let envelope = LocalTemplateEnvelope { free_vars, db };
        to_json_bytes(&envelope)
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        // Note: This returns a type with generated variable names,
        // since de Bruijn indices don't preserve names.
        let db: LocalTypeRDB = from_json_bytes(bytes)?;
        Ok(local_from_de_bruijn(&db, &mut vec![]))
    }

    #[cfg(feature = "dag-cbor")]
    fn to_cbor_bytes(&self) -> Result<Vec<u8>, ContentableError> {
        if !self.all_vars_bound() {
            return Err(ContentableError::InvalidFormat(
                "canonical serialization requires all recursion variables to be bound".to_string(),
            ));
        }
        let db = LocalTypeRDB::from(self).normalize();
        to_cbor_bytes_impl(&db)
    }

    #[cfg(feature = "dag-cbor")]
    fn from_cbor_bytes(bytes: &[u8]) -> Result<Self, ContentableError> {
        let db: LocalTypeRDB = from_cbor_bytes_impl(bytes)?;
        Ok(local_from_de_bruijn(&db, &mut vec![]))
    }
}

// ============================================================================
// De Bruijn back-conversion (generates fresh variable names)
// ============================================================================

fn global_from_de_bruijn(db: &GlobalTypeDB, names: &mut Vec<String>) -> GlobalType {
    match db {
        GlobalTypeDB::End => GlobalType::End,
        GlobalTypeDB::Comm {
            sender,
            receiver,
            branches,
        } => GlobalType::Comm {
            sender: sender.clone(),
            receiver: receiver.clone(),
            branches: branches
                .iter()
                .map(|(l, cont)| (l.clone(), global_from_de_bruijn(cont, names)))
                .collect(),
        },
        GlobalTypeDB::Rec(body) => {
            // Generate a fresh variable name
            let var_name = format!("t{}", names.len());
            names.push(var_name.clone());
            let body_converted = global_from_de_bruijn(body, names);
            names.pop();
            GlobalType::Mu {
                var: var_name,
                body: Box::new(body_converted),
            }
        }
        GlobalTypeDB::Var(idx) => {
            // Look up the variable name from the environment
            let name = names
                .get(names.len().saturating_sub(1 + idx))
                .cloned()
                .unwrap_or_else(|| format!("free{idx}"));
            GlobalType::Var(name)
        }
    }
}

fn local_from_de_bruijn(db: &LocalTypeRDB, names: &mut Vec<String>) -> LocalTypeR {
    match db {
        LocalTypeRDB::End => LocalTypeR::End,
        LocalTypeRDB::Send { partner, branches } => LocalTypeR::Send {
            partner: partner.clone(),
            branches: branches
                .iter()
                .map(|(l, vt, cont)| (l.clone(), vt.clone(), local_from_de_bruijn(cont, names)))
                .collect(),
        },
        LocalTypeRDB::Recv { partner, branches } => LocalTypeR::Recv {
            partner: partner.clone(),
            branches: branches
                .iter()
                .map(|(l, vt, cont)| (l.clone(), vt.clone(), local_from_de_bruijn(cont, names)))
                .collect(),
        },
        LocalTypeRDB::Rec(body) => {
            // Generate a fresh variable name
            let var_name = format!("t{}", names.len());
            names.push(var_name.clone());
            let body_converted = local_from_de_bruijn(body, names);
            names.pop();
            LocalTypeR::Mu {
                var: var_name,
                body: Box::new(body_converted),
            }
        }
        LocalTypeRDB::Var(idx) => {
            // Look up the variable name from the environment
            let name = names
                .get(names.len().saturating_sub(1 + idx))
                .cloned()
                .unwrap_or_else(|| format!("free{idx}"));
            LocalTypeR::Var(name)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_content_id_helper() {
        let g = GlobalType::send("A", "B", Label::new("msg"), GlobalType::End);
        let cid = g.content_id_default().unwrap();
        assert_eq!(cid.algorithm(), "blake3");
    }

    #[test]
    fn test_payload_sort_roundtrip() {
        let sort = PayloadSort::prod(PayloadSort::Nat, PayloadSort::Bool);
        let bytes = sort.to_bytes().unwrap();
        let recovered = PayloadSort::from_bytes(&bytes).unwrap();
        assert_eq!(sort, recovered);
    }

    #[test]
    fn test_label_roundtrip() {
        let label = Label::with_sort("data", PayloadSort::Nat);
        let bytes = label.to_bytes().unwrap();
        let recovered = Label::from_bytes(&bytes).unwrap();
        assert_eq!(label, recovered);
    }

    #[test]
    fn test_global_type_alpha_equivalence() {
        // μx. A → B : msg. x
        let g1 = GlobalType::mu(
            "x",
            GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("x")),
        );
        // μy. A → B : msg. y (same structure, different variable name)
        let g2 = GlobalType::mu(
            "y",
            GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("y")),
        );

        // α-equivalent types should produce the same bytes
        assert_eq!(g1.to_bytes().unwrap(), g2.to_bytes().unwrap());

        // And the same content ID
        assert_eq!(
            g1.content_id_default().unwrap(),
            g2.content_id_default().unwrap()
        );
    }

    #[test]
    fn test_local_type_alpha_equivalence() {
        // μx. !B{msg.x}
        let t1 = LocalTypeR::mu(
            "x",
            LocalTypeR::send("B", Label::new("msg"), LocalTypeR::var("x")),
        );
        // μy. !B{msg.y}
        let t2 = LocalTypeR::mu(
            "y",
            LocalTypeR::send("B", Label::new("msg"), LocalTypeR::var("y")),
        );

        assert_eq!(t1.to_bytes().unwrap(), t2.to_bytes().unwrap());
        assert_eq!(
            t1.content_id_default().unwrap(),
            t2.content_id_default().unwrap()
        );
    }

    #[test]
    fn test_global_type_roundtrip() {
        let g = GlobalType::mu(
            "x",
            GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("x")),
        );

        let bytes = g.to_bytes().unwrap();
        let recovered = GlobalType::from_bytes(&bytes).unwrap();

        // Roundtrip should be α-equivalent (same structure, possibly different names)
        assert_eq!(g.to_bytes().unwrap(), recovered.to_bytes().unwrap());
    }

    #[test]
    fn test_local_type_roundtrip() {
        let t = LocalTypeR::mu(
            "x",
            LocalTypeR::send("B", Label::new("msg"), LocalTypeR::var("x")),
        );

        let bytes = t.to_bytes().unwrap();
        let recovered = LocalTypeR::from_bytes(&bytes).unwrap();

        assert_eq!(t.to_bytes().unwrap(), recovered.to_bytes().unwrap());
    }

    #[test]
    fn test_local_type_roundtrip_preserves_payload_annotation() {
        let t = LocalTypeR::Send {
            partner: "B".to_string(),
            branches: vec![(
                Label::new("msg"),
                Some(crate::ValType::Nat),
                LocalTypeR::Recv {
                    partner: "A".to_string(),
                    branches: vec![(
                        Label::new("ack"),
                        Some(crate::ValType::Bool),
                        LocalTypeR::End,
                    )],
                },
            )],
        };

        let bytes = t.to_bytes().unwrap();
        let recovered = LocalTypeR::from_bytes(&bytes).unwrap();
        assert_eq!(t, recovered);
    }

    #[test]
    fn test_branch_ordering_normalized() {
        // Branches in different order should produce same bytes
        let g1 = GlobalType::comm(
            "A",
            "B",
            vec![
                (Label::new("b"), GlobalType::End),
                (Label::new("a"), GlobalType::End),
            ],
        );
        let g2 = GlobalType::comm(
            "A",
            "B",
            vec![
                (Label::new("a"), GlobalType::End),
                (Label::new("b"), GlobalType::End),
            ],
        );

        assert_eq!(g1.to_bytes().unwrap(), g2.to_bytes().unwrap());
    }

    #[test]
    fn test_different_types_different_bytes() {
        let g1 = GlobalType::send("A", "B", Label::new("msg"), GlobalType::End);
        let g2 = GlobalType::send("A", "B", Label::new("other"), GlobalType::End);

        assert_ne!(g1.to_bytes().unwrap(), g2.to_bytes().unwrap());
        assert_ne!(
            g1.content_id_default().unwrap(),
            g2.content_id_default().unwrap()
        );
    }

    #[test]
    fn test_nested_recursion_content_id() {
        // μx. μy. A → B : msg. y
        let g1 = GlobalType::mu(
            "x",
            GlobalType::mu(
                "y",
                GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("y")),
            ),
        );
        // μa. μb. A → B : msg. b
        let g2 = GlobalType::mu(
            "a",
            GlobalType::mu(
                "b",
                GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("b")),
            ),
        );

        assert_eq!(
            g1.content_id_default().unwrap(),
            g2.content_id_default().unwrap()
        );
    }

    #[test]
    fn test_different_binder_reference() {
        // μx. μy. A → B : msg. x (references OUTER binder)
        let g1 = GlobalType::mu(
            "x",
            GlobalType::mu(
                "y",
                GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("x")),
            ),
        );
        // μx. μy. A → B : msg. y (references INNER binder)
        let g2 = GlobalType::mu(
            "x",
            GlobalType::mu(
                "y",
                GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("y")),
            ),
        );

        // These are NOT α-equivalent
        assert_ne!(
            g1.content_id_default().unwrap(),
            g2.content_id_default().unwrap()
        );
    }

    #[test]
    fn test_global_type_open_term_rejected_for_canonical_serialization() {
        let open = GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("free_t"));
        let err = open.to_bytes().expect_err("open terms must be rejected");
        assert!(matches!(err, ContentableError::InvalidFormat(_)));
    }

    #[test]
    fn test_local_type_open_term_rejected_for_canonical_serialization() {
        let open = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::var("free_t"));
        let err = open.to_bytes().expect_err("open terms must be rejected");
        assert!(matches!(err, ContentableError::InvalidFormat(_)));
    }

    #[test]
    fn test_global_type_open_term_has_template_id() {
        let open = GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("free_t"));
        let tid = open
            .template_id_default()
            .expect("open terms should support template IDs");
        let tid2 = open
            .template_id_default()
            .expect("template IDs should be deterministic");
        assert_eq!(tid, tid2);
    }

    #[test]
    fn test_local_type_open_term_has_template_id() {
        let open = LocalTypeR::send("B", Label::new("msg"), LocalTypeR::var("free_t"));
        let tid = open
            .template_id_default()
            .expect("open terms should support template IDs");
        let tid2 = open
            .template_id_default()
            .expect("template IDs should be deterministic");
        assert_eq!(tid, tid2);
    }

    #[test]
    fn test_template_id_distinguishes_free_variable_interfaces() {
        let g1 = GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("x"));
        let g2 = GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("y"));
        assert_ne!(
            g1.template_id_default().unwrap(),
            g2.template_id_default().unwrap()
        );
    }

    // ========================================================================
    // DAG-CBOR tests (require dag-cbor feature)
    // ========================================================================

    #[cfg(feature = "dag-cbor")]
    mod cbor_tests {
        use super::*;

        #[test]
        fn test_payload_sort_cbor_roundtrip() {
            let sort = PayloadSort::prod(PayloadSort::Nat, PayloadSort::Bool);
            let bytes = sort.to_cbor_bytes().unwrap();
            let recovered = PayloadSort::from_cbor_bytes(&bytes).unwrap();
            assert_eq!(sort, recovered);
        }

        #[test]
        fn test_label_cbor_roundtrip() {
            let label = Label::with_sort("data", PayloadSort::Nat);
            let bytes = label.to_cbor_bytes().unwrap();
            let recovered = Label::from_cbor_bytes(&bytes).unwrap();
            assert_eq!(label, recovered);
        }

        #[test]
        fn test_global_type_cbor_roundtrip() {
            let g = GlobalType::mu(
                "x",
                GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("x")),
            );

            let bytes = g.to_cbor_bytes().unwrap();
            let recovered = GlobalType::from_cbor_bytes(&bytes).unwrap();

            // Roundtrip should be α-equivalent
            assert_eq!(
                g.to_cbor_bytes().unwrap(),
                recovered.to_cbor_bytes().unwrap()
            );
        }

        #[test]
        fn test_local_type_cbor_roundtrip() {
            let t = LocalTypeR::mu(
                "x",
                LocalTypeR::send("B", Label::new("msg"), LocalTypeR::var("x")),
            );

            let bytes = t.to_cbor_bytes().unwrap();
            let recovered = LocalTypeR::from_cbor_bytes(&bytes).unwrap();

            assert_eq!(
                t.to_cbor_bytes().unwrap(),
                recovered.to_cbor_bytes().unwrap()
            );
        }

        #[test]
        fn test_cbor_alpha_equivalence() {
            // Two α-equivalent types should produce the same CBOR bytes
            let g1 = GlobalType::mu(
                "x",
                GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("x")),
            );
            let g2 = GlobalType::mu(
                "y",
                GlobalType::send("A", "B", Label::new("msg"), GlobalType::var("y")),
            );

            assert_eq!(g1.to_cbor_bytes().unwrap(), g2.to_cbor_bytes().unwrap());
            assert_eq!(
                g1.content_id_cbor_default().unwrap(),
                g2.content_id_cbor_default().unwrap()
            );
        }

        #[test]
        fn test_cbor_more_compact_than_json() {
            // CBOR should typically be more compact than JSON
            let g = GlobalType::comm(
                "A",
                "B",
                vec![
                    (Label::new("msg1"), GlobalType::End),
                    (Label::new("msg2"), GlobalType::End),
                    (Label::new("msg3"), GlobalType::End),
                ],
            );

            let json_bytes = g.to_bytes().unwrap();
            let cbor_bytes = g.to_cbor_bytes().unwrap();

            // CBOR is typically 30-50% smaller than JSON for structured data
            assert!(
                cbor_bytes.len() < json_bytes.len(),
                "CBOR ({} bytes) should be smaller than JSON ({} bytes)",
                cbor_bytes.len(),
                json_bytes.len()
            );
        }

        #[test]
        fn test_json_and_cbor_produce_different_bytes() {
            // JSON and CBOR are different formats, so bytes should differ
            let g = GlobalType::send("A", "B", Label::new("msg"), GlobalType::End);

            let json_bytes = g.to_bytes().unwrap();
            let cbor_bytes = g.to_cbor_bytes().unwrap();

            assert_ne!(json_bytes, cbor_bytes);
        }
    }
}

// ============================================================================
// Property-based tests for α-equivalence
// ============================================================================

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    /// Generate a random variable name from a small set
    fn arb_var_name() -> impl Strategy<Value = String> {
        prop_oneof![
            Just("x".to_string()),
            Just("y".to_string()),
            Just("z".to_string()),
            Just("t".to_string()),
            Just("s".to_string()),
        ]
    }

    /// Generate a random role name
    fn arb_role() -> impl Strategy<Value = String> {
        prop_oneof![
            Just("A".to_string()),
            Just("B".to_string()),
            Just("C".to_string()),
        ]
    }

    /// Generate a random label
    fn arb_label() -> impl Strategy<Value = Label> {
        prop_oneof![
            Just(Label::new("msg")),
            Just(Label::new("data")),
            Just(Label::new("ack")),
            Just(Label::with_sort("value", PayloadSort::Nat)),
            Just(Label::with_sort("flag", PayloadSort::Bool)),
        ]
    }

    /// Generate a random LocalTypeR (limited depth)
    #[allow(dead_code)]
    fn arb_local_type(depth: usize) -> impl Strategy<Value = LocalTypeR> {
        if depth == 0 {
            prop_oneof![
                Just(LocalTypeR::End),
                arb_var_name().prop_map(LocalTypeR::var),
            ]
            .boxed()
        } else {
            prop_oneof![
                Just(LocalTypeR::End),
                // Simple send
                (arb_role(), arb_label(), arb_local_type(depth - 1))
                    .prop_map(|(partner, label, cont)| LocalTypeR::send(partner, label, cont)),
                // Simple recv
                (arb_role(), arb_label(), arb_local_type(depth - 1))
                    .prop_map(|(partner, label, cont)| LocalTypeR::recv(partner, label, cont)),
                // Recursive type
                (arb_var_name(), arb_local_type(depth - 1))
                    .prop_map(|(var, body)| LocalTypeR::mu(var, body)),
                // Variable
                arb_var_name().prop_map(LocalTypeR::var),
            ]
            .boxed()
        }
    }

    /// Rename all bound variables in a GlobalType using a mapping
    fn rename_global_type(g: &GlobalType, mapping: &[(&str, &str)]) -> GlobalType {
        fn rename_inner(
            g: &GlobalType,
            mapping: &[(&str, &str)],
            bound: &mut Vec<(String, String)>,
        ) -> GlobalType {
            match g {
                GlobalType::End => GlobalType::End,
                GlobalType::Comm {
                    sender,
                    receiver,
                    branches,
                } => GlobalType::Comm {
                    sender: sender.clone(),
                    receiver: receiver.clone(),
                    branches: branches
                        .iter()
                        .map(|(l, cont)| (l.clone(), rename_inner(cont, mapping, bound)))
                        .collect(),
                },
                GlobalType::Mu { var, body } => {
                    // Find new name for this variable
                    let new_var = mapping
                        .iter()
                        .find(|(old, _)| *old == var)
                        .map(|(_, new)| (*new).to_string())
                        .unwrap_or_else(|| var.clone());

                    bound.push((var.clone(), new_var.clone()));
                    let new_body = rename_inner(body, mapping, bound);
                    bound.pop();

                    GlobalType::Mu {
                        var: new_var,
                        body: Box::new(new_body),
                    }
                }
                GlobalType::Var(name) => {
                    // Check if this is a bound variable that was renamed
                    let new_name = bound
                        .iter()
                        .rev()
                        .find(|(old, _)| old == name)
                        .map(|(_, new)| new.clone())
                        .unwrap_or_else(|| name.clone());
                    GlobalType::Var(new_name)
                }
            }
        }
        rename_inner(g, mapping, &mut vec![])
    }

    /// Generate a CLOSED global type (no free variables)
    /// Uses a fixed variable name to ensure the body only references the bound var
    fn arb_closed_global_type(depth: usize) -> impl Strategy<Value = GlobalType> {
        // Use a fixed variable name for the binder
        arb_var_name().prop_flat_map(move |var| {
            let var_clone = var.clone();
            arb_global_type_closed_body(depth, var)
                .prop_map(move |body| GlobalType::mu(var_clone.clone(), body))
        })
    }

    /// Generate a global type body that only references the given bound variable
    fn arb_global_type_closed_body(
        depth: usize,
        bound_var: String,
    ) -> impl Strategy<Value = GlobalType> {
        if depth == 0 {
            prop_oneof![
                Just(GlobalType::End),
                Just(GlobalType::var(bound_var)), // Reference the bound variable
            ]
            .boxed()
        } else {
            let bv = bound_var.clone();
            let bv2 = bound_var.clone();
            prop_oneof![
                Just(GlobalType::End),
                Just(GlobalType::var(bv)),
                // Simple send
                (arb_role(), arb_role(), arb_label()).prop_flat_map(
                    move |(sender, receiver, label)| {
                        let bv_inner = bv2.clone();
                        arb_global_type_closed_body(depth - 1, bv_inner).prop_map(move |cont| {
                            GlobalType::send(sender.clone(), receiver.clone(), label.clone(), cont)
                        })
                    }
                ),
            ]
            .boxed()
        }
    }

    proptest! {
        /// Property: Same type produces same content ID
        #[test]
        fn prop_content_id_deterministic(g in arb_closed_global_type(3)) {
            let cid1 = g.content_id_default().unwrap();
            let cid2 = g.content_id_default().unwrap();
            prop_assert_eq!(cid1, cid2);
        }

        /// Property: Same type produces same bytes
        #[test]
        fn prop_to_bytes_deterministic(g in arb_closed_global_type(3)) {
            let bytes1 = g.to_bytes().unwrap();
            let bytes2 = g.to_bytes().unwrap();
            prop_assert_eq!(bytes1, bytes2);
        }

        /// Property: α-equivalent CLOSED types produce same content ID
        /// (Free variables are NOT subject to α-equivalence)
        #[test]
        fn prop_alpha_equivalence_closed(g in arb_closed_global_type(3)) {
            // Rename bound variable x → y throughout the type
            let renamed = rename_global_type(&g, &[("x", "renamed_x"), ("y", "renamed_y"), ("t", "renamed_t")]);

            // α-equivalent closed types should have same content ID
            prop_assert_eq!(
                g.content_id_default().unwrap(),
                renamed.content_id_default().unwrap(),
                "α-equivalent closed types should have same content ID"
            );
        }

        /// Property: roundtrip preserves content ID for well-formed types
        #[test]
        fn prop_roundtrip_closed(g in arb_closed_global_type(3)) {
            let bytes = g.to_bytes().unwrap();
            if let Ok(recovered) = GlobalType::from_bytes(&bytes) {
                // Roundtrip should preserve content ID (α-equivalence)
                prop_assert_eq!(
                    g.content_id_default().unwrap(),
                    recovered.content_id_default().unwrap(),
                    "roundtrip should preserve content ID for closed types"
                );
            }
        }

        /// Property: branch order doesn't affect content ID
        #[test]
        fn prop_branch_order_invariant(
            sender in arb_role(),
            receiver in arb_role(),
            label1 in arb_label(),
            label2 in arb_label(),
        ) {
            // Different label order
            let g1 = GlobalType::comm(
                &sender, &receiver,
                vec![
                    (label1.clone(), GlobalType::End),
                    (label2.clone(), GlobalType::End),
                ],
            );
            let g2 = GlobalType::comm(
                &sender, &receiver,
                vec![
                    (label2, GlobalType::End),
                    (label1, GlobalType::End),
                ],
            );

            // Same content ID regardless of branch order
            prop_assert_eq!(
                g1.content_id_default().unwrap(),
                g2.content_id_default().unwrap(),
                "branch order should not affect content ID"
            );
        }

        /// Property: LocalTypeR α-equivalence
        #[test]
        fn prop_local_type_alpha_equiv(
            partner in arb_role(),
            label in arb_label(),
        ) {
            let t1 = LocalTypeR::mu("x", LocalTypeR::send(&partner, label.clone(), LocalTypeR::var("x")));
            let t2 = LocalTypeR::mu("y", LocalTypeR::send(&partner, label, LocalTypeR::var("y")));

            prop_assert_eq!(
                t1.content_id_default().unwrap(),
                t2.content_id_default().unwrap(),
                "α-equivalent local types should have same content ID"
            );
        }
    }
}