1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use super::super::{ExecutionNode, ExecutionNodeDesc, NodeSearchDesc};
use crate::annis::db::aql::conjunction::BinaryOperatorArguments;
use crate::annis::operator::BinaryOperatorIndex;
use crate::{annis::operator::EstimationType, errors::Result, graph::Match};
use graphannis_core::annostorage::NodeAnnotationStorage;
use graphannis_core::{annostorage::MatchGroup, types::NodeID};
use rayon::prelude::*;
use std::error::Error;
use std::iter::Peekable;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel};
const MAX_BUFFER_SIZE: usize = 512;
/// A join that takes any iterator as left-hand-side (LHS) and an annotation condition as right-hand-side (RHS).
/// It then retrieves all matches as defined by the operator for each LHS element and checks
/// if the annotation condition is true.
pub struct IndexJoin<'a> {
lhs: Peekable<Box<dyn ExecutionNode<Item = Result<MatchGroup>> + 'a>>,
match_receiver: Option<Receiver<Result<MatchGroup>>>,
op: Arc<dyn BinaryOperatorIndex + 'a>,
lhs_idx: usize,
node_search_desc: Arc<NodeSearchDesc>,
node_annos: &'a dyn NodeAnnotationStorage,
desc: ExecutionNodeDesc,
global_reflexivity: bool,
}
impl<'a> IndexJoin<'a> {
/// Create a new `IndexJoin`
/// # Arguments
///
/// * `lhs` - An iterator for a left-hand-side
/// * `lhs_idx` - The index of the element in the LHS that should be used as a source
/// * `op_entry` - The operator that connects the LHS and RHS (with description)
/// * `anno_qname` A pair of the annotation namespace and name (both optional) to define which annotations to fetch
/// * `anno_cond` - A filter function to determine if a RHS candidate is included
pub fn new(
lhs: Box<dyn ExecutionNode<Item = Result<MatchGroup>> + 'a>,
lhs_idx: usize,
op: Box<dyn BinaryOperatorIndex + 'a>,
op_args: &BinaryOperatorArguments,
node_search_desc: Arc<NodeSearchDesc>,
node_annos: &'a dyn NodeAnnotationStorage,
rhs_desc: Option<&ExecutionNodeDesc>,
) -> Result<IndexJoin<'a>> {
let lhs_desc = lhs.get_desc().cloned();
let lhs_peek = lhs.peekable();
let processed_func = |est_type: EstimationType, out_lhs: usize, out_rhs: usize| {
match est_type {
EstimationType::Selectivity(op_sel) => {
// A index join processes each LHS and for each LHS the number of reachable nodes given by the operator.
// The selectivity of the operator itself an estimation how many nodes are filtered out by the cross product.
// We can use this number (without the edge annotation selectivity) to re-construct the number of reachable nodes.
// avgReachable = (sel * cross) / lhs
// = (sel * lhs * rhs) / lhs
// = sel * rhs
// processedInStep = lhs + (avgReachable * lhs)
// = lhs + (sel * rhs * lhs)
let result = (out_lhs as f64) + (op_sel * (out_rhs as f64) * (out_lhs as f64));
result.round() as usize
}
EstimationType::Min => out_lhs,
}
};
let join = IndexJoin {
desc: ExecutionNodeDesc::join(
op.as_binary_operator(),
lhs_desc.as_ref(),
rhs_desc,
"indexjoin (parallel)",
&format!("#{} {} #{}", op_args.left, &op, op_args.right),
&processed_func,
)?,
lhs: lhs_peek,
lhs_idx,
op: Arc::from(op),
node_search_desc,
node_annos,
match_receiver: None,
global_reflexivity: op_args.global_reflexivity,
};
Ok(join)
}
fn next_lhs_buffer(
&mut self,
tx: &Sender<Result<MatchGroup>>,
) -> Vec<(Result<MatchGroup>, Sender<Result<MatchGroup>>)> {
let mut lhs_buffer = Vec::with_capacity(MAX_BUFFER_SIZE);
while lhs_buffer.len() < MAX_BUFFER_SIZE {
if let Some(lhs) = self.lhs.next() {
lhs_buffer.push((lhs, tx.clone()));
} else {
break;
}
}
lhs_buffer
}
fn next_match_receiver(&mut self) -> Option<Receiver<Result<MatchGroup>>> {
let (tx, rx) = channel();
let lhs_buffer = self.next_lhs_buffer(&tx);
if lhs_buffer.is_empty() {
return None;
}
let node_search_desc: Arc<NodeSearchDesc> = self.node_search_desc.clone();
let op: Arc<dyn BinaryOperatorIndex> = self.op.clone();
let lhs_idx = self.lhs_idx;
let node_annos = self.node_annos;
let op: &dyn BinaryOperatorIndex = op.as_ref();
let global_reflexivity = self.global_reflexivity;
// find all RHS in parallel
lhs_buffer.into_par_iter().for_each(|(m_lhs, tx)| {
match m_lhs {
Ok(m_lhs) => {
match next_candidates(&m_lhs, op, lhs_idx, node_annos, &node_search_desc) {
Ok(rhs_candidate) => {
let mut rhs_candidate = rhs_candidate.into_iter().peekable();
while let Some(mut m_rhs) = rhs_candidate.next() {
// check if all filters are true
let mut include_match = true;
for f in &node_search_desc.cond {
let func_result = (f)(&m_rhs, node_annos);
match func_result {
Ok(func_result) => {
if !func_result {
include_match = false;
break;
}
}
Err(e) => {
if let Err(e) = tx.send(Err(e)) {
trace!(
"Could not send error in parallel index join {}", e
);
}
}
};
}
if include_match {
// replace the annotation with a constant value if needed
if let Some(ref const_anno) = node_search_desc.const_output {
m_rhs = (m_rhs.node, const_anno.clone()).into();
}
// check if lhs and rhs are equal and if this is allowed in this query
if op.is_reflexive()
|| (global_reflexivity && m_rhs.different_to_all(&m_lhs)
|| (!global_reflexivity
&& m_rhs.different_to(&m_lhs[lhs_idx])))
{
// filters have been checked, return the result
let mut result: MatchGroup = m_lhs.clone();
let matched_node = m_rhs.node;
result.push(m_rhs);
if node_search_desc.const_output.is_some() {
// only return the one unique constAnno for this node and no duplicates
// skip all RHS candidates that have the same node ID
#[allow(clippy::while_let_loop)]
loop {
if let Some(next_match) = rhs_candidate.peek() {
if next_match.node != matched_node {
break;
}
} else {
break;
}
rhs_candidate.next();
}
}
if tx.send(Ok(result)).is_err() {
return;
}
}
}
}
}
Err(e) => {
if let Err(e) = tx.send(Err(e)) {
trace!("Could not send error in parallel index join: {}", e);
};
}
}
}
Err(e) => {
if let Err(e) = tx.send(Err(e)) {
trace!("Could not send error in parallel index join: {}", e);
}
}
};
});
Some(rx)
}
}
fn next_candidates(
m_lhs: &[Match],
op: &dyn BinaryOperatorIndex,
lhs_idx: usize,
node_annos: &dyn NodeAnnotationStorage,
node_search_desc: &Arc<NodeSearchDesc>,
) -> Result<Vec<Match>> {
let it_nodes = op.retrieve_matches(&m_lhs[lhs_idx]).fuse().map(|m| {
m.map_err(|e| {
let e: Box<dyn Error + Send + Sync> = Box::new(e);
e
})
.map(|m| m.node)
});
let it_nodes: Box<
dyn Iterator<Item = std::result::Result<NodeID, Box<dyn Error + Send + Sync>>>,
> = Box::from(it_nodes);
let result = node_annos.get_keys_for_iterator(
node_search_desc.qname.0.as_deref(),
node_search_desc.qname.1.as_deref(),
it_nodes,
)?;
Ok(result)
}
impl ExecutionNode for IndexJoin<'_> {
fn get_desc(&self) -> Option<&ExecutionNodeDesc> {
Some(&self.desc)
}
}
impl Iterator for IndexJoin<'_> {
type Item = Result<MatchGroup>;
fn next(&mut self) -> Option<Self::Item> {
// lazily initialize
if self.match_receiver.is_none() {
self.match_receiver = if let Some(rhs) = self.next_match_receiver() {
Some(rhs)
} else {
return None;
};
}
loop {
{
let match_receiver = self.match_receiver.as_mut()?;
if let Ok(result) = match_receiver.recv() {
return Some(result);
}
}
// inner was completed once, get new candidates
if let Some(rhs) = self.next_match_receiver() {
self.match_receiver = Some(rhs);
} else {
// no more results to fetch
return None;
}
}
}
}