-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathbase_merge.rs
294 lines (257 loc) · 9.77 KB
/
base_merge.rs
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use std::{
io,
path::{Path, PathBuf},
};
use futures::{Stream, StreamExt, TryStreamExt};
use tempfile::TempDir;
use tokio::{fs::OpenOptions, io::AsyncWriteExt};
use crate::{
chrono_log,
layer::{builder::build_indexes, open_base_triple_stream, BaseLayerFileBuilderPhase2},
storage::{
directory::DirectoryLayerStore, AdjacencyListFiles, BaseLayerFiles, DictionaryFiles,
FileLoad, FileStore, PersistentLayerStore, TypedDictionaryFiles,
},
};
use tdb_succinct::{
dedup_merge_string_dictionaries_stream, dedup_merge_typed_dictionary_streams,
stream::{TfcDictStream, TfcTypedDictStream},
util::heap_sorted_stream,
};
#[allow(unused)]
fn try_enumerate<T, E, S: Stream<Item = Result<T, E>> + Send>(
s: S,
) -> impl Stream<Item = Result<(usize, T), E>> + Send {
s.enumerate().map(|(ix, r)| r.map(|v| (ix, v)))
}
async fn dicts_to_map<
F1: FileLoad + FileStore + 'static,
F2: FileLoad + FileStore + 'static,
I: ExactSizeIterator<Item = DictionaryFiles<F1>>,
>(
inputs: I,
output: DictionaryFiles<F2>,
) -> io::Result<(Vec<Vec<usize>>, usize)> {
let mut streams = Vec::with_capacity(inputs.len());
for input in inputs {
let reader = input.blocks_file.open_read().await?;
let stream = TfcDictStream::new(reader)
.map_ok(|e| e.0)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e));
streams.push(stream);
}
let map_result = dedup_merge_string_dictionaries_stream(streams, output).await?;
Ok(map_result)
}
async fn typed_dicts_to_map<
F1: FileLoad + FileStore + 'static,
F2: FileLoad + FileStore + 'static,
I: ExactSizeIterator<Item = TypedDictionaryFiles<F1>>,
>(
inputs: I,
output: TypedDictionaryFiles<F2>,
) -> io::Result<(Vec<Vec<usize>>, usize)> {
let mut streams = Vec::with_capacity(inputs.len());
for input in inputs {
let reader = input.blocks_file.open_read().await?;
let raw_stream = TfcTypedDictStream::new(
reader,
input.types_present_file.map().await?,
input.type_offsets_file.map().await?,
)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let stream = raw_stream.map_err(|e| io::Error::new(io::ErrorKind::Other, e));
streams.push(stream);
}
let map_result = dedup_merge_typed_dictionary_streams(streams, output).await?;
Ok(map_result)
}
fn map_triple(
triple: (u64, u64, u64),
node_map: &[usize],
predicate_map: &[usize],
value_map: &[usize],
num_nodes: usize,
) -> (u64, u64, u64) {
let s = node_map[triple.0 as usize - 1] as u64 + 1;
let p = predicate_map[triple.1 as usize - 1] as u64 + 1;
let o = if (triple.2 as usize - 1) < node_map.len() {
node_map[triple.2 as usize - 1] as u64 + 1
} else {
value_map[triple.2 as usize - 1 - node_map.len()] as u64 + num_nodes as u64 + 1
};
(s, p, o)
}
async fn test_write_file<F: FileLoad + FileStore + 'static, P: Into<PathBuf>>(
file: &F,
to: P,
) -> io::Result<()> {
let mut input_file = file.open_read().await?;
let to = to.into();
let mut options = OpenOptions::new();
options.create(true);
options.write(true);
let mut output_file = options.open(&to).await?;
tokio::io::copy(&mut input_file, &mut output_file).await?;
output_file.flush().await?;
chrono_log!("wrote {to:?}");
Ok(())
}
#[allow(unused)]
async fn test_write_dict<F: FileLoad + FileStore + 'static>(
prefix: &str,
files: &DictionaryFiles<F>,
) -> io::Result<()> {
chrono_log!("writing {prefix} files");
let blocks_path = format!("{prefix}.blocks");
let offsets_path = format!("{prefix}.offsets");
test_write_file(&files.blocks_file, &blocks_path).await?;
test_write_file(&files.offsets_file, &offsets_path).await?;
Ok(())
}
#[allow(unused)]
async fn test_write_typed_dict<F: FileLoad + FileStore + 'static>(
prefix: &str,
files: &TypedDictionaryFiles<F>,
) -> io::Result<()> {
chrono_log!("writing {prefix} files");
let types_present_path = format!("{prefix}.types_present");
let type_offsets_path = format!("{prefix}.type_offsets");
let blocks_path = format!("{prefix}.blocks");
let offsets_path = format!("{prefix}.offsets");
test_write_file(&files.types_present_file, &types_present_path).await?;
test_write_file(&files.type_offsets_file, &type_offsets_path).await?;
test_write_file(&files.blocks_file, &blocks_path).await?;
test_write_file(&files.offsets_file, &offsets_path).await?;
Ok(())
}
#[allow(unused)]
async fn test_write_adjacency_list_files<F: FileLoad + FileStore + 'static>(
prefix: &str,
files: &AdjacencyListFiles<F>,
) -> io::Result<()> {
let nums_path = format!("{prefix}.nums");
let bits_path = format!("{prefix}.bits");
let bit_index_blocks_path = format!("{prefix}.bit_index_blocks");
let bit_index_sblocks_path = format!("{prefix}.bit_index_sblocks");
test_write_file(&files.nums_file, &nums_path).await?;
test_write_file(&files.bitindex_files.bits_file, &bits_path).await?;
test_write_file(&files.bitindex_files.blocks_file, &bit_index_blocks_path).await?;
test_write_file(&files.bitindex_files.sblocks_file, &bit_index_sblocks_path).await?;
Ok(())
}
pub async fn merge_base_layers<F: FileLoad + FileStore + 'static, P: AsRef<Path>>(
inputs: &[BaseLayerFiles<F>],
output: BaseLayerFiles<F>,
temp_path: P,
) -> io::Result<()> {
chrono_log!("started merge of base layers");
// we are going to assume that this is a big expensive merge. all
// files will be constructed on disk first and only after being
// fully built will we actually copy things over to the output.
let temp_dir = TempDir::new_in(&temp_path)?;
let temp_store = DirectoryLayerStore::new(temp_dir.path());
let temp_layer_id = temp_store.create_directory().await?;
let temp_output_files = temp_store.base_layer_files(temp_layer_id).await?;
let node_dicts: Vec<_> = inputs
.iter()
.map(|i| i.node_dictionary_files.clone())
.collect();
let predicate_dicts: Vec<_> = inputs
.iter()
.map(|i| i.predicate_dictionary_files.clone())
.collect();
let value_dicts: Vec<_> = inputs
.iter()
.map(|i| i.value_dictionary_files.clone())
.collect();
let node_map_task = tokio::spawn(dicts_to_map(
node_dicts.into_iter(),
temp_output_files.node_dictionary_files.clone(),
));
let predicate_map_task = tokio::spawn(dicts_to_map(
predicate_dicts.into_iter(),
temp_output_files.predicate_dictionary_files.clone(),
));
let value_map_task = tokio::spawn(typed_dicts_to_map(
value_dicts.into_iter(),
temp_output_files.value_dictionary_files.clone(),
));
let (node_map, node_count) = node_map_task.await??;
chrono_log!(" merged node dicts");
let (predicate_map, predicate_count) = predicate_map_task.await??;
chrono_log!(" merged predicate dicts");
let (value_map, value_count) = value_map_task.await??;
chrono_log!("merged value dicts");
//test_write_dict("/tmp/node_dict", &temp_output_files.node_dictionary_files).await?;
//test_write_dict(
// "/tmp/predicate_dict",
// &temp_output_files.predicate_dictionary_files,
//)
//.await?;
//test_write_typed_dict("/tmp/value_dict", &temp_output_files.value_dictionary_files).await?;
let mut triple_streams = Vec::with_capacity(inputs.len());
for (ix, input) in inputs.into_iter().enumerate() {
let raw_stream = open_base_triple_stream(
input.s_p_adjacency_list_files.clone(),
input.sp_o_adjacency_list_files.clone(),
)
.await?;
let inner_node_map = &node_map[ix];
let inner_predicate_map = &predicate_map[ix];
let inner_value_map = &value_map[ix];
let stream = raw_stream.map_ok(move |triple| {
map_triple(
triple,
inner_node_map,
inner_predicate_map,
inner_value_map,
node_count,
)
});
triple_streams.push(stream);
}
let mut merged_triples = heap_sorted_stream(triple_streams).await?;
let mut builder = BaseLayerFileBuilderPhase2::new(
temp_output_files.clone(),
node_count,
predicate_count,
value_count,
)
.await?;
chrono_log!("constructed phase 2 builder");
let mut last_triple = None;
let mut tally: u64 = 0;
while let Some(triple) = merged_triples.try_next().await? {
if Some(triple) == last_triple {
continue;
}
last_triple = Some(triple);
builder.add_triple(triple.0, triple.1, triple.2).await?;
tally += 1;
if tally % 1000000 == 0 {
chrono_log!("wrote {tally} triples");
}
}
chrono_log!("added all merged triples");
let files = builder.partial_finalize().await?;
chrono_log!("finalized triple map");
//test_write_adjacency_list_files("/tmp/triples_s_p", &files.s_p_adjacency_list_files).await?;
//test_write_adjacency_list_files("/tmp/triples_sp_o", &files.sp_o_adjacency_list_files).await?;
let s_p_adjacency_list_files = files.s_p_adjacency_list_files.clone();
let sp_o_adjacency_list_files = files.sp_o_adjacency_list_files.clone();
let o_ps_adjacency_list_files = files.o_ps_adjacency_list_files.clone();
let predicate_wavelet_tree_files = files.predicate_wavelet_tree_files.clone();
build_indexes(
s_p_adjacency_list_files,
sp_o_adjacency_list_files,
o_ps_adjacency_list_files,
None,
predicate_wavelet_tree_files,
)
.await?;
chrono_log!(" built indexes");
// now that everything has been constructed on disk, copy over to the actual layer store
output.copy_from(&temp_output_files).await?;
Ok(())
}