uni-cypher 2.0.3

OpenCypher query parser and AST for Uni graph database
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
use serde::{Deserialize, Serialize};

use crate::ast::{Direction, Expr, Pattern, Query, ReturnClause, UnaryOp};

/// A complete Locy program: optional module header, imports, and body statements.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LocyProgram {
    pub module: Option<ModuleDecl>,
    pub uses: Vec<UseDecl>,
    pub statements: Vec<LocyStatement>,
}

/// A dotted name like `acme.compliance.rules`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QualifiedName {
    pub parts: Vec<String>,
}

impl std::fmt::Display for QualifiedName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.parts.join("."))
    }
}

/// `MODULE acme.compliance`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModuleDecl {
    pub name: QualifiedName,
}

/// `USE acme.common` or `USE acme.common { control, reachable }`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UseDecl {
    pub name: QualifiedName,
    /// `None` = glob import (all rules), `Some(vec)` = selective imports.
    pub imports: Option<Vec<String>>,
}

/// A top-level statement in a Locy program.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum LocyStatement {
    /// A standard Cypher query (passthrough).
    Cypher(Query),
    /// `CREATE RULE ... AS ...`
    Rule(RuleDefinition),
    /// `QUERY ruleName WHERE expr RETURN ...`
    GoalQuery(GoalQuery),
    /// `DERIVE ruleName WHERE ...`
    DeriveCommand(DeriveCommand),
    /// `ASSUME { mutations } THEN body`
    AssumeBlock(AssumeBlock),
    /// `ABDUCE [NOT] ruleName WHERE expr RETURN ...`
    AbduceQuery(AbduceQuery),
    /// `EXPLAIN RULE ruleName WHERE expr RETURN ...`
    ExplainRule(ExplainRule),
    /// `CREATE MODEL name AS INPUT (...) FEATURES ... OUTPUT type name USING xervo('...')`
    /// Phase B neural-predicate preview. The grammar always parses this;
    /// the compiler rejects it unless `LocyConfig::neural_predicates_preview`
    /// is set.
    Model(ModelDefinition),
    /// `CALIBRATE name ON MATCH pattern [WHERE ...] TARGET expr METHOD method [HOLDOUT 0.2]`
    /// Phase C C2 calibration statement.
    Calibrate(CalibrateCommand),
    /// `VALIDATE name ON MATCH pattern [WHERE ...] TARGET expr METRICS m1, m2, ...`
    /// Phase C C3 validation statement.
    Validate(ValidateCommand),
}

// ═══════════════════════════════════════════════════════════════════════════
// RULE DEFINITION
// ═══════════════════════════════════════════════════════════════════════════

/// `CREATE RULE name [PRIORITY n] AS MATCH pattern [WHERE conds] [ALONG ...] [FOLD ...] [WHERE having] [BEST BY ...] YIELD/DERIVE ...`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RuleDefinition {
    pub name: QualifiedName,
    pub priority: Option<i64>,
    pub match_pattern: Pattern,
    pub where_conditions: Vec<RuleCondition>,
    pub along: Vec<AlongBinding>,
    pub fold: Vec<FoldBinding>,
    /// Post-FOLD filter conditions (HAVING semantics). These filter on
    /// aggregate results after FOLD computation.
    pub having: Vec<Expr>,
    pub best_by: Option<BestByClause>,
    pub output: RuleOutput,
}

/// A condition in a rule WHERE clause.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RuleCondition {
    /// `x IS rule`, `x IS rule TO y`, `(x,y) IS rule`
    IsReference(IsReference),
    /// A standard Cypher expression used as a boolean condition.
    Expression(Expr),
}

/// An IS rule reference in various forms.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IsReference {
    pub subjects: Vec<String>,
    pub rule_name: QualifiedName,
    pub target: Option<String>,
    pub negated: bool,
}

// ═══════════════════════════════════════════════════════════════════════════
// ALONG (path-carried values)
// ═══════════════════════════════════════════════════════════════════════════

/// `name = along_expression`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AlongBinding {
    pub name: String,
    pub expr: LocyExpr,
}

/// Locy expression: extends Cypher expressions with `prev.field`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum LocyExpr {
    /// `prev.fieldName` — reference to previous hop's value.
    PrevRef(String),
    /// A standard Cypher expression.
    Cypher(Expr),
    /// Binary operation between Locy expressions.
    BinaryOp {
        left: Box<LocyExpr>,
        op: LocyBinaryOp,
        right: Box<LocyExpr>,
    },
    /// Unary operation (NOT, negation).
    UnaryOp(UnaryOp, Box<LocyExpr>),
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum LocyBinaryOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Pow,
    And,
    Or,
    Xor,
    // Comparisons are handled via Cypher expression re-parse
}

// ═══════════════════════════════════════════════════════════════════════════
// FOLD (aggregation)
// ═══════════════════════════════════════════════════════════════════════════

/// `name = fold_expression`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FoldBinding {
    pub name: String,
    pub aggregate: Expr,
}

// ═══════════════════════════════════════════════════════════════════════════
// BEST BY (optimized selection)
// ═══════════════════════════════════════════════════════════════════════════

/// Wrapper for the BEST BY clause items.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BestByClause {
    pub items: Vec<BestByItem>,
}

/// `expr [ASC|DESC]`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BestByItem {
    pub expr: Expr,
    pub ascending: bool,
}

// ═══════════════════════════════════════════════════════════════════════════
// YIELD (rule output schema)
// ═══════════════════════════════════════════════════════════════════════════

/// Either YIELD items or DERIVE clause as a rule's output.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RuleOutput {
    Yield(YieldClause),
    Derive(DeriveClause),
}

/// Wrapper for the YIELD clause items.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct YieldClause {
    pub items: Vec<LocyYieldItem>,
}

/// A single YIELD item, possibly marked as KEY or PROB.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LocyYieldItem {
    pub is_key: bool,
    pub is_prob: bool,
    pub expr: Expr,
    pub alias: Option<String>,
}

// ═══════════════════════════════════════════════════════════════════════════
// DERIVE (graph derivation in rule heads)
// ═══════════════════════════════════════════════════════════════════════════

/// `DERIVE pattern, pattern, ...` or `DERIVE MERGE a, b`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DeriveClause {
    Patterns(Vec<DerivePattern>),
    Merge(String, String),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DerivePattern {
    pub direction: Direction,
    pub source: DeriveNodeSpec,
    pub edge: DeriveEdgeSpec,
    pub target: DeriveNodeSpec,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeriveNodeSpec {
    pub is_new: bool,
    pub variable: String,
    pub labels: Vec<String>,
    pub properties: Option<Expr>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeriveEdgeSpec {
    pub edge_type: String,
    pub properties: Option<Expr>,
}

// ═══════════════════════════════════════════════════════════════════════════
// GOAL-DIRECTED QUERY
// ═══════════════════════════════════════════════════════════════════════════

/// `QUERY ruleName [WHERE expr] [RETURN ...]`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GoalQuery {
    pub rule_name: QualifiedName,
    pub where_expr: Option<Expr>,
    pub return_clause: Option<ReturnClause>,
}

// ═══════════════════════════════════════════════════════════════════════════
// DERIVE COMMAND (top-level)
// ═══════════════════════════════════════════════════════════════════════════

/// `DERIVE ruleName [WHERE expr]`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeriveCommand {
    pub rule_name: QualifiedName,
    pub where_expr: Option<Expr>,
}

// ═══════════════════════════════════════════════════════════════════════════
// ASSUME BLOCK
// ═══════════════════════════════════════════════════════════════════════════

/// `ASSUME { mutations } THEN body`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssumeBlock {
    pub mutations: Vec<crate::ast::Clause>,
    pub body: Vec<LocyStatement>,
}

// ═══════════════════════════════════════════════════════════════════════════
// ABDUCE QUERY
// ═══════════════════════════════════════════════════════════════════════════

/// `ABDUCE [NOT] ruleName [WHERE expr] [RETURN ...]`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AbduceQuery {
    pub negated: bool,
    pub rule_name: QualifiedName,
    pub where_expr: Option<Expr>,
    pub return_clause: Option<ReturnClause>,
}

// ═══════════════════════════════════════════════════════════════════════════
// EXPLAIN RULE
// ═══════════════════════════════════════════════════════════════════════════

/// `EXPLAIN RULE ruleName [WHERE expr] [RETURN ...]`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExplainRule {
    pub rule_name: QualifiedName,
    pub where_expr: Option<Expr>,
    pub return_clause: Option<ReturnClause>,
}

// ═══════════════════════════════════════════════════════════════════════════
// CREATE MODEL (neural predicate, Phase B preview)
// ═══════════════════════════════════════════════════════════════════════════

/// `CREATE MODEL` declaration. Parses the full surface from impl plan §2.1;
/// `Conformal` / `Dirichlet` calibration methods are deferred to Phase C.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ModelDefinition {
    pub name: QualifiedName,
    pub inputs: Vec<InputBinding>,
    /// Feature expressions evaluated against input bindings. Empty when
    /// the `FEATURES` clause is omitted (model receives all bound node
    /// properties — interpretation deferred to the runtime adapter).
    pub features: Vec<Expr>,
    /// Phase D D3: `FEATURES (subject, column) FROM rule_name` pulls
    /// `column` from a prior-derived relation `rule_name` (keyed by
    /// `subject`) at runtime, and feeds it as a feature alongside any
    /// `INPUT` bindings. MVP: at most one path-context feature per
    /// model, mutually exclusive with the expression-`features` form.
    pub path_context: Option<PathContextFeature>,
    pub output: OutputBinding,
    pub xervo_alias: String,
    /// Phase D D2 follow-up: optional embedder alias surfaced by the
    /// `USING xervo('classify/X', embedder='alias')` form. When
    /// `None`, the runtime falls back to the alias `"default"` for
    /// `semantic_match` query-text embedding.
    pub embedder_alias: Option<String>,
    pub calibration: Option<CalibrationMethod>,
    pub version: Option<String>,
    pub annotations: ModelAnnotations,
}

/// One INPUT binding, e.g. `(s:Supplier)`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InputBinding {
    pub variable: String,
    pub label: Option<String>,
}

/// Phase D D3: `FEATURES (subject_var, column) FROM source_rule`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PathContextFeature {
    pub subject_var: String,
    pub column: String,
    pub source_rule: String,
}

/// The OUTPUT declaration, e.g. `OUTPUT PROB risk`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OutputBinding {
    pub output_type: OutputType,
    pub name: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OutputType {
    Prob,
    Score,
    Label,
    Vector,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum CalibrationMethod {
    PlattScaling,
    IsotonicRegression,
    TemperatureScaling,
    BetaCalibration,
    None,
    /// Phase C C1a: split-conformal predictor. The point prediction
    /// passes through unchanged; the calibrator carries a
    /// `(1 - alpha)`-quantile of holdout nonconformity scores which
    /// gates a per-prediction `ConfidenceBand` at inference. `alpha`
    /// defaults to 0.1 (90% bands) when omitted.
    Conformal {
        alpha: f64,
    },
    /// Phase D D-C1d: multi-class Dirichlet calibration. The CALIBRATE
    /// statement collects per-row `(class_index, score_vector)` pairs
    /// instead of `(prediction, ground_truth)`. Compiler routes this
    /// through `MulticlassCalibratorFitter` rather than the binary
    /// `CalibratorFitter` trait. Method-of-moments fit by default.
    Dirichlet,
}

/// Statement-level annotations. Currently only `@independent`, which
/// suppresses Phase-C F2 shared-neural-input warnings. Parsed in Slice
/// 1+2; semantically meaningful when F2 lands.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelAnnotations {
    pub independent: bool,
}

// ═══════════════════════════════════════════════════════════════════════════
// CALIBRATE COMMAND  (Phase C C2)
// ═══════════════════════════════════════════════════════════════════════════

/// `CALIBRATE` statement. The runtime collects
/// `(prediction, ground_truth)` pairs by invoking the registered
/// classifier for `model_name` over the MATCH pattern, fits the
/// chosen calibrator on a holdout-split, and returns the fitted
/// transform + holdout metrics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CalibrateCommand {
    pub model_name: QualifiedName,
    pub pattern: Pattern,
    pub where_expr: Option<Expr>,
    pub target_expr: Expr,
    pub method: CalibrationMethod,
    /// Holdout fraction (must be in `(0, 1)`). `None` → compiler
    /// resolves to default 0.2.
    pub holdout: Option<f64>,
}

// ═══════════════════════════════════════════════════════════════════════════
// VALIDATE COMMAND  (Phase C C3)
// ═══════════════════════════════════════════════════════════════════════════

/// `VALIDATE` statement. Runs the named rule, joins its PROB column
/// output against the TARGET expression (ground truth), and computes
/// the requested metrics. Unlike CALIBRATE, this never fits anything
/// — it just measures.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ValidateCommand {
    pub rule_name: QualifiedName,
    pub pattern: Pattern,
    pub where_expr: Option<Expr>,
    pub target_expr: Expr,
    pub metrics: Vec<ValidationMetric>,
}

/// Supported metrics in `VALIDATE METRICS ...`. Each metric is a
/// proper scoring rule or a calibration-quality summary; see
/// `crates/uni-locy/src/calibration.rs` for definitions and
/// numerical references.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ValidationMetric {
    BrierScore,
    LogLoss,
    /// Naive equal-width-binning ECE. Triggers
    /// `WarningCode::EceBinningBias` (impl plan §3.4) suggesting
    /// `DebiasedEce` instead.
    Ece,
    /// Debiased ECE per Kumar et al. NeurIPS 2019 — recommended.
    DebiasedEce,
    Accuracy,
    Auc,
}