tessellate-core 0.1.0

Compiler and deterministic runtime for the Tess rule language
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
//! Deterministic structural views of decisions, rules, overrides, and sources.
//!
//! A policy graph is intentionally descriptive rather than executable. It is
//! built from an already compiled program, so every referenced decision, rule,
//! and named source has passed normal Tess name and type checking.

use crate::ast::{Effect, SourceRef};
use crate::compiler::{CompiledProgram, display_symbol_name, normalize_name};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{self, Write};

/// Version of the serialized policy graph schema.
pub const POLICY_GRAPH_SCHEMA_VERSION: u32 = 1;

/// A stable, deterministically ordered policy graph.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PolicyGraph {
    pub schema_version: u32,
    pub module: String,
    /// Present when the graph was restricted to one decision.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision: Option<String>,
    pub nodes: Vec<PolicyNode>,
    pub edges: Vec<PolicyEdge>,
}

/// A graph node with a kind-qualified, stable identifier.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PolicyNode {
    pub id: String,
    pub kind: PolicyNodeKind,
    pub name: String,
    /// Only source nodes carry source metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<PolicySourceMetadata>,
}

/// The declaration represented by a graph node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyNodeKind {
    Decision,
    Rule,
    Source,
}

/// Metadata retained for a named or legacy inline source reference.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PolicySourceMetadata {
    pub title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub section: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri: Option<String>,
    /// `true` for a legacy `source "..."` reference without a declaration.
    pub inline: bool,
}

/// A directed relationship between two policy nodes.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PolicyEdge {
    pub from: String,
    pub to: String,
    pub kind: PolicyEdgeKind,
}

/// The meaning of a directed policy graph edge.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PolicyEdgeKind {
    /// A rule contributes a candidate to a decision.
    Proposes,
    /// A rule explicitly overrides another rule.
    Overrides,
    /// A rule cites a named or legacy inline source.
    Cites,
}

impl PolicyEdgeKind {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Proposes => "proposes",
            Self::Overrides => "overrides",
            Self::Cites => "cites",
        }
    }
}

/// Failure to select a requested graph root.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PolicyGraphError {
    UnknownDecision {
        name: String,
        available: Vec<String>,
    },
}

impl fmt::Display for PolicyGraphError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownDecision { name, available } if available.is_empty() => {
                write!(
                    formatter,
                    "decision `{name}` was not found; this target declares no decisions"
                )
            }
            Self::UnknownDecision { name, available } => write!(
                formatter,
                "decision `{name}` was not found; available decisions: {}",
                available.join(", ")
            ),
        }
    }
}

impl std::error::Error for PolicyGraphError {}

/// Build a complete graph, or the subgraph that can directly affect one decision.
///
/// A decision-filtered graph contains rules that propose that decision, rules
/// that directly override one of those proposing rules, and the sources cited
/// by the included rules. Unrelated effects on a multi-effect rule are omitted.
///
/// # Errors
///
/// Returns [`PolicyGraphError::UnknownDecision`] when `decision` does not name
/// a declared decision.
pub fn build_policy_graph(
    program: &CompiledProgram,
    decision: Option<&str>,
) -> Result<PolicyGraph, PolicyGraphError> {
    let selected = decision.map(normalize_name);
    let selected_declaration = if let (Some(selected), Some(requested)) = (&selected, decision) {
        Some(program.decisions().get(selected).ok_or_else(|| {
            PolicyGraphError::UnknownDecision {
                name: requested.to_owned(),
                available: program
                    .decisions()
                    .values()
                    .map(|declaration| display_symbol_name(&declaration.name.value))
                    .collect(),
            }
        })?)
    } else {
        None
    };

    let relevant_rules = relevant_rules(program, selected.as_deref());
    let mut nodes = BTreeMap::<String, PolicyNode>::new();
    let mut edges = BTreeSet::<PolicyEdge>::new();

    if let Some((selected, declaration)) = selected.as_ref().zip(selected_declaration) {
        insert_node(
            &mut nodes,
            PolicyNode {
                id: decision_id(selected),
                kind: PolicyNodeKind::Decision,
                name: display_symbol_name(&declaration.name.value),
                source: None,
            },
        );
    } else {
        for (name, declaration) in program.decisions() {
            insert_node(
                &mut nodes,
                PolicyNode {
                    id: decision_id(name),
                    kind: PolicyNodeKind::Decision,
                    name: display_symbol_name(&declaration.name.value),
                    source: None,
                },
            );
        }
        for (name, declaration) in program.sources() {
            insert_named_source(&mut nodes, name, declaration);
        }
    }

    for rule_name in &relevant_rules {
        let rule = &program.rules()[rule_name];
        insert_node(
            &mut nodes,
            PolicyNode {
                id: rule_id(rule_name),
                kind: PolicyNodeKind::Rule,
                name: display_symbol_name(&rule.name.value),
                source: None,
            },
        );

        for effect in &rule.effects {
            match effect {
                Effect::Decide { decision, .. } => {
                    let target = normalize_name(&decision.value);
                    if selected.as_ref().is_none_or(|selected| selected == &target) {
                        edges.insert(PolicyEdge {
                            from: rule_id(rule_name),
                            to: decision_id(&target),
                            kind: PolicyEdgeKind::Proposes,
                        });
                    }
                }
                Effect::Override { rule: target, .. } => {
                    let target = normalize_name(&target.value);
                    if relevant_rules.contains(&target) {
                        edges.insert(PolicyEdge {
                            from: rule_id(rule_name),
                            to: rule_id(&target),
                            kind: PolicyEdgeKind::Overrides,
                        });
                    }
                }
            }
        }

        for source in &rule.sources {
            let target = match source {
                SourceRef::Named(name) => {
                    let name = normalize_name(&name.value);
                    if let Some(declaration) = program.sources().get(&name) {
                        insert_named_source(&mut nodes, &name, declaration);
                    }
                    named_source_id(&name)
                }
                SourceRef::Inline(value) => {
                    let id = inline_source_id(&value.value);
                    insert_node(
                        &mut nodes,
                        PolicyNode {
                            id: id.clone(),
                            kind: PolicyNodeKind::Source,
                            name: value.value.clone(),
                            source: Some(PolicySourceMetadata {
                                title: value.value.clone(),
                                section: None,
                                version: None,
                                uri: None,
                                inline: true,
                            }),
                        },
                    );
                    id
                }
            };
            edges.insert(PolicyEdge {
                from: rule_id(rule_name),
                to: target,
                kind: PolicyEdgeKind::Cites,
            });
        }
    }

    Ok(PolicyGraph {
        schema_version: POLICY_GRAPH_SCHEMA_VERSION,
        module: program.ast().module.value.clone(),
        decision: selected_declaration
            .map(|declaration| display_symbol_name(&declaration.name.value)),
        nodes: nodes.into_values().collect(),
        edges: edges.into_iter().collect(),
    })
}

impl PolicyGraph {
    /// Render a canonical Graphviz DOT document.
    #[must_use]
    pub fn render_dot(&self) -> String {
        let mut output = String::from("digraph policy {\n  rankdir=LR;\n");
        for node in &self.nodes {
            let shape = match node.kind {
                PolicyNodeKind::Decision => "box",
                PolicyNodeKind::Rule => "ellipse",
                PolicyNodeKind::Source => "note",
            };
            let kind = match node.kind {
                PolicyNodeKind::Decision => "decision",
                PolicyNodeKind::Rule => "rule",
                PolicyNodeKind::Source => "source",
            };
            let mut label = format!("{kind}\n{}", node.name);
            if let Some(source) = node
                .source
                .as_ref()
                .filter(|source| source.title != node.name)
            {
                label.push('\n');
                label.push_str(&source.title);
            }
            let _ = writeln!(
                output,
                "  \"{}\" [label=\"{}\", shape={}];",
                dot_escape(&node.id),
                dot_escape(&label),
                shape
            );
        }
        for edge in &self.edges {
            let _ = writeln!(
                output,
                "  \"{}\" -> \"{}\" [label=\"{}\"];",
                dot_escape(&edge.from),
                dot_escape(&edge.to),
                edge.kind.as_str()
            );
        }
        output.push_str("}\n");
        output
    }
}

fn relevant_rules(program: &CompiledProgram, selected: Option<&str>) -> BTreeSet<String> {
    let Some(selected) = selected else {
        return program.rules().keys().cloned().collect();
    };
    let proposing = program
        .rules()
        .iter()
        .filter(|(_, rule)| {
            rule.effects.iter().any(|effect| {
                matches!(effect, Effect::Decide { decision, .. }
                    if normalize_name(&decision.value) == selected)
            })
        })
        .map(|(name, _)| name.clone())
        .collect::<BTreeSet<_>>();
    let mut relevant = proposing.clone();
    for (name, rule) in program.rules() {
        if rule.effects.iter().any(|effect| {
            matches!(effect, Effect::Override { rule, .. }
                if proposing.contains(&normalize_name(&rule.value)))
        }) {
            relevant.insert(name.clone());
        }
    }
    relevant
}

fn insert_node(nodes: &mut BTreeMap<String, PolicyNode>, node: PolicyNode) {
    nodes.entry(node.id.clone()).or_insert(node);
}

fn insert_named_source(
    nodes: &mut BTreeMap<String, PolicyNode>,
    name: &str,
    declaration: &crate::ast::SourceDecl,
) {
    insert_node(
        nodes,
        PolicyNode {
            id: named_source_id(name),
            kind: PolicyNodeKind::Source,
            name: display_symbol_name(&declaration.name.value),
            source: Some(PolicySourceMetadata {
                title: declaration.title.value.clone(),
                section: declaration
                    .section
                    .as_ref()
                    .map(|value| value.value.clone()),
                version: declaration
                    .version
                    .as_ref()
                    .map(|value| value.value.clone()),
                uri: declaration.uri.as_ref().map(|value| value.value.clone()),
                inline: false,
            }),
        },
    );
}

fn decision_id(name: &str) -> String {
    format!("decision:{}", display_symbol_name(name))
}

fn rule_id(name: &str) -> String {
    format!("rule:{}", display_symbol_name(name))
}

fn named_source_id(name: &str) -> String {
    format!("source:named:{}", display_symbol_name(name))
}

fn inline_source_id(value: &str) -> String {
    format!("source:inline:{value}")
}

fn dot_escape(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for character in value.chars() {
        match character {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            control if control.is_control() => {
                let _ = write!(escaped, "\\\\u{{{:x}}}", u32::from(control));
            }
            value => escaped.push(value),
        }
    }
    escaped
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{SourceFile, compile_source};

    const GRAPH_SOURCE: &str = r#"module graph

enum Result { Yes, No }
entity Request { enabled: Bool }

decision eligibility(Request r) -> Result
decision audit(Request r) -> Bool many

source Statute {
  title: "Policy \"A\"",
  section: "4.2",
}
source Unused { title: "Unused" }

rule base(Request r):
  when r.enabled
  then eligibility(r) = Yes
  source Statute

rule exception(Request r):
  when not r.enabled
  then eligibility(r) = No
  then override base
  source "Legacy\nMemo"

rule audit_rule(Request r):
  when r.enabled
  then audit(r) = true
"#;

    fn compiled(text: &str) -> CompiledProgram {
        let output = compile_source(SourceFile::new("graph.tes", text));
        assert!(!output.has_errors(), "{:?}", output.diagnostics);
        output.program.expect("valid graph fixture")
    }

    #[test]
    fn full_graph_has_stable_nodes_edges_and_source_metadata() {
        let graph = build_policy_graph(&compiled(GRAPH_SOURCE), None).unwrap();
        assert_eq!(graph.schema_version, 1);
        assert_eq!(graph.module, "graph");
        assert_eq!(graph.nodes.len(), 8);
        assert_eq!(graph.edges.len(), 6);
        assert!(graph.nodes.windows(2).all(|pair| pair[0].id < pair[1].id));
        assert!(graph.edges.windows(2).all(|pair| pair[0] < pair[1]));
        let statute = graph
            .nodes
            .iter()
            .find(|node| node.id == "source:named:Statute")
            .unwrap();
        assert_eq!(
            statute.source.as_ref().unwrap().section.as_deref(),
            Some("4.2")
        );
        assert!(!statute.source.as_ref().unwrap().inline);
        assert!(graph.nodes.iter().any(|node| {
            node.id == "source:inline:Legacy\nMemo"
                && node.source.as_ref().is_some_and(|source| source.inline)
        }));
    }

    #[test]
    fn decision_filter_keeps_proposers_direct_overriders_and_their_sources() {
        let program = compiled(GRAPH_SOURCE);
        let graph = build_policy_graph(&program, Some("eligibility")).unwrap();
        assert_eq!(graph.decision.as_deref(), Some("eligibility"));
        assert_eq!(
            graph
                .nodes
                .iter()
                .map(|node| node.id.as_str())
                .collect::<Vec<_>>(),
            [
                "decision:eligibility",
                "rule:base",
                "rule:exception",
                "source:inline:Legacy\nMemo",
                "source:named:Statute",
            ]
        );
        assert_eq!(graph.edges.len(), 5);
        assert!(
            !graph
                .nodes
                .iter()
                .any(|node| node.id == "decision:audit" || node.id == "source:named:Unused")
        );
    }

    #[test]
    fn declaration_order_does_not_change_the_graph() {
        let first = build_policy_graph(&compiled(GRAPH_SOURCE), None).unwrap();
        let reordered = GRAPH_SOURCE.replace(
            "decision eligibility(Request r) -> Result\ndecision audit(Request r) -> Bool many",
            "decision audit(Request r) -> Bool many\ndecision eligibility(Request r) -> Result",
        );
        let second = build_policy_graph(&compiled(&reordered), None).unwrap();
        assert_eq!(first, second);
        let encoded = serde_json::to_string(&first).unwrap();
        assert_eq!(
            serde_json::from_str::<PolicyGraph>(&encoded).unwrap(),
            first
        );
    }

    #[test]
    fn dot_output_escapes_quotes_newlines_and_backslashes() {
        let graph = build_policy_graph(&compiled(GRAPH_SOURCE), Some("eligibility")).unwrap();
        let dot = graph.render_dot();
        assert!(dot.starts_with("digraph policy {\n  rankdir=LR;\n"));
        assert!(dot.contains("Policy \\\"A\\\""));
        assert!(dot.contains("Legacy\\nMemo"));
        assert!(dot.contains("[label=\"overrides\"]"));
        assert!(dot.ends_with("}\n"));
    }

    #[test]
    fn unknown_decision_lists_stable_available_names() {
        let error = build_policy_graph(&compiled(GRAPH_SOURCE), Some("missing")).unwrap_err();
        assert_eq!(
            error,
            PolicyGraphError::UnknownDecision {
                name: "missing".into(),
                available: vec!["audit".into(), "eligibility".into()],
            }
        );
        assert_eq!(
            error.to_string(),
            "decision `missing` was not found; available decisions: audit, eligibility"
        );
    }
}