Skip to main content

ursa_viz/model/
result.rs

1//! [`GraphResult`]: the nodes, edges, highlights and provenance of one result.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::hash::{BuildHasher, RandomState};
6
7use hashbrown::HashTable;
8
9use serde::{Deserialize, Serialize};
10
11use crate::pace::{ready, Pace};
12
13/// How many nodes, and how many edges, a paced check reads between two
14/// chances to give the thread up: a few milliseconds of work each.
15const PACED_NODES: usize = 1 << 13;
16const PACED_EDGES: usize = 1 << 18;
17
18/// The null of a `u32` column and of a dictionary column's codes.
19pub const NULL: u32 = u32::MAX;
20
21/// An edge whose row in its edge table the engine does not know.
22pub const NO_ROW: u64 = u64::MAX;
23
24/// A broken invariant of the model, or a delta that does not fit the result
25/// it was applied to. The message says which.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct ModelError(pub(crate) String);
28
29impl fmt::Display for ModelError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        f.write_str(&self.0)
32    }
33}
34
35impl std::error::Error for ModelError {}
36
37pub(crate) fn err<T>(message: impl Into<String>) -> Result<T, ModelError> {
38    Err(ModelError(message.into()))
39}
40
41/// A node's key in its vertex table.
42#[derive(Debug, Clone, PartialEq, Eq, Hash)]
43pub enum Key {
44    Int(i64),
45    Text(String),
46}
47
48impl Key {
49    /// Read `text` as a key of type `ty`. An integer key's text is its
50    /// canonical decimal form: `"7"`, never `"+7"` or `"07"`.
51    pub fn parse(ty: KeyType, text: &str) -> Result<Self, ModelError> {
52        match ty {
53            KeyType::Text => Ok(Key::Text(text.to_string())),
54            KeyType::Int => match text.parse::<i64>() {
55                Ok(v) if v.to_string() == text => Ok(Key::Int(v)),
56                _ => err(format!("the key '{text}' is not an integer")),
57            },
58        }
59    }
60
61    /// Whether `text` is a key of type `ty` ([`Key::parse`]), without
62    /// making one.
63    pub fn check(ty: KeyType, text: &str) -> Result<(), ModelError> {
64        match ty {
65            KeyType::Text => Ok(()),
66            KeyType::Int => Key::parse(ty, text).map(|_| ()),
67        }
68    }
69
70    pub fn key_type(&self) -> KeyType {
71        match self {
72            Key::Int(_) => KeyType::Int,
73            Key::Text(_) => KeyType::Text,
74        }
75    }
76}
77
78impl fmt::Display for Key {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            Key::Int(v) => write!(f, "{v}"),
82            Key::Text(v) => f.write_str(v),
83        }
84    }
85}
86
87impl From<i64> for Key {
88    fn from(v: i64) -> Self {
89        Key::Int(v)
90    }
91}
92
93impl From<&str> for Key {
94    fn from(v: &str) -> Self {
95        Key::Text(v.to_string())
96    }
97}
98
99impl From<String> for Key {
100    fn from(v: String) -> Self {
101        Key::Text(v)
102    }
103}
104
105/// The type of a vertex table's key column.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
107#[serde(rename_all = "snake_case")]
108pub enum KeyType {
109    Int,
110    Text,
111}
112
113/// A vertex table: its name, and the type of its keys. A result that is not
114/// part of a property graph has one label, named `""`.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct NodeLabel {
117    pub name: String,
118    pub key: KeyType,
119}
120
121impl NodeLabel {
122    pub fn new(name: impl Into<String>, key: KeyType) -> Self {
123        Self {
124            name: name.into(),
125            key,
126        }
127    }
128}
129
130/// What a column is, as the engine's `ursa.role` field metadata says it
131/// (design §3). A column of a result is usually a `Metric`, a `Category`, a
132/// `Property` or a `Distance`.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
134#[serde(rename_all = "snake_case")]
135pub enum Role {
136    Node,
137    Src,
138    Dst,
139    Seed,
140    Distance,
141    PathNodes,
142    PathEdges,
143    PathElements,
144    Metric,
145    Category,
146    Property,
147}
148
149/// Strings stored as the wire format stores them: one run of UTF-8 and the
150/// offset of each string's start, plus the end of the last.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct Strings {
153    pub(crate) offsets: Vec<u32>,
154    pub(crate) bytes: Vec<u8>,
155}
156
157impl Default for Strings {
158    fn default() -> Self {
159        Self {
160            offsets: vec![0],
161            bytes: Vec::new(),
162        }
163    }
164}
165
166impl Strings {
167    pub fn new() -> Self {
168        Self::default()
169    }
170
171    /// From the wire's two arrays: `len + 1` offsets, rising from 0 to
172    /// `bytes.len()`, each on a character boundary of valid UTF-8.
173    pub fn from_parts(offsets: Vec<u32>, bytes: Vec<u8>) -> Result<Self, ModelError> {
174        let Ok(text) = std::str::from_utf8(&bytes) else {
175            return err("the text is not UTF-8");
176        };
177        if offsets.first() != Some(&0) || offsets.last().map(|&o| o as usize) != Some(bytes.len()) {
178            return err("the text's offsets do not run from 0 to its length");
179        }
180        for pair in offsets.windows(2) {
181            if pair[0] > pair[1] || !text.is_char_boundary(pair[1] as usize) {
182                return err("the text's offsets do not rise, or split a character");
183            }
184        }
185        Ok(Self { offsets, bytes })
186    }
187
188    pub fn len(&self) -> usize {
189        self.offsets.len() - 1
190    }
191
192    /// Room for `count` more strings of `bytes` bytes in all.
193    pub fn reserve(&mut self, count: usize, bytes: usize) {
194        self.offsets.reserve(count);
195        self.bytes.reserve(bytes);
196    }
197
198    pub fn is_empty(&self) -> bool {
199        self.len() == 0
200    }
201
202    /// Panics past 4 GiB of text, which the format's `u32` offsets cannot
203    /// address.
204    pub fn push(&mut self, text: &str) {
205        self.bytes.extend_from_slice(text.as_bytes());
206        let end = u32::try_from(self.bytes.len()).expect("more than 4 GiB of text");
207        self.offsets.push(end);
208    }
209
210    pub fn get(&self, i: usize) -> &str {
211        let range = self.offsets[i] as usize..self.offsets[i + 1] as usize;
212        // Checked when built: `push` takes a `&str`, `from_parts` validates.
213        std::str::from_utf8(&self.bytes[range]).expect("Strings holds UTF-8")
214    }
215
216    pub fn iter(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
217        (0..self.len()).map(|i| self.get(i))
218    }
219
220    pub fn truncate(&mut self, len: usize) {
221        if len < self.len() {
222            self.offsets.truncate(len + 1);
223            self.bytes.truncate(self.offsets[len] as usize);
224        }
225    }
226
227    pub(crate) fn extend(&mut self, other: &Strings) {
228        for text in other.iter() {
229            self.push(text);
230        }
231    }
232
233    /// Whether the last `tail.len()` strings are `tail`'s.
234    pub(crate) fn ends_with(&self, tail: &Strings) -> bool {
235        let Some(start) = self.len().checked_sub(tail.len()) else {
236            return false;
237        };
238        self.bytes[self.offsets[start] as usize..] == tail.bytes[..]
239            && (0..tail.len()).all(|i| self.get(start + i).len() == tail.get(i).len())
240    }
241
242    /// The offsets and the UTF-8, as the wire format writes them.
243    pub fn parts(&self) -> (&[u32], &[u8]) {
244        (&self.offsets, &self.bytes)
245    }
246}
247
248impl<S: AsRef<str>> FromIterator<S> for Strings {
249    fn from_iter<I: IntoIterator<Item = S>>(iter: I) -> Self {
250        let mut out = Strings::new();
251        for text in iter {
252            out.push(text.as_ref());
253        }
254        out
255    }
256}
257
258/// A column's values, one per node or per edge.
259///
260/// Nulls: NaN in `F32`, [`NULL`] in `U32` and in a dictionary's codes.
261/// Two columns are equal when their bits are, so a NaN equals itself.
262#[derive(Debug, Clone)]
263pub enum Values {
264    F32(Vec<f32>),
265    U32(Vec<u32>),
266    /// Text, as codes into the distinct values.
267    Dict {
268        values: Strings,
269        codes: Vec<u32>,
270    },
271}
272
273pub(crate) fn bits_eq(a: &[f32], b: &[f32]) -> bool {
274    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
275}
276
277impl PartialEq for Values {
278    fn eq(&self, other: &Self) -> bool {
279        match (self, other) {
280            (Values::F32(a), Values::F32(b)) => bits_eq(a, b),
281            (Values::U32(a), Values::U32(b)) => a == b,
282            (
283                Values::Dict { values, codes },
284                Values::Dict {
285                    values: v,
286                    codes: c,
287                },
288            ) => values == v && codes == c,
289            _ => false,
290        }
291    }
292}
293
294impl Values {
295    /// A dictionary column from text, `None` for null. The values are in
296    /// order of first appearance.
297    pub fn dict<'a>(texts: impl IntoIterator<Item = Option<&'a str>>) -> Self {
298        let mut values = Strings::new();
299        let mut seen: HashMap<&str, u32> = HashMap::new();
300        let mut codes = Vec::new();
301        for text in texts {
302            codes.push(match text {
303                None => NULL,
304                Some(text) => *seen.entry(text).or_insert_with(|| {
305                    values.push(text);
306                    values.len() as u32 - 1
307                }),
308            });
309        }
310        Values::Dict { values, codes }
311    }
312
313    pub fn len(&self) -> usize {
314        match self {
315            Values::F32(v) => v.len(),
316            Values::U32(v) => v.len(),
317            Values::Dict { codes, .. } => codes.len(),
318        }
319    }
320
321    pub fn is_empty(&self) -> bool {
322        self.len() == 0
323    }
324
325    /// `"f32"`, `"u32"` or `"dict"`: the wire format's name of the type.
326    pub fn type_name(&self) -> &'static str {
327        match self {
328            Values::F32(_) => "f32",
329            Values::U32(_) => "u32",
330            Values::Dict { .. } => "dict",
331        }
332    }
333
334    /// Row `i` of a dictionary column as text; `None` for a null and for
335    /// the other types.
336    pub fn text(&self, i: usize) -> Option<&str> {
337        match self {
338            Values::Dict { values, codes } if codes[i] != NULL => {
339                Some(values.get(codes[i] as usize))
340            }
341            _ => None,
342        }
343    }
344
345    pub(crate) fn check(&self, len: usize, what: &str) -> Result<(), ModelError> {
346        if self.len() != len {
347            return err(format!("{what} has {} values, for {len} rows", self.len()));
348        }
349        if let Values::Dict { values, codes } = self {
350            check_codes(codes, values.len(), what)?;
351        }
352        Ok(())
353    }
354}
355
356fn check_codes(codes: &[u32], n_values: usize, what: &str) -> Result<(), ModelError> {
357    match codes.iter().find(|&&c| c != NULL && c as usize >= n_values) {
358        Some(code) => err(format!(
359            "{what} has the code {code}, but only {n_values} values"
360        )),
361        None => Ok(()),
362    }
363}
364
365/// `(label, key)` → node, for the nodes of a result.
366///
367/// It is a table of node indexes, hashed and compared by the label and the
368/// key text that the result already holds: four bytes and a control byte a
369/// node, where a map from the keys themselves would hold every key a second
370/// time (60 bytes a node, and three megabytes of a 46,318-node result).
371/// The price is that every call is given the result's keys and labels.
372#[derive(Debug, Clone, Default)]
373pub(crate) struct KeyIndex {
374    nodes: HashTable<u32>,
375    hasher: RandomState,
376}
377
378impl KeyIndex {
379    fn hash(&self, label: u16, key: &str) -> u64 {
380        self.hasher.hash_one((label, key))
381    }
382
383    /// The node of `label` with the key `key`, as text.
384    pub(crate) fn get(&self, keys: &Strings, labels: &[u16], label: u16, key: &str) -> Option<u32> {
385        let same = |&i: &u32| labels[i as usize] == label && keys.get(i as usize) == key;
386        self.nodes.find(self.hash(label, key), same).copied()
387    }
388
389    /// Add node `i`, whose key and label are in `keys` and `labels`; or, if
390    /// another node has its identity, add nothing and say which.
391    pub(crate) fn insert(&mut self, keys: &Strings, labels: &[u16], i: u32) -> Option<u32> {
392        let (label, key) = (labels[i as usize], keys.get(i as usize));
393        if let Some(first) = self.get(keys, labels, label, key) {
394            return Some(first);
395        }
396        let hasher = &self.hasher;
397        let rehash = |&j: &u32| hasher.hash_one((labels[j as usize], keys.get(j as usize)));
398        self.nodes
399            .insert_unique(hasher.hash_one((label, key)), i, rehash);
400        None
401    }
402
403    /// Take node `i` out, while `keys` and `labels` still have it.
404    pub(crate) fn remove(&mut self, keys: &Strings, labels: &[u16], i: u32) {
405        let hash = self.hash(labels[i as usize], keys.get(i as usize));
406        if let Ok(entry) = self.nodes.find_entry(hash, |&j| j == i) {
407            entry.remove();
408        }
409    }
410
411    /// Room for `more` nodes.
412    pub(crate) fn reserve(&mut self, keys: &Strings, labels: &[u16], more: usize) {
413        let hasher = &self.hasher;
414        let rehash = |&j: &u32| hasher.hash_one((labels[j as usize], keys.get(j as usize)));
415        self.nodes.reserve(more, rehash);
416    }
417
418    pub(crate) fn clear(&mut self) {
419        self.nodes.clear();
420    }
421
422    pub(crate) fn len(&self) -> usize {
423        self.nodes.len()
424    }
425
426    /// The nodes it holds, in index order.
427    pub(crate) fn nodes(&self) -> Vec<u32> {
428        let mut nodes: Vec<u32> = self.nodes.iter().copied().collect();
429        nodes.sort_unstable();
430        nodes
431    }
432}
433
434/// Equal when they hold the same nodes: of results that are equal, the same
435/// index.
436impl PartialEq for KeyIndex {
437    fn eq(&self, other: &Self) -> bool {
438        self.len() == other.len() && self.nodes() == other.nodes()
439    }
440}
441
442/// A small number per slot that is zero in most results: an edge's label
443/// where there is one edge table, its flags where none is removed. While
444/// every one is zero nothing is held for them, as the wire format writes
445/// nothing: at a million edges that is three megabytes a result does not
446/// take. Two are equal when their values are, held or not.
447#[derive(Debug, Clone, Default)]
448pub struct Sparse<T> {
449    len: usize,
450    /// One per slot, or empty while every one is zero.
451    data: Vec<T>,
452}
453
454impl<T: Copy + Default + PartialEq> Sparse<T> {
455    /// `len` zeros.
456    pub fn zeros(len: usize) -> Self {
457        Self {
458            len,
459            data: Vec::new(),
460        }
461    }
462
463    /// One value per slot. The vector is dropped if every one is zero.
464    pub fn from_vec(data: Vec<T>) -> Self {
465        let zero = T::default();
466        if data.iter().all(|v| *v == zero) {
467            Self::zeros(data.len())
468        } else {
469            Self {
470                len: data.len(),
471                data,
472            }
473        }
474    }
475
476    pub fn len(&self) -> usize {
477        self.len
478    }
479
480    pub fn is_empty(&self) -> bool {
481        self.len == 0
482    }
483
484    /// The values as a slice; `None` while nothing is held for them, when
485    /// every one is zero.
486    pub fn as_slice(&self) -> Option<&[T]> {
487        (!self.data.is_empty()).then_some(&self.data[..])
488    }
489
490    /// Slot `i`'s value. Panics past the last slot.
491    pub fn get(&self, i: usize) -> T {
492        assert!(i < self.len, "slot {i} of {}", self.len);
493        self.data.get(i).copied().unwrap_or_default()
494    }
495
496    pub fn iter(&self) -> impl ExactSizeIterator<Item = T> + '_ {
497        (0..self.len).map(|i| self.data.get(i).copied().unwrap_or_default())
498    }
499
500    pub fn to_vec(&self) -> Vec<T> {
501        match self.as_slice() {
502            Some(data) => data.to_vec(),
503            None => vec![T::default(); self.len],
504        }
505    }
506
507    pub fn contains(&self, value: &T) -> bool {
508        match self.as_slice() {
509            Some(data) => data.contains(value),
510            None => self.len > 0 && *value == T::default(),
511        }
512    }
513
514    /// Whether the slots from `from` on hold `tail`.
515    pub(crate) fn ends_with(&self, from: usize, tail: &[T]) -> bool {
516        match self.as_slice() {
517            Some(data) => data[from..] == *tail,
518            None => self.len - from == tail.len() && tail.iter().all(|v| *v == T::default()),
519        }
520    }
521
522    /// Whether any slot from `from` on is not zero.
523    pub(crate) fn any_from(&self, from: usize) -> bool {
524        self.as_slice()
525            .is_some_and(|data| data[from..].iter().any(|v| *v != T::default()))
526    }
527
528    /// The values held, one per slot: to change one.
529    pub(crate) fn make_mut(&mut self) -> &mut [T] {
530        if self.data.is_empty() {
531            self.data = vec![T::default(); self.len];
532        }
533        &mut self.data
534    }
535
536    pub(crate) fn extend_from_slice(&mut self, more: &[T]) {
537        let held = !self.data.is_empty();
538        if held || more.iter().any(|v| *v != T::default()) {
539            if !held {
540                // The zeros so far, and then the first that is not.
541                self.data = Vec::with_capacity(self.len + more.len());
542                self.data.resize(self.len, T::default());
543            }
544            self.data.extend_from_slice(more);
545        }
546        self.len += more.len();
547    }
548
549    pub(crate) fn extend_zeros(&mut self, more: usize) {
550        self.len += more;
551        if !self.data.is_empty() {
552            self.data.resize(self.len, T::default());
553        }
554    }
555
556    pub(crate) fn truncate(&mut self, len: usize) {
557        self.len = self.len.min(len);
558        self.data.truncate(len);
559    }
560
561    pub(crate) fn reserve(&mut self, more: usize) {
562        if !self.data.is_empty() {
563            self.data.reserve_exact(more);
564        }
565    }
566}
567
568impl<T: Copy + Default + PartialEq> PartialEq for Sparse<T> {
569    fn eq(&self, other: &Self) -> bool {
570        self.len == other.len
571            && match (self.as_slice(), other.as_slice()) {
572                (Some(a), Some(b)) => a == b,
573                (Some(held), None) | (None, Some(held)) => held.iter().all(|v| *v == T::default()),
574                (None, None) => true,
575            }
576    }
577}
578
579impl<T: Copy + Default + PartialEq> PartialEq<[T]> for Sparse<T> {
580    fn eq(&self, other: &[T]) -> bool {
581        self.len == other.len() && self.ends_with(0, other)
582    }
583}
584
585macro_rules! sparse_index {
586    ($($t:ty),*) => {$(
587        impl std::ops::Index<usize> for Sparse<$t> {
588            type Output = $t;
589            /// Slot `i`'s value. Panics past the last slot.
590            fn index(&self, i: usize) -> &$t {
591                static ZERO: $t = 0;
592                assert!(i < self.len, "slot {i} of {}", self.len);
593                self.data.get(i).unwrap_or(&ZERO)
594            }
595        }
596    )*};
597}
598sparse_index!(u8, u16);
599
600/// A named column of the nodes or of the edges: a property or a metric.
601#[derive(Debug, Clone, PartialEq)]
602pub struct Column {
603    pub name: String,
604    pub role: Option<Role>,
605    pub values: Values,
606}
607
608impl Column {
609    pub fn new(name: impl Into<String>, role: Option<Role>, values: Values) -> Self {
610        Self {
611            name: name.into(),
612            role,
613            values,
614        }
615    }
616}
617
618/// Whether a column belongs to the nodes or to the edges.
619#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
620#[serde(rename_all = "snake_case")]
621pub enum Target {
622    Nodes,
623    Edges,
624}
625
626/// A place per node. Equal when the bits are.
627#[derive(Debug, Clone, Default)]
628pub struct Positions {
629    pub x: Vec<f32>,
630    pub y: Vec<f32>,
631}
632
633impl PartialEq for Positions {
634    fn eq(&self, other: &Self) -> bool {
635        bits_eq(&self.x, &other.x) && bits_eq(&self.y, &other.y)
636    }
637}
638
639/// A path: its nodes in order, and the edge between each two. `edges` is
640/// empty when the result names only the nodes.
641#[derive(Debug, Clone, Default, PartialEq, Eq)]
642pub struct Path {
643    pub nodes: Vec<u32>,
644    pub edges: Vec<u32>,
645}
646
647/// What a result points at: paths, seeds, and each node's distance from the
648/// seeds.
649#[derive(Debug, Clone, Default, PartialEq, Eq)]
650pub struct Highlights {
651    pub paths: Vec<Path>,
652    pub seeds: Vec<u32>,
653    /// The `u32` node column that holds the distances ([`NULL`]: not
654    /// reached). A column, so that it grows with the nodes like any other.
655    pub distance: Option<String>,
656}
657
658impl Highlights {
659    pub fn is_empty(&self) -> bool {
660        self.paths.is_empty() && self.seeds.is_empty() && self.distance.is_none()
661    }
662}
663
664/// The layout a result asks for.
665#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
666#[serde(rename_all = "snake_case")]
667pub enum Layout {
668    #[default]
669    Force,
670    Rings,
671    Layers,
672}
673
674/// How columns are drawn. Each names a node column.
675#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
676pub struct Encodings {
677    /// An `f32` or `u32` column.
678    pub size_by: Option<String>,
679    pub color_by: Option<String>,
680    pub group_by: Option<String>,
681    pub layout: Layout,
682}
683
684/// Where a result, or a delta, came from.
685#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
686pub struct Provenance {
687    /// The SQL that produced it.
688    pub sql: Option<String>,
689    /// The result → graph rule that fired (`"path"`, `"rings"`, `"edges"`, …).
690    pub rule: Option<String>,
691    /// The columns of the SQL's result that the rule read, and what each
692    /// was read as. Left out of the wire format when empty.
693    #[serde(default, skip_serializing_if = "Vec::is_empty")]
694    pub roles: Vec<ColumnRole>,
695    /// What a status line adds to the rule: what was left out, and what else
696    /// the result could have been drawn as. Left out when empty.
697    #[serde(default, skip_serializing_if = "Vec::is_empty")]
698    pub notes: Vec<String>,
699}
700
701/// A column of a result, and what a rule read it as: the engine's
702/// `ursa.role` (`"node"`, `"src"`, `"path_nodes"`, `"step"`, …).
703#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
704pub struct ColumnRole {
705    pub column: String,
706    pub role: String,
707}
708
709impl ColumnRole {
710    pub fn new(column: impl Into<String>, role: impl Into<String>) -> Self {
711        Self {
712            column: column.into(),
713            role: role.into(),
714        }
715    }
716}
717
718/// Flag bit: the node or edge was removed. It keeps its slot and its data,
719/// so every index stays valid and restoring it needs nothing else.
720pub const REMOVED: u8 = 1;
721
722/// Nodes, edges, highlights, and where they came from: everything drawn.
723///
724/// See the [module docs](super) for the invariants. A result is built and
725/// changed only by [`apply`](GraphResult::apply)ing deltas, and read through
726/// the accessors here.
727#[derive(Debug, Clone, Default)]
728pub struct GraphResult {
729    pub(crate) graph: Option<String>,
730    pub(crate) node_labels: Vec<NodeLabel>,
731    pub(crate) edge_labels: Vec<String>,
732
733    pub(crate) node_keys: Strings,
734    pub(crate) node_label: Vec<u16>,
735    pub(crate) node_flags: Vec<u8>,
736    pub(crate) node_columns: Vec<Column>,
737    pub(crate) positions: Option<Positions>,
738
739    pub(crate) src: Vec<u32>,
740    pub(crate) dst: Vec<u32>,
741    pub(crate) edge_label: Sparse<u16>,
742    /// `None` when no edge's row is known; else one per edge, [`NO_ROW`]
743    /// for the unknown, and never all of them unknown.
744    pub(crate) edge_rows: Option<Vec<u64>>,
745    pub(crate) edge_flags: Sparse<u8>,
746    pub(crate) edge_columns: Vec<Column>,
747
748    pub(crate) highlights: Highlights,
749    pub(crate) encodings: Encodings,
750    pub(crate) provenance: Provenance,
751
752    /// `(label, key)` → node index. Derived from the keys and labels.
753    pub(crate) index: KeyIndex,
754    /// The greatest node index the edges name, as it rises along them:
755    /// `(edge, node)` for each edge that names a node past every earlier
756    /// edge's. Derived from the edges. Its last entry says whether an edge
757    /// still names one of the last nodes, without reading the edges, so
758    /// taking nodes off the end costs what they hold.
759    pub(crate) named: Vec<(u32, u32)>,
760}
761
762impl PartialEq for GraphResult {
763    fn eq(&self, other: &Self) -> bool {
764        // All but `index` and `named`, which the rest determines.
765        self.graph == other.graph
766            && self.node_labels == other.node_labels
767            && self.edge_labels == other.edge_labels
768            && self.node_keys == other.node_keys
769            && self.node_label == other.node_label
770            && self.node_flags == other.node_flags
771            && self.node_columns == other.node_columns
772            && self.positions == other.positions
773            && self.src == other.src
774            && self.dst == other.dst
775            && self.edge_label == other.edge_label
776            && self.edge_rows == other.edge_rows
777            && self.edge_flags == other.edge_flags
778            && self.edge_columns == other.edge_columns
779            && self.highlights == other.highlights
780            && self.encodings == other.encodings
781            && self.provenance == other.provenance
782    }
783}
784
785impl GraphResult {
786    /// An empty result: no labels, nodes or edges. `graph` is the property
787    /// graph it is part of, if any.
788    pub fn new(graph: Option<String>, provenance: Provenance) -> Self {
789        Self {
790            graph,
791            provenance,
792            ..Self::default()
793        }
794    }
795
796    /// The property graph this is part of.
797    pub fn graph(&self) -> Option<&str> {
798        self.graph.as_deref()
799    }
800
801    pub fn provenance(&self) -> &Provenance {
802        &self.provenance
803    }
804
805    pub fn encodings(&self) -> &Encodings {
806        &self.encodings
807    }
808
809    pub fn highlights(&self) -> &Highlights {
810        &self.highlights
811    }
812
813    // Nodes.
814
815    /// How many node slots there are, removed ones included.
816    pub fn n_nodes(&self) -> usize {
817        self.node_label.len()
818    }
819
820    pub fn node_labels(&self) -> &[NodeLabel] {
821        &self.node_labels
822    }
823
824    /// Each node's label, as an index into [`node_labels`](Self::node_labels).
825    pub fn node_label(&self) -> &[u16] {
826        &self.node_label
827    }
828
829    /// Every node's key as text.
830    pub fn node_keys(&self) -> &Strings {
831        &self.node_keys
832    }
833
834    /// Node `i`'s key, typed as its label's keys are.
835    pub fn node_key(&self, i: usize) -> Key {
836        let text = self.node_keys.get(i);
837        match self.node_labels[self.node_label[i] as usize].key {
838            KeyType::Text => Key::Text(text.to_string()),
839            // Checked when the node was added.
840            KeyType::Int => Key::Int(text.parse().expect("an integer key")),
841        }
842    }
843
844    /// The node with this identity, removed or not.
845    pub fn node(&self, label: u16, key: &Key) -> Option<u32> {
846        // A label's keys are all of one type, and an integer key's text is
847        // its decimal form.
848        if self.node_labels.get(label as usize)?.key != key.key_type() {
849            return None;
850        }
851        let text = key.to_string();
852        self.index
853            .get(&self.node_keys, &self.node_label, label, &text)
854    }
855
856    /// Each node's flags ([`REMOVED`]).
857    pub fn node_flags(&self) -> &[u8] {
858        &self.node_flags
859    }
860
861    pub fn node_is_removed(&self, i: usize) -> bool {
862        self.node_flags[i] & REMOVED != 0
863    }
864
865    pub fn node_columns(&self) -> &[Column] {
866        &self.node_columns
867    }
868
869    pub fn node_column(&self, name: &str) -> Option<&Column> {
870        self.node_columns.iter().find(|c| c.name == name)
871    }
872
873    pub fn positions(&self) -> Option<&Positions> {
874        self.positions.as_ref()
875    }
876
877    // Edges.
878
879    /// How many edge slots there are, removed ones included.
880    pub fn n_edges(&self) -> usize {
881        self.src.len()
882    }
883
884    pub fn edge_labels(&self) -> &[String] {
885        &self.edge_labels
886    }
887
888    pub fn src(&self) -> &[u32] {
889        &self.src
890    }
891
892    pub fn dst(&self) -> &[u32] {
893        &self.dst
894    }
895
896    /// Each edge's label, as an index into [`edge_labels`](Self::edge_labels).
897    pub fn edge_label(&self) -> &Sparse<u16> {
898        &self.edge_label
899    }
900
901    /// Edge `i`'s row in its edge table, where the engine knew it. With its
902    /// label, that is the edge's identity; without, the identity is its
903    /// endpoints and its place among their parallel edges.
904    pub fn edge_row(&self, i: usize) -> Option<u64> {
905        let row = self.edge_rows.as_ref().map_or(NO_ROW, |rows| rows[i]);
906        (row != NO_ROW).then_some(row)
907    }
908
909    /// Every edge's row ([`NO_ROW`] for the unknown), or `None` when none
910    /// is known.
911    pub fn edge_rows(&self) -> Option<&[u64]> {
912        self.edge_rows.as_deref()
913    }
914
915    /// Each edge's flags ([`REMOVED`]).
916    pub fn edge_flags(&self) -> &Sparse<u8> {
917        &self.edge_flags
918    }
919
920    /// Whether edge `i` is itself removed, whatever its ends are.
921    pub fn edge_is_removed(&self, i: usize) -> bool {
922        self.edge_flags.get(i) & REMOVED != 0
923    }
924
925    /// Whether edge `i` is to be drawn: it is not removed, and neither end
926    /// is. So removing a node hides its edges, and restoring it shows them.
927    pub fn edge_is_shown(&self, i: usize) -> bool {
928        !self.edge_is_removed(i)
929            && !self.node_is_removed(self.src[i] as usize)
930            && !self.node_is_removed(self.dst[i] as usize)
931    }
932
933    pub fn edge_columns(&self) -> &[Column] {
934        &self.edge_columns
935    }
936
937    pub fn edge_column(&self, name: &str) -> Option<&Column> {
938        self.edge_columns.iter().find(|c| c.name == name)
939    }
940
941    pub fn columns(&self, target: Target) -> &[Column] {
942        match target {
943            Target::Nodes => &self.node_columns,
944            Target::Edges => &self.edge_columns,
945        }
946    }
947
948    pub(crate) fn columns_mut(&mut self, target: Target) -> &mut Vec<Column> {
949        match target {
950            Target::Nodes => &mut self.node_columns,
951            Target::Edges => &mut self.edge_columns,
952        }
953    }
954
955    pub(crate) fn rows(&self, target: Target) -> usize {
956        match target {
957            Target::Nodes => self.n_nodes(),
958            Target::Edges => self.n_edges(),
959        }
960    }
961
962    /// Make room for `nodes` more nodes and `edges` more edges, so that a
963    /// delta that adds up to as many moves nothing the result holds: a view
964    /// that takes deltas does this once, when it is made, and not under the
965    /// first of them.
966    pub fn reserve(&mut self, nodes: usize, edges: usize) {
967        fn columns(columns: &mut [Column], more: usize) {
968            for column in columns {
969                match &mut column.values {
970                    Values::F32(v) => v.reserve_exact(more),
971                    Values::U32(v) | Values::Dict { codes: v, .. } => v.reserve_exact(more),
972                }
973            }
974        }
975        // A key is a few bytes of text.
976        self.node_keys.reserve(nodes, 8 * nodes);
977        self.node_label.reserve_exact(nodes);
978        self.node_flags.reserve_exact(nodes);
979        columns(&mut self.node_columns, nodes);
980        if let Some(p) = &mut self.positions {
981            p.x.reserve_exact(nodes);
982            p.y.reserve_exact(nodes);
983        }
984        self.index.reserve(&self.node_keys, &self.node_label, nodes);
985        // Exactly: `reserve` would double a full vector, eight megabytes of
986        // room at a million edges where a sixty-fourth was asked for.
987        self.src.reserve_exact(edges);
988        self.dst.reserve_exact(edges);
989        self.edge_label.reserve(edges);
990        self.edge_flags.reserve(edges);
991        if let Some(rows) = &mut self.edge_rows {
992            rows.reserve_exact(edges);
993        }
994        columns(&mut self.edge_columns, edges);
995    }
996
997    // Invariants.
998
999    /// Check every invariant, and rebuild the key index. `apply` keeps them,
1000    /// so this is for a result made another way: the wire format's decoder
1001    /// calls it.
1002    pub fn validate(&mut self) -> Result<(), ModelError> {
1003        ready(self.validate_paced(&mut Pace::never()))
1004    }
1005
1006    /// [`GraphResult::validate`], giving the event loop a turn as `pace`
1007    /// says between its passes over the nodes and the edges.
1008    pub(crate) async fn validate_paced(&mut self, pace: &mut Pace) -> Result<(), ModelError> {
1009        let n = self.n_nodes();
1010        let m = self.n_edges();
1011        if self.node_labels.len() > u16::MAX as usize || self.edge_labels.len() > u16::MAX as usize
1012        {
1013            return err("more labels than a u16 can number");
1014        }
1015        if n > NULL as usize || m > NULL as usize {
1016            return err("more nodes or edges than a u32 can number");
1017        }
1018        if self.node_keys.len() != n || self.node_flags.len() != n {
1019            return err(format!(
1020                "{n} nodes, but {} keys and {} flags",
1021                self.node_keys.len(),
1022                self.node_flags.len()
1023            ));
1024        }
1025        self.index.clear();
1026        self.index.reserve(&self.node_keys, &self.node_label, n);
1027        for i in 0..n {
1028            if i % PACED_NODES == PACED_NODES - 1 {
1029                pace.breathe().await;
1030            }
1031            let label = self.node_label[i];
1032            let Some(node_label) = self.node_labels.get(label as usize) else {
1033                return err(format!(
1034                    "node {i} has the label {label}, but the result has {} node labels",
1035                    self.node_labels.len()
1036                ));
1037            };
1038            Key::check(node_label.key, self.node_keys.get(i))
1039                .map_err(|e| ModelError(format!("node {i}: {e}")))?;
1040            let first = self
1041                .index
1042                .insert(&self.node_keys, &self.node_label, i as u32);
1043            if let Some(first) = first {
1044                return err(format!(
1045                    "nodes {first} and {i} are both '{}' of the label '{}'",
1046                    self.node_keys.get(i),
1047                    node_label.name
1048                ));
1049            }
1050        }
1051        if let Some(p) = &self.positions {
1052            if p.x.len() != n || p.y.len() != n {
1053                return err(format!(
1054                    "{n} nodes, but {} x and {} y positions",
1055                    p.x.len(),
1056                    p.y.len()
1057                ));
1058            }
1059        }
1060
1061        if self.dst.len() != m || self.edge_label.len() != m || self.edge_flags.len() != m {
1062            return err(format!(
1063                "{m} edges, but {} dst, {} labels and {} flags",
1064                self.dst.len(),
1065                self.edge_label.len(),
1066                self.edge_flags.len()
1067            ));
1068        }
1069        pace.breathe().await;
1070        let mut start = 0;
1071        while start < m {
1072            let end = m.min(start + PACED_EDGES);
1073            let label = self.edge_label.as_slice().map(|l| &l[start..end]);
1074            self.check_edges(
1075                &self.src[start..end],
1076                &self.dst[start..end],
1077                label,
1078                n,
1079                start,
1080            )?;
1081            start = end;
1082            pace.breathe().await;
1083        }
1084        self.named.clear();
1085        self.note_named(0);
1086        pace.breathe().await;
1087        if let Some(rows) = &self.edge_rows {
1088            if rows.len() != m {
1089                return err(format!("{m} edges, but {} rows", rows.len()));
1090            }
1091            if rows.iter().all(|&r| r == NO_ROW) {
1092                return err("the edges' rows are present, but none is known");
1093            }
1094        }
1095
1096        for target in [Target::Nodes, Target::Edges] {
1097            let columns = self.columns(target);
1098            for (i, column) in columns.iter().enumerate() {
1099                let what = format!("the {} column '{}'", target.noun(), column.name);
1100                column.values.check(self.rows(target), &what)?;
1101                if columns[..i].iter().any(|c| c.name == column.name) {
1102                    return err(format!("there are two of {what}"));
1103                }
1104            }
1105        }
1106        self.check_highlights(&self.highlights)?;
1107        self.check_encodings(&self.encodings)
1108    }
1109
1110    /// Note the nodes the edges from `first` on name, in `named`.
1111    pub(crate) fn note_named(&mut self, first: usize) {
1112        let mut top = self.named.last().map(|&(_, node)| node);
1113        for e in first..self.src.len() {
1114            let node = self.src[e].max(self.dst[e]);
1115            if top.is_none_or(|t| node > t) {
1116                self.named.push((e as u32, node));
1117                top = Some(node);
1118            }
1119        }
1120    }
1121
1122    /// Forget, in `named`, the edges from `len` on.
1123    pub(crate) fn forget_named(&mut self, len: usize) {
1124        while self.named.last().is_some_and(|&(e, _)| e as usize >= len) {
1125            self.named.pop();
1126        }
1127    }
1128
1129    /// Whether an edge names a node at or past `n`.
1130    pub(crate) fn names_past(&self, n: usize) -> bool {
1131        self.named
1132            .last()
1133            .is_some_and(|&(_, node)| node as usize >= n)
1134    }
1135
1136    /// The edges `src[i] → dst[i]` name nodes below `n_nodes` and labels the
1137    /// result has. `first` is the index of the first, for the message.
1138    ///
1139    /// `label` is each edge's label, or `None` for the first label on every
1140    /// one.
1141    pub(crate) fn check_edges(
1142        &self,
1143        src: &[u32],
1144        dst: &[u32],
1145        label: Option<&[u16]>,
1146        n_nodes: usize,
1147        first: usize,
1148    ) -> Result<(), ModelError> {
1149        for (i, (&s, &d)) in src.iter().zip(dst).enumerate() {
1150            for node in [s, d] {
1151                if node as usize >= n_nodes {
1152                    return err(format!(
1153                        "edge {} names node {node}, but the result has {n_nodes} nodes",
1154                        first + i
1155                    ));
1156                }
1157            }
1158        }
1159        let labels = match label {
1160            Some(label) => label,
1161            None if src.is_empty() => &[],
1162            None => &[0],
1163        };
1164        for (i, &l) in labels.iter().enumerate() {
1165            if l as usize >= self.edge_labels.len() {
1166                return err(format!(
1167                    "edge {} has the label {l}, but the result has {} edge labels",
1168                    first + i,
1169                    self.edge_labels.len()
1170                ));
1171            }
1172        }
1173        Ok(())
1174    }
1175
1176    pub(crate) fn check_highlights(&self, h: &Highlights) -> Result<(), ModelError> {
1177        let n = self.n_nodes();
1178        if let Some(&seed) = h.seeds.iter().find(|&&s| s as usize >= n) {
1179            return err(format!(
1180                "a seed is node {seed}, but the result has {n} nodes"
1181            ));
1182        }
1183        for (p, path) in h.paths.iter().enumerate() {
1184            if path.nodes.is_empty() {
1185                return err(format!("path {p} has no nodes"));
1186            }
1187            if let Some(&node) = path.nodes.iter().find(|&&v| v as usize >= n) {
1188                return err(format!(
1189                    "path {p} names node {node}, but the result has {n} nodes"
1190                ));
1191            }
1192            if path.edges.is_empty() {
1193                continue;
1194            }
1195            if path.edges.len() != path.nodes.len() - 1 {
1196                return err(format!(
1197                    "path {p} has {} nodes and {} edges; it needs one edge fewer than nodes, or none",
1198                    path.nodes.len(),
1199                    path.edges.len()
1200                ));
1201            }
1202            for (step, &e) in path.edges.iter().enumerate() {
1203                let (a, b) = (path.nodes[step], path.nodes[step + 1]);
1204                let Some((&s, &d)) = self.src.get(e as usize).zip(self.dst.get(e as usize)) else {
1205                    return err(format!(
1206                        "path {p} names edge {e}, but the result has {} edges",
1207                        self.n_edges()
1208                    ));
1209                };
1210                if (s, d) != (a, b) && (s, d) != (b, a) {
1211                    return err(format!(
1212                        "path {p}: edge {e} joins nodes {s} and {d}, not {a} and {b}"
1213                    ));
1214                }
1215            }
1216        }
1217        if let Some(name) = &h.distance {
1218            match self.node_column(name).map(|c| &c.values) {
1219                Some(Values::U32(_)) => {}
1220                Some(_) => return err(format!("the distance column '{name}' is not a u32 column")),
1221                None => {
1222                    return err(format!(
1223                        "there is no node column '{name}' for the distances"
1224                    ))
1225                }
1226            }
1227        }
1228        Ok(())
1229    }
1230
1231    pub(crate) fn check_encodings(&self, e: &Encodings) -> Result<(), ModelError> {
1232        for (what, name) in [
1233            ("size", &e.size_by),
1234            ("colour", &e.color_by),
1235            ("group", &e.group_by),
1236        ] {
1237            let Some(name) = name else { continue };
1238            match self.node_column(name).map(|c| &c.values) {
1239                None => return err(format!("there is no node column '{name}' to {what} by")),
1240                Some(Values::Dict { .. }) if what == "size" => {
1241                    return err(format!(
1242                        "the column '{name}' is text, so it cannot size the nodes"
1243                    ))
1244                }
1245                Some(_) => {}
1246            }
1247        }
1248        Ok(())
1249    }
1250}
1251
1252impl Target {
1253    pub(crate) fn noun(self) -> &'static str {
1254        match self {
1255            Target::Nodes => "node",
1256            Target::Edges => "edge",
1257        }
1258    }
1259}