Skip to main content

lean_ctx/core/context_checkpoint/
migration.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Strict, bounded migration into the canonical V1 checkpoint wire contract.
4
5use std::fmt;
6
7use lean_ctx_protocol::{
8    ContextCheckpointMigrationV1, ContextCheckpointV1, MAX_CONTEXT_CHECKPOINT_ENCODED_BYTES,
9    Sha256Digest,
10};
11use serde::Serialize;
12use serde_json::Value;
13use sha2::{Digest, Sha256};
14
15pub(super) const MIGRATION_SIGNATURE_DOMAIN: &[u8] = b"leanctx/context-checkpoint-migration/v1\0";
16
17/// Exact source form accepted by the V1 migrator.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
19#[serde(rename_all = "snake_case")]
20pub enum ContextCheckpointMigrationKindV1 {
21    CanonicalV1,
22    LegacyV1MissingUpdatedAt,
23}
24
25/// Content-addressed proof of a deterministic checkpoint migration.
26#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
27#[serde(deny_unknown_fields)]
28pub struct ContextCheckpointMigrationReceiptV1 {
29    schema_version: u32,
30    kind: ContextCheckpointMigrationKindV1,
31    source_digest: Sha256Digest,
32    output_digest: Sha256Digest,
33}
34
35impl ContextCheckpointMigrationReceiptV1 {
36    pub const SCHEMA_VERSION: u32 = 1;
37    pub fn kind(&self) -> ContextCheckpointMigrationKindV1 {
38        self.kind
39    }
40    pub fn source_digest(&self) -> &Sha256Digest {
41        &self.source_digest
42    }
43    pub fn output_digest(&self) -> &Sha256Digest {
44        &self.output_digest
45    }
46    pub fn signing_payload(&self) -> Vec<u8> {
47        let mut bytes = MIGRATION_SIGNATURE_DOMAIN.to_vec();
48        bytes.extend(crate::core::canonical::canonical_serialize(self));
49        bytes
50    }
51}
52
53/// Validated output and provenance receipt returned by a migration.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct ContextCheckpointMigrationResultV1 {
56    checkpoint: ContextCheckpointV1,
57    receipt: ContextCheckpointMigrationReceiptV1,
58}
59
60impl ContextCheckpointMigrationResultV1 {
61    pub fn checkpoint(&self) -> &ContextCheckpointV1 {
62        &self.checkpoint
63    }
64    pub fn receipt(&self) -> &ContextCheckpointMigrationReceiptV1 {
65        &self.receipt
66    }
67    pub fn into_parts(self) -> (ContextCheckpointV1, ContextCheckpointMigrationReceiptV1) {
68        (self.checkpoint, self.receipt)
69    }
70}
71
72/// Fail-closed migration error; unsupported shapes are never guessed.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub enum ContextCheckpointMigrationErrorV1 {
75    EncodedLimitExceeded,
76    InvalidJson(String),
77    UnsupportedSchema,
78    NonCanonicalSource,
79    InvalidCheckpoint(String),
80}
81
82impl fmt::Display for ContextCheckpointMigrationErrorV1 {
83    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(formatter, "{self:?}")
85    }
86}
87
88impl std::error::Error for ContextCheckpointMigrationErrorV1 {}
89
90/// Stateless deterministic migrator for the only deployed V1 predecessor.
91#[derive(Clone, Copy, Debug, Default)]
92pub struct StrictContextCheckpointMigratorV1;
93
94impl StrictContextCheckpointMigratorV1 {
95    pub fn migrate_with_receipt(
96        &self,
97        bytes: &[u8],
98    ) -> Result<ContextCheckpointMigrationResultV1, ContextCheckpointMigrationErrorV1> {
99        if bytes.len() > MAX_CONTEXT_CHECKPOINT_ENCODED_BYTES {
100            return Err(ContextCheckpointMigrationErrorV1::EncodedLimitExceeded);
101        }
102        let value: Value = serde_json::from_slice(bytes)
103            .map_err(|error| ContextCheckpointMigrationErrorV1::InvalidJson(error.to_string()))?;
104        if value.get("schema_version").and_then(Value::as_u64) != Some(1) {
105            return Err(ContextCheckpointMigrationErrorV1::UnsupportedSchema);
106        }
107        let missing_updated_at = value.get("updated_at").is_none();
108        let canonical_source = canonical_json_bytes(&value)?;
109        if canonical_source != bytes {
110            return Err(ContextCheckpointMigrationErrorV1::NonCanonicalSource);
111        }
112        let checkpoint: ContextCheckpointV1 = serde_json::from_value(value).map_err(|error| {
113            ContextCheckpointMigrationErrorV1::InvalidCheckpoint(error.to_string())
114        })?;
115        checkpoint.validate().map_err(|error| {
116            ContextCheckpointMigrationErrorV1::InvalidCheckpoint(error.to_string())
117        })?;
118        let kind = if missing_updated_at {
119            ContextCheckpointMigrationKindV1::LegacyV1MissingUpdatedAt
120        } else {
121            ContextCheckpointMigrationKindV1::CanonicalV1
122        };
123        let source_digest =
124            Sha256Digest::new(format!("sha256:{}", hex::encode(Sha256::digest(bytes)))).map_err(
125                |error| ContextCheckpointMigrationErrorV1::InvalidCheckpoint(error.to_string()),
126            )?;
127        let output_digest = checkpoint.digest().map_err(|error| {
128            ContextCheckpointMigrationErrorV1::InvalidCheckpoint(error.to_string())
129        })?;
130        Ok(ContextCheckpointMigrationResultV1 {
131            checkpoint,
132            receipt: ContextCheckpointMigrationReceiptV1 {
133                schema_version: ContextCheckpointMigrationReceiptV1::SCHEMA_VERSION,
134                kind,
135                source_digest,
136                output_digest,
137            },
138        })
139    }
140}
141
142impl ContextCheckpointMigrationV1 for StrictContextCheckpointMigratorV1 {
143    type Error = ContextCheckpointMigrationErrorV1;
144
145    fn migrate(&self, bytes: &[u8]) -> Result<ContextCheckpointV1, Self::Error> {
146        self.migrate_with_receipt(bytes)
147            .map(|result| result.checkpoint)
148    }
149}
150
151fn canonical_json_bytes(value: &Value) -> Result<Vec<u8>, ContextCheckpointMigrationErrorV1> {
152    serde_json::to_vec(&crate::core::canonical::canonical_value(value))
153        .map_err(|error| ContextCheckpointMigrationErrorV1::InvalidJson(error.to_string()))
154}