stateknot-runtime 0.1.0-alpha.1

Executable registries and durable graph driving for StateKnot
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
// Copyright 2026 StateKnot contributors
// SPDX-License-Identifier: Apache-2.0

//! Offline, digest-pinned JSON Schema 2020-12 registry.

use std::{collections::HashMap, sync::Arc};

use jsonschema::{Draft, Registry, Validator};
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde_json::Value;
use stateknot_core::{
    BoundedJson, Digest, GraphSchemaValidationError, GraphSchemaValidator, ModelSchemaRegistry,
    SchemaId, SchemaReference, ToolSchemaRegistry, ToolSchemaRole, ToolSchemaValidationError,
    Version,
};
use thiserror::Error;

const MEBIBYTE: usize = 1024 * 1024;
const DRAFT_2020_12: &str = "https://json-schema.org/draft/2020-12/schema";

/// Resource ceilings applied while an executable schema registry is built.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(clippy::struct_field_names)]
pub struct JsonSchemaRegistryLimits {
    maximum_schemas: usize,
    maximum_schema_bytes: usize,
    maximum_total_bytes: usize,
}

impl JsonSchemaRegistryLimits {
    /// Absolute implementation ceiling for registered resources.
    pub const HARD_MAXIMUM_SCHEMAS: usize = 4096;
    /// Absolute implementation ceiling for one canonical schema document.
    pub const HARD_MAXIMUM_SCHEMA_BYTES: usize = 8 * MEBIBYTE;
    /// Absolute implementation ceiling for all canonical schema documents.
    pub const HARD_MAXIMUM_TOTAL_BYTES: usize = 256 * MEBIBYTE;

    /// Constructs positive limits within implementation ceilings.
    ///
    /// # Errors
    ///
    /// Returns [`JsonSchemaRegistryLimitsError`] for zero, inconsistent, or
    /// implementation-exceeding limits.
    pub const fn new(
        maximum_schemas: usize,
        maximum_schema_bytes: usize,
        maximum_total_bytes: usize,
    ) -> Result<Self, JsonSchemaRegistryLimitsError> {
        if maximum_schemas == 0 {
            return Err(JsonSchemaRegistryLimitsError::ZeroSchemas);
        }
        if maximum_schema_bytes == 0 {
            return Err(JsonSchemaRegistryLimitsError::ZeroSchemaBytes);
        }
        if maximum_total_bytes < maximum_schema_bytes {
            return Err(JsonSchemaRegistryLimitsError::TotalBelowSingleSchema);
        }
        if maximum_schemas > Self::HARD_MAXIMUM_SCHEMAS {
            return Err(JsonSchemaRegistryLimitsError::TooManySchemas {
                maximum: Self::HARD_MAXIMUM_SCHEMAS,
                actual: maximum_schemas,
            });
        }
        if maximum_schema_bytes > Self::HARD_MAXIMUM_SCHEMA_BYTES {
            return Err(JsonSchemaRegistryLimitsError::SchemaBytesTooLarge {
                maximum: Self::HARD_MAXIMUM_SCHEMA_BYTES,
                actual: maximum_schema_bytes,
            });
        }
        if maximum_total_bytes > Self::HARD_MAXIMUM_TOTAL_BYTES {
            return Err(JsonSchemaRegistryLimitsError::TotalBytesTooLarge {
                maximum: Self::HARD_MAXIMUM_TOTAL_BYTES,
                actual: maximum_total_bytes,
            });
        }
        Ok(Self {
            maximum_schemas,
            maximum_schema_bytes,
            maximum_total_bytes,
        })
    }

    /// Returns the configured resource-count ceiling.
    #[must_use]
    pub const fn maximum_schemas(self) -> usize {
        self.maximum_schemas
    }

    /// Returns the configured per-document canonical byte ceiling.
    #[must_use]
    pub const fn maximum_schema_bytes(self) -> usize {
        self.maximum_schema_bytes
    }

    /// Returns the configured aggregate canonical byte ceiling.
    #[must_use]
    pub const fn maximum_total_bytes(self) -> usize {
        self.maximum_total_bytes
    }
}

impl Default for JsonSchemaRegistryLimits {
    fn default() -> Self {
        Self {
            maximum_schemas: 1024,
            maximum_schema_bytes: 2 * MEBIBYTE,
            maximum_total_bytes: 64 * MEBIBYTE,
        }
    }
}

/// Invalid executable schema-registry limits.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum JsonSchemaRegistryLimitsError {
    /// A registry could contain no resources.
    #[error("schema registry maximum schema count must be positive")]
    ZeroSchemas,
    /// A schema document could contain no bytes.
    #[error("schema registry per-schema byte maximum must be positive")]
    ZeroSchemaBytes,
    /// The aggregate ceiling could not contain one maximum-size document.
    #[error("schema registry total byte maximum is below its per-schema maximum")]
    TotalBelowSingleSchema,
    /// The resource-count ceiling exceeded the implementation bound.
    #[error("schema registry maximum is {actual}; implementation maximum is {maximum}")]
    TooManySchemas {
        /// Absolute implementation maximum.
        maximum: usize,
        /// Rejected configured value.
        actual: usize,
    },
    /// The per-document byte ceiling exceeded the implementation bound.
    #[error("schema byte maximum is {actual}; implementation maximum is {maximum}")]
    SchemaBytesTooLarge {
        /// Absolute implementation maximum.
        maximum: usize,
        /// Rejected configured value.
        actual: usize,
    },
    /// The aggregate byte ceiling exceeded the implementation bound.
    #[error("schema aggregate byte maximum is {actual}; implementation maximum is {maximum}")]
    TotalBytesTooLarge {
        /// Absolute implementation maximum.
        maximum: usize,
        /// Rejected configured value.
        actual: usize,
    },
}

#[derive(Clone)]
struct PendingSchema {
    reference: SchemaReference,
    document: Value,
    canonical: Arc<[u8]>,
}

/// Mutable startup-only builder for an immutable offline schema registry.
///
/// Every document must name the exact reference URI in `$id`, explicitly use
/// JSON Schema 2020-12, match the reference's SHA-256 digest after RFC 8785
/// canonicalization, and pass meta-schema validation before it is retained.
/// The final build eagerly compiles every validator and rejects unresolved
/// references. No schema retrieval path exists on [`JsonSchemaRegistry`].
#[derive(Debug)]
pub struct JsonSchemaRegistryBuilder {
    limits: JsonSchemaRegistryLimits,
    schemas: Vec<PendingSchema>,
    by_reference: HashMap<SchemaReference, usize>,
    by_id: HashMap<String, SchemaReference>,
    total_bytes: usize,
}

impl JsonSchemaRegistryBuilder {
    /// Creates an empty startup builder with explicit resource ceilings.
    #[must_use]
    pub fn new(limits: JsonSchemaRegistryLimits) -> Self {
        Self {
            limits,
            schemas: Vec::new(),
            by_reference: HashMap::new(),
            by_id: HashMap::new(),
            total_bytes: 0,
        }
    }

    /// Creates an empty startup builder with production defaults.
    #[must_use]
    pub fn with_default_limits() -> Self {
        Self::new(JsonSchemaRegistryLimits::default())
    }

    /// Registers one owned schema document after integrity and dialect checks.
    ///
    /// A URI may identify only one immutable resource in a registry. This is
    /// stricter than keying by the full reference because JSON Schema `$ref`
    /// resolution uses the URI and cannot select a version or digest sideband.
    ///
    /// # Errors
    ///
    /// Returns [`JsonSchemaRegistryError`] for duplicate identity, resource
    /// exhaustion, canonicalization/digest drift, an invalid `$id`/dialect, or
    /// a meta-schema violation.
    pub fn register(
        &mut self,
        reference: SchemaReference,
        document: Value,
    ) -> Result<(), JsonSchemaRegistryError> {
        if self.schemas.len() == self.limits.maximum_schemas {
            return Err(JsonSchemaRegistryError::TooManySchemas {
                maximum: self.limits.maximum_schemas,
                actual: self.limits.maximum_schemas + 1,
            });
        }
        if self.by_reference.contains_key(&reference) {
            return Err(JsonSchemaRegistryError::DuplicateReference {
                reference: Box::new(reference),
            });
        }
        let id = reference.id().as_str();
        if let Some(existing) = self.by_id.get(id) {
            return Err(JsonSchemaRegistryError::DuplicateId {
                existing: Box::new(existing.clone()),
                rejected: Box::new(reference),
            });
        }

        let object = document
            .as_object()
            .ok_or(JsonSchemaRegistryError::SchemaRootNotObject)?;
        match object.get("$schema").and_then(Value::as_str) {
            Some(DRAFT_2020_12) => {}
            _ => return Err(JsonSchemaRegistryError::UnsupportedDialect),
        }
        if object.get("$id").and_then(Value::as_str) != Some(id) {
            return Err(JsonSchemaRegistryError::IdMismatch {
                reference: Box::new(reference),
            });
        }

        jsonschema::draft202012::meta::validate(&document).map_err(|source| {
            JsonSchemaRegistryError::InvalidSchema {
                diagnostic: source.to_string().into_boxed_str(),
            }
        })?;
        let canonical = serde_json_canonicalizer::to_vec(&document)
            .map_err(|_| JsonSchemaRegistryError::Canonicalization)?;
        if canonical.len() > self.limits.maximum_schema_bytes {
            return Err(JsonSchemaRegistryError::SchemaTooLarge {
                maximum: self.limits.maximum_schema_bytes,
                actual: canonical.len(),
            });
        }
        if Digest::sha256(&canonical) != reference.digest() {
            return Err(JsonSchemaRegistryError::DigestMismatch {
                reference: Box::new(reference),
            });
        }
        let total_bytes = self.total_bytes.checked_add(canonical.len()).ok_or(
            JsonSchemaRegistryError::AggregateTooLarge {
                maximum: self.limits.maximum_total_bytes,
                actual: usize::MAX,
            },
        )?;
        if total_bytes > self.limits.maximum_total_bytes {
            return Err(JsonSchemaRegistryError::AggregateTooLarge {
                maximum: self.limits.maximum_total_bytes,
                actual: total_bytes,
            });
        }

        let index = self.schemas.len();
        self.by_id.insert(id.to_owned(), reference.clone());
        self.by_reference.insert(reference.clone(), index);
        self.schemas.push(PendingSchema {
            reference,
            document,
            canonical: canonical.into(),
        });
        self.total_bytes = total_bytes;
        Ok(())
    }

    /// Generates, pins, and registers the JSON Schema for one Rust type.
    ///
    /// The generated document receives the supplied canonical `$id`; its
    /// version and RFC 8785 digest are then frozen in the returned reference.
    /// Use that reference in the corresponding tool descriptor. At
    /// [`stateknot_core::ToolAdapter`] construction, the frozen registry proves
    /// that the currently compiled Rust type still matches these exact bytes.
    ///
    /// # Errors
    ///
    /// Returns [`JsonSchemaRegistryError`] when generation cannot be encoded or
    /// when the resulting document violates any ordinary registry invariant.
    pub fn register_rust_type<T: JsonSchema>(
        &mut self,
        id: SchemaId,
        version: Version,
    ) -> Result<SchemaReference, JsonSchemaRegistryError> {
        let generated = SchemaGenerator::default().into_root_schema_for::<T>();
        let mut document = serde_json::to_value(generated)
            .map_err(|_| JsonSchemaRegistryError::GeneratedSchemaSerialization)?;
        let object = document
            .as_object_mut()
            .ok_or(JsonSchemaRegistryError::SchemaRootNotObject)?;
        object.insert("$id".to_owned(), Value::String(id.as_str().to_owned()));
        let canonical = serde_json_canonicalizer::to_vec(&document)
            .map_err(|_| JsonSchemaRegistryError::Canonicalization)?;
        let reference = SchemaReference::new(id, version, Digest::sha256(canonical));
        self.register(reference.clone(), document)?;
        Ok(reference)
    }

    /// Freezes all resources and eagerly compiles offline validators.
    ///
    /// # Errors
    ///
    /// Returns [`JsonSchemaRegistryError`] when the registry is empty, a URI
    /// cannot be indexed, or any local `$ref` cannot be resolved and compiled.
    pub fn build(self) -> Result<JsonSchemaRegistry, JsonSchemaRegistryError> {
        if self.schemas.is_empty() {
            return Err(JsonSchemaRegistryError::Empty);
        }

        let mut registry_builder = Registry::new().draft(Draft::Draft202012);
        for schema in &self.schemas {
            registry_builder = registry_builder
                .add(schema.reference.id().as_str(), schema.document.clone())
                .map_err(|source| JsonSchemaRegistryError::RegistryPreparation {
                    diagnostic: source.to_string().into_boxed_str(),
                })?;
        }
        let registry = registry_builder.prepare().map_err(|source| {
            JsonSchemaRegistryError::RegistryPreparation {
                diagnostic: source.to_string().into_boxed_str(),
            }
        })?;

        let mut entries = HashMap::with_capacity(self.schemas.len());
        for schema in self.schemas {
            let validator = jsonschema::draft202012::options()
                .with_registry(&registry)
                .should_validate_formats(true)
                .offline()
                .build(&schema.document)
                .map_err(|source| JsonSchemaRegistryError::ValidatorCompilation {
                    reference: Box::new(schema.reference.clone()),
                    diagnostic: source.to_string().into_boxed_str(),
                })?;
            entries.insert(
                schema.reference,
                CompiledSchema {
                    canonical: schema.canonical,
                    validator,
                },
            );
        }

        Ok(JsonSchemaRegistry {
            inner: Arc::new(JsonSchemaRegistryInner {
                entries,
                total_bytes: self.total_bytes,
            }),
        })
    }
}

impl Default for JsonSchemaRegistryBuilder {
    fn default() -> Self {
        Self::with_default_limits()
    }
}

impl std::fmt::Debug for PendingSchema {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PendingSchema")
            .field("reference", &self.reference)
            .field("canonical_bytes", &self.canonical.len())
            .finish_non_exhaustive()
    }
}

struct CompiledSchema {
    canonical: Arc<[u8]>,
    validator: Validator,
}

struct JsonSchemaRegistryInner {
    entries: HashMap<SchemaReference, CompiledSchema>,
    total_bytes: usize,
}

/// Immutable, shareable registry of eagerly compiled offline validators.
#[derive(Clone)]
pub struct JsonSchemaRegistry {
    inner: Arc<JsonSchemaRegistryInner>,
}

impl JsonSchemaRegistry {
    /// Returns whether the exact URI, version, and digest are installed.
    #[must_use]
    pub fn contains(&self, reference: &SchemaReference) -> bool {
        self.inner.entries.contains_key(reference)
    }

    /// Returns the number of immutable schema resources.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.entries.len()
    }

    /// Returns whether the frozen registry contains no resources.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.entries.is_empty()
    }

    /// Returns the total retained canonical schema bytes.
    #[must_use]
    pub fn total_bytes(&self) -> usize {
        self.inner.total_bytes
    }

    /// Returns the exact canonical document bytes for trusted diagnostics.
    #[must_use]
    pub fn canonical_bytes(&self, reference: &SchemaReference) -> Option<&[u8]> {
        self.inner
            .entries
            .get(reference)
            .map(|entry| entry.canonical.as_ref())
    }

    /// Validates a bounded instance and retains no instance data.
    ///
    /// # Errors
    ///
    /// Returns [`GraphSchemaValidationError::Unavailable`] when the complete
    /// reference is absent and [`GraphSchemaValidationError::Rejected`] when
    /// the instance violates the compiled contract.
    pub fn validate_bounded(
        &self,
        reference: &SchemaReference,
        value: &BoundedJson,
    ) -> Result<(), GraphSchemaValidationError> {
        let entry = self
            .inner
            .entries
            .get(reference)
            .ok_or(GraphSchemaValidationError::Unavailable)?;
        if entry.validator.is_valid(value.as_value()) {
            Ok(())
        } else {
            Err(GraphSchemaValidationError::Rejected)
        }
    }
}

impl std::fmt::Debug for JsonSchemaRegistry {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("JsonSchemaRegistry")
            .field("schemas", &self.len())
            .field("total_bytes", &self.total_bytes())
            .finish_non_exhaustive()
    }
}

impl GraphSchemaValidator for JsonSchemaRegistry {
    fn validate(
        &self,
        schema: &SchemaReference,
        value: &BoundedJson,
    ) -> Result<(), GraphSchemaValidationError> {
        self.validate_bounded(schema, value)
    }
}

impl ModelSchemaRegistry for JsonSchemaRegistry {
    fn canonical_schema_bytes(&self, schema: &SchemaReference) -> Option<&[u8]> {
        self.canonical_bytes(schema)
    }
}

impl ToolSchemaRegistry for JsonSchemaRegistry {
    fn validate_type_schema(
        &self,
        reference: &SchemaReference,
        role: ToolSchemaRole,
        generated: &Schema,
    ) -> Result<(), ToolSchemaValidationError> {
        let mut document = serde_json::to_value(generated).map_err(tool_schema_error)?;
        let object = document
            .as_object_mut()
            .ok_or_else(|| tool_schema_message("generated tool schema is not an object"))?;
        if matches!(role, ToolSchemaRole::Input)
            && object.get("type").and_then(Value::as_str) != Some("object")
        {
            return Err(tool_schema_message(
                "generated tool input schema must have an object root",
            ));
        }
        object.insert(
            "$id".to_owned(),
            Value::String(reference.id().as_str().to_owned()),
        );
        let canonical = serde_json_canonicalizer::to_vec(&document).map_err(tool_schema_error)?;
        let installed = self
            .canonical_bytes(reference)
            .ok_or_else(|| tool_schema_message("tool schema reference is not installed"))?;
        if installed != canonical {
            return Err(tool_schema_message(
                "generated Rust schema differs from the installed tool contract",
            ));
        }
        Ok(())
    }

    fn validate_instance(
        &self,
        reference: &SchemaReference,
        _role: ToolSchemaRole,
        value: &BoundedJson,
    ) -> Result<(), ToolSchemaValidationError> {
        self.validate_bounded(reference, value)
            .map_err(tool_schema_error)
    }
}

fn tool_schema_error(
    source: impl std::error::Error + Send + Sync + 'static,
) -> ToolSchemaValidationError {
    ToolSchemaValidationError::new(source)
}

fn tool_schema_message(message: &'static str) -> ToolSchemaValidationError {
    ToolSchemaValidationError::new(std::io::Error::other(message))
}

/// Startup-time failure while constructing an offline schema registry.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum JsonSchemaRegistryError {
    /// Runtime execution without any trusted schema would fail open.
    #[error("schema registry must contain at least one resource")]
    Empty,
    /// The configured resource count was exhausted.
    #[error("schema registry contains {actual} resources; maximum is {maximum}")]
    TooManySchemas {
        /// Configured maximum.
        maximum: usize,
        /// First rejected count.
        actual: usize,
    },
    /// The complete immutable reference was registered twice.
    #[error("schema reference was registered more than once")]
    DuplicateReference {
        /// Repeated reference.
        reference: Box<SchemaReference>,
    },
    /// One URI attempted to identify multiple immutable resources.
    #[error("schema URI was reused by another version or digest")]
    DuplicateId {
        /// First immutable reference.
        existing: Box<SchemaReference>,
        /// Rejected immutable reference.
        rejected: Box<SchemaReference>,
    },
    /// A schema document was not an object and could not carry identity.
    #[error("schema document root must be an object")]
    SchemaRootNotObject,
    /// The exact mandatory dialect declaration was absent.
    #[error("schema must declare JSON Schema 2020-12")]
    UnsupportedDialect,
    /// `$id` did not equal the normalized pinned URI.
    #[error("schema $id does not match its immutable reference")]
    IdMismatch {
        /// Expected immutable reference.
        reference: Box<SchemaReference>,
    },
    /// The schema did not satisfy the official meta-schema.
    #[error("schema violates JSON Schema 2020-12: {diagnostic}")]
    InvalidSchema {
        /// Startup-safe schema diagnostic; no runtime instance is involved.
        diagnostic: Box<str>,
    },
    /// RFC 8785 serialization unexpectedly failed.
    #[error("schema canonicalization failed")]
    Canonicalization,
    /// A generated Rust schema could not be represented as JSON.
    #[error("generated Rust schema serialization failed")]
    GeneratedSchemaSerialization,
    /// Canonical bytes exceeded the configured single-resource limit.
    #[error("canonical schema is {actual} bytes; maximum is {maximum}")]
    SchemaTooLarge {
        /// Configured maximum.
        maximum: usize,
        /// Observed canonical bytes.
        actual: usize,
    },
    /// Canonical schema bytes did not match the pinned digest.
    #[error("canonical schema digest does not match its immutable reference")]
    DigestMismatch {
        /// Rejected immutable reference.
        reference: Box<SchemaReference>,
    },
    /// Aggregate canonical bytes exceeded the configured limit.
    #[error("schema registry contains {actual} canonical bytes; maximum is {maximum}")]
    AggregateTooLarge {
        /// Configured maximum.
        maximum: usize,
        /// Observed or saturated aggregate.
        actual: usize,
    },
    /// The local resource graph could not be prepared.
    #[error("schema registry resource preparation failed: {diagnostic}")]
    RegistryPreparation {
        /// Startup-safe schema diagnostic.
        diagnostic: Box<str>,
    },
    /// One exact schema could not compile with offline reference resolution.
    #[error("schema validator compilation failed: {diagnostic}")]
    ValidatorCompilation {
        /// Exact resource that failed compilation.
        reference: Box<SchemaReference>,
        /// Startup-safe schema diagnostic.
        diagnostic: Box<str>,
    },
}

#[cfg(test)]
mod tests {
    use schemars::{JsonSchema, SchemaGenerator};
    use serde::{Deserialize, Serialize};
    use serde_json::json;
    use stateknot_core::{SchemaId, Version};

    use super::*;

    fn reference(id: &str, document: &Value) -> SchemaReference {
        let canonical = serde_json_canonicalizer::to_vec(document).unwrap();
        SchemaReference::new(
            id.parse::<SchemaId>().unwrap(),
            "1.0.0".parse::<Version>().unwrap(),
            Digest::sha256(canonical),
        )
    }

    #[test]
    fn registry_is_offline_digest_pinned_and_resolves_local_resources() {
        let address_id = "https://schemas.example.com/address/1.0.0";
        let address = json!({
            "$schema": DRAFT_2020_12,
            "$id": address_id,
            "type": "object",
            "properties": {"postcode": {"type": "string", "pattern": "^[0-9]{5}$"}},
            "required": ["postcode"],
            "additionalProperties": false
        });
        let user_id = "https://schemas.example.com/user/1.0.0";
        let user = json!({
            "$schema": DRAFT_2020_12,
            "$id": user_id,
            "type": "object",
            "properties": {
                "email": {"type": "string", "format": "email"},
                "address": {"$ref": address_id}
            },
            "required": ["email", "address"],
            "additionalProperties": false
        });
        let address_reference = reference(address_id, &address);
        let user_reference = reference(user_id, &user);
        let mut builder = JsonSchemaRegistryBuilder::default();
        builder
            .register(address_reference.clone(), address)
            .unwrap();
        builder.register(user_reference.clone(), user).unwrap();
        let registry = builder.build().unwrap();

        let valid = BoundedJson::try_from_value(json!({
            "email": "agent@example.com",
            "address": {"postcode": "31000"}
        }))
        .unwrap();
        let bad_format = BoundedJson::try_from_value(json!({
            "email": "not-an-email",
            "address": {"postcode": "31000"}
        }))
        .unwrap();
        let bad_reference_value = BoundedJson::try_from_value(json!({
            "email": "agent@example.com",
            "address": {"postcode": "broken"}
        }))
        .unwrap();

        assert_eq!(registry.len(), 2);
        assert!(registry.total_bytes() > 0);
        assert!(registry.canonical_bytes(&address_reference).is_some());
        assert_eq!(registry.validate_bounded(&user_reference, &valid), Ok(()));
        assert_eq!(
            registry.validate_bounded(&user_reference, &bad_format),
            Err(GraphSchemaValidationError::Rejected)
        );
        assert_eq!(
            registry.validate_bounded(&user_reference, &bad_reference_value),
            Err(GraphSchemaValidationError::Rejected)
        );
    }

    #[test]
    fn registration_rejects_digest_dialect_id_and_uri_aliases() {
        let id = "https://schemas.example.com/state/1.0.0";
        let document = json!({
            "$schema": DRAFT_2020_12,
            "$id": id,
            "type": "object"
        });
        let exact = reference(id, &document);

        let mut mismatch = JsonSchemaRegistryBuilder::default();
        let wrong = SchemaReference::new(
            exact.id().clone(),
            exact.version(),
            Digest::sha256(b"wrong"),
        );
        assert!(matches!(
            mismatch.register(wrong, document.clone()),
            Err(JsonSchemaRegistryError::DigestMismatch { .. })
        ));

        let mut dialect = document.clone();
        dialect["$schema"] = json!("https://json-schema.org/draft/2019-09/schema");
        assert_eq!(
            JsonSchemaRegistryBuilder::default().register(reference(id, &dialect), dialect),
            Err(JsonSchemaRegistryError::UnsupportedDialect)
        );

        let mut wrong_id = document.clone();
        wrong_id["$id"] = json!("https://schemas.example.com/other/1.0.0");
        assert!(matches!(
            JsonSchemaRegistryBuilder::default().register(reference(id, &wrong_id), wrong_id),
            Err(JsonSchemaRegistryError::IdMismatch { .. })
        ));

        let mut duplicate = JsonSchemaRegistryBuilder::default();
        duplicate.register(exact.clone(), document.clone()).unwrap();
        let alias =
            SchemaReference::new(exact.id().clone(), "2.0.0".parse().unwrap(), exact.digest());
        assert!(matches!(
            duplicate.register(alias, document),
            Err(JsonSchemaRegistryError::DuplicateId { .. })
        ));
    }

    #[test]
    fn build_rejects_unresolved_network_reference() {
        let id = "https://schemas.example.com/offline/1.0.0";
        let document = json!({
            "$schema": DRAFT_2020_12,
            "$id": id,
            "$ref": "https://schemas.example.com/not-installed/1.0.0"
        });
        let mut builder = JsonSchemaRegistryBuilder::default();
        builder
            .register(reference(id, &document), document)
            .unwrap();
        assert!(matches!(
            builder.build(),
            Err(JsonSchemaRegistryError::ValidatorCompilation { .. }
                | JsonSchemaRegistryError::RegistryPreparation { .. })
        ));
    }

    #[test]
    fn absent_full_reference_is_unavailable() {
        let id = "https://schemas.example.com/value/1.0.0";
        let document = json!({
            "$schema": DRAFT_2020_12,
            "$id": id,
            "type": "integer"
        });
        let installed = reference(id, &document);
        let mut builder = JsonSchemaRegistryBuilder::default();
        builder.register(installed.clone(), document).unwrap();
        let registry = builder.build().unwrap();
        let missing = SchemaReference::new(
            installed.id().clone(),
            installed.version(),
            Digest::sha256(b"different"),
        );
        let value = BoundedJson::try_from_value(json!(1)).unwrap();
        assert_eq!(
            registry.validate_bounded(&missing, &value),
            Err(GraphSchemaValidationError::Unavailable)
        );
    }

    #[test]
    fn limits_fail_closed() {
        assert_eq!(
            JsonSchemaRegistryLimits::new(0, 1, 1),
            Err(JsonSchemaRegistryLimitsError::ZeroSchemas)
        );
        assert_eq!(
            JsonSchemaRegistryLimits::new(1, 2, 1),
            Err(JsonSchemaRegistryLimitsError::TotalBelowSingleSchema)
        );

        let limits = JsonSchemaRegistryLimits::new(1, 1024, 1024).unwrap();
        let first_id = "https://schemas.example.com/one/1.0.0";
        let first = json!({"$schema": DRAFT_2020_12, "$id": first_id});
        let second_id = "https://schemas.example.com/two/1.0.0";
        let second = json!({"$schema": DRAFT_2020_12, "$id": second_id});
        let mut builder = JsonSchemaRegistryBuilder::new(limits);
        builder
            .register(reference(first_id, &first), first)
            .unwrap();
        assert_eq!(
            builder.register(reference(second_id, &second), second),
            Err(JsonSchemaRegistryError::TooManySchemas {
                maximum: 1,
                actual: 2
            })
        );
    }

    #[derive(Deserialize, JsonSchema)]
    #[serde(deny_unknown_fields)]
    #[allow(dead_code)]
    struct LookupInput {
        incident_id: String,
    }

    #[derive(JsonSchema, Serialize)]
    #[serde(deny_unknown_fields)]
    struct LookupOutput {
        found: bool,
    }

    #[test]
    fn rust_type_registration_drives_exact_tool_validation() {
        let mut builder = JsonSchemaRegistryBuilder::default();
        let input = builder
            .register_rust_type::<LookupInput>(
                "https://schemas.example.com/tools/lookup/input/1.0.0"
                    .parse()
                    .unwrap(),
                Version::new(1, 0, 0),
            )
            .unwrap();
        let output = builder
            .register_rust_type::<LookupOutput>(
                "https://schemas.example.com/tools/lookup/output/1.0.0"
                    .parse()
                    .unwrap(),
                Version::new(1, 0, 0),
            )
            .unwrap();
        let registry = builder.build().unwrap();

        registry
            .validate_type_schema(
                &input,
                ToolSchemaRole::Input,
                &SchemaGenerator::default().into_root_schema_for::<LookupInput>(),
            )
            .unwrap();
        registry
            .validate_type_schema(
                &output,
                ToolSchemaRole::Output,
                &SchemaGenerator::default().into_root_schema_for::<LookupOutput>(),
            )
            .unwrap();

        let valid = BoundedJson::try_from_value(json!({"incident_id": "INC-42"})).unwrap();
        let invalid = BoundedJson::try_from_value(json!({"unexpected": true})).unwrap();
        assert!(
            registry
                .validate_instance(&input, ToolSchemaRole::Input, &valid)
                .is_ok()
        );
        assert!(
            registry
                .validate_instance(&input, ToolSchemaRole::Input, &invalid)
                .is_err()
        );
        assert!(
            registry
                .validate_type_schema(
                    &input,
                    ToolSchemaRole::Input,
                    &SchemaGenerator::default().into_root_schema_for::<LookupOutput>(),
                )
                .is_err()
        );
    }
}