asupersync 0.3.6

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Stable, structural schema fingerprints for typed named computations.
//!
//! This is the foundation of the typed `spawn_remote` registry (bead
//! `asupersync-dist-otp-completeness-8y37kz.7`). Remote computations are named
//! and carry serialized input/output payloads; without a schema check, a
//! wrong-schema bug surfaces as an opaque deserialization failure at the remote
//! node — or, worse, a silent misinterpretation. This module lets each
//! computation advertise a content-hashed **schema fingerprint** that travels
//! in the spawn envelope, so a mismatch is caught (and *named*) up front.
//!
//! # Critical design decision: structural fingerprint, NOT `TypeId`
//!
//! The fingerprint is derived from a [`SchemaDescriptor`] — a canonical,
//! declaration-order structural description of a type's wire shape (field names
//! and types) — and hashed with a fixed FNV-1a-64 function over a canonical
//! byte encoding. It deliberately does **not** use [`std::any::TypeId`] or any
//! memory-layout/`type_name` value, because those are neither stable across
//! compiler versions nor meaningful across two independently-built nodes. Two
//! nodes that were compiled separately but declare the same logical schema must
//! agree on the fingerprint; two that differ in any wire-visible way must not.
//!
//! # Layering
//!
//! This module is a pure typing layer: it has no I/O and no dependency on the
//! spawn protocol. The typed envelope fields + dispatcher in `remote.rs` and
//! the `#[remote_computation]` derive (which will auto-generate
//! [`HasSchema`] impls) build on top of it in sibling slices of the bead.

use std::{collections::BTreeMap, fmt};

/// Canonical, declaration-order structural description of a value's wire schema.
///
/// Equality and the derived fingerprint are intentionally structural: anything
/// that changes the serialized shape (a primitive type, a field name, field
/// order, an added/removed field, a renamed struct/enum) changes the descriptor
/// and therefore the [`SchemaFingerprint`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaDescriptor {
    /// A scalar/leaf type, identified by a stable canonical name (e.g. `"u64"`).
    Primitive(&'static str),
    /// The unit type `()`.
    Unit,
    /// An optional value (`Option<T>`).
    Option(Box<SchemaDescriptor>),
    /// A homogeneous sequence (`Vec<T>`, `[T]`).
    Seq(Box<SchemaDescriptor>),
    /// A key/value map.
    Map(Box<SchemaDescriptor>, Box<SchemaDescriptor>),
    /// A fixed-arity tuple, in element order.
    Tuple(Vec<SchemaDescriptor>),
    /// A named struct with fields in declaration order.
    Struct {
        /// The struct's canonical name.
        name: &'static str,
        /// Fields as `(name, schema)` in declaration order.
        fields: Vec<(&'static str, SchemaDescriptor)>,
    },
    /// A named enum with variants in declaration order.
    Enum {
        /// The enum's canonical name.
        name: &'static str,
        /// Variants as `(name, payload schema)` in declaration order.
        variants: Vec<(&'static str, SchemaDescriptor)>,
    },
}

impl SchemaDescriptor {
    /// A leaf/primitive schema with the given canonical name.
    #[must_use]
    pub const fn primitive(name: &'static str) -> Self {
        Self::Primitive(name)
    }

    /// An `Option<inner>` schema.
    #[must_use]
    pub fn option(inner: Self) -> Self {
        Self::Option(Box::new(inner))
    }

    /// A sequence-of-`inner` schema.
    #[must_use]
    pub fn seq(inner: Self) -> Self {
        Self::Seq(Box::new(inner))
    }

    /// A map schema with the given key and value schemas.
    #[must_use]
    pub fn map(key: Self, value: Self) -> Self {
        Self::Map(Box::new(key), Box::new(value))
    }

    /// A tuple schema from its element schemas, in order.
    #[must_use]
    pub fn tuple(elements: Vec<Self>) -> Self {
        Self::Tuple(elements)
    }

    /// A named struct schema from its fields, in declaration order.
    #[must_use]
    pub fn structure(name: &'static str, fields: Vec<(&'static str, Self)>) -> Self {
        Self::Struct { name, fields }
    }

    /// A named enum schema from its variants, in declaration order.
    #[must_use]
    pub fn enumeration(name: &'static str, variants: Vec<(&'static str, Self)>) -> Self {
        Self::Enum { name, variants }
    }

    /// The content-hashed fingerprint of this schema.
    #[must_use]
    pub fn fingerprint(&self) -> SchemaFingerprint {
        SchemaFingerprint::of(self)
    }

    /// A short, human/agent-readable name for this descriptor's variant.
    const fn kind_name(&self) -> &'static str {
        match self {
            Self::Primitive(_) => "primitive",
            Self::Unit => "unit",
            Self::Option(_) => "option",
            Self::Seq(_) => "seq",
            Self::Map(..) => "map",
            Self::Tuple(_) => "tuple",
            Self::Struct { .. } => "struct",
            Self::Enum { .. } => "enum",
        }
    }

    /// Appends a canonical, deterministic byte encoding of this descriptor to
    /// `out`. The encoding is tag-prefixed and length-delimited so that no two
    /// structurally-distinct descriptors can collide on the encoded bytes (and
    /// therefore — modulo the hash — on the fingerprint).
    fn canonical_encode(&self, out: &mut Vec<u8>) {
        match self {
            Self::Primitive(name) => {
                out.push(0);
                encode_str(name, out);
            }
            Self::Unit => out.push(1),
            Self::Option(inner) => {
                out.push(2);
                inner.canonical_encode(out);
            }
            Self::Seq(inner) => {
                out.push(3);
                inner.canonical_encode(out);
            }
            Self::Map(key, value) => {
                out.push(4);
                key.canonical_encode(out);
                value.canonical_encode(out);
            }
            Self::Tuple(elements) => {
                out.push(5);
                encode_len(elements.len(), out);
                for element in elements {
                    element.canonical_encode(out);
                }
            }
            Self::Struct { name, fields } => {
                out.push(6);
                encode_str(name, out);
                encode_len(fields.len(), out);
                for (field_name, field_schema) in fields {
                    encode_str(field_name, out);
                    field_schema.canonical_encode(out);
                }
            }
            Self::Enum { name, variants } => {
                out.push(7);
                encode_str(name, out);
                encode_len(variants.len(), out);
                for (variant_name, variant_schema) in variants {
                    encode_str(variant_name, out);
                    variant_schema.canonical_encode(out);
                }
            }
        }
    }

    /// Returns the first structural difference between an `expected` schema and
    /// an `actual` one, or `None` if they are identical.
    ///
    /// The reported [`SchemaMismatch`] carries a path into the schema and a
    /// kind naming the difference (primitive/type change, renamed type, missing
    /// or extra field, changed tuple arity) so that agents reading the error
    /// can pinpoint it. A renamed field surfaces as a missing field (its old
    /// name) followed, on a subsequent comparison, by an extra field.
    #[must_use]
    pub fn diff(expected: &Self, actual: &Self) -> Option<SchemaMismatch> {
        diff_at(expected, actual, "$")
    }
}

fn encode_str(value: &str, out: &mut Vec<u8>) {
    encode_len(value.len(), out);
    out.extend_from_slice(value.as_bytes());
}

fn encode_len(len: usize, out: &mut Vec<u8>) {
    out.extend_from_slice(&(len as u64).to_le_bytes());
}

/// FNV-1a 64-bit hash. Fixed constants make the output stable across compiler
/// versions and machines — the property `TypeId` lacks.
fn fnv1a64(bytes: &[u8]) -> u64 {
    const OFFSET_BASIS: u64 = 0xcbf29ce484222325;
    const PRIME: u64 = 0x0000_0100_0000_01b3;
    let mut hash = OFFSET_BASIS;
    for &byte in bytes {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(PRIME);
    }
    hash
}

// clippy::explicit_auto_deref is a false positive here: matching the
// `(&SchemaDescriptor, &SchemaDescriptor)` tuple binds the `&'static str`
// primitive names in `ref` mode (e.g. `e: &&'static str`), so the `*e`/`*a`
// derefs are required to place `&'static str` values into the mismatch fields —
// removing them does not type-check.
#[allow(clippy::explicit_auto_deref)]
fn diff_at(
    expected: &SchemaDescriptor,
    actual: &SchemaDescriptor,
    path: &str,
) -> Option<SchemaMismatch> {
    use SchemaDescriptor as D;
    match (expected, actual) {
        (D::Primitive(e), D::Primitive(a)) => {
            if e == a {
                None
            } else {
                Some(SchemaMismatch::new(
                    path,
                    SchemaMismatchKind::PrimitiveChanged {
                        expected: *e,
                        actual: *a,
                    },
                ))
            }
        }
        (D::Unit, D::Unit) => None,
        (D::Option(e), D::Option(a)) => diff_at(e, a, &format!("{path}?")),
        (D::Seq(e), D::Seq(a)) => diff_at(e, a, &format!("{path}[]")),
        (D::Map(ek, ev), D::Map(ak, av)) => diff_at(ek, ak, &format!("{path}.<key>"))
            .or_else(|| diff_at(ev, av, &format!("{path}.<value>"))),
        (D::Tuple(e), D::Tuple(a)) => {
            if e.len() != a.len() {
                return Some(SchemaMismatch::new(
                    path,
                    SchemaMismatchKind::ArityChanged {
                        expected: e.len(),
                        actual: a.len(),
                    },
                ));
            }
            for (index, (ei, ai)) in e.iter().zip(a.iter()).enumerate() {
                if let Some(mismatch) = diff_at(ei, ai, &format!("{path}.{index}")) {
                    return Some(mismatch);
                }
            }
            None
        }
        (
            D::Struct {
                name: en,
                fields: ef,
            },
            D::Struct {
                name: an,
                fields: af,
            },
        ) => {
            if en != an {
                return Some(SchemaMismatch::new(
                    path,
                    SchemaMismatchKind::NameChanged {
                        expected: (*en).to_string(),
                        actual: (*an).to_string(),
                    },
                ));
            }
            diff_named(ef, af, path)
        }
        (
            D::Enum {
                name: en,
                variants: ev,
            },
            D::Enum {
                name: an,
                variants: av,
            },
        ) => {
            if en != an {
                return Some(SchemaMismatch::new(
                    path,
                    SchemaMismatchKind::NameChanged {
                        expected: (*en).to_string(),
                        actual: (*an).to_string(),
                    },
                ));
            }
            diff_named(ev, av, path)
        }
        (e, a) => Some(SchemaMismatch::new(
            path,
            SchemaMismatchKind::KindChanged {
                expected: e.kind_name(),
                actual: a.kind_name(),
            },
        )),
    }
}

fn diff_named(
    expected: &[(&'static str, SchemaDescriptor)],
    actual: &[(&'static str, SchemaDescriptor)],
    path: &str,
) -> Option<SchemaMismatch> {
    for (name, expected_schema) in expected {
        match actual.iter().find(|(other, _)| other == name) {
            Some((_, actual_schema)) => {
                if let Some(mismatch) =
                    diff_at(expected_schema, actual_schema, &format!("{path}.{name}"))
                {
                    return Some(mismatch);
                }
            }
            None => {
                return Some(SchemaMismatch::new(
                    path,
                    SchemaMismatchKind::FieldMissing {
                        field: (*name).to_string(),
                    },
                ));
            }
        }
    }
    for (name, _) in actual {
        if !expected.iter().any(|(other, _)| other == name) {
            return Some(SchemaMismatch::new(
                path,
                SchemaMismatchKind::FieldExtra {
                    field: (*name).to_string(),
                },
            ));
        }
    }
    None
}

/// A content-hashed fingerprint of a [`SchemaDescriptor`].
///
/// Stable across compiler versions and independently-built nodes (it is a fixed
/// hash over the canonical structural encoding, never `TypeId`/layout).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SchemaFingerprint(u64);

impl SchemaFingerprint {
    /// Computes the fingerprint of a schema descriptor.
    #[must_use]
    pub fn of(descriptor: &SchemaDescriptor) -> Self {
        let mut buffer = Vec::new();
        descriptor.canonical_encode(&mut buffer);
        Self(fnv1a64(&buffer))
    }

    /// The raw 64-bit fingerprint value (e.g. to embed in a spawn envelope).
    #[must_use]
    pub const fn to_u64(self) -> u64 {
        self.0
    }
}

impl fmt::Display for SchemaFingerprint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:016x}", self.0)
    }
}

/// A located structural difference between two schemas.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SchemaMismatch {
    /// A path into the schema where the difference was found (`$` is the root).
    pub path: String,
    /// What differs at that path.
    pub kind: SchemaMismatchKind,
}

impl SchemaMismatch {
    fn new(path: &str, kind: SchemaMismatchKind) -> Self {
        Self {
            path: path.to_string(),
            kind,
        }
    }
}

impl fmt::Display for SchemaMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "schema mismatch at `{}`: {}", self.path, self.kind)
    }
}

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

/// The specific way two schemas differ at a point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SchemaMismatchKind {
    /// The descriptor variant changed (e.g. `struct` vs `seq`).
    KindChanged {
        /// The expected descriptor kind.
        expected: &'static str,
        /// The actual descriptor kind.
        actual: &'static str,
    },
    /// A primitive's canonical type name changed.
    PrimitiveChanged {
        /// The expected primitive name.
        expected: &'static str,
        /// The actual primitive name.
        actual: &'static str,
    },
    /// A named struct/enum was renamed.
    NameChanged {
        /// The expected type name.
        expected: String,
        /// The actual type name.
        actual: String,
    },
    /// A field/variant present in the expected schema is absent from the actual.
    FieldMissing {
        /// The missing field/variant name.
        field: String,
    },
    /// A field/variant present in the actual schema is absent from the expected.
    FieldExtra {
        /// The unexpected field/variant name.
        field: String,
    },
    /// A tuple's arity changed.
    ArityChanged {
        /// The expected element count.
        expected: usize,
        /// The actual element count.
        actual: usize,
    },
}

impl fmt::Display for SchemaMismatchKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::KindChanged { expected, actual } => {
                write!(f, "kind changed: expected `{expected}`, found `{actual}`")
            }
            Self::PrimitiveChanged { expected, actual } => write!(
                f,
                "primitive type changed: expected `{expected}`, found `{actual}`"
            ),
            Self::NameChanged { expected, actual } => {
                write!(f, "type renamed: expected `{expected}`, found `{actual}`")
            }
            Self::FieldMissing { field } => write!(f, "missing field `{field}`"),
            Self::FieldExtra { field } => write!(f, "unexpected extra field `{field}`"),
            Self::ArityChanged { expected, actual } => {
                write!(
                    f,
                    "tuple arity changed: expected {expected}, found {actual}"
                )
            }
        }
    }
}

/// A type that can describe its own wire schema for typed remote computations.
///
/// The `#[remote_computation]` derive (a sibling slice of this bead) will
/// auto-generate these impls from a type's declaration; until then, types may
/// implement it by hand. Primitives, `Option`, `Vec`, `Box`, the unit type, and
/// small tuples are provided here.
///
/// ```
/// use asupersync::distributed::computation_schema::HasSchema;
///
/// // Fingerprints are structural and stable, not based on `TypeId`.
/// assert_eq!(u64::schema_fingerprint(), u64::schema_fingerprint());
/// assert_ne!(u64::schema_fingerprint(), u32::schema_fingerprint());
/// assert_ne!(<Vec<u8>>::schema_fingerprint(), <Vec<u16>>::schema_fingerprint());
/// ```
pub trait HasSchema {
    /// The canonical structural schema of this type.
    fn schema() -> SchemaDescriptor;

    /// The content-hashed fingerprint of this type's schema.
    #[must_use]
    fn schema_fingerprint() -> SchemaFingerprint {
        SchemaFingerprint::of(&Self::schema())
    }
}

macro_rules! impl_primitive_schema {
    ($($t:ty => $name:literal),+ $(,)?) => {
        $(
            impl HasSchema for $t {
                fn schema() -> SchemaDescriptor {
                    SchemaDescriptor::Primitive($name)
                }
            }
        )+
    };
}

impl_primitive_schema! {
    u8 => "u8", u16 => "u16", u32 => "u32", u64 => "u64", u128 => "u128", usize => "usize",
    i8 => "i8", i16 => "i16", i32 => "i32", i64 => "i64", i128 => "i128", isize => "isize",
    bool => "bool", char => "char", f32 => "f32", f64 => "f64", String => "String",
}

impl HasSchema for () {
    fn schema() -> SchemaDescriptor {
        SchemaDescriptor::Unit
    }
}

impl<T: HasSchema> HasSchema for Option<T> {
    fn schema() -> SchemaDescriptor {
        SchemaDescriptor::option(T::schema())
    }
}

impl<T: HasSchema> HasSchema for Vec<T> {
    fn schema() -> SchemaDescriptor {
        SchemaDescriptor::seq(T::schema())
    }
}

impl<T: HasSchema> HasSchema for Box<T> {
    fn schema() -> SchemaDescriptor {
        T::schema()
    }
}

impl<A: HasSchema, B: HasSchema> HasSchema for (A, B) {
    fn schema() -> SchemaDescriptor {
        SchemaDescriptor::tuple(vec![A::schema(), B::schema()])
    }
}

impl<A: HasSchema, B: HasSchema, C: HasSchema> HasSchema for (A, B, C) {
    fn schema() -> SchemaDescriptor {
        SchemaDescriptor::tuple(vec![A::schema(), B::schema(), C::schema()])
    }
}

/// Registered schema metadata for one named remote computation.
///
/// This is the runtime-introspection shape that a node can advertise to peers:
/// computation name plus the structural input/output schema fingerprints that
/// must match the spawn envelope before dispatch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisteredComputationSchema {
    name: String,
    input_schema: SchemaDescriptor,
    output_schema: SchemaDescriptor,
    input_fingerprint: SchemaFingerprint,
    output_fingerprint: SchemaFingerprint,
}

impl RegisteredComputationSchema {
    /// Creates a named computation schema entry from explicit descriptors.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        input_schema: SchemaDescriptor,
        output_schema: SchemaDescriptor,
    ) -> Self {
        let input_fingerprint = input_schema.fingerprint();
        let output_fingerprint = output_schema.fingerprint();
        Self {
            name: name.into(),
            input_schema,
            output_schema,
            input_fingerprint,
            output_fingerprint,
        }
    }

    /// Creates a named computation schema entry from typed input/output values.
    #[must_use]
    pub fn typed<I, O>(name: impl Into<String>) -> Self
    where
        I: HasSchema,
        O: HasSchema,
    {
        Self::new(name, I::schema(), O::schema())
    }

    /// Stable computation name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Expected input schema.
    #[must_use]
    pub const fn input_schema(&self) -> &SchemaDescriptor {
        &self.input_schema
    }

    /// Expected output schema.
    #[must_use]
    pub const fn output_schema(&self) -> &SchemaDescriptor {
        &self.output_schema
    }

    /// Expected input schema fingerprint.
    #[must_use]
    pub const fn input_fingerprint(&self) -> SchemaFingerprint {
        self.input_fingerprint
    }

    /// Expected output schema fingerprint.
    #[must_use]
    pub const fn output_fingerprint(&self) -> SchemaFingerprint {
        self.output_fingerprint
    }
}

/// Deterministic registry of named remote-computation schemas.
///
/// Entries are keyed and iterated in sorted name order so metadata emission is
/// byte-stable across independently-built nodes and deterministic lab replays.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ComputationSchemaRegistry {
    entries: BTreeMap<String, RegisteredComputationSchema>,
}

impl ComputationSchemaRegistry {
    /// Creates an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a computation entry.
    ///
    /// Duplicate names are rejected instead of replacing an existing schema;
    /// schema evolution must be explicit at the caller layer.
    pub fn register(
        &mut self,
        entry: RegisteredComputationSchema,
    ) -> Result<(), ComputationSchemaRegistryError> {
        let name = entry.name.clone();
        if self.entries.contains_key(&name) {
            return Err(ComputationSchemaRegistryError::DuplicateName { name });
        }
        self.entries.insert(name, entry);
        Ok(())
    }

    /// Registers a typed input/output pair under `name`.
    pub fn register_typed<I, O>(
        &mut self,
        name: impl Into<String>,
    ) -> Result<(), ComputationSchemaRegistryError>
    where
        I: HasSchema,
        O: HasSchema,
    {
        self.register(RegisteredComputationSchema::typed::<I, O>(name))
    }

    /// Returns the schema entry for `name`, if registered.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&RegisteredComputationSchema> {
        self.entries.get(name)
    }

    /// Returns true when a computation name is registered.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.entries.contains_key(name)
    }

    /// Iterates registered computations in deterministic name order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &RegisteredComputationSchema> + '_ {
        self.entries.values()
    }

    /// Number of registered computations.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true when the registry is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// Errors raised while building a computation schema registry.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ComputationSchemaRegistryError {
    /// A computation name was registered more than once.
    DuplicateName {
        /// Duplicate computation name.
        name: String,
    },
}

impl fmt::Display for ComputationSchemaRegistryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DuplicateName { name } => {
                write!(f, "duplicate remote computation schema `{name}`")
            }
        }
    }
}

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

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

    fn person() -> SchemaDescriptor {
        SchemaDescriptor::structure(
            "Person",
            vec![
                ("id", u64::schema()),
                ("name", String::schema()),
                ("tags", <Vec<String>>::schema()),
            ],
        )
    }

    #[test]
    fn fingerprint_is_deterministic_and_distinct() {
        // AC3: stable across recomputation; distinct for distinct structure.
        assert_eq!(person().fingerprint(), person().fingerprint());
        assert_eq!(u64::schema_fingerprint(), u64::schema_fingerprint());
        assert_ne!(u64::schema_fingerprint(), u32::schema_fingerprint());
        assert_ne!(
            <Vec<u8>>::schema_fingerprint(),
            <Vec<u16>>::schema_fingerprint()
        );
        assert_ne!(
            <Option<u64>>::schema_fingerprint(),
            u64::schema_fingerprint()
        );
    }

    #[test]
    fn fingerprint_not_type_id_based() {
        // Two independently-constructed-but-identical descriptors agree.
        let a = SchemaDescriptor::structure("P", vec![("x", u8::schema())]);
        let b = SchemaDescriptor::structure("P", vec![("x", u8::schema())]);
        assert_eq!(a.fingerprint(), b.fingerprint());
    }

    #[test]
    fn diff_detects_type_change() {
        let expected = person();
        let actual = SchemaDescriptor::structure(
            "Person",
            vec![
                ("id", u32::schema()), // changed u64 -> u32
                ("name", String::schema()),
                ("tags", <Vec<String>>::schema()),
            ],
        );
        let mismatch = SchemaDescriptor::diff(&expected, &actual).expect("should differ");
        assert_eq!(mismatch.path, "$.id");
        assert!(matches!(
            mismatch.kind,
            SchemaMismatchKind::PrimitiveChanged {
                expected: "u64",
                actual: "u32"
            }
        ));
    }

    #[test]
    fn diff_detects_missing_field() {
        let expected = person();
        let actual = SchemaDescriptor::structure(
            "Person",
            vec![("id", u64::schema()), ("name", String::schema())], // dropped "tags"
        );
        let mismatch = SchemaDescriptor::diff(&expected, &actual).expect("should differ");
        assert!(matches!(
            mismatch.kind,
            SchemaMismatchKind::FieldMissing { ref field } if field == "tags"
        ));
    }

    #[test]
    fn diff_detects_extra_field() {
        let expected = SchemaDescriptor::structure("P", vec![("a", u8::schema())]);
        let actual =
            SchemaDescriptor::structure("P", vec![("a", u8::schema()), ("b", u8::schema())]);
        let mismatch = SchemaDescriptor::diff(&expected, &actual).expect("should differ");
        assert!(matches!(
            mismatch.kind,
            SchemaMismatchKind::FieldExtra { ref field } if field == "b"
        ));
    }

    #[test]
    fn diff_detects_rename() {
        let expected = SchemaDescriptor::structure("Old", vec![("a", u8::schema())]);
        let actual = SchemaDescriptor::structure("New", vec![("a", u8::schema())]);
        let mismatch = SchemaDescriptor::diff(&expected, &actual).expect("should differ");
        assert!(matches!(
            mismatch.kind,
            SchemaMismatchKind::NameChanged { .. }
        ));
    }

    #[test]
    fn identical_schema_has_no_diff() {
        assert!(SchemaDescriptor::diff(&person(), &person()).is_none());
    }

    #[test]
    fn mismatch_messages_name_the_difference() {
        // AC2: messages are agent-readable and name the difference.
        let expected = person();
        let actual = SchemaDescriptor::structure(
            "Person",
            vec![
                ("id", u32::schema()),
                ("name", String::schema()),
                ("tags", <Vec<String>>::schema()),
            ],
        );
        let mismatch = SchemaDescriptor::diff(&expected, &actual).expect("should differ");
        let rendered = mismatch.to_string();
        assert!(rendered.contains("$.id"), "rendered: {rendered}");
        assert!(rendered.contains("u64"), "rendered: {rendered}");
        assert!(rendered.contains("u32"), "rendered: {rendered}");
    }

    #[test]
    fn computation_registry_enumerates_entries_in_name_order() {
        let mut registry = ComputationSchemaRegistry::new();
        registry
            .register_typed::<u64, String>("zeta.encode")
            .unwrap();
        registry
            .register_typed::<(u64, String), Vec<u8>>("alpha.decode")
            .unwrap();

        assert_eq!(registry.len(), 2);
        assert!(registry.contains("alpha.decode"));

        let names: Vec<&str> = registry
            .iter()
            .map(RegisteredComputationSchema::name)
            .collect();
        assert_eq!(names, vec!["alpha.decode", "zeta.encode"]);

        let alpha = registry.get("alpha.decode").unwrap();
        assert_eq!(
            alpha.input_fingerprint(),
            <(u64, String)>::schema_fingerprint()
        );
        assert_eq!(alpha.output_fingerprint(), <Vec<u8>>::schema_fingerprint());
    }

    #[test]
    fn computation_registry_rejects_duplicate_names() {
        let mut registry = ComputationSchemaRegistry::new();
        registry.register_typed::<u64, u64>("work").unwrap();
        let err = registry
            .register_typed::<String, String>("work")
            .expect_err("duplicate computation names must fail closed");

        assert!(matches!(
            err,
            ComputationSchemaRegistryError::DuplicateName { ref name } if name == "work"
        ));
        assert_eq!(registry.len(), 1);
        let work = registry.get("work").unwrap();
        assert_eq!(work.input_fingerprint(), u64::schema_fingerprint());
        assert_eq!(work.output_fingerprint(), u64::schema_fingerprint());
    }
}