Skip to content

web search done right

continously dump inserted edges into sorted files in edge store writer to avoid oom

Mikkel Denker43c3744de24e
diff --git a/crates/core/examples/search_preindexed.rs b/crates/core/examples/search_preindexed.rs
index 37c23151..44072038 100644
--- a/crates/core/examples/search_preindexed.rs
+++ b/crates/core/examples/search_preindexed.rs
@@ -147,9 +147,13 @@ pub async fn main() {
let searcher: ApiSearcher<Searcher, LiveSearcher> =
ApiSearcher::new(searcher, None, None, None, None, bangs, config);
- for query in &queries {
+ for query in queries {
+ let mut query = query;
+ query.push(' ');
+ let query = query.repeat(32);
+
let mut desc = "search '".to_string();
- desc.push_str(query);
+ desc.push_str(&query);
desc.push('\'');
println!("{desc}");
diff --git a/crates/core/src/file_store/iterable.rs b/crates/core/src/file_store/iterable.rs
new file mode 100644
index 00000000..abf47791
--- /dev/null
+++ b/crates/core/src/file_store/iterable.rs
@@ -0,0 +1,240 @@
+// Stract is an open source web search engine.
+// Copyright (C) 2024 Stract ApS
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>
+
+//! This module contains the implementation of the `IterableStoreWriter` and `IterableStoreReader`.
+//! The iterable store is a simple format for storing a sequence of items in a file such that they
+//! can be read back in order. The format is as follows:
+//!
+//! 1. A 64-bit little-endian integer representing the number of bytes in the upcoming item.
+//! 2. The serialized item.
+//! 3. Repeat 1-2 until the end of the file.
+
+use crate::Result;
+use std::io::{self, Read, Write};
+
+use super::Peekable;
+
+struct IterableHeader {
+ num_upcoming_bytes: u64,
+}
+
+impl IterableHeader {
+ fn serialize<W>(&self, writer: &mut W) -> io::Result<()>
+ where
+ W: io::Write,
+ {
+ writer.write_all(&self.num_upcoming_bytes.to_le_bytes())
+ }
+
+ fn deserialize<R>(reader: &mut R) -> io::Result<Self>
+ where
+ R: io::Read,
+ {
+ let mut num_upcoming_bytes = [0; 8];
+ reader.read_exact(&mut num_upcoming_bytes)?;
+ Ok(IterableHeader {
+ num_upcoming_bytes: u64::from_le_bytes(num_upcoming_bytes),
+ })
+ }
+}
+
+pub struct IterableStoreWriter<T, W>
+where
+ W: io::Write,
+{
+ writer: io::BufWriter<W>,
+ _marker: std::marker::PhantomData<T>,
+}
+
+impl<T, W> IterableStoreWriter<T, W>
+where
+ T: bincode::Encode,
+ W: io::Write,
+{
+ pub fn new(writer: W) -> Self {
+ Self {
+ writer: io::BufWriter::new(writer),
+ _marker: std::marker::PhantomData,
+ }
+ }
+
+ pub fn write(&mut self, item: &T) -> Result<()> {
+ let serialized = bincode::encode_to_vec(item, bincode::config::standard())?;
+ let header = IterableHeader {
+ num_upcoming_bytes: serialized.len() as u64,
+ };
+ header.serialize(&mut self.writer)?;
+ self.writer.write_all(&serialized)?;
+ Ok(())
+ }
+
+ pub fn finalize(mut self) -> Result<W> {
+ self.writer.flush()?;
+
+ self.writer.into_inner().map_err(|e| anyhow::anyhow!("{e}"))
+ }
+}
+
+pub struct IterableStoreReader<T, R> {
+ reader: io::BufReader<R>,
+ _marker: std::marker::PhantomData<T>,
+}
+
+impl<T, R> IterableStoreReader<T, R>
+where
+ R: io::Read,
+{
+ pub fn new(reader: R) -> Self {
+ Self {
+ reader: io::BufReader::new(reader),
+ _marker: std::marker::PhantomData,
+ }
+ }
+}
+
+impl<T, R> Iterator for IterableStoreReader<T, R>
+where
+ T: bincode::Decode,
+ R: io::Read,
+{
+ type Item = Result<T>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let header = match IterableHeader::deserialize(&mut self.reader) {
+ Ok(header) => header,
+ Err(_err) => return None,
+ };
+
+ let mut serialized = vec![0; header.num_upcoming_bytes as usize];
+ match self.reader.read_exact(&mut serialized) {
+ Ok(()) => (),
+ Err(err) => return Some(Err(err.into())),
+ }
+
+ Some(
+ match bincode::decode_from_slice(&serialized, bincode::config::standard()) {
+ Ok((item, _)) => Ok(item),
+ Err(err) => Err(err.into()),
+ },
+ )
+ }
+}
+
+pub struct SortedIterableStoreReader<T, R>
+where
+ R: io::Read,
+ T: bincode::Decode,
+{
+ readers: Vec<Peekable<IterableStoreReader<T, R>>>,
+}
+
+impl<T, R> SortedIterableStoreReader<T, R>
+where
+ T: Ord + bincode::Decode,
+ R: io::Read,
+{
+ pub fn new(readers: Vec<IterableStoreReader<T, R>>) -> Self {
+ let readers = readers.into_iter().map(Peekable::new).collect::<Vec<_>>();
+
+ Self { readers }
+ }
+}
+
+impl<T, R> Iterator for SortedIterableStoreReader<T, R>
+where
+ T: Ord + bincode::Decode,
+ R: io::Read,
+{
+ type Item = Result<T>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let mut min_index = None;
+
+ let num_readers = self.readers.len();
+ for i in 0..num_readers {
+ let reader = &self.readers[i];
+ if let Some(item) = reader.peek() {
+ match item {
+ Ok(item) => match min_index {
+ Some(cur_min) => {
+ let cur_min_reader: &Peekable<IterableStoreReader<T, R>> =
+ &self.readers[cur_min];
+
+ match cur_min_reader.peek().unwrap().as_ref() {
+ Ok(cur_min_item) => {
+ if item < cur_min_item {
+ min_index = Some(i);
+ }
+ }
+ Err(err) => return Some(Err(anyhow::anyhow!("{err}"))),
+ }
+ }
+ None => min_index = Some(i),
+ },
+ Err(err) => return Some(Err(anyhow::anyhow!("{err}"))),
+ }
+ }
+ }
+
+ match min_index {
+ Some(min_index) => Some(self.readers[min_index].next().unwrap()),
+ None => None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_iterable_store() {
+ let mut writer = IterableStoreWriter::new(Vec::new());
+ writer.write(&1).unwrap();
+ writer.write(&2).unwrap();
+ writer.write(&3).unwrap();
+ let writer = writer.finalize().unwrap();
+
+ let reader = IterableStoreReader::new(writer.as_slice());
+
+ let items: Vec<i32> = reader.map(|item| item.unwrap()).collect();
+ assert_eq!(items, vec![1, 2, 3]);
+ }
+
+ #[test]
+ fn test_sorted_iterable_store() {
+ let mut writer1 = IterableStoreWriter::new(Vec::new());
+ writer1.write(&1).unwrap();
+ writer1.write(&3).unwrap();
+ writer1.write(&5).unwrap();
+ let writer1 = writer1.finalize().unwrap();
+
+ let mut writer2 = IterableStoreWriter::new(Vec::new());
+ writer2.write(&2).unwrap();
+ writer2.write(&4).unwrap();
+ writer2.write(&6).unwrap();
+ let writer2 = writer2.finalize().unwrap();
+
+ let reader1 = IterableStoreReader::new(writer1.as_slice());
+
+ let reader2 = IterableStoreReader::new(writer2.as_slice());
+
+ let reader = SortedIterableStoreReader::new(vec![reader1, reader2]);
+
+ let items: Vec<i32> = reader.map(|item| item.unwrap()).collect();
+ assert_eq!(items, vec![1, 2, 3, 4, 5, 6]);
+ }
+}
diff --git a/crates/core/src/file_store/mod.rs b/crates/core/src/file_store/mod.rs
new file mode 100644
index 00000000..806478cb
--- /dev/null
+++ b/crates/core/src/file_store/mod.rs
@@ -0,0 +1,20 @@
+// Stract is an open source web search engine.
+// Copyright (C) 2024 Stract ApS
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>
+
+pub mod iterable;
+pub mod peekable;
+
+pub use peekable::Peekable;
diff --git a/crates/core/src/file_store/peekable.rs b/crates/core/src/file_store/peekable.rs
new file mode 100644
index 00000000..00d62225
--- /dev/null
+++ b/crates/core/src/file_store/peekable.rs
@@ -0,0 +1,61 @@
+// Stract is an open source web search engine.
+// Copyright (C) 2024 Stract ApS
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/
+
+// TODO: Remove peekable from speedy_kv::segment and replace it with this
+
+/// An iterator that allows peeking at the next element.
+/// Unlike the standard library's `Peekable`, this implementation
+/// *is not* lazy and will always consume the next element when peeking.
+/// This is useful when you want to peek at the next element without
+/// having a mutable reference to the iterator.
+pub struct Peekable<I>
+where
+ I: Iterator,
+{
+ iter: I,
+ peeked: Option<I::Item>,
+}
+
+impl<I> Peekable<I>
+where
+ I: Iterator,
+{
+ pub fn new(iter: I) -> Self {
+ let mut iter = iter;
+ let peeked = iter.next();
+ Self { iter, peeked }
+ }
+
+ pub fn peek(&self) -> Option<&I::Item> {
+ self.peeked.as_ref()
+ }
+}
+
+impl<I> Iterator for Peekable<I>
+where
+ I: Iterator,
+{
+ type Item = I::Item;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let peeked = self.peeked.take();
+ if peeked.is_some() {
+ self.peeked = self.iter.next();
+ }
+
+ peeked
+ }
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 8ddf0572..d452cc81 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -51,6 +51,7 @@ mod executor;
mod external_sort;
mod fastfield_reader;
pub mod feed;
+mod file_store;
mod highlighted;
mod human_website_annotations;
pub mod hyperloglog;
diff --git a/crates/core/src/webgraph/edge.rs b/crates/core/src/webgraph/edge.rs
index 71972c75..0557e551 100644
--- a/crates/core/src/webgraph/edge.rs
+++ b/crates/core/src/webgraph/edge.rs
@@ -58,7 +58,7 @@ where
pub label: L,
}
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, bincode::Encode, bincode::Decode)]
pub struct InnerEdge<L>
where
L: EdgeLabel,
diff --git a/crates/core/src/webgraph/mod.rs b/crates/core/src/webgraph/mod.rs
index ecb53f34..e430ecd2 100644
--- a/crates/core/src/webgraph/mod.rs
+++ b/crates/core/src/webgraph/mod.rs
@@ -43,6 +43,7 @@ mod node;
mod segment;
mod shortest_path;
mod store;
+mod store_writer;
mod writer;
type SegmentID = String;
diff --git a/crates/core/src/webgraph/segment.rs b/crates/core/src/webgraph/segment.rs
index b767c297..50055101 100644
--- a/crates/core/src/webgraph/segment.rs
+++ b/crates/core/src/webgraph/segment.rs
@@ -34,12 +34,12 @@ pub struct SegmentWriter {
impl SegmentWriter {
pub fn open<P: AsRef<Path>>(folder_path: P, id: String, compression: Compression) -> Self {
SegmentWriter {
- adjacency: EdgeStoreWriter::open(
+ adjacency: EdgeStoreWriter::new(
folder_path.as_ref().join(&id).join(ADJACENCY_STORE),
compression,
false,
),
- reversed_adjacency: EdgeStoreWriter::open(
+ reversed_adjacency: EdgeStoreWriter::new(
folder_path
.as_ref()
.join(&id)
diff --git a/crates/core/src/webgraph/store.rs b/crates/core/src/webgraph/store.rs
index 9e11a950..3f4f71f5 100644
--- a/crates/core/src/webgraph/store.rs
+++ b/crates/core/src/webgraph/store.rs
@@ -1,5 +1,5 @@
// Stract is an open source web search engine.
-// Copyright (C) 2023 Stract ApS
+// Copyright (C) 2024 Stract ApS
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
@@ -14,12 +14,7 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
-use std::{
- fs::File,
- io::Write,
- ops::Range,
- path::{Path, PathBuf},
-};
+use std::{fs::File, io::Write, ops::Range, path::Path};
use fst::Automaton;
use itertools::Itertools;
@@ -27,7 +22,8 @@ use memmap2::Mmap;
use crate::speedy_kv;
-use super::{Compression, Edge, EdgeLabel, FullNodeID, InnerEdge, NodeID};
+pub use super::store_writer::EdgeStoreWriter;
+use super::{Compression, Edge, FullNodeID, InnerEdge, NodeID};
#[derive(
Debug,
@@ -46,70 +42,6 @@ struct SerializedEdge {
label: Vec<u8>,
}
-struct SortableEdge<L: EdgeLabel> {
- sort_node: NodeID,
- edge: InnerEdge<L>,
-}
-
-impl<L: EdgeLabel> PartialOrd for SortableEdge<L> {
- fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
- Some(self.cmp(other))
- }
-}
-
-impl<L: EdgeLabel> Ord for SortableEdge<L> {
- fn cmp(&self, other: &Self) -> std::cmp::Ordering {
- self.sort_node.cmp(&other.sort_node)
- }
-}
-
-impl<L: EdgeLabel> PartialEq for SortableEdge<L> {
- fn eq(&self, other: &Self) -> bool {
- self.sort_node == other.sort_node
- }
-}
-
-impl<L: EdgeLabel> Eq for SortableEdge<L> {}
-
-pub struct EdgeStoreWriter {
- reversed: bool,
- path: PathBuf,
- edges: Vec<SortableEdge<String>>,
- compression: Compression,
-}
-
-impl EdgeStoreWriter {
- pub fn open<P: AsRef<Path>>(path: P, compression: Compression, reversed: bool) -> Self {
- Self {
- edges: Vec::new(),
- reversed,
- path: path.as_ref().to_path_buf(),
- compression,
- }
- }
-
- pub fn put(&mut self, edge: InnerEdge<String>) {
- let sort_node = if self.reversed {
- edge.to.id
- } else {
- edge.from.id
- };
-
- self.edges.push(SortableEdge { sort_node, edge });
- }
-
- pub fn finalize(mut self) -> EdgeStore {
- self.edges.sort_unstable();
-
- EdgeStore::build(
- self.path,
- self.compression,
- self.reversed,
- self.edges.into_iter().map(|e| e.edge),
- )
- }
-}
-
struct PrefixDb {
db: speedy_kv::Db<Vec<u8>, Vec<u8>>,
}
@@ -283,9 +215,11 @@ impl EdgeStore {
);
}
- /// Build a new edge store from a set of edges. The edges must be sorted by
+ /// Build a new edge store from a set of edges.
+ ///
+ /// **IMPORTANT** The edges must be sorted by
/// either the from or to node, depending on the value of `reversed`.
- fn build<P: AsRef<Path>>(
+ pub fn build<P: AsRef<Path>>(
path: P,
compression: Compression,
reversed: bool,
@@ -489,7 +423,7 @@ mod tests {
#[test]
fn test_insert() {
- let mut kv: EdgeStoreWriter = EdgeStoreWriter::open(
+ let mut kv: EdgeStoreWriter = EdgeStoreWriter::new(
crate::gen_temp_path().join("test-segment"),
Compression::default(),
false,
@@ -523,7 +457,7 @@ mod tests {
#[test]
fn test_reversed() {
- let mut kv: EdgeStoreWriter = EdgeStoreWriter::open(
+ let mut kv: EdgeStoreWriter = EdgeStoreWriter::new(
crate::gen_temp_path().join("test-segment"),
Compression::default(),
true,
diff --git a/crates/core/src/webgraph/store_writer.rs b/crates/core/src/webgraph/store_writer.rs
new file mode 100644
index 00000000..e803846c
--- /dev/null
+++ b/crates/core/src/webgraph/store_writer.rs
@@ -0,0 +1,187 @@
+// Stract is an open source web search engine.
+// Copyright (C) 2024 Stract ApS
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+use std::{
+ fs::File,
+ path::{Path, PathBuf},
+};
+
+use crate::file_store::{
+ self,
+ iterable::{IterableStoreReader, SortedIterableStoreReader},
+};
+use crate::Result;
+
+use super::{store::EdgeStore, Compression, EdgeLabel, InnerEdge, NodeID};
+
+#[derive(bincode::Encode, bincode::Decode)]
+struct SortableEdge<L: EdgeLabel> {
+ sort_node: NodeID,
+ edge: InnerEdge<L>,
+}
+
+impl<L: EdgeLabel> PartialOrd for SortableEdge<L> {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl<L: EdgeLabel> Ord for SortableEdge<L> {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.sort_node.cmp(&other.sort_node)
+ }
+}
+
+impl<L: EdgeLabel> PartialEq for SortableEdge<L> {
+ fn eq(&self, other: &Self) -> bool {
+ self.sort_node == other.sort_node
+ }
+}
+
+impl<L: EdgeLabel> Eq for SortableEdge<L> {}
+
+pub const MAX_BATCH_SIZE: usize = 100_000;
+
+struct SortedEdgeIterator<M, D>
+where
+ M: Iterator<Item = SortableEdge<String>>,
+ D: Iterator<Item = SortableEdge<String>>,
+{
+ mem: file_store::Peekable<M>,
+ file_reader: file_store::Peekable<D>,
+}
+
+impl<M, D> Iterator for SortedEdgeIterator<M, D>
+where
+ M: Iterator<Item = SortableEdge<String>>,
+ D: Iterator<Item = SortableEdge<String>>,
+{
+ type Item = SortableEdge<String>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if let Some(edge) = self.mem.peek() {
+ if let Some(file_edge) = self.file_reader.peek() {
+ if edge.sort_node < file_edge.sort_node {
+ self.mem.next()
+ } else {
+ self.file_reader.next()
+ }
+ } else {
+ self.mem.next()
+ }
+ } else {
+ self.file_reader.next()
+ }
+ }
+}
+
+pub struct EdgeStoreWriter {
+ reversed: bool,
+ path: PathBuf,
+ edges: Vec<SortableEdge<String>>,
+ stored_writers: Vec<PathBuf>,
+ compression: Compression,
+}
+
+impl EdgeStoreWriter {
+ pub fn new<P: AsRef<Path>>(path: P, compression: Compression, reversed: bool) -> Self {
+ let path = path.as_ref().join("writer");
+
+ if !path.exists() {
+ std::fs::create_dir_all(&path).unwrap();
+ }
+
+ Self {
+ edges: Vec::new(),
+ reversed,
+ path: path.to_path_buf(),
+ compression,
+ stored_writers: Vec::new(),
+ }
+ }
+
+ fn flush_to_file(&mut self) -> Result<()> {
+ let file_path = self
+ .path
+ .join(format!("{}.store", self.stored_writers.len()));
+ let file = File::create(&file_path)?;
+
+ let mut writer = file_store::iterable::IterableStoreWriter::new(file);
+
+ for edge in &self.edges {
+ writer.write(edge)?;
+ }
+ writer.finalize()?;
+
+ self.edges.clear();
+
+ self.stored_writers.push(file_path);
+
+ Ok(())
+ }
+
+ pub fn put(&mut self, edge: InnerEdge<String>) {
+ let sort_node = if self.reversed {
+ edge.to.id
+ } else {
+ edge.from.id
+ };
+
+ self.edges.push(SortableEdge { sort_node, edge });
+
+ if self.edges.len() >= MAX_BATCH_SIZE {
+ self.flush_to_file().unwrap();
+ }
+ }
+
+ fn sorted_edges(mut self) -> impl Iterator<Item = SortableEdge<String>> {
+ self.edges.sort_unstable();
+ let readers = self
+ .stored_writers
+ .iter()
+ .map(|p| {
+ let file = File::open(p).unwrap();
+ IterableStoreReader::new(file)
+ })
+ .collect();
+ let file_reader = SortedIterableStoreReader::new(readers).map(|r| r.unwrap());
+
+ let edges = std::mem::take(&mut self.edges);
+
+ SortedEdgeIterator {
+ mem: file_store::Peekable::new(edges.into_iter()),
+ file_reader: file_store::Peekable::new(file_reader),
+ }
+ }
+
+ pub fn finalize(self) -> EdgeStore {
+ let p = self.path.parent().unwrap().to_path_buf();
+
+ EdgeStore::build(
+ p,
+ self.compression,
+ self.reversed,
+ self.sorted_edges().map(|e| e.edge),
+ )
+ }
+}
+
+impl Drop for EdgeStoreWriter {
+ fn drop(&mut self) {
+ // cleanup writer directory
+ std::fs::remove_dir_all(&self.path).unwrap();
+ }
+}