#[cfg(test)]
use std::cell::Cell;
use relate_core::{Error, NodeId, RelId, Result};
use relate_ir::NodePattern;
use crate::ctx::ExecCtx;
use crate::exec::pushdown::expr_ready;
use crate::pattern_walk::{
admitted, binding, bound_node, node_candidates, node_candidates_capped,
point_candidates_capped, Admitted, Capped, NodeBinding,
};
use crate::shortest::Search;
use super::end_filter::SideCell;
use super::far_set::FarSet;
use super::route::Route;
pub(super) const SEEK_PAIR_LIMIT: usize = 16;
const SEEK_LIST_LIMIT: usize = 1 << 20;
#[cfg(test)]
thread_local! {
static LIST_LIMIT: Cell<Option<usize>> = const { Cell::new(None) };
}
fn list_limit() -> usize {
#[cfg(test)]
if let Some(limit) = LIST_LIMIT.with(Cell::get) {
return limit;
}
SEEK_LIST_LIMIT
}
#[cfg(test)]
pub(super) fn with_list_limit<T>(limit: usize, f: impl FnOnce() -> T) -> T {
crate::exec::test_support::with_override(&LIST_LIMIT, limit, f)
}
#[cfg(test)]
thread_local! {
static FAR_SET_OFF: Cell<bool> = const { Cell::new(false) };
}
fn far_set(ids: &[NodeId]) -> Option<FarSet> {
#[cfg(test)]
if FAR_SET_OFF.with(Cell::get) {
return None;
}
let set = FarSet::of(ids);
#[cfg(test)]
if set.is_some() {
FAR_LISTINGS.with(|c| c.set(c.get() + 1));
}
set
}
#[cfg(test)]
thread_local! {
static FAR_LISTINGS: Cell<u64> = const { Cell::new(0) };
}
#[cfg(test)]
pub(super) fn take_far_listings() -> u64 {
FAR_LISTINGS.with(|c| c.replace(0))
}
#[cfg(test)]
pub(super) fn without_far_set<T>(f: impl FnOnce() -> T) -> T {
crate::exec::test_support::with_flag_disabled(&FAR_SET_OFF, f)
}
#[cfg(test)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum AnchorArm {
Pair,
FanForward,
FanBackward,
Loop,
}
#[cfg(test)]
thread_local! {
static ANCHOR_ARMS: std::cell::RefCell<Vec<AnchorArm>> =
const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(test)]
pub(super) fn note_anchor(arm: AnchorArm) {
ANCHOR_ARMS.with(|c| c.borrow_mut().push(arm));
}
#[cfg(test)]
pub(super) fn take_anchor_arms() -> Vec<AnchorArm> {
ANCHOR_ARMS.with(|c| std::mem::take(&mut *c.borrow_mut()))
}
pub(super) enum Anchor {
Pair { starts: Side, ends: Side },
Fan {
origins: Side,
way: Way,
far: Option<FarSet>,
},
Loop { starts: Vec<NodeId> },
}
impl Anchor {
fn fits_pair(starts: &Side, ends: &Side) -> bool {
starts.ids().len().saturating_mul(ends.ids().len()) <= SEEK_PAIR_LIMIT
}
fn fan(origins: Side, way: Way) -> Self {
Anchor::Fan {
origins,
way,
far: None,
}
}
#[cfg(test)]
pub(super) fn arm(&self) -> AnchorArm {
match self {
Anchor::Pair { .. } => AnchorArm::Pair,
Anchor::Fan {
way: Way::Forward, ..
} => AnchorArm::FanForward,
Anchor::Fan {
way: Way::Backward, ..
} => AnchorArm::FanBackward,
Anchor::Loop { .. } => AnchorArm::Loop,
}
}
}
pub(super) enum Side {
One(NodeId),
Many(Vec<NodeId>),
}
impl Side {
pub(super) fn ids(&self) -> &[NodeId] {
match self {
Side::One(id) => std::slice::from_ref(id),
Side::Many(ids) => ids,
}
}
pub(super) fn shares(&self) -> bool {
self.ids().len() >= 2
}
}
enum Probed {
Scan { props_ready: bool },
Over(Ask),
Within(Side),
}
#[derive(Clone, Copy)]
struct ScanFar<'a> {
np: &'a NodePattern,
props_ready: bool,
}
impl Probed {
fn scan_side(self, np: &NodePattern) -> Option<ScanFar<'_>> {
match self {
Probed::Scan { props_ready } => Some(ScanFar { np, props_ready }),
Probed::Over(_) | Probed::Within(_) => None,
}
}
}
#[derive(Clone, Copy)]
enum Ask {
Point,
Map,
}
#[derive(Clone, Copy)]
pub(super) enum Way {
Forward,
Backward,
}
impl Way {
pub(super) fn search<'a, 'g>(self, base: &Search<'a, 'g>) -> Search<'a, 'g> {
match self {
Way::Forward => base.clone(),
Way::Backward => base.reversed(),
}
}
pub(super) fn ends(self, origin: NodeId, far: NodeId) -> (NodeId, NodeId) {
match self {
Way::Forward => (origin, far),
Way::Backward => (far, origin),
}
}
pub(super) fn orient(self, mut trails: Vec<Vec<RelId>>) -> Vec<Vec<RelId>> {
if matches!(self, Way::Backward) {
trails.iter_mut().for_each(|t| t.reverse());
}
trails
}
}
impl Route<'_> {
pub(super) fn anchor(&self) -> Result<Option<Anchor>> {
let counted = self.counted();
let (start, end) = (self.shape.start, self.shape.end);
if start.variable.is_some() && start.variable == end.variable && self.bound(start).is_none()
{
if self.shape.qpp_inner.is_some() {
return Ok(None);
}
return Ok(Some(Anchor::Loop {
starts: self.start_candidates()?,
}));
}
let side_caches = &self.caches.ends;
let probed = (
self.probe(start, &side_caches.start)?,
self.probe(end, &side_caches.end)?,
);
if counted {
return Ok(match probed {
(Probed::Within(starts), Probed::Within(ends)) => {
Anchor::fits_pair(&starts, &ends).then_some(Anchor::Pair { starts, ends })
}
_ => None,
});
}
let anchor = match probed {
(Probed::Over(start_ask), Probed::Over(end_ask)) => Self::listed(
self.listed_side(start, start_ask)?,
self.listed_side(end, end_ask)?,
),
(Probed::Within(starts), Probed::Within(ends)) => Self::listed(starts, ends),
(Probed::Within(starts), far @ (Probed::Over(_) | Probed::Scan { .. })) => {
self.fan_or_empty(starts, Way::Forward, far.scan_side(end))?
}
(far @ (Probed::Over(_) | Probed::Scan { .. }), Probed::Within(ends)) => {
self.fan_or_empty(ends, Way::Backward, far.scan_side(start))?
}
(_, far) => self.fan_or_empty(
Side::Many(self.start_candidates()?),
Way::Forward,
far.scan_side(end),
)?,
};
if self.shape.qpp_inner.is_some() && !matches!(anchor, Anchor::Pair { .. }) {
return Ok(None);
}
Ok(Some(anchor))
}
fn empty_pair() -> Anchor {
Anchor::Pair {
starts: Side::Many(Vec::new()),
ends: Side::Many(Vec::new()),
}
}
fn fan_or_empty(
&self,
origins: Side,
way: Way,
scan_far: Option<ScanFar<'_>>,
) -> Result<Anchor> {
if origins.ids().is_empty() {
return Ok(Self::empty_pair());
}
let listing = match scan_far {
Some(far) if origins.shares() => self.far_listing(far)?,
_ => None,
};
Ok(match listing {
Some(far) if far.is_empty() => Self::empty_pair(),
Some(far) => Anchor::Fan {
far: far_set(&far),
origins,
way,
},
None => Anchor::fan(origins, way),
})
}
fn far_listing(&self, far: ScanFar<'_>) -> Result<Option<Vec<NodeId>>> {
let ScanFar { np, props_ready } = far;
if np.labels.is_empty() || !props_ready {
return Ok(None);
}
Ok(match self.asked(np, Ask::Map, list_limit())? {
Some(Capped::Within(ids)) => Some(ids),
Some(Capped::Over) | None => None,
})
}
fn listed(starts: Side, ends: Side) -> Anchor {
let (s, e) = (starts.ids().len(), ends.ids().len());
if s == 0 || e == 0 {
Self::empty_pair()
} else if Anchor::fits_pair(&starts, &ends) {
Anchor::Pair { starts, ends }
} else if e < s {
Anchor::Fan {
far: far_set(starts.ids()),
origins: ends,
way: Way::Backward,
}
} else {
Anchor::Fan {
far: far_set(ends.ids()),
origins: starts,
way: Way::Forward,
}
}
}
fn probe(&self, np: &NodePattern, cell: &SideCell) -> Result<Probed> {
let class = binding(np, self.row);
let unbound = match admitted(class) {
Admitted::One(id) => return Ok(Probed::Within(Side::One(id))),
Admitted::Empty => return Ok(Probed::Within(Side::Many(Vec::new()))),
Admitted::Scan => false,
Admitted::Seek(_) => true,
};
let props_ready = np
.properties
.as_ref()
.is_none_or(|props| expr_ready(props, self.row));
let Some(ask) = self.side_sizing(np, unbound, props_ready) else {
return self.scanned_side(np, class, cell, props_ready);
};
Ok(match self.asked(np, ask, SEEK_PAIR_LIMIT)? {
Some(Capped::Within(ids)) => Probed::Within(Side::Many(ids)),
Some(Capped::Over) => Probed::Over(ask),
None => self.scanned_side(np, class, cell, props_ready)?,
})
}
fn scanned_side(
&self,
np: &NodePattern,
class: NodeBinding<'_>,
cell: &SideCell,
props_ready: bool,
) -> Result<Probed> {
Ok(self
.filtered_side(np, class, cell)?
.map_or(Probed::Scan { props_ready }, Probed::Within))
}
fn side_sizing(&self, np: &NodePattern, unbound: bool, props_ready: bool) -> Option<Ask> {
match np.properties.as_ref() {
Some(_) if props_ready => Some(Ask::Map),
None if unbound => Some(Ask::Point),
_ => None,
}
}
fn bound(&self, np: &NodePattern) -> Option<NodeId> {
bound_node(np, self.row)
}
fn listed_side(&self, np: &NodePattern, ask: Ask) -> Result<Side> {
let limit = list_limit();
let capped = self.asked(np, ask, limit)?.ok_or_else(|| {
Error::internal("shortest-path route: a probed side lost its point seek")
})?;
Ok(match capped {
Capped::Within(ids) => Side::Many(ids),
Capped::Over => {
return Err(Error::capacity_seek_candidates(
limit as u64 + 1,
limit as u64,
))
}
})
}
fn asked(&self, np: &NodePattern, ask: Ask, cap: usize) -> Result<Option<Capped>> {
let ExecCtx { graph, params, .. } = self.ctx;
let conjuncts = &self.filters.endpoint;
Ok(match ask {
Ask::Point => point_candidates_capped(graph, np, self.row, params, conjuncts, cap)?,
Ask::Map => node_candidates_capped(graph, np, self.row, params, conjuncts, cap)?,
})
}
fn start_candidates(&self) -> Result<Vec<NodeId>> {
let ExecCtx { graph, params, .. } = self.ctx;
node_candidates(
graph,
self.shape.start,
self.row,
params,
&self.filters.endpoint,
)
}
}