ursa_engine/graph/provenance.rs
1//! What a result's columns are: the `ursa.*` Arrow field metadata the graph
2//! functions and `GRAPH_TABLE` put on their output (#431).
3//!
4//! A consumer (the graph view, a notebook, a file's reader) should not guess
5//! from names that `id` is a node key and `pagerank` a metric. So every graph
6//! function marks its output fields, and DataFusion carries the marks with
7//! the column: through a projection of the column, an alias, a filter, a
8//! sort, a limit, a join, a subquery and `SELECT *`, and into exported Arrow
9//! and Parquet files. An expression that computes a new value
10//! (`round(pagerank, 4)`, `id + 1`) has none, which is right: the new column
11//! is no longer known to be what its input was. `tests/provenance.rs` in
12//! `ursa-sql` holds DataFusion to this, operator by operator.
13//!
14//! The keys:
15//!
16//! - [`ROLE`] (`ursa.role`): what the column is, one of the `ROLE_*` values.
17//! - [`GRAPH`] (`ursa.graph`): the property graph the column came from.
18//! - [`LABEL`] (`ursa.label`): the vertex table a node key belongs to, or the
19//! edge table an edge row or an edge's property belongs to. Left out for a
20//! node of a graph without a vertex table.
21//! - [`VAR`] (`ursa.var`): in `GRAPH_TABLE`, the pattern variable the column
22//! reads.
23//! - [`PATTERN`] (`ursa.pattern`): on the schema of a `GRAPH_TABLE`, not on a
24//! field: the pattern's edges, as JSON (see [`PatternEdge`]).
25//!
26//! Nothing here changes a result's values, column names or types.
27
28use std::collections::BTreeMap;
29use std::sync::Arc;
30
31use datafusion::arrow::datatypes::{Field, Schema};
32use datafusion::common::metadata::FieldMetadata;
33use datafusion::common::tree_node::Transformed;
34use datafusion::common::{Column, ExprSchema, JoinType};
35use datafusion::error::Result;
36use datafusion::logical_expr::expr::Alias;
37use datafusion::logical_expr::utils::split_conjunction;
38use datafusion::logical_expr::{BinaryExpr, Expr, LogicalPlan, LogicalPlanBuilder, Operator};
39
40/// What the column is.
41pub const ROLE: &str = "ursa.role";
42/// The property graph the column came from.
43pub const GRAPH: &str = "ursa.graph";
44/// The vertex or edge table the column belongs to (its element name).
45pub const LABEL: &str = "ursa.label";
46/// The `GRAPH_TABLE` pattern variable the column reads.
47pub const VAR: &str = "ursa.var";
48/// On a `GRAPH_TABLE`'s schema: the pattern's edges, as JSON.
49pub const PATTERN: &str = "ursa.pattern";
50
51/// A node key: an algorithm's `id`, `hop`'s `id`, `random_walk`'s `node`, a
52/// node variable's key in `GRAPH_TABLE`.
53pub const ROLE_NODE: &str = "node";
54/// The node key an edge or a path step starts at.
55pub const ROLE_SRC: &str = "src";
56/// The node key an edge or a path step ends at.
57pub const ROLE_DST: &str = "dst";
58/// An edge's row in its edge table, as `edges(p)` numbers them.
59pub const ROLE_EDGE: &str = "edge";
60/// The node key a `hop` row started from.
61pub const ROLE_SEED: &str = "seed";
62/// The fewest steps from the seed to the node.
63pub const ROLE_DISTANCE: &str = "distance";
64/// A row's position in its path or walk.
65pub const ROLE_STEP: &str = "step";
66/// Which walk a `random_walk` row belongs to.
67pub const ROLE_WALK: &str = "walk";
68/// A per-node number an algorithm computed (`pagerank`, `degree`).
69pub const ROLE_METRIC: &str = "metric";
70/// A per-node group an algorithm assigned (`louvain`'s community).
71pub const ROLE_CATEGORY: &str = "category";
72/// A property of a `GRAPH_TABLE` variable.
73pub const ROLE_PROPERTY: &str = "property";
74/// `vertices(p)`: a path's node keys, in order.
75pub const ROLE_PATH_NODES: &str = "path_nodes";
76/// `edges(p)`: a path's edge rows, in order.
77pub const ROLE_PATH_EDGES: &str = "path_edges";
78/// `element_id(p)`: a path's nodes and edges, alternating.
79pub const ROLE_PATH_ELEMENTS: &str = "path_elements";
80
81/// The metadata of one field: its role in `graph`, and the element table
82/// `label` it belongs to, if one is known.
83pub fn metadata(role: &str, graph: &str, label: Option<&str>) -> BTreeMap<String, String> {
84 let mut m = BTreeMap::new();
85 m.insert(ROLE.to_string(), role.to_string());
86 m.insert(GRAPH.to_string(), graph.to_string());
87 if let Some(label) = label {
88 m.insert(LABEL.to_string(), label.to_string());
89 }
90 m
91}
92
93/// `field`, marked with `role` (see [`metadata`]).
94pub fn field(field: Field, role: &str, graph: &str, label: Option<&str>) -> Field {
95 field.with_metadata(metadata(role, graph, label).into_iter().collect())
96}
97
98/// `expr` under the same name and qualifier, its field marked with
99/// `metadata`. A column stays a column reference (aliased to its own name),
100/// so nothing about the plan's shape or the output's names changes.
101pub fn marked(expr: Expr, metadata: BTreeMap<String, String>) -> Expr {
102 let metadata = FieldMetadata::from(metadata);
103 match expr {
104 Expr::Alias(Alias {
105 expr,
106 relation,
107 name,
108 metadata: prior,
109 }) => {
110 let merged = FieldMetadata::merge_options(prior.as_ref(), Some(&metadata));
111 expr.alias_qualified_with_metadata(relation, name, merged)
112 }
113 Expr::Column(c) => {
114 let (relation, name) = (c.relation.clone(), c.name.clone());
115 Expr::Column(c).alias_qualified_with_metadata(relation, name, Some(metadata))
116 }
117 other => other,
118 }
119}
120
121/// One edge of a `GRAPH_TABLE` pattern, as [`PATTERN`] lists it.
122///
123/// `ursa.pattern` is a JSON array with one object per edge of the pattern,
124/// in the order written:
125///
126/// ```json
127/// [{"from": "a", "to": "b", "directed": true, "edge": "e", "label": "ties"}]
128/// ```
129///
130/// `from` and `to` are node variables, in the edge's direction (`(a)<-[e]-(b)`
131/// has `from` `b`); for an undirected edge (`-[e]-`), `directed` is false and
132/// they are in the order written. A variable the pattern does not name is
133/// `null`. `label` is the edge table. A quantified edge (`-[e]->{1,3}`,
134/// `->*`) also has `"min"` and `"max"` (`null` for no upper bound), and the
135/// edge of a path with a variable has `"path"`: such an edge stands for a
136/// path between its two nodes, not for one edge.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct PatternEdge {
139 pub from: Option<String>,
140 pub to: Option<String>,
141 pub directed: bool,
142 pub edge: Option<String>,
143 pub label: String,
144 /// `(min, max)` of a quantified edge.
145 pub quantifier: Option<(u32, Option<u32>)>,
146 /// The path variable of the edge's path.
147 pub path: Option<String>,
148}
149
150/// [`PATTERN`]'s value for `edges`.
151pub fn pattern_json(edges: &[PatternEdge]) -> String {
152 use serde_json::{json, Map, Value};
153 let edges: Vec<Value> = edges
154 .iter()
155 .map(|e| {
156 let mut o = Map::new();
157 o.insert("from".into(), json!(e.from));
158 o.insert("to".into(), json!(e.to));
159 o.insert("directed".into(), json!(e.directed));
160 o.insert("edge".into(), json!(e.edge));
161 o.insert("label".into(), json!(e.label));
162 if let Some((min, max)) = e.quantifier {
163 o.insert("min".into(), json!(min));
164 o.insert("max".into(), json!(max));
165 }
166 if let Some(path) = &e.path {
167 o.insert("path".into(), json!(path));
168 }
169 Value::Object(o)
170 })
171 .collect();
172 Value::Array(edges).to_string()
173}
174
175/// `schema` with `key` set to `value` in its own (not a field's) metadata.
176pub fn with_schema_metadata(schema: &Schema, key: &str, value: &str) -> Arc<Schema> {
177 let mut metadata = schema.metadata().clone();
178 metadata.insert(key.to_string(), value.to_string());
179 Arc::new(schema.clone().with_metadata(metadata))
180}
181
182/// Carry a node key's metadata across an inner join on it.
183///
184/// `FROM members JOIN pagerank(karate) USING (id)` returns one `id`, and
185/// DataFusion takes it from `members`: a plain table's column, which says
186/// nothing. But an inner join on `members.id = pagerank.id` keeps only the
187/// rows where the two are equal, so `members.id` is the node key too. This
188/// rewrite says so: under every inner join, a plain column that `USING`,
189/// `NATURAL` or an `ON a.x = b.y` equates with a node key (a field whose role is [`ROLE_NODE`]) of
190/// the same type takes that field's metadata, through a projection of its
191/// side that changes nothing else.
192///
193/// Only an inner join, where every row kept has the two equal; only a
194/// column equated as written, not one a cast was needed to compare; and only
195/// a column with no role of its own.
196pub fn carry_through_joins(plan: LogicalPlan) -> Result<LogicalPlan> {
197 // Whether a join below was rewritten: the plans above it then take
198 // their schemas from their new inputs.
199 let mut carried = false;
200 plan.transform_up_with_subqueries(|plan| {
201 let LogicalPlan::Join(join) = &plan else {
202 return match carried {
203 true => plan.recompute_schema().map(Transformed::yes),
204 false => Ok(Transformed::no(plan)),
205 };
206 };
207 if join.join_type != JoinType::Inner {
208 return match carried {
209 true => plan.recompute_schema().map(Transformed::yes),
210 false => Ok(Transformed::no(plan)),
211 };
212 }
213 // Per side, the columns to mark and what with.
214 let mut marks: [Vec<(Column, FieldMetadata)>; 2] = [Vec::new(), Vec::new()];
215 // The pairs of columns the join equates: `USING`'s, and those of
216 // `ON a.x = b.y [AND …]`, which is still a filter when this runs.
217 let mut pairs: Vec<(&Column, &Column)> = Vec::new();
218 for (l, r) in &join.on {
219 if let (Expr::Column(l), Expr::Column(r)) = (l, r) {
220 pairs.push((l, r));
221 }
222 }
223 for conjunct in join.filter.iter().flat_map(split_conjunction) {
224 let Expr::BinaryExpr(BinaryExpr {
225 left,
226 op: Operator::Eq,
227 right,
228 }) = conjunct
229 else {
230 continue;
231 };
232 let (Expr::Column(x), Expr::Column(y)) = (left.as_ref(), right.as_ref()) else {
233 continue;
234 };
235 let on_left = |c: &Column| join.left.schema().has_column(c);
236 let on_right = |c: &Column| join.right.schema().has_column(c);
237 if on_left(x) && on_right(y) && !on_right(x) && !on_left(y) {
238 pairs.push((x, y));
239 } else if on_left(y) && on_right(x) && !on_right(y) && !on_left(x) {
240 pairs.push((y, x));
241 }
242 }
243 for (l, r) in pairs {
244 let (Ok(lf), Ok(rf)) = (
245 join.left.schema().field_from_column(l),
246 join.right.schema().field_from_column(r),
247 ) else {
248 continue;
249 };
250 if lf.data_type() != rf.data_type() {
251 continue;
252 }
253 let role = |f: &Field| f.metadata().get(ROLE).cloned();
254 let ours = |f: &Field| -> BTreeMap<String, String> {
255 f.metadata()
256 .iter()
257 .filter(|(k, _)| [ROLE, GRAPH, LABEL].contains(&k.as_str()))
258 .map(|(k, v)| (k.clone(), v.clone()))
259 .collect()
260 };
261 match (role(lf).as_deref(), role(rf).as_deref()) {
262 (Some(ROLE_NODE), None) => marks[1].push((r.clone(), ours(lf).into())),
263 (None, Some(ROLE_NODE)) => marks[0].push((l.clone(), ours(rf).into())),
264 _ => {}
265 }
266 }
267 if marks.iter().all(Vec::is_empty) {
268 return match carried {
269 true => plan.recompute_schema().map(Transformed::yes),
270 false => Ok(Transformed::no(plan)),
271 };
272 }
273 carried = true;
274 let side = |input: &Arc<LogicalPlan>, marks: &[(Column, FieldMetadata)]| {
275 if marks.is_empty() {
276 return Ok(input.as_ref().clone());
277 }
278 let columns = input.schema().iter().map(|(qualifier, field)| {
279 let column = Column::new(qualifier.cloned(), field.name());
280 let mark = marks.iter().find(|(c, _)| {
281 input.schema().index_of_column(c).ok()
282 == input.schema().index_of_column(&column).ok()
283 });
284 match mark {
285 Some((_, metadata)) => Expr::Column(column).alias_qualified_with_metadata(
286 qualifier.cloned(),
287 field.name(),
288 Some(metadata.clone()),
289 ),
290 None => Expr::Column(column),
291 }
292 });
293 LogicalPlanBuilder::from(input.as_ref().clone())
294 .project(columns)?
295 .build()
296 };
297 let inputs = vec![side(&join.left, &marks[0])?, side(&join.right, &marks[1])?];
298 Ok(Transformed::yes(
299 plan.with_new_exprs(plan.expressions(), inputs)?,
300 ))
301 })
302 .map(|t| t.data)
303}