panproto-lens 0.52.0

Bidirectional lens combinators for panproto
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
//! # panproto-lens
//!
//! Bidirectional lenses via protolens (schema-independent lens families).
//!
//! Every schema migration is a lens with a `get` direction (= restrict,
//! projecting data forward) and a `put` direction (= restore from
//! complement, bringing modifications back). The lens laws (`GetPut`
//! and `PutGet`) guarantee round-trip fidelity.
//!
//! This crate provides:
//!
//! - **[`Lens`]**: An asymmetric lens backed by a compiled migration.
//! - **[`get`]** / **[`put`]**: Forward and backward lens directions.
//! - **[`Complement`]**: Data discarded by `get`, needed by `put`.
//! - **[`Protolens`]**: A dependent function from schemas to lenses
//!   (`Π(S : Schema | P(S)). Lens(F(S), G(S))`).
//! - **[`ProtolensChain`]**: Composable sequence of protolenses.
//! - **[`auto_generate`]**: Automatic protolens generation from two schemas.
//! - **[`compose()`]**: Compose two lenses sequentially.
//! - **[`check_laws`]**: Verify `GetPut` and `PutGet` on a test instance.
//!
//! The mathematical foundations are based on asymmetric lenses with
//! complement (Diskin et al., 2011), GAT-based protolenses (natural
//! transformations between theory endofunctors), and Cambria's
//! approach to schema evolution (Ink & Switch, 2020).

// Allow concrete HashMap/HashSet in public API signatures per ENGINEERING.md spec.
#![allow(clippy::implicit_hasher)]

pub mod asymmetric;
pub mod auto_lens;
pub mod candidate;
pub mod coercion_laws;
pub mod complement_type;
pub mod compose;
pub mod cost;
pub mod diff_to_protolens;
pub mod edit_error;
pub mod edit_laws;
pub mod edit_lens;
pub mod edit_pipeline;
pub mod edit_provenance;
pub mod enrichment_registry;
pub mod error;
pub mod fibration;
pub mod graph;
pub mod hint;
pub mod laws;
pub mod layout_complement;
pub mod optic;
pub mod protolens;
pub mod symbolic;
pub mod symmetric;

// Re-exports for convenience.
pub use asymmetric::{Complement, get, put};
pub use auto_lens::{
    AutoLensConfig, AutoLensResult, Stringency, auto_generate, auto_generate_candidates,
    auto_generate_candidates_with_hints, auto_generate_with_hints,
};
pub use candidate::{CandidateStep, LensCandidate};
pub use complement_type::{
    CapturedField, ComplementKind, ComplementSpec, DefaultRequirement, chain_complement_spec,
    complement_spec_at,
};
pub use compose::compose;
pub use cost::{chain_cost, complement_cost, verify_identity_cost, verify_subadditivity};
pub use diff_to_protolens::{DiffSpec, KindChange, diff_to_lens, diff_to_protolens};
pub use edit_error::EditLensError;
pub use edit_lens::EditLens;
pub use edit_pipeline::EditPipeline;
pub use edit_provenance::EditProvenance;
pub use error::{LawViolation, LensError};
pub use graph::LensGraph;
pub use laws::{check_get_put, check_laws, check_put_get};
pub use optic::{OpticKind, classify_transform, refine_scoped_optic};
pub use protolens::{
    ComplementConstructor, FleetResult, Protolens, ProtolensChain, SchemaConstraint,
    apply_to_fleet, combinators, elementary, horizontal_compose as protolens_horizontal,
    lift_chain, lift_protolens, vertical_compose as protolens_vertical,
};
pub use symbolic::{SymbolicStep, simplify_steps};
pub use symmetric::{CoherenceViolation, SymmetricLens};

use panproto_inst::CompiledMigration;
use panproto_schema::Schema;

/// An asymmetric lens with complement tracking.
///
/// A `Lens` encapsulates a compiled migration between a source and target
/// schema. The `get` direction projects data forward (restricting to the
/// target view), while `put` restores the original source from a modified
/// view and the complement.
#[derive(Debug)]
pub struct Lens {
    /// The compiled migration driving the restrict operation.
    pub compiled: CompiledMigration,
    /// The source schema.
    pub src_schema: Schema,
    /// The target schema (view).
    pub tgt_schema: Schema,
}

impl Lens {
    /// Compute the composite coercion class of this lens's migration.
    ///
    /// Delegates to the underlying `CompiledMigration::coercion_class()`.
    #[must_use]
    pub fn coercion_class(&self) -> panproto_gat::CoercionClass {
        self.compiled.coercion_class()
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::collections::HashMap;

    use panproto_gat::Name;
    use panproto_inst::value::{FieldPresence, Value};
    use panproto_inst::{CompiledMigration, Node, WInstance};
    use panproto_schema::{Edge, Schema, Vertex};
    use smallvec::SmallVec;

    use crate::Lens;

    /// Build a 3-vertex schema: `post:body` (object) with two children
    /// `post:body.text` (string) and `post:body.createdAt` (string).
    pub fn three_node_schema() -> Schema {
        let mut vertices = HashMap::new();
        vertices.insert(
            Name::from("post:body"),
            Vertex {
                id: "post:body".into(),
                kind: "object".into(),
                nsid: None,
            },
        );
        vertices.insert(
            Name::from("post:body.text"),
            Vertex {
                id: "post:body.text".into(),
                kind: "string".into(),
                nsid: None,
            },
        );
        vertices.insert(
            Name::from("post:body.createdAt"),
            Vertex {
                id: "post:body.createdAt".into(),
                kind: "string".into(),
                nsid: None,
            },
        );

        let edge_text = Edge {
            src: "post:body".into(),
            tgt: "post:body.text".into(),
            kind: "prop".into(),
            name: Some("text".into()),
        };
        let edge_created = Edge {
            src: "post:body".into(),
            tgt: "post:body.createdAt".into(),
            kind: "prop".into(),
            name: Some("createdAt".into()),
        };

        let mut edges = HashMap::new();
        edges.insert(edge_text.clone(), Name::from("prop"));
        edges.insert(edge_created.clone(), Name::from("prop"));

        let mut outgoing: HashMap<Name, SmallVec<Edge, 4>> = HashMap::new();
        outgoing
            .entry("post:body".into())
            .or_default()
            .push(edge_text.clone());
        outgoing
            .entry("post:body".into())
            .or_default()
            .push(edge_created.clone());

        let mut incoming: HashMap<Name, SmallVec<Edge, 4>> = HashMap::new();
        incoming
            .entry("post:body.text".into())
            .or_default()
            .push(edge_text.clone());
        incoming
            .entry("post:body.createdAt".into())
            .or_default()
            .push(edge_created.clone());

        let mut between: HashMap<(Name, Name), SmallVec<Edge, 2>> = HashMap::new();
        between
            .entry((Name::from("post:body"), Name::from("post:body.text")))
            .or_default()
            .push(edge_text);
        between
            .entry((Name::from("post:body"), Name::from("post:body.createdAt")))
            .or_default()
            .push(edge_created);

        Schema {
            protocol: "test".into(),
            vertices,
            edges,
            hyper_edges: HashMap::new(),
            constraints: HashMap::new(),
            required: HashMap::new(),
            nsids: HashMap::new(),
            entries: Vec::new(),
            variants: HashMap::new(),
            orderings: HashMap::new(),
            recursion_points: HashMap::new(),
            spans: HashMap::new(),
            usage_modes: HashMap::new(),
            nominal: HashMap::new(),
            coercions: HashMap::new(),
            mergers: HashMap::new(),
            defaults: HashMap::new(),
            policies: HashMap::new(),
            outgoing,
            incoming,
            between,
        }
    }

    /// Build a 3-node W-type instance matching [`three_node_schema`].
    pub fn three_node_instance() -> WInstance {
        let mut nodes = HashMap::new();
        nodes.insert(0, Node::new(0, "post:body"));
        nodes.insert(
            1,
            Node::new(1, "post:body.text")
                .with_value(FieldPresence::Present(Value::Str("hello".into()))),
        );
        nodes.insert(
            2,
            Node::new(2, "post:body.createdAt")
                .with_value(FieldPresence::Present(Value::Str("2024-01-01".into()))),
        );

        let arcs = vec![
            (
                0,
                1,
                Edge {
                    src: "post:body".into(),
                    tgt: "post:body.text".into(),
                    kind: "prop".into(),
                    name: Some("text".into()),
                },
            ),
            (
                0,
                2,
                Edge {
                    src: "post:body".into(),
                    tgt: "post:body.createdAt".into(),
                    kind: "prop".into(),
                    name: Some("createdAt".into()),
                },
            ),
        ];

        WInstance::new(nodes, arcs, vec![], 0, Name::from("post:body"))
    }

    /// Build an identity lens for the given schema.
    pub fn identity_lens(schema: &Schema) -> Lens {
        let surviving_verts = schema.vertices.keys().cloned().collect();
        let surviving_edges = schema.edges.keys().cloned().collect();

        let compiled = CompiledMigration {
            surviving_verts,
            surviving_edges,
            vertex_remap: HashMap::new(),
            edge_remap: HashMap::new(),
            resolver: HashMap::new(),
            hyper_resolver: HashMap::new(),
            field_transforms: HashMap::new(),
            conditional_survival: HashMap::new(),
            expansion_path: HashMap::new(),
        };

        Lens {
            compiled,
            src_schema: schema.clone(),
            tgt_schema: schema.clone(),
        }
    }

    /// Build a projection lens that removes a single field from the schema.
    pub fn projection_lens(schema: &Schema, field_to_remove: &str) -> Lens {
        let mut tgt_schema = schema.clone();

        // Find and remove the edge + target vertex for this field
        let edges_to_remove: Vec<Edge> = tgt_schema
            .edges
            .keys()
            .filter(|e| e.name.as_deref() == Some(field_to_remove))
            .cloned()
            .collect();

        let mut removed_vertices = Vec::new();
        for edge in &edges_to_remove {
            tgt_schema.edges.remove(edge);
            tgt_schema.vertices.remove(&edge.tgt);
            removed_vertices.push(edge.tgt.clone());
        }

        // Rebuild indices
        crate::protolens::rebuild_indices(&mut tgt_schema);

        let mut surviving_verts: std::collections::HashSet<Name> =
            schema.vertices.keys().cloned().collect();
        let mut surviving_edges: std::collections::HashSet<Edge> =
            schema.edges.keys().cloned().collect();

        for v in &removed_vertices {
            surviving_verts.remove(v);
        }
        for e in &edges_to_remove {
            surviving_edges.remove(e);
        }

        let compiled = CompiledMigration {
            surviving_verts,
            surviving_edges,
            vertex_remap: HashMap::new(),
            edge_remap: HashMap::new(),
            resolver: HashMap::new(),
            hyper_resolver: HashMap::new(),
            field_transforms: HashMap::new(),
            conditional_survival: HashMap::new(),
            expansion_path: HashMap::new(),
        };

        Lens {
            compiled,
            src_schema: schema.clone(),
            tgt_schema,
        }
    }

    // -----------------------------------------------------------------------
    // Test 1: Identity lens satisfies laws (covered in laws.rs)
    // Test 2: Compose rename + add_field laws (below)
    // Test 3: Round-trip get/put (below)
    // Test 4: Modified view propagation (below)
    // -----------------------------------------------------------------------

    #[test]
    fn round_trip_get_then_put_recovers_original() {
        let schema = three_node_schema();
        let lens = identity_lens(&schema);
        let instance = three_node_instance();

        let (view, complement) =
            crate::get(&lens, &instance).unwrap_or_else(|e| panic!("get failed: {e}"));
        let restored =
            crate::put(&lens, &view, &complement).unwrap_or_else(|e| panic!("put failed: {e}"));

        assert_eq!(restored.node_count(), instance.node_count());
        assert_eq!(restored.root, instance.root);
        assert_eq!(restored.schema_root, instance.schema_root);

        // Verify all node anchors match
        for (&id, node) in &instance.nodes {
            let restored_node = restored
                .nodes
                .get(&id)
                .unwrap_or_else(|| panic!("node {id} missing from restored instance"));
            assert_eq!(
                node.anchor, restored_node.anchor,
                "anchor mismatch for node {id}"
            );
        }
    }

    #[test]
    fn modified_view_propagates_changes() {
        let schema = three_node_schema();
        let lens = identity_lens(&schema);
        let instance = three_node_instance();

        // Get the view
        let (mut view, complement) =
            crate::get(&lens, &instance).unwrap_or_else(|e| panic!("get failed: {e}"));

        // Modify a field in the view
        if let Some(node) = view.nodes.get_mut(&1) {
            node.value = Some(FieldPresence::Present(Value::Str("modified".into())));
        }

        // Put back
        let restored =
            crate::put(&lens, &view, &complement).unwrap_or_else(|e| panic!("put failed: {e}"));

        // Verify the modification propagated
        let node = restored
            .nodes
            .get(&1)
            .unwrap_or_else(|| panic!("node 1 missing"));
        assert_eq!(
            node.value,
            Some(FieldPresence::Present(Value::Str("modified".into()))),
            "modification should be preserved"
        );
    }

    #[test]
    fn projection_lens_drops_field() {
        let schema = three_node_schema();
        let lens = projection_lens(&schema, "createdAt");
        let instance = three_node_instance();

        let (view, complement) =
            crate::get(&lens, &instance).unwrap_or_else(|e| panic!("get failed: {e}"));

        assert_eq!(view.node_count(), 2, "projection should drop one node");
        assert!(
            !complement.dropped_nodes.is_empty(),
            "complement should have dropped node"
        );
    }

    #[test]
    fn projection_get_then_put_restores_with_complement() {
        let schema = three_node_schema();
        let lens = projection_lens(&schema, "createdAt");
        let instance = three_node_instance();

        let (view, complement) =
            crate::get(&lens, &instance).unwrap_or_else(|e| panic!("get failed: {e}"));

        let restored =
            crate::put(&lens, &view, &complement).unwrap_or_else(|e| panic!("put failed: {e}"));

        assert_eq!(
            restored.node_count(),
            instance.node_count(),
            "restoration should bring back all nodes"
        );
    }

    #[test]
    fn compose_rename_then_identity_preserves_laws() {
        let schema = three_node_schema();
        let l1 = identity_lens(&schema);
        let l2 = identity_lens(&schema);

        let composed = crate::compose(&l1, &l2).unwrap_or_else(|e| panic!("compose failed: {e}"));
        let instance = three_node_instance();

        let result = crate::check_laws(&composed, &instance);
        assert!(
            result.is_ok(),
            "composed identity lenses should satisfy laws: {result:?}"
        );
    }
}