Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 158 additions & 13 deletions crates/lance-csr/src/csr_expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ struct CsrBase {
sources: Sources,
neighbors: ScalarBuffer<u64>,
edge_rows: PackedU64,
/// The most edges any source has.
max_degree: usize,
}

/// Source key -> its neighbours' positions in the base.
Expand Down Expand Up @@ -231,10 +233,12 @@ impl CsrBase {
}
}
};
let max_degree = offsets.windows(2).map(|w| w[1] - w[0]).max().unwrap_or(0) as usize;
Some(Self {
sources,
neighbors: neighbors.clone(),
edge_rows: edge_rows.clone(),
max_degree,
})
}

Expand Down Expand Up @@ -500,6 +504,15 @@ impl Adjacency {
self.base_range(key).len() + self.added.get(&key).map_or(0, Vec::len)
}

/// An upper bound on any source's edges, or `usize::MAX` once edges were appended.
fn max_degree_bound(&self) -> usize {
if self.added_count == 0 {
self.base.max_degree
} else {
usize::MAX
}
}

/// Resume at an occurrence offset, borrowing all neighbour and deletion storage.
#[inline(always)]
fn neighbors_from<'a>(
Expand Down Expand Up @@ -1894,6 +1907,8 @@ impl AdjacencyCatalog {
pub struct Neighbors {
forward: Arc<Adjacency>,
reverse: Option<Arc<Adjacency>>,
/// A directed hop's edges keyed by their other end (see [`Self::flipped`]).
back: Option<Arc<Adjacency>>,
}

/// Occurrence offsets are sufficient to pause even a high-degree source row.
Expand All @@ -1908,13 +1923,32 @@ impl Neighbors {
Self {
forward: adjacency,
reverse: None,
back: None,
}
}

pub fn undirected(outgoing: Arc<Adjacency>, incoming: Arc<Adjacency>) -> Self {
Self {
forward: outgoing,
reverse: Some(incoming),
back: None,
}
}

/// The same directed hop, with `back` (the adjacency of the other direction) kept
/// for closing edges.
pub(crate) fn with_back(mut self, back: Option<Arc<Adjacency>>) -> Self {
self.back = back;
self
}

/// These edges listed from their other end, with the same edge rows: for a closing
/// edge, whose two ends are both bound, either end's list holds its edges.
fn flipped(&self) -> Option<Neighbors> {
match &self.reverse {
// Undirected: each end's outgoing and incoming lists cover the same edges.
Some(_) => Some(self.clone()),
None => self.back.clone().map(Neighbors::directed),
}
}

Expand Down Expand Up @@ -1963,6 +1997,12 @@ impl Neighbors {
self.forward.degree_bound(key) + reverse
}

/// An upper bound on the edges a hop from any key visits.
fn max_degree_bound(&self) -> usize {
let reverse = self.reverse.as_ref().map_or(0, |r| r.max_degree_bound());
self.forward.max_degree_bound().saturating_add(reverse)
}

/// Edges visited over all keys (self-loops count once per direction in this estimate).
pub fn num_edges(&self) -> u64 {
self.forward.num_edges() + self.reverse.as_ref().map_or(0, |r| r.num_edges())
Expand Down Expand Up @@ -2513,6 +2553,10 @@ impl CsrExpandExec {
}
}

/// A closing edge whose source has at most this many edges scans them rather than
/// comparing its two ends' degrees.
const SCAN_CLOSING_UP_TO: usize = 32;

/// One input batch and its current row/occurrence, independent of total fan-out.
struct BatchExpansion {
batch: RecordBatch,
Expand Down Expand Up @@ -2613,10 +2657,21 @@ impl BatchExpansion {
) -> ExpandedRows {
let mut chunk = ExpandedRows::default();
loop {
let paused = if self.edge_rows {
self.fill_chunk::<true>(adjacency, target, batch_size, &mut chunk)
} else {
self.fill_chunk::<false>(adjacency, target, batch_size, &mut chunk)
// Closing edges get their own copy of the loop, so the common path compiles
// exactly as it did before they read the shorter end.
let paused = match (self.edge_rows, self.bound.is_some()) {
(true, true) => {
self.fill_chunk::<true, true>(adjacency, target, batch_size, &mut chunk)
}
(true, false) => {
self.fill_chunk::<true, false>(adjacency, target, batch_size, &mut chunk)
}
(false, true) => {
self.fill_chunk::<false, true>(adjacency, target, batch_size, &mut chunk)
}
(false, false) => {
self.fill_chunk::<false, false>(adjacency, target, batch_size, &mut chunk)
}
};
if paused {
cooperative_yield().await;
Expand All @@ -2628,7 +2683,7 @@ impl BatchExpansion {
}

/// Keep coroutine state outside the scan while counting deleted occurrences as work.
fn fill_chunk<const ROWS: bool>(
fn fill_chunk<const ROWS: bool, const CLOSING: bool>(
&mut self,
adjacency: &Neighbors,
target: Option<&TargetLookup>,
Expand All @@ -2638,14 +2693,34 @@ impl BatchExpansion {
let mut position = self.position;
let mut row = self.row;
let mut work = 0_usize;
// A closing edge reads the shorter of its two ends' lists, so a hub at one end
// costs no more than the other end's degree.
// Decided once per hop: with no long list anywhere, every row just scans.
let back = if CLOSING && adjacency.max_degree_bound() > SCAN_CLOSING_UP_TO {
adjacency.flipped()
} else {
None
};
'rows: while row < self.keys.len() {
let i = row;
let previous_work = work;
if self.keys.is_valid(i) && self.bound.as_ref().is_none_or(|b| b.is_valid(i)) {
let key = self.keys.value(i);
let required = self.bound.as_ref().map(|b| b.value(i));
for candidate in adjacency
.candidates_from::<ROWS>(key, &mut position)
let (list, from, wanted) = match (&back, required) {
(Some(back), Some(r))
if CLOSING && {
// A short list is cheaper to scan than to look up the other end.
let here = adjacency.degree_bound(key);
here > SCAN_CLOSING_UP_TO && back.degree_bound(r) < here
} =>
{
(back, r, Some(key))
}
_ => (adjacency, key, required),
};
for candidate in list
.candidates_from::<ROWS>(from, &mut position)
.take(1024 - work)
{
work += 1;
Expand All @@ -2660,10 +2735,14 @@ impl BatchExpansion {
{
continue;
}
let neighbor = neighbor as i64;
if required.is_some_and(|r| r != neighbor) {
if wanted.is_some_and(|w| w != neighbor as i64) {
continue;
}
let neighbor = if CLOSING {
required.unwrap_or(neighbor as i64)
} else {
neighbor as i64
};
if let Some(target) = target {
let Some(target_row) = target.rows.position(neighbor) else {
continue;
Expand Down Expand Up @@ -3878,6 +3957,7 @@ mod tests {
},
neighbors: neighbours.to_vec().into(),
edge_rows: rows.clone(),
max_degree: 0,
};
let bitmaps = CsrBase::with_layout(keys, csr(), true).unwrap();
let allowed =
Expand Down Expand Up @@ -4010,6 +4090,7 @@ mod tests {
),
neighbors: Vec::new().into(),
edge_rows: PackedU64::pack(&[]),
max_degree: 0,
};
assert_eq!(base.range(1), (end - 1) as usize..end as usize);
assert_eq!(base.range(2), 0..end as usize);
Expand Down Expand Up @@ -4484,6 +4565,73 @@ mod tests {
.is_empty());
}

#[tokio::test]
async fn closing_edges_read_the_shorter_end_with_the_same_rows() {
// Hub 1 points at 2..=300 and a second time at 5; 7 points at 5.
let mut src: Vec<Option<i64>> = vec![Some(1); 299];
let mut dst: Vec<Option<i64>> = (2..=300).map(Some).collect();
src.extend([Some(1), Some(7)]);
dst.extend([Some(5), Some(5)]);
let out = Adjacency::build(edge_stream(src.clone(), dst.clone()), "src", "dst");
let out = Arc::new(out.await.unwrap());
assert_eq!(out.max_degree_bound(), 300);
let appended = out.with_changes(&[(7, 9, 301)], &RemovedRows::default());
assert_eq!(appended.max_degree_bound(), usize::MAX);
let inc = Arc::new(
Adjacency::build(edge_stream(src, dst), "dst", "src")
.await
.unwrap(),
);
// (key, bound target): two hub rows the back list shortens, a non-hub row, a
// missing target, and a reversed pair with no edge that way.
let input = RecordBatch::try_from_iter([
(
"key",
Arc::new(Int64Array::from(vec![1, 1, 7, 1, 5])) as ArrayRef,
),
(
"bound",
Arc::new(Int64Array::from(vec![5, 3, 5, 9999, 1])) as ArrayRef,
),
])
.unwrap();
let expand = |adjacency: Neighbors| {
let input = input.clone();
async move {
let mut expansion = BatchExpansion::try_new(input, 0, Some(1)).unwrap();
expansion.edge_rows = true;
let chunk = expansion.next_chunk(&adjacency, None, 8192).await;
let mut rows: Vec<_> = (0..chunk.rows.len())
.map(|i| {
let neighbor = chunk.neighbor_values[i];
(
chunk.rows[i],
chunk.key_values[i],
neighbor,
chunk.edge_rows[i],
)
})
.collect();
rows.sort_unstable();
rows
}
};

let scanned = expand(Neighbors::directed(out.clone())).await;
let pairs = |rows: &[(u32, i64, i64, u64)]| -> Vec<(u32, i64)> {
rows.iter().map(|r| (r.0, r.2)).collect()
};
assert_eq!(pairs(&scanned), vec![(0, 5), (0, 5), (1, 3), (2, 5)]);
let shortened = Neighbors::directed(out.clone()).with_back(Some(inc.clone()));
assert_eq!(expand(shortened).await, scanned);

// Undirected: either end's two lists hold the same edges.
let both = expand(Neighbors::undirected(out, inc)).await;
let expected = vec![(0, 5), (0, 5), (1, 3), (2, 5), (4, 1), (4, 1)];
assert_eq!(pairs(&both), expected);
assert_eq!(both[..4], scanned[..]);
}

#[tokio::test]
async fn resumed_neighbors_keep_duplicate_deletions_and_self_loops_exact() {
let edges = || edge_stream(vec![Some(1); 4], vec![Some(1), Some(2), Some(2), Some(3)]);
Expand Down Expand Up @@ -4953,10 +5101,7 @@ mod tests {
assert_eq!(forward.degree_bound(3), 0);
let directed = Neighbors::directed(forward.clone());
assert_eq!([1, 2, 9].map(|key| directed.degree_bound(key)), [2, 1, 0]);
let undirected = Neighbors {
forward,
reverse: Some(reverse),
};
let undirected = Neighbors::undirected(forward, reverse);
assert_eq!([1, 2, 3].map(|key| undirected.degree_bound(key)), [3, 2, 1]);
}

Expand Down
17 changes: 9 additions & 8 deletions crates/lance-csr/src/datafusion_planner/builder/expand_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,15 +335,16 @@ impl DataFusionPlanner {
let Some(catalog) = self.adjacency.as_ref() else {
return Ok(None);
};
// A directed hop keeps the other direction too, for a closing edge to read the
// shorter end's list.
let directed = |outgoing: bool| {
catalog.get(rel_type, outgoing).cloned().map(|a| {
Neighbors::directed(a).with_back(catalog.get(rel_type, !outgoing).cloned())
})
};
let adjacency = match direction {
RelationshipDirection::Outgoing => catalog
.get(rel_type, true)
.cloned()
.map(Neighbors::directed),
RelationshipDirection::Incoming => catalog
.get(rel_type, false)
.cloned()
.map(Neighbors::directed),
RelationshipDirection::Outgoing => directed(true),
RelationshipDirection::Incoming => directed(false),
// Outgoing endpoint names, as the reversed-edge scan of the join path uses.
RelationshipDirection::Undirected => catalog
.get(rel_type, true)
Expand Down
2 changes: 1 addition & 1 deletion docs/internals/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ keeps the two hops from reusing one edge. Both plans start from `c` (Dan), not `
| [Relationship properties](../csr.md#relationship-variables) fetched by edge row, since each CSR entry records the row its edge came from | `edge=k[k__since]` | Keeping the relationship table in the join |
| Target filter: reads the filter's columns first, and fetches the rest only for neighbours that pass | `filter=age > 35` | `FilterExec` after a full fetch |
| Relationship filter: drops failing edges before anything else is fetched | `edge_filter=since > 2020` | `FilterExec` after the join |
| Closing edge: the target is already bound (a cycle), so only neighbours equal to it are kept | `match=b__id` | Expanding everything, then filtering |
| Closing edge: the target is already bound (a cycle), so only neighbours equal to it are kept. Each row reads the shorter of its two ends' lists (for a directed hop, the target's list is its incoming one), so a hub at one end costs no more than the other end's degree | `match=b__id` | Expanding everything, then filtering |
| [Iterative variable-length traversal](../csr.md#variable-length-traversal): one cursor per hop over typed (label, key) frontiers, with bounded output batches | `iterative hops=1..3` | One join branch per path length, combined with `UNION ALL` |
| Outer expansion for a one-hop `OPTIONAL MATCH` with no `WHERE` of its own: an input row with no neighbour keeps one row, with nulls in the columns the hop adds. No filter moves into an outer hop, because that would turn rows dropped by the filter into rows of nulls | `outer` | Planning the input a second time to start the optional side, then a left join back |
| Degrees: one row per input node with the number of its neighbours that pass the target filter, and how many of them are the node itself, for the [two-hop count](optimizer.md#two-hop-counts-from-degrees) | `degrees=[__n1, __s1]` | A hash aggregate over one row per edge |
Expand Down
Loading