plexus-engine 0.3.6

Engine integration traits for consuming Plexus plans
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
use std::collections::BTreeSet;
use std::str::FromStr;

use plexus_serde::{
    deserialize_engine_capability_decl, serialize_engine_capability_decl,
    CapabilitySemver as WireSemver, CapabilityVersionRange as WireVersionRange,
    EngineCapabilityDecl as WireCapabilityDecl, OpOrderingDecl as WireOpOrderingDecl, Version,
};
use serde::{Deserialize, Serialize};

use crate::capabilities::ordering::{op_ordering_contract, OpOrderingContract};
use crate::capabilities::wire::{
    from_wire_ordering_contract, to_wire_ordering_contract, EngineCapabilityDocument,
    OpOrderingDocument,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PlanSemver {
    pub major: u32,
    pub minor: u32,
    pub patch: u32,
}

impl PlanSemver {
    pub const fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }
}

impl From<&Version> for PlanSemver {
    fn from(v: &Version) -> Self {
        Self::new(v.major, v.minor, v.patch)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionRange {
    pub min_supported: PlanSemver,
    pub max_supported: PlanSemver,
}

impl VersionRange {
    pub const fn new(min_supported: PlanSemver, max_supported: PlanSemver) -> Self {
        Self {
            min_supported,
            max_supported,
        }
    }

    pub fn supports(&self, version: PlanSemver) -> bool {
        self.min_supported <= version && version <= self.max_supported
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum OpKind {
    ScanNodes,
    ScanRels,
    Expand,
    OptionalExpand,
    SemiExpand,
    ExpandVarLen,
    Filter,
    BlockMarker,
    Project,
    Aggregate,
    Sort,
    Limit,
    Unwind,
    PathConstruct,
    Union,
    CreateNode,
    CreateRel,
    Merge,
    Delete,
    SetProperty,
    RemoveProperty,
    VectorScan,
    Rerank,
    Return,
    ConstRow,
}

impl OpKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ScanNodes => "ScanNodes",
            Self::ScanRels => "ScanRels",
            Self::Expand => "Expand",
            Self::OptionalExpand => "OptionalExpand",
            Self::SemiExpand => "SemiExpand",
            Self::ExpandVarLen => "ExpandVarLen",
            Self::Filter => "Filter",
            Self::BlockMarker => "BlockMarker",
            Self::Project => "Project",
            Self::Aggregate => "Aggregate",
            Self::Sort => "Sort",
            Self::Limit => "Limit",
            Self::Unwind => "Unwind",
            Self::PathConstruct => "PathConstruct",
            Self::Union => "Union",
            Self::CreateNode => "CreateNode",
            Self::CreateRel => "CreateRel",
            Self::Merge => "Merge",
            Self::Delete => "Delete",
            Self::SetProperty => "SetProperty",
            Self::RemoveProperty => "RemoveProperty",
            Self::VectorScan => "VectorScan",
            Self::Rerank => "Rerank",
            Self::Return => "Return",
            Self::ConstRow => "ConstRow",
        }
    }
}

impl FromStr for OpKind {
    type Err = ();

    fn from_str(name: &str) -> Result<Self, Self::Err> {
        match name {
            "ScanNodes" => Ok(Self::ScanNodes),
            "ScanRels" => Ok(Self::ScanRels),
            "Expand" => Ok(Self::Expand),
            "OptionalExpand" => Ok(Self::OptionalExpand),
            "SemiExpand" => Ok(Self::SemiExpand),
            "ExpandVarLen" => Ok(Self::ExpandVarLen),
            "Filter" => Ok(Self::Filter),
            "BlockMarker" => Ok(Self::BlockMarker),
            "Project" => Ok(Self::Project),
            "Aggregate" => Ok(Self::Aggregate),
            "Sort" => Ok(Self::Sort),
            "Limit" => Ok(Self::Limit),
            "Unwind" => Ok(Self::Unwind),
            "PathConstruct" => Ok(Self::PathConstruct),
            "Union" => Ok(Self::Union),
            "CreateNode" => Ok(Self::CreateNode),
            "CreateRel" => Ok(Self::CreateRel),
            "Merge" => Ok(Self::Merge),
            "Delete" => Ok(Self::Delete),
            "SetProperty" => Ok(Self::SetProperty),
            "RemoveProperty" => Ok(Self::RemoveProperty),
            "VectorScan" => Ok(Self::VectorScan),
            "Rerank" => Ok(Self::Rerank),
            "Return" => Ok(Self::Return),
            "ConstRow" => Ok(Self::ConstRow),
            _ => Err(()),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum ExprKind {
    ColRef,
    PropAccess,
    IntLiteral,
    FloatLiteral,
    BoolLiteral,
    StringLiteral,
    NullLiteral,
    Cmp,
    And,
    Or,
    Not,
    IsNull,
    IsNotNull,
    StartsWith,
    EndsWith,
    Contains,
    In,
    ListLiteral,
    MapLiteral,
    Exists,
    ListComprehension,
    Agg,
    Arith,
    Param,
    Case,
    VectorSimilarity,
}

impl ExprKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ColRef => "ColRef",
            Self::PropAccess => "PropAccess",
            Self::IntLiteral => "IntLiteral",
            Self::FloatLiteral => "FloatLiteral",
            Self::BoolLiteral => "BoolLiteral",
            Self::StringLiteral => "StringLiteral",
            Self::NullLiteral => "NullLiteral",
            Self::Cmp => "Cmp",
            Self::And => "And",
            Self::Or => "Or",
            Self::Not => "Not",
            Self::IsNull => "IsNull",
            Self::IsNotNull => "IsNotNull",
            Self::StartsWith => "StartsWith",
            Self::EndsWith => "EndsWith",
            Self::Contains => "Contains",
            Self::In => "In",
            Self::ListLiteral => "ListLiteral",
            Self::MapLiteral => "MapLiteral",
            Self::Exists => "Exists",
            Self::ListComprehension => "ListComprehension",
            Self::Agg => "Agg",
            Self::Arith => "Arith",
            Self::Param => "Param",
            Self::Case => "Case",
            Self::VectorSimilarity => "VectorSimilarity",
        }
    }
}

impl FromStr for ExprKind {
    type Err = ();

    fn from_str(name: &str) -> Result<Self, Self::Err> {
        match name {
            "ColRef" => Ok(Self::ColRef),
            "PropAccess" => Ok(Self::PropAccess),
            "IntLiteral" => Ok(Self::IntLiteral),
            "FloatLiteral" => Ok(Self::FloatLiteral),
            "BoolLiteral" => Ok(Self::BoolLiteral),
            "StringLiteral" => Ok(Self::StringLiteral),
            "NullLiteral" => Ok(Self::NullLiteral),
            "Cmp" => Ok(Self::Cmp),
            "And" => Ok(Self::And),
            "Or" => Ok(Self::Or),
            "Not" => Ok(Self::Not),
            "IsNull" => Ok(Self::IsNull),
            "IsNotNull" => Ok(Self::IsNotNull),
            "StartsWith" => Ok(Self::StartsWith),
            "EndsWith" => Ok(Self::EndsWith),
            "Contains" => Ok(Self::Contains),
            "In" => Ok(Self::In),
            "ListLiteral" => Ok(Self::ListLiteral),
            "MapLiteral" => Ok(Self::MapLiteral),
            "Exists" => Ok(Self::Exists),
            "ListComprehension" => Ok(Self::ListComprehension),
            "Agg" => Ok(Self::Agg),
            "Arith" => Ok(Self::Arith),
            "Param" => Ok(Self::Param),
            "Case" => Ok(Self::Case),
            "VectorSimilarity" => Ok(Self::VectorSimilarity),
            _ => Err(()),
        }
    }
}

pub const ALL_OP_KINDS: [OpKind; 25] = [
    OpKind::ScanNodes,
    OpKind::ScanRels,
    OpKind::Expand,
    OpKind::OptionalExpand,
    OpKind::SemiExpand,
    OpKind::ExpandVarLen,
    OpKind::Filter,
    OpKind::BlockMarker,
    OpKind::Project,
    OpKind::Aggregate,
    OpKind::Sort,
    OpKind::Limit,
    OpKind::Unwind,
    OpKind::PathConstruct,
    OpKind::Union,
    OpKind::CreateNode,
    OpKind::CreateRel,
    OpKind::Merge,
    OpKind::Delete,
    OpKind::SetProperty,
    OpKind::RemoveProperty,
    OpKind::VectorScan,
    OpKind::Rerank,
    OpKind::Return,
    OpKind::ConstRow,
];

pub const ALL_EXPR_KINDS: [ExprKind; 26] = [
    ExprKind::ColRef,
    ExprKind::PropAccess,
    ExprKind::IntLiteral,
    ExprKind::FloatLiteral,
    ExprKind::BoolLiteral,
    ExprKind::StringLiteral,
    ExprKind::NullLiteral,
    ExprKind::Cmp,
    ExprKind::And,
    ExprKind::Or,
    ExprKind::Not,
    ExprKind::IsNull,
    ExprKind::IsNotNull,
    ExprKind::StartsWith,
    ExprKind::EndsWith,
    ExprKind::Contains,
    ExprKind::In,
    ExprKind::ListLiteral,
    ExprKind::MapLiteral,
    ExprKind::Exists,
    ExprKind::ListComprehension,
    ExprKind::Agg,
    ExprKind::Arith,
    ExprKind::Param,
    ExprKind::Case,
    ExprKind::VectorSimilarity,
];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequiredCapabilities {
    pub plan_version: PlanSemver,
    pub required_ops: BTreeSet<OpKind>,
    pub required_exprs: BTreeSet<ExprKind>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EngineCapabilities {
    pub version_range: VersionRange,
    pub supported_ops: BTreeSet<OpKind>,
    pub supported_exprs: BTreeSet<ExprKind>,
    pub supports_graph_ref: bool,
    pub supports_multi_graph: bool,
    pub supports_graph_params: bool,
}

impl EngineCapabilities {
    pub fn full(version_range: VersionRange) -> Self {
        Self {
            version_range,
            supported_ops: BTreeSet::from_iter(ALL_OP_KINDS),
            supported_exprs: BTreeSet::from_iter(ALL_EXPR_KINDS),
            supports_graph_ref: false,
            supports_multi_graph: false,
            supports_graph_params: false,
        }
    }

    pub fn to_document(&self) -> EngineCapabilityDocument {
        EngineCapabilityDocument {
            version_range: self.version_range,
            supported_ops: self
                .supported_ops
                .iter()
                .copied()
                .map(OpKind::as_str)
                .map(str::to_string)
                .collect(),
            supported_exprs: self
                .supported_exprs
                .iter()
                .copied()
                .map(ExprKind::as_str)
                .map(str::to_string)
                .collect(),
            op_ordering_contracts: self
                .supported_ops
                .iter()
                .copied()
                .map(|op| OpOrderingDocument {
                    op: op.as_str().to_string(),
                    contract: op_ordering_contract(op),
                })
                .collect(),
            supports_graph_ref: self.supports_graph_ref,
            supports_multi_graph: self.supports_multi_graph,
            supports_graph_params: self.supports_graph_params,
        }
    }

    pub fn from_document(doc: EngineCapabilityDocument) -> Result<Self, CapabilityError> {
        let mut supported_ops = BTreeSet::new();
        for name in doc.supported_ops {
            let Some(kind) = name.parse::<OpKind>().ok() else {
                return Err(CapabilityError::InvalidCapabilityName { kind: "op", name });
            };
            supported_ops.insert(kind);
        }

        let mut supported_exprs = BTreeSet::new();
        for name in doc.supported_exprs {
            let Some(kind) = name.parse::<ExprKind>().ok() else {
                return Err(CapabilityError::InvalidCapabilityName { kind: "expr", name });
            };
            supported_exprs.insert(kind);
        }

        let mut declared_ops = BTreeSet::new();
        for decl in doc.op_ordering_contracts {
            let Some(kind) = decl.op.parse::<OpKind>().ok() else {
                return Err(CapabilityError::InvalidCapabilityName {
                    kind: "op-ordering",
                    name: decl.op,
                });
            };
            if !supported_ops.contains(&kind) {
                return Err(CapabilityError::OrderingDeclarationForUnsupportedOp {
                    op: kind.as_str().to_string(),
                });
            }
            let expected = op_ordering_contract(kind);
            if decl.contract != expected {
                return Err(CapabilityError::OrderingContractMismatch {
                    op: kind.as_str().to_string(),
                    expected,
                    actual: decl.contract,
                });
            }
            declared_ops.insert(kind);
        }

        if !declared_ops.is_empty() {
            for op in &supported_ops {
                if !declared_ops.contains(op) {
                    return Err(CapabilityError::MissingOrderingDeclaration {
                        op: op.as_str().to_string(),
                    });
                }
            }
        }

        Ok(Self {
            version_range: doc.version_range,
            supported_ops,
            supported_exprs,
            supports_graph_ref: doc.supports_graph_ref,
            supports_multi_graph: doc.supports_multi_graph,
            supports_graph_params: doc.supports_graph_params,
        })
    }

    pub fn to_json_pretty(&self) -> Result<String, CapabilityError> {
        serde_json::to_string_pretty(&self.to_document()).map_err(CapabilityError::Serialize)
    }

    pub fn from_json(json: &str) -> Result<Self, CapabilityError> {
        let doc: EngineCapabilityDocument =
            serde_json::from_str(json).map_err(CapabilityError::Deserialize)?;
        Self::from_document(doc)
    }

    fn to_wire_decl(&self) -> WireCapabilityDecl {
        WireCapabilityDecl {
            version_range: WireVersionRange {
                min_supported: WireSemver {
                    major: self.version_range.min_supported.major,
                    minor: self.version_range.min_supported.minor,
                    patch: self.version_range.min_supported.patch,
                },
                max_supported: WireSemver {
                    major: self.version_range.max_supported.major,
                    minor: self.version_range.max_supported.minor,
                    patch: self.version_range.max_supported.patch,
                },
            },
            supported_ops: self
                .supported_ops
                .iter()
                .copied()
                .map(OpKind::as_str)
                .map(str::to_string)
                .collect(),
            supported_exprs: self
                .supported_exprs
                .iter()
                .copied()
                .map(ExprKind::as_str)
                .map(str::to_string)
                .collect(),
            op_ordering: self
                .supported_ops
                .iter()
                .copied()
                .map(|op| WireOpOrderingDecl {
                    op: op.as_str().to_string(),
                    contract: to_wire_ordering_contract(op_ordering_contract(op)),
                })
                .collect(),
            supports_graph_ref: self.supports_graph_ref,
            supports_multi_graph: self.supports_multi_graph,
            supports_graph_params: self.supports_graph_params,
        }
    }

    fn from_wire_decl(doc: WireCapabilityDecl) -> Result<Self, CapabilityError> {
        let mut supported_ops = BTreeSet::new();
        for name in doc.supported_ops {
            let Some(kind) = name.parse::<OpKind>().ok() else {
                return Err(CapabilityError::InvalidCapabilityName { kind: "op", name });
            };
            supported_ops.insert(kind);
        }

        let mut supported_exprs = BTreeSet::new();
        for name in doc.supported_exprs {
            let Some(kind) = name.parse::<ExprKind>().ok() else {
                return Err(CapabilityError::InvalidCapabilityName { kind: "expr", name });
            };
            supported_exprs.insert(kind);
        }

        let mut declared_ops = BTreeSet::new();
        for decl in doc.op_ordering {
            let Some(kind) = decl.op.parse::<OpKind>().ok() else {
                return Err(CapabilityError::InvalidCapabilityName {
                    kind: "op-ordering",
                    name: decl.op,
                });
            };
            if !supported_ops.contains(&kind) {
                return Err(CapabilityError::OrderingDeclarationForUnsupportedOp {
                    op: kind.as_str().to_string(),
                });
            }
            let actual = from_wire_ordering_contract(decl.contract);
            let expected = op_ordering_contract(kind);
            if actual != expected {
                return Err(CapabilityError::OrderingContractMismatch {
                    op: kind.as_str().to_string(),
                    expected,
                    actual,
                });
            }
            declared_ops.insert(kind);
        }

        if !declared_ops.is_empty() {
            for op in &supported_ops {
                if !declared_ops.contains(op) {
                    return Err(CapabilityError::MissingOrderingDeclaration {
                        op: op.as_str().to_string(),
                    });
                }
            }
        }

        Ok(Self {
            version_range: VersionRange {
                min_supported: PlanSemver {
                    major: doc.version_range.min_supported.major,
                    minor: doc.version_range.min_supported.minor,
                    patch: doc.version_range.min_supported.patch,
                },
                max_supported: PlanSemver {
                    major: doc.version_range.max_supported.major,
                    minor: doc.version_range.max_supported.minor,
                    patch: doc.version_range.max_supported.patch,
                },
            },
            supported_ops,
            supported_exprs,
            supports_graph_ref: doc.supports_graph_ref,
            supports_multi_graph: doc.supports_multi_graph,
            supports_graph_params: doc.supports_graph_params,
        })
    }

    pub fn to_flatbuffer_bytes(&self) -> Result<Vec<u8>, CapabilityError> {
        serialize_engine_capability_decl(&self.to_wire_decl()).map_err(CapabilityError::WireSerde)
    }

    pub fn from_flatbuffer_bytes(bytes: &[u8]) -> Result<Self, CapabilityError> {
        let doc = deserialize_engine_capability_decl(bytes).map_err(CapabilityError::WireSerde)?;
        Self::from_wire_decl(doc)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum CapabilityError {
    #[error(
        "unsupported plan version {plan_major}.{plan_minor}.{plan_patch}; supported range {min_major}.{min_minor}.{min_patch}..={max_major}.{max_minor}.{max_patch}"
    )]
    UnsupportedPlanVersion {
        plan_major: u32,
        plan_minor: u32,
        plan_patch: u32,
        min_major: u32,
        min_minor: u32,
        min_patch: u32,
        max_major: u32,
        max_minor: u32,
        max_patch: u32,
    },
    #[error("plan requires unsupported features")]
    MissingFeatureSupport {
        missing_ops: Vec<OpKind>,
        missing_exprs: Vec<ExprKind>,
    },
    #[error("plan requires graph_ref support but engine declares supports_graph_ref=false")]
    GraphRefUnsupported,
    #[error("plan mixes multiple graph_ref values but engine declares supports_multi_graph=false")]
    MultiGraphUnsupported,
    #[error(
        "plan uses graph parameter variables ($g) but engine declares supports_graph_params=false"
    )]
    GraphParamUnsupported,
    #[error("unknown capability {kind} name `{name}`")]
    InvalidCapabilityName { kind: &'static str, name: String },
    #[error("failed to serialize capability JSON: {0}")]
    Serialize(serde_json::Error),
    #[error("failed to deserialize capability JSON: {0}")]
    Deserialize(serde_json::Error),
    #[error("failed to encode/decode capability flatbuffer: {0}")]
    WireSerde(plexus_serde::SerdeError),
    #[error("ordering declaration provided for unsupported op `{op}`")]
    OrderingDeclarationForUnsupportedOp { op: String },
    #[error("missing ordering declaration for supported op `{op}`")]
    MissingOrderingDeclaration { op: String },
    #[error("ordering contract mismatch for `{op}`: expected `{expected:?}`, got `{actual:?}`")]
    OrderingContractMismatch {
        op: String,
        expected: OpOrderingContract,
        actual: OpOrderingContract,
    },
}