Skip to main content

ursa_engine/graph/view/
inspect.rs

1//! What a graph's tables say of one node or one edge of a drawing: the
2//! inspector's rows (design §4, #444).
3//!
4//! A drawing's node is a key of a vertex table, and its edge a row of an
5//! edge table, when the drawing names a property graph. [`inspect`] reads
6//! that row with one query by key:
7//!
8//! - **a node:** `SELECT * FROM members WHERE id = 33`, on the vertex table
9//!   its label names. A drawing with one label `""` (`.graph NAME`, a plain
10//!   result on a graph) reads the graph's vertex tables in turn, and gives
11//!   the first that has the key.
12//! - **an edge:** `SELECT * FROM ties WHERE src = 0 AND dst = 33`, the rows
13//!   of the edge table between its two ends. Where several rows join them
14//!   (parallel edges) and the drawing knows the edge's row number, that row
15//!   alone is read (`LIMIT 1 OFFSET row`), when the table is read as one
16//!   partition, as it is in the browser: there the scan's order is the row
17//!   numbers'. Otherwise all the rows between the ends are given, and
18//!   [`Inspected::note`] says so. An edge with no row number may be drawn
19//!   against the way the table stores it (a path's steps are), so its rows
20//!   are looked for both ways.
21//!
22//! The queries are built as plans, not as text, so a table that is a file
23//! path, and any name, reads the same; [`Inspected::sql`] is the query as a
24//! user would type it. Nothing here changes the session or its last result.
25//!
26//! **An edge's rows are found through the graph's index** (#489), where they
27//! can be: scanning a million edges for two ends took 90 to 160 ms in the
28//! browser. `induced_edges(G, nodes => [a, b])` reads the two nodes'
29//! adjacency and gives the row number of each edge between them, and those
30//! rows are then read by number ([`super::rows`]): from a Parquet file with a
31//! row selection, which passes over the pages before them, and from any other
32//! table by passing over the rows before. The rows read are checked against the two
33//! ends, so they are the rows the query by the ends gives, in the same order.
34//! A table of the two key columns alone is not read at all: its rows are the
35//! ends the index gave. Among parallel edges, the drawing's row number picks
36//! one of the rows the index found.
37//! The scan stays for what the index cannot say: a graph with several edge
38//! tables, a table read as several partitions (its row numbers are then not
39//! the scan's order), ends the index does not hold, or a check that fails.
40//!
41//! [`graph_neighbours`] is how many neighbours a node has in the whole graph,
42//! for "9 drawn, 17 neighbours in karate".
43
44use datafusion::arrow::array::{Array, AsArray, RecordBatch};
45use datafusion::arrow::compute::cast;
46use datafusion::arrow::datatypes::{DataType, UInt64Type};
47use datafusion::arrow::util::display::{ArrayFormatter, FormatOptions};
48use datafusion::common::TableReference;
49use datafusion::dataframe::DataFrame;
50use datafusion::datasource::provider_as_source;
51use datafusion::error::Result;
52use datafusion::logical_expr::{Expr, LogicalPlanBuilder};
53use datafusion::prelude::{ident, lit, SessionContext};
54use ursa_viz::model::{GraphResult, KeyType};
55
56use super::rows::take;
57use super::{plan_err, RunSql};
58use crate::graph::schema::graph_table;
59use crate::graph::{registry_of, PropertyGraph};
60
61/// The most rows given for one edge: the edges between two nodes, when the
62/// drawing cannot say which of them it drew.
63pub const MAX_ROWS: usize = 20;
64
65/// The most characters of one value; a longer one ends with `…`.
66pub const MAX_VALUE_CHARS: usize = 4096;
67
68/// What to inspect: a node or an edge of the drawing, by its index, with the
69/// keys the asker shows for it. The keys are checked against the drawing, so
70/// an asker whose picture is not the session's is told, not shown another
71/// node's row.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Inspect<'a> {
74    Node {
75        node: u32,
76        key: &'a str,
77    },
78    Edge {
79        edge: u32,
80        src: &'a str,
81        dst: &'a str,
82    },
83}
84
85/// A column of an inspected row.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct InspectedColumn {
88    pub name: String,
89    /// Whether its values are numbers: what `SIZE BY` can read.
90    pub numeric: bool,
91}
92
93/// The rows the graph's tables have for a node or an edge.
94#[derive(Debug, Clone, Default, PartialEq, Eq)]
95pub struct Inspected {
96    /// The table read: the vertex or edge table's element name. `None` when
97    /// there is none to read ([`Self::note`] says why).
98    pub table: Option<String>,
99    /// The query, as a user would type it.
100    pub sql: Option<String>,
101    pub columns: Vec<InspectedColumn>,
102    /// Each row's values as the shell prints them, `None` for NULL. One row
103    /// for a node; for an edge, one, or every row between its ends.
104    pub rows: Vec<Vec<Option<String>>>,
105    /// An edge's row number in its table, where the drawing knows it.
106    pub row: Option<u64>,
107    /// What a reader should know: why there is no row, or that the rows are
108    /// several edges'.
109    pub note: Option<String>,
110    /// Whether an edge's rows were found through the graph's index and read
111    /// by their numbers, not by a scan of the edge table (see the
112    /// [module](self)). The rows are the same either way.
113    pub indexed: bool,
114}
115
116impl Inspected {
117    fn said(note: impl Into<String>) -> Inspected {
118        Inspected {
119            note: Some(note.into()),
120            ..Inspected::default()
121        }
122    }
123}
124
125/// `name` as SQL reads an identifier: bare when it is a plain lower-case
126/// name, else quoted.
127fn name(name: &str) -> String {
128    let plain = name
129        .chars()
130        .enumerate()
131        .all(|(i, c)| c == '_' || c.is_ascii_lowercase() || (i > 0 && c.is_ascii_digit()));
132    if plain && !name.is_empty() {
133        name.to_string()
134    } else {
135        format!("\"{}\"", name.replace('"', "\"\""))
136    }
137}
138
139/// `table` as a query names it: its name, or a file path as a string.
140fn table_name(ctx: &SessionContext, graph: &PropertyGraph, table: &TableReference) -> String {
141    if registry_of(ctx).file_table(&graph.name, table).is_some() {
142        format!("'{}'", table.table().replace('\'', "''"))
143    } else {
144        match table.schema() {
145            Some(schema) => format!("{}.{}", name(schema), name(table.table())),
146            None => name(table.table()),
147        }
148    }
149}
150
151/// `key` as a literal, to compare and to print.
152fn literal(key: &str, ty: KeyType) -> (Expr, String) {
153    match (ty, key.parse::<i64>()) {
154        (KeyType::Int, Ok(n)) => (lit(n), key.to_string()),
155        _ => (lit(key), format!("'{}'", key.replace('\'', "''"))),
156    }
157}
158
159/// Every row of `table` that `filter` keeps, up to `limit`, after `skip`.
160async fn read(
161    ctx: &SessionContext,
162    graph: &PropertyGraph,
163    table: &TableReference,
164    filter: Option<Expr>,
165    skip: usize,
166    limit: usize,
167) -> Result<(Vec<InspectedColumn>, Vec<Vec<Option<String>>>)> {
168    let frame = scan(ctx, graph, table).await?;
169    let frame = match filter {
170        Some(filter) => frame.filter(filter)?,
171        None => frame,
172    };
173    let columns = columns_of(&frame);
174    let batches = frame.limit(skip, Some(limit))?.collect().await?;
175    Ok((columns, rows_of(&batches)?))
176}
177
178/// The columns of `frame`, as the inspector names them.
179fn columns_of(frame: &DataFrame) -> Vec<InspectedColumn> {
180    frame
181        .schema()
182        .fields()
183        .iter()
184        .map(|f| InspectedColumn {
185            name: f.name().clone(),
186            numeric: f.data_type().is_numeric(),
187        })
188        .collect()
189}
190
191/// The rows of `table` numbered `rows` (ascending, each once), in that
192/// order, as text: fewer when the table ends before one of them. `None` when
193/// the table is read as several partitions ([`take`]).
194async fn read_rows(
195    ctx: &SessionContext,
196    graph: &PropertyGraph,
197    table: &TableReference,
198    rows: &[u64],
199) -> Result<Option<(Vec<InspectedColumn>, Vec<Vec<Option<String>>>)>> {
200    let frame = scan(ctx, graph, table).await?;
201    let columns = columns_of(&frame);
202    match take(ctx, frame, rows).await? {
203        Some(taken) => Ok(Some((columns, rows_of(&taken)?))),
204        None => Ok(None),
205    }
206}
207
208async fn scan(
209    ctx: &SessionContext,
210    graph: &PropertyGraph,
211    table: &TableReference,
212) -> Result<DataFrame> {
213    let state = ctx.state();
214    let provider = graph_table(&state, &graph.name, table).await?;
215    let plan =
216        LogicalPlanBuilder::scan(table.clone(), provider_as_source(provider), None)?.build()?;
217    Ok(DataFrame::new(state, plan))
218}
219
220/// The batches' rows as text, as the shell prints a value.
221fn rows_of(batches: &[RecordBatch]) -> Result<Vec<Vec<Option<String>>>> {
222    let options = FormatOptions::default();
223    let mut rows = Vec::new();
224    for batch in batches {
225        let shown = batch
226            .columns()
227            .iter()
228            .map(|c| ArrayFormatter::try_new(c.as_ref(), &options))
229            .collect::<std::result::Result<Vec<_>, _>>()?;
230        for i in 0..batch.num_rows() {
231            let row = batch
232                .columns()
233                .iter()
234                .zip(&shown)
235                .map(|(column, shown)| {
236                    if column.is_null(i) {
237                        return None;
238                    }
239                    let mut text = shown.value(i).to_string();
240                    if let Some((at, _)) = text.char_indices().nth(MAX_VALUE_CHARS) {
241                        text.truncate(at);
242                        text.push('…');
243                    }
244                    Some(text)
245                })
246                .collect();
247            rows.push(row);
248        }
249    }
250    Ok(rows)
251}
252
253/// The property graph `result` names, or why there is none to read.
254fn graph_of(
255    ctx: &SessionContext,
256    result: &GraphResult,
257) -> std::result::Result<std::sync::Arc<PropertyGraph>, String> {
258    let Some(graph) = result.graph() else {
259        return Err(
260            "this drawing is not of a property graph, so there is no table row to show; draw \
261             a graph's (.graph NAME) or a query's on one"
262                .into(),
263        );
264    };
265    registry_of(ctx)
266        .get(graph)
267        .ok_or_else(|| format!("the graph '{graph}' is gone, and its tables with it"))
268}
269
270/// The row of the graph's tables for one node or edge of `result`: see the
271/// [module](self). A drawing with no table to read gives no rows and a
272/// [`note`](Inspected::note), not an error; an index or a key that is not the
273/// drawing's is an error.
274pub async fn inspect(
275    ctx: &SessionContext,
276    sql: &dyn RunSql,
277    result: &GraphResult,
278    what: Inspect<'_>,
279) -> Result<Inspected> {
280    match what {
281        Inspect::Node { node, key } => {
282            let at = node as usize;
283            if at >= result.n_nodes() || result.node_keys().get(at) != key {
284                return plan_err(format!(
285                    "the drawing has changed: its node {node} is not '{key}'; draw it again \
286                     (.graph)"
287                ));
288            }
289            inspect_node(ctx, result, at).await
290        }
291        Inspect::Edge { edge, src, dst } => {
292            let at = edge as usize;
293            let keys = result.node_keys();
294            if at >= result.n_edges()
295                || keys.get(result.src()[at] as usize) != src
296                || keys.get(result.dst()[at] as usize) != dst
297            {
298                return plan_err(format!(
299                    "the drawing has changed: its edge {edge} does not join '{src}' and \
300                     '{dst}'; draw it again (.graph)"
301                ));
302            }
303            inspect_edge(ctx, sql, result, at).await
304        }
305    }
306}
307
308async fn inspect_node(
309    ctx: &SessionContext,
310    result: &GraphResult,
311    node: usize,
312) -> Result<Inspected> {
313    let graph = match graph_of(ctx, result) {
314        Ok(graph) => graph,
315        Err(note) => return Ok(Inspected::said(note)),
316    };
317    if super::groups::is_group(result, node) {
318        return Ok(Inspected::said(format!(
319            "a group of {}'s nodes, not a row of its tables: its values are above, and .expand \
320             group:{} opens it",
321            graph.name,
322            result.node_keys().get(node)
323        )));
324    }
325    let label = &result.node_labels()[result.node_label()[node] as usize];
326    let key = result.node_keys().get(node);
327    // The label's vertex table; with no label, each of the graph's in turn.
328    let tables: Vec<_> = graph
329        .vertex_tables
330        .iter()
331        .filter(|v| label.name.is_empty() || v.name == label.name)
332        .collect();
333    if tables.is_empty() {
334        return Ok(Inspected::said(if graph.vertex_tables.is_empty() {
335            format!(
336                "the graph {} has no vertex tables: a node is its key and its edges",
337                graph.name
338            )
339        } else {
340            format!(
341                "the graph {} has no vertex table '{}'",
342                graph.name, label.name
343            )
344        }));
345    }
346    let mut first = None;
347    for v in tables {
348        let (value, shown) = literal(key, label.key);
349        let (columns, rows) =
350            read(ctx, &graph, &v.table, Some(ident(&v.key).eq(value)), 0, 1).await?;
351        let found = Inspected {
352            table: Some(v.name.clone()),
353            sql: Some(format!(
354                "SELECT * FROM {} WHERE {} = {shown}",
355                table_name(ctx, &graph, &v.table),
356                name(&v.key)
357            )),
358            columns,
359            rows,
360            row: None,
361            note: None,
362            indexed: false,
363        };
364        if !found.rows.is_empty() {
365            return Ok(found);
366        }
367        first.get_or_insert(found);
368    }
369    let mut none = first.expect("there is a table");
370    none.note = Some(format!(
371        "no row of {} has the key {key}: the node is named only by an edge",
372        none.table.as_deref().unwrap_or_default()
373    ));
374    Ok(none)
375}
376
377async fn inspect_edge(
378    ctx: &SessionContext,
379    run: &dyn RunSql,
380    result: &GraphResult,
381    edge: usize,
382) -> Result<Inspected> {
383    let graph = match graph_of(ctx, result) {
384        Ok(graph) => graph,
385        Err(note) => return Ok(Inspected::said(note)),
386    };
387    if super::groups::is_group(result, result.src()[edge] as usize) {
388        return Ok(Inspected::said(format!(
389            "the edges of {} between two groups, counted: not one row of its tables",
390            graph.name
391        )));
392    }
393    let label = &result.edge_labels()[result.edge_label()[edge] as usize];
394    let row = result.edge_row(edge);
395    let end = |node: u32| {
396        let at = node as usize;
397        let ty = result.node_labels()[result.node_label()[at] as usize].key;
398        (
399            result.node_keys().get(at),
400            literal(result.node_keys().get(at), ty),
401        )
402    };
403    let (s_key, (s, s_shown)) = end(result.src()[edge]);
404    let (d_key, (d, d_shown)) = end(result.dst()[edge]);
405    let tables: Vec<_> = graph
406        .edge_tables
407        .iter()
408        .filter(|e| label.is_empty() || &e.name == label)
409        .collect();
410    if tables.is_empty() {
411        return Ok(Inspected::said(format!(
412            "the graph {} has no edge table '{label}'",
413            graph.name
414        )));
415    }
416    let mut first = None;
417    for e in tables {
418        let (source, destination) = (ident(&e.source), ident(&e.destination));
419        let table = table_name(ctx, &graph, &e.table);
420        let (from, to) = (name(&e.source), name(&e.destination));
421        let mut filter = source
422            .clone()
423            .eq(s.clone())
424            .and(destination.clone().eq(d.clone()));
425        let mut sql =
426            format!("SELECT * FROM {table} WHERE {from} = {s_shown} AND {to} = {d_shown}");
427        // With no row number, the drawing may have it the other way round.
428        let either_way = row.is_none() && s_shown != d_shown;
429        if either_way {
430            filter = filter.or(source.eq(d.clone()).and(destination.eq(s.clone())));
431            sql = format!(
432                "SELECT * FROM {table} WHERE ({from} = {s_shown} AND {to} = {d_shown}) OR \
433                 ({from} = {d_shown} AND {to} = {s_shown})"
434            );
435        }
436        // Through the index, where it finds them; else by a scan.
437        let ends = Ends {
438            literals: [&s_shown, &d_shown],
439            keys: [s_key, d_key],
440            either_way,
441        };
442        // (With the rows' numbers, when the index gave them.)
443        let (numbers, (columns, rows)) = match between(ctx, run, &graph, e, &ends).await {
444            Some((numbers, found)) => (Some(numbers), found),
445            None => (
446                None,
447                read(ctx, &graph, &e.table, Some(filter), 0, MAX_ROWS + 1).await?,
448            ),
449        };
450        let mut found = Inspected {
451            table: Some(e.name.clone()),
452            sql: Some(sql),
453            columns,
454            rows,
455            row,
456            note: None,
457            indexed: numbers.is_some(),
458        };
459        if found.rows.len() > 1 {
460            // Parallel edges: the one row, where its number finds it.
461            // Among those the index found, else read by its number.
462            let among = |row: u64| numbers.as_ref()?.iter().position(|&n| n == row);
463            let one = match row {
464                Some(row) => match among(row) {
465                    Some(i) => Some((row, vec![found.rows[i].clone()])),
466                    None => read_rows(ctx, &graph, &e.table, &[row])
467                        .await?
468                        .filter(|(_, rows)| !rows.is_empty())
469                        .map(|(_, rows)| (row, rows)),
470                },
471                None => None,
472            };
473            match one {
474                Some((row, rows)) => {
475                    found.rows = rows;
476                    found.sql = Some(format!("SELECT * FROM {table} LIMIT 1 OFFSET {row}"));
477                }
478                None => {
479                    let more = found.rows.len() > MAX_ROWS;
480                    found.rows.truncate(MAX_ROWS);
481                    found.note = Some(format!(
482                        "{}{} rows of {} join these two nodes; the drawing does not say which \
483                         this edge is",
484                        if more { "more than " } else { "" },
485                        found.rows.len(),
486                        e.name
487                    ));
488                }
489            }
490        }
491        if !found.rows.is_empty() {
492            return Ok(found);
493        }
494        first.get_or_insert(found);
495    }
496    let mut none = first.expect("there is a table");
497    none.note = Some(format!(
498        "no row of {} joins these two nodes: the edge is not the graph's (a query made it)",
499        none.table.as_deref().unwrap_or_default()
500    ));
501    Ok(none)
502}
503
504/// The two ends of an edge, to find its rows by.
505struct Ends<'a> {
506    /// The ends as SQL literals, source first.
507    literals: [&'a str; 2],
508    /// The ends as the drawing's keys: how a value of the table prints.
509    keys: [&'a str; 2],
510    /// Whether a row from the second end to the first is the edge's too.
511    either_way: bool,
512}
513
514impl Ends<'_> {
515    /// Whether a row from `src` to `dst` (as they print) joins the ends.
516    fn joins(&self, src: Option<&str>, dst: Option<&str>) -> bool {
517        let [s, d] = self.keys.map(Some);
518        (src, dst) == (s, d) || (self.either_way && (src, dst) == (d, s))
519    }
520}
521
522/// The rows of the edge table `e` between `ends`, found through the graph's
523/// index: the first `MAX_ROWS + 1` of them in the table's order, which is
524/// what the scan by the two ends gives, with their row numbers. A table of
525/// the two key columns alone is not read: its rows are the ends. `None` when
526/// the index cannot say, and the scan must: the graph has several edge
527/// tables (an index is of one), the index has no edge between the ends, the
528/// table is read as several partitions, or a row read by its number does
529/// not join the ends.
530async fn between(
531    ctx: &SessionContext,
532    run: &dyn RunSql,
533    graph: &PropertyGraph,
534    e: &crate::graph::EdgeTable,
535    ends: &Ends<'_>,
536) -> Option<(Vec<u64>, (Vec<InspectedColumn>, Vec<Vec<Option<String>>>))> {
537    if graph.pair(None, None).ok()?.edges.name != e.name {
538        return None;
539    }
540    let [s, d] = ends.literals;
541    let (_, batches) = run
542        .run(
543            ctx,
544            &format!(
545                "SELECT src, dst, edge FROM induced_edges(\"{}\", nodes => [{s}, {d}])",
546                graph.name.replace('"', "\"\"")
547            ),
548        )
549        .await
550        .ok()?;
551    // The edges among the two nodes, by row: those between them (not a loop
552    // at one end), the way the drawing has them, with their ends as text.
553    let mut rows = Vec::new();
554    for batch in &batches {
555        let number = cast(batch.column(2), &DataType::UInt64).ok()?;
556        let number = number.as_primitive::<UInt64Type>();
557        let shown = rows_of(std::slice::from_ref(&batch.project(&[0, 1]).ok()?)).ok()?;
558        for (i, ends_of) in shown.into_iter().enumerate() {
559            if number.is_valid(i) && ends.joins(ends_of[0].as_deref(), ends_of[1].as_deref()) {
560                let ends_of: [Option<String>; 2] = ends_of.try_into().ok()?;
561                rows.push((number.value(i), ends_of));
562            }
563        }
564    }
565    rows.sort_unstable_by_key(|(row, _)| *row);
566    rows.dedup_by_key(|(row, _)| *row);
567    rows.truncate(MAX_ROWS + 1);
568    if rows.is_empty() {
569        return None;
570    }
571    // A table of the two keys alone: its rows are the ends the index gave,
572    // and there is nothing more to read.
573    let frame = scan(ctx, graph, &e.table).await.ok()?;
574    let columns = columns_of(&frame);
575    let at = |name: &str| columns.iter().position(|c| c.name == name);
576    let (src, dst) = (at(&e.source)?, at(&e.destination)?);
577    let numbers: Vec<u64> = rows.iter().map(|(row, _)| *row).collect();
578    if columns.len() == 2 && src != dst {
579        let found = rows
580            .into_iter()
581            .map(|(_, [s, d])| if src == 0 { vec![s, d] } else { vec![d, s] })
582            .collect();
583        return Some((numbers, (columns, found)));
584    }
585    let found = rows_of(&take(ctx, frame, &numbers).await.ok()??).ok()?;
586    // The rows read are the rows asked for: each joins the two ends.
587    let all = found.len() == numbers.len()
588        && found
589            .iter()
590            .all(|row| ends.joins(row[src].as_deref(), row[dst].as_deref()));
591    all.then_some((numbers, (columns, found)))
592}
593
594/// How many neighbours node `node` has in the whole graph `result` names,
595/// whichever way the edges run: `SELECT count(*) FROM hop(G, seeds => [key],
596/// steps => 1, direction => 'both')`, run by `sql`. It reads the node's edges
597/// from the graph's index, not every edge, so it costs what the node's degree
598/// does. On a graph with no parallel edges and no loops it is the node's
599/// degree. `None` when the drawing names no graph.
600pub async fn graph_neighbours(
601    ctx: &SessionContext,
602    sql: &dyn RunSql,
603    result: &GraphResult,
604    node: u32,
605) -> Result<Option<u64>> {
606    let at = node as usize;
607    let Some(graph) = result.graph() else {
608        return Ok(None);
609    };
610    if at >= result.n_nodes() {
611        return plan_err(format!("the drawing has no node {node}"));
612    }
613    // A group is no node of the graph.
614    if super::groups::is_group(result, at) {
615        return Ok(None);
616    }
617    let ty = result.node_labels()[result.node_label()[at] as usize].key;
618    let (_, key) = literal(result.node_keys().get(at), ty);
619    let (_, batches) = sql
620        .run(
621            ctx,
622            &format!(
623                "SELECT count(*) FROM hop(\"{}\", seeds => [{key}], steps => 1, direction => 'both')",
624                graph.replace('"', "\"\"")
625            ),
626        )
627        .await?;
628    for batch in &batches {
629        if batch.num_rows() > 0 {
630            let count = cast(batch.column(0), &DataType::UInt64)?;
631            let count = count.as_primitive::<UInt64Type>();
632            return Ok(count.is_valid(0).then(|| count.value(0)));
633        }
634    }
635    Ok(None)
636}