Skip to content
Closed
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
92 changes: 85 additions & 7 deletions src/query/gds_procedure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
//! every option that would change the answer and is not implemented is
//! refused by name rather than ignored.

use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};

use super::path_procedure::{lex, Token};
use crate::{GraphError, QueryColumn, QueryFailureReason, Result, VertexPropertyValue};
use crate::{GraphError, QueryColumn, QueryFailureReason, Result, VertexId, VertexPropertyValue};

/// The GDS release whose procedure signatures this surface answers. The
/// client compares it with the oldest server version it supports.
Expand Down Expand Up @@ -284,6 +284,10 @@ pub(crate) struct GdsPageRankConfig {
pub(crate) tolerance: f64,
/// The `.write` mode's `writeProperty`; `None` is `.stream`.
pub(crate) write_property: Option<String>,
/// `sourceNodes`: the vertices the teleport mass is spread over, in the
/// order given. `None` spreads it over every vertex, which is the
/// unpersonalized algorithm.
pub(crate) source_nodes: Option<Vec<VertexId>>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -717,6 +721,7 @@ fn page_rank_config(name: &str, config: Option<&GdsValue>) -> Result<GdsPageRank
damping_factor: PAGE_RANK_DAMPING_FACTOR,
tolerance: PAGE_RANK_TOLERANCE,
write_property: None,
source_nodes: None,
};
let entries = match config {
Some(config) => configuration(name, config)?.iter().collect(),
Expand Down Expand Up @@ -748,18 +753,37 @@ fn page_rank_config(name: &str, config: Option<&GdsValue>) -> Result<GdsPageRank
"scaler" if is_no_scaler(value) => {}
"scaler" => return unsupported(format!("{name} scaler is not supported; scores are returned unscaled")),
"sourceNodes" if *value == GdsValue::Null => {}
"sourceNodes" => {
return unsupported(format!(
"{name} sourceNodes is not supported; personalised PageRank is not implemented"
))
}
"sourceNodes" => result.source_nodes = Some(source_nodes(name, value)?),
key => algorithm_option(name, key, value)?,
}
}
require_write_property(name, &result.write_property)?;
Ok(result)
}

fn source_nodes(name: &str, value: &GdsValue) -> Result<Vec<VertexId>> {
let GdsValue::List(values) = value else {
return unsupported(format!("{name} sourceNodes must be a list of node ids, not {}", value.kind()));
};
if values.is_empty() {
return unsupported(format!("{name} sourceNodes must not be empty"));
}
let mut nodes = Vec::with_capacity(values.len());
let mut seen = BTreeSet::new();
for value in values {
let GdsValue::Integer(id) = value else {
return unsupported(format!("{name} sourceNodes must hold node ids, not {}", value.kind()));
};
let id = u64::try_from(*id)
.map_err(|_| procedure_error(format!("{name} sourceNodes node id {id} is negative; node ids are unsigned")))?;
if !seen.insert(id) {
return unsupported(format!("{name} sourceNodes lists node id {id} more than once"));
}
nodes.push(id);
}
Ok(nodes)
}

fn betweenness_config(name: &str, config: Option<&GdsValue>) -> Result<GdsBetweennessConfig> {
let mut result = GdsBetweennessConfig {
sampling_size: None,
Expand Down Expand Up @@ -1136,6 +1160,9 @@ impl GdsProcedure {
("dampingFactor".to_string(), float(config.damping_factor)),
("tolerance".to_string(), float(config.tolerance)),
];
if let Some(nodes) = &config.source_nodes {
entries.push(("sourceNodes".to_string(), list(nodes.iter().map(|node| node.to_string()))));
}
if let Some(property) = &config.write_property {
entries.push(("writeProperty".to_string(), quote_string(property)));
}
Expand Down Expand Up @@ -1212,3 +1239,54 @@ fn map(entries: impl IntoIterator<Item = (String, String)>) -> String {
.collect::<Vec<_>>();
format!("{{{}}}", entries.join(", "))
}

#[cfg(test)]
mod tests {
use super::*;

fn parse(query: &str) -> GdsProcedure {
parse_gds_procedure(query, &BTreeMap::new()).unwrap_or_else(|error| panic!("{query} was refused: {error}"))
}

fn page_rank(query: &str) -> GdsPageRankConfig {
match parse(query).call {
GdsCall::PageRank { config, .. } => config,
call => panic!("{query} parsed as {call:?}"),
}
}

#[test]
fn source_nodes_parse_in_stream_and_write() {
let config = page_rank("CALL gds.pageRank.stream('g', {sourceNodes: [4, 2]}) YIELD nodeId, score");
assert_eq!(config.source_nodes, Some(vec![4, 2]));
assert_eq!(config.write_property, None);
let config = page_rank("CALL gds.pageRank.write('g', {sourceNodes: [4], writeProperty: 'ppr'})");
assert_eq!(config.source_nodes, Some(vec![4]));
assert_eq!(config.write_property.as_deref(), Some("ppr"));
}

#[test]
fn a_null_source_nodes_is_the_unpersonalized_algorithm() {
let config = page_rank("CALL gds.pageRank.stream('g', {sourceNodes: null}) YIELD nodeId, score");
assert_eq!(config.source_nodes, None);
}

#[test]
fn source_nodes_round_trip_through_the_printed_call() {
let procedure = parse("CALL gds.pageRank.stream('g', {sourceNodes: [4, 2], dampingFactor: 0.5}) YIELD nodeId, score");
assert_eq!(parse(&procedure.to_cypher()), procedure);
}

#[test]
fn source_nodes_are_refused_when_empty_duplicated_or_not_ids() {
for query in [
"CALL gds.pageRank.stream('g', {sourceNodes: []}) YIELD nodeId, score",
"CALL gds.pageRank.stream('g', {sourceNodes: [1, 1]}) YIELD nodeId, score",
"CALL gds.pageRank.stream('g', {sourceNodes: [1, -1]}) YIELD nodeId, score",
"CALL gds.pageRank.stream('g', {sourceNodes: [1.5]}) YIELD nodeId, score",
"CALL gds.pageRank.stream('g', {sourceNodes: 'n'}) YIELD nodeId, score",
] {
assert!(parse_gds_procedure(query, &BTreeMap::new()).is_err(), "{query} was accepted");
}
}
}
145 changes: 131 additions & 14 deletions src/shard/gds_procedure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -634,16 +634,34 @@ impl GraphShard {
let config = config.clone();
let graph = Arc::clone(&graph);
run_graph_compute(Arc::clone(&self.operation_metrics), "gds_page_rank", move || {
// One library call: the iteration limit bounds it, not
// the deadline, which is checked only before it starts.
compute_budget.check("gds_page_rank")?;
let Some((scores, iterations)) = crate::sparse_kernel::pagerank(
&graph.edges,
config.damping_factor as f32,
config.tolerance as f32,
config.max_iterations,
)?
else {
let sources = config
.source_nodes
.as_deref()
.map(|nodes| source_ordinals(&graph, nodes, &graph_name))
.transpose()?;
let result = match sources {
// One library call: the iteration limit bounds it, not
// the deadline, which is checked only before it starts.
None => crate::sparse_kernel::pagerank(
&graph.edges,
config.damping_factor as f32,
config.tolerance as f32,
config.max_iterations,
),
// The power iteration checks the deadline between
// iterations, so a large personalized run stops when
// the query is cancelled or times out.
Some(sources) => crate::sparse_kernel::personalized_pagerank(
&graph.edges,
&sources,
config.damping_factor as f32,
config.tolerance as f32,
config.max_iterations,
|| compute_budget.check("gds_page_rank"),
),
};
let Some((scores, iterations)) = result? else {
// GDS would return these scores with didConverge
// false; LAGraph frees them, so there is nothing to
// return but the reason.
Expand Down Expand Up @@ -718,11 +736,19 @@ impl GraphShard {
("deletedPairsDropped", QueryValue::Count(deleted_pairs)),
];
match &procedure.call {
GdsCall::PageRank { config, .. } => configuration.extend([
("maxIterations", QueryValue::Count(u64::from(config.max_iterations))),
("dampingFactor", QueryValue::Float(QueryFloat(config.damping_factor))),
("tolerance", QueryValue::Float(QueryFloat(config.tolerance))),
]),
GdsCall::PageRank { config, .. } => {
configuration.extend([
("maxIterations", QueryValue::Count(u64::from(config.max_iterations))),
("dampingFactor", QueryValue::Float(QueryFloat(config.damping_factor))),
("tolerance", QueryValue::Float(QueryFloat(config.tolerance))),
]);
if let Some(nodes) = &config.source_nodes {
configuration.push((
"sourceNodes",
QueryValue::List(nodes.iter().copied().map(QueryValue::VertexId).collect()),
));
}
}
_ => configuration.extend([
("samplingSize", QueryValue::Count(sampling.0)),
(
Expand Down Expand Up @@ -1087,6 +1113,56 @@ impl GraphShard {
}
}

/// Returns the position of each `sourceNodes` id within `graph.vertices`, in
/// the same order. The kernel addresses vertices by position, not by id.
///
/// Label projections keep `vertices` sorted, so each id is a binary search.
/// `'*'` keeps them in first-encounter order, so one pass finds them all,
/// using a map of only the requested ids. A missing id is an error.
fn source_ordinals(graph: &GdsProjectedGraph, nodes: &[VertexId], graph_name: &str) -> Result<Vec<u64>> {
let unknown = |node: VertexId| {
gds_refusal(format!(
"sourceNodes node {node} is not a vertex of graph '{graph_name}'; project the node or drop it from sourceNodes"
))
};
let ascending = graph.vertices.is_sorted();
if ascending {
return nodes
.iter()
.map(|node| {
graph
.vertices
.binary_search(node)
.map(|ordinal| ordinal as u64)
.map_err(|_| unknown(*node))
})
.collect();
}
let mut wanted = HashMap::with_capacity(nodes.len());
for (position, node) in nodes.iter().enumerate() {
wanted.entry(*node).or_insert(position);
}
let mut ordinals = vec![u64::MAX; nodes.len()];
let mut missing = nodes.len();
for (ordinal, vertex) in graph.vertices.iter().enumerate() {
let Some(&position) = wanted.get(vertex) else {
continue;
};
if ordinals[position] == u64::MAX {
ordinals[position] = ordinal as u64;
missing -= 1;
if missing == 0 {
break;
}
}
}
if missing > 0 {
let position = ordinals.iter().position(|ordinal| *ordinal == u64::MAX).unwrap_or_default();
return Err(unknown(nodes[position]));
}
Ok(ordinals)
}

/// The edge walk of [`GraphShard::gds_projected_graph`]. With labels,
/// `members` are the vertices, in ascending id order, isolated ones
/// included, and an edge is kept only when both ends are members. With
Expand Down Expand Up @@ -1420,3 +1496,44 @@ fn dense_sample_is_smaller(vertices: u64, size: u64) -> bool {
};
vertices.saturating_mul(8) <= buckets.saturating_mul(17).saturating_add(size.saturating_mul(8))
}

#[cfg(test)]
mod tests {
use super::*;

fn projected_graph(vertices: Vec<VertexId>) -> GdsProjectedGraph {
let mut edges = OrdinalEdges::new(vertices.len() as u64);
if vertices.len() >= 2 {
edges.push(0, 1);
}
GdsProjectedGraph {
vertices,
edges,
deleted_pairs_dropped: 0,
distinct_pairs: std::sync::OnceLock::new(),
}
}

#[test]
fn a_sorted_projection_resolves_by_binary_search() {
let graph = projected_graph(vec![2, 4, 8]);
assert_eq!(source_ordinals(&graph, &[8, 2], "g").unwrap(), vec![2, 0]);
assert_eq!(source_ordinals(&graph, &[4], "g").unwrap(), vec![1]);
}

#[test]
fn an_unsorted_projection_resolves_by_map() {
let graph = projected_graph(vec![8, 2, 4]);
assert_eq!(source_ordinals(&graph, &[2, 4], "g").unwrap(), vec![1, 2]);
assert_eq!(source_ordinals(&graph, &[8], "g").unwrap(), vec![0]);
}

#[test]
fn a_node_outside_the_projection_is_refused() {
for vertices in [vec![2, 4, 8], vec![8, 2, 4]] {
let graph = projected_graph(vertices);
let error = source_ordinals(&graph, &[3], "g").unwrap_err();
assert!(error.to_string().contains("sourceNodes node 3"), "{error}");
}
}
}
Loading
Loading