panproto-check 0.2.0

Breaking change detection 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
//! Classification of schema diffs into breaking vs. non-breaking changes.
//!
//! [`classify`] takes a [`SchemaDiff`] and a [`Protocol`] and determines
//! which changes are backward-incompatible (breaking) and which are safe
//! (non-breaking). The classification is protocol-aware: for example,
//! removing a vertex that serves as the target of a required edge is
//! always breaking.

use panproto_schema::Protocol;
use serde::{Deserialize, Serialize};

use crate::diff::{ConstraintChange, SchemaDiff};

/// The result of classifying a schema diff.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompatReport {
    /// Changes that break backward compatibility.
    pub breaking: Vec<BreakingChange>,
    /// Changes that are safe for existing consumers.
    pub non_breaking: Vec<NonBreakingChange>,
    /// `true` if the migration is fully backward-compatible.
    pub compatible: bool,
}

/// A change that breaks backward compatibility.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum BreakingChange {
    /// A vertex was removed from the schema.
    RemovedVertex {
        /// The removed vertex ID.
        vertex_id: String,
    },

    /// An edge was removed from the schema.
    RemovedEdge {
        /// Source vertex ID.
        src: String,
        /// Target vertex ID.
        tgt: String,
        /// Edge kind.
        kind: String,
        /// Edge name, if present.
        name: Option<String>,
    },

    /// A vertex's kind changed.
    KindChanged {
        /// The vertex ID.
        vertex_id: String,
        /// The old kind.
        old_kind: String,
        /// The new kind.
        new_kind: String,
    },

    /// A constraint was tightened (made more restrictive).
    ConstraintTightened {
        /// The vertex ID.
        vertex_id: String,
        /// The constraint sort.
        sort: String,
        /// The old value.
        old_value: String,
        /// The new value.
        new_value: String,
    },

    /// A new constraint was added to an existing vertex.
    ConstraintAdded {
        /// The vertex ID.
        vertex_id: String,
        /// The constraint sort.
        sort: String,
        /// The constraint value.
        value: String,
    },
}

/// A non-breaking (backward-compatible) change.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum NonBreakingChange {
    /// A new vertex was added.
    AddedVertex {
        /// The added vertex ID.
        vertex_id: String,
    },

    /// A new edge was added.
    AddedEdge {
        /// Source vertex ID.
        src: String,
        /// Target vertex ID.
        tgt: String,
        /// Edge kind.
        kind: String,
        /// Edge name, if present.
        name: Option<String>,
    },

    /// A constraint was relaxed (made less restrictive).
    ConstraintRelaxed {
        /// The vertex ID.
        vertex_id: String,
        /// The constraint sort.
        sort: String,
        /// The old value.
        old_value: String,
        /// The new value.
        new_value: String,
    },

    /// A constraint was removed from a vertex.
    ConstraintRemoved {
        /// The vertex ID.
        vertex_id: String,
        /// The constraint sort.
        sort: String,
    },
}

/// Classify a [`SchemaDiff`] into breaking and non-breaking changes.
///
/// The classification depends on the protocol's constraint sorts and
/// edge rules to determine the severity of each change.
#[must_use]
pub fn classify(diff: &SchemaDiff, protocol: &Protocol) -> CompatReport {
    let mut breaking = Vec::new();
    let mut non_breaking = Vec::new();

    // Removed vertices are always breaking.
    for v in &diff.removed_vertices {
        breaking.push(BreakingChange::RemovedVertex {
            vertex_id: v.clone(),
        });
    }

    // Added vertices are non-breaking.
    for v in &diff.added_vertices {
        non_breaking.push(NonBreakingChange::AddedVertex {
            vertex_id: v.clone(),
        });
    }

    // Removed edges: breaking if the edge kind is governed by an edge rule
    // in the protocol (i.e., the protocol considers that edge kind
    // structurally significant). Edges with no matching rule are
    // non-breaking removals.
    for e in &diff.removed_edges {
        if protocol.find_edge_rule(&e.kind).is_some() {
            breaking.push(BreakingChange::RemovedEdge {
                src: e.src.clone(),
                tgt: e.tgt.clone(),
                kind: e.kind.clone(),
                name: e.name.clone(),
            });
        } else {
            non_breaking.push(NonBreakingChange::AddedEdge {
                src: e.src.clone(),
                tgt: e.tgt.clone(),
                kind: e.kind.clone(),
                name: e.name.clone(),
            });
        }
    }

    // Added edges are non-breaking.
    for e in &diff.added_edges {
        non_breaking.push(NonBreakingChange::AddedEdge {
            src: e.src.clone(),
            tgt: e.tgt.clone(),
            kind: e.kind.clone(),
            name: e.name.clone(),
        });
    }

    // Kind changes are always breaking.
    for kc in &diff.kind_changes {
        breaking.push(BreakingChange::KindChanged {
            vertex_id: kc.vertex_id.clone(),
            old_kind: kc.old_kind.clone(),
            new_kind: kc.new_kind.clone(),
        });
    }

    // Constraint changes — only classify constraints whose sort is
    // recognized by the protocol. Unknown sorts are silently ignored
    // (they are not part of this protocol's contract).
    for (vid, cdiff) in &diff.modified_constraints {
        // New constraints on existing vertices are breaking
        // (only for recognized sorts).
        for c in &cdiff.added {
            if protocol.constraint_sorts.iter().any(|s| s == &c.sort) {
                breaking.push(BreakingChange::ConstraintAdded {
                    vertex_id: vid.clone(),
                    sort: c.sort.clone(),
                    value: c.value.clone(),
                });
            }
        }

        // Removed constraints are non-breaking (relaxation)
        // (only for recognized sorts).
        for c in &cdiff.removed {
            if protocol.constraint_sorts.iter().any(|s| s == &c.sort) {
                non_breaking.push(NonBreakingChange::ConstraintRemoved {
                    vertex_id: vid.clone(),
                    sort: c.sort.clone(),
                });
            }
        }

        // Changed constraints: direction depends on the sort
        // (only for recognized sorts).
        for change in &cdiff.changed {
            if protocol.constraint_sorts.iter().any(|s| s == &change.sort) {
                classify_constraint_change(vid, change, &mut breaking, &mut non_breaking);
            }
        }
    }

    let compatible = breaking.is_empty();
    CompatReport {
        breaking,
        non_breaking,
        compatible,
    }
}

/// Determine whether a constraint value change is tightening or relaxing.
fn classify_constraint_change(
    vertex_id: &str,
    change: &ConstraintChange,
    breaking: &mut Vec<BreakingChange>,
    non_breaking: &mut Vec<NonBreakingChange>,
) {
    let is_tightened = is_constraint_tightened(&change.sort, &change.old_value, &change.new_value);

    if is_tightened {
        breaking.push(BreakingChange::ConstraintTightened {
            vertex_id: vertex_id.to_string(),
            sort: change.sort.clone(),
            old_value: change.old_value.clone(),
            new_value: change.new_value.clone(),
        });
    } else {
        non_breaking.push(NonBreakingChange::ConstraintRelaxed {
            vertex_id: vertex_id.to_string(),
            sort: change.sort.clone(),
            old_value: change.old_value.clone(),
            new_value: change.new_value.clone(),
        });
    }
}

/// Determine if a constraint value change is a tightening.
///
/// For upper-bound constraints (`maxLength`, `maximum`, etc.), a smaller
/// new value is tighter. For lower-bound constraints (`minLength`, `minimum`),
/// a larger new value is tighter. For all others, any change is
/// considered tightening.
fn is_constraint_tightened(sort: &str, old_val: &str, new_val: &str) -> bool {
    match sort {
        "maxLength" | "maxSize" | "maximum" | "maxGraphemes" => {
            let old_n: Result<i64, _> = old_val.parse();
            let new_n: Result<i64, _> = new_val.parse();
            if let (Ok(o), Ok(n)) = (old_n, new_n) {
                return n < o;
            }
            // Non-numeric: any change is tightening.
            true
        }
        "minLength" | "minimum" => {
            let old_n: Result<i64, _> = old_val.parse();
            let new_n: Result<i64, _> = new_val.parse();
            if let (Ok(o), Ok(n)) = (old_n, new_n) {
                return n > o;
            }
            true
        }
        _ => {
            // For unknown constraint sorts, any change is tightening.
            true
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::{ConstraintDiff, KindChange};
    use panproto_schema::{Edge, EdgeRule};

    fn test_protocol() -> Protocol {
        Protocol {
            name: "test".into(),
            schema_theory: "ThTest".into(),
            instance_theory: "ThWType".into(),
            edge_rules: vec![EdgeRule {
                edge_kind: "prop".into(),
                src_kinds: vec!["object".into()],
                tgt_kinds: vec![],
            }],
            obj_kinds: vec!["object".into()],
            constraint_sorts: vec!["maxLength".into()],
        }
    }

    #[test]
    fn classify_removed_required_field_as_breaking() {
        let diff = SchemaDiff {
            removed_vertices: vec!["body.text".into()],
            removed_edges: vec![Edge {
                src: "body".into(),
                tgt: "body.text".into(),
                kind: "prop".into(),
                name: Some("text".into()),
            }],
            ..SchemaDiff::default()
        };

        let report = classify(&diff, &test_protocol());
        assert!(!report.compatible, "removing a vertex should be breaking");
        assert_eq!(report.breaking.len(), 2); // vertex + edge
    }

    #[test]
    fn classify_added_optional_field_as_non_breaking() {
        let diff = SchemaDiff {
            added_vertices: vec!["body.newField".into()],
            added_edges: vec![Edge {
                src: "body".into(),
                tgt: "body.newField".into(),
                kind: "prop".into(),
                name: Some("newField".into()),
            }],
            ..SchemaDiff::default()
        };

        let report = classify(&diff, &test_protocol());
        assert!(report.compatible, "adding a vertex should be non-breaking");
        assert_eq!(report.non_breaking.len(), 2); // vertex + edge
        assert!(report.breaking.is_empty());
    }

    #[test]
    fn classify_constraint_tightening_as_breaking() {
        let diff = SchemaDiff {
            modified_constraints: std::iter::once((
                "body.text".into(),
                ConstraintDiff {
                    added: vec![],
                    removed: vec![],
                    changed: vec![crate::diff::ConstraintChange {
                        sort: "maxLength".into(),
                        old_value: "3000".into(),
                        new_value: "300".into(),
                    }],
                },
            ))
            .collect(),
            ..SchemaDiff::default()
        };

        let report = classify(&diff, &test_protocol());
        assert!(
            !report.compatible,
            "tightening maxLength should be breaking"
        );
        assert!(
            report
                .breaking
                .iter()
                .any(|b| matches!(b, BreakingChange::ConstraintTightened { .. }))
        );
    }

    #[test]
    fn classify_constraint_relaxing_as_non_breaking() {
        let diff = SchemaDiff {
            modified_constraints: std::iter::once((
                "body.text".into(),
                ConstraintDiff {
                    added: vec![],
                    removed: vec![],
                    changed: vec![crate::diff::ConstraintChange {
                        sort: "maxLength".into(),
                        old_value: "300".into(),
                        new_value: "3000".into(),
                    }],
                },
            ))
            .collect(),
            ..SchemaDiff::default()
        };

        let report = classify(&diff, &test_protocol());
        assert!(
            report.compatible,
            "relaxing maxLength should be non-breaking"
        );
        assert!(
            report
                .non_breaking
                .iter()
                .any(|nb| matches!(nb, NonBreakingChange::ConstraintRelaxed { .. }))
        );
    }

    #[test]
    fn classify_kind_change_as_breaking() {
        let diff = SchemaDiff {
            kind_changes: vec![KindChange {
                vertex_id: "x".into(),
                old_kind: "string".into(),
                new_kind: "integer".into(),
            }],
            ..SchemaDiff::default()
        };

        let report = classify(&diff, &test_protocol());
        assert!(!report.compatible, "kind change should be breaking");
    }
}