diff --git a/CHANGELOG.md b/CHANGELOG.md index cf4245d9..c6450d61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,12 @@ versions may change the store format and the API; the release notes say how to u ### Performance +- `tripletrail load` reads N-Triples and N-Quads from a pipe as fast as from a file (#775): a + pipe gives at most 64 KB a read, and each such read cost about 2 ms, so a load from + `zcat … |` or a named pipe took 4.5 times as long. The loader now reads into a block it zeroed + once, and parses each block while it reads the next. 25M triples: 17.2 s from a named pipe, + 16.4 s from the file. The `read/input` load step overlaps `read/parse` now. + - Large SELECT answers are written faster (#722): a `LIMIT` (and `OFFSET`) without an `ORDER BY` over one triple pattern, the shape of an export read page by page, is answered from the ids, and answers on ids are written in parallel batches. 500,000 rows of `?s ?p ?o` take 2.3 times diff --git a/crates/tripletrail-store/src/lib.rs b/crates/tripletrail-store/src/lib.rs index e62322c9..dcdfdde8 100644 --- a/crates/tripletrail-store/src/lib.rs +++ b/crates/tripletrail-store/src/lib.rs @@ -1602,6 +1602,8 @@ impl Store { // The time the parsing thread spends reading the input and waiting for the // dictionary to take its batches; the rest of its time is parsing. let (mut input, mut handing) = (steps::Busy::default(), steps::Busy::default()); + // The parsing of N-Triples and N-Quads blocks, on their own threads (#775). + let mut parse = steps::Busy::default(); let ids = if matches!(format, RdfFormat::NTriples | RdfFormat::NQuads) && threads > 1 { // Read a block at a time, so the text and the parsed terms of only a few blocks // are in memory at once. The parts of a block are parsed on every core, each into @@ -1610,53 +1612,69 @@ impl Store { self.intern_pipelined(sorter, |tx| { // The block grows as text comes in: a body of a few hundred bytes made a // zero-filled block of 64 MB, 40 ms under the writer lock (#702). - let mut block: Vec = Vec::new(); - loop { - let start = block.len(); - let size = PARSE_BLOCK.max(start * 2); - // A first piece, then, if there is more, room for the whole block at once. - let first = (64 << 10).min(size - start); - input.time(|| -> std::io::Result<()> { - (&mut reader).take(first as u64).read_to_end(&mut block)?; - if block.len() == start + first { - block.reserve_exact(size - block.len()); - (&mut reader) - .take((size - block.len()) as u64) - .read_to_end(&mut block)?; + // `block[..filled]` holds the text read so far; the rest is zeroed room, + // kept from block to block. + let (mut block, mut filled) = (Vec::new(), 0); + // Each block is parsed on its own thread while this one reads the next: a + // pipe holds only 64 KB, so its writer would wait for the whole parse (#775). + let mut spare = Vec::new(); + std::thread::scope(|threads_scope| -> Result<(), StoreError> { + let mut parsing: Option> = None; + // Takes a parsed block's times, and its text back to read into again, and + // whether the dictionary's thread took its batches. + let mut finish_parsed = + |parsed: Parsed| -> Result<(Vec, bool), StoreError> { + parse.0 += parsed.parse; + handing.0 += parsed.handing; + parsed.result?; + Ok((parsed.text, parsed.sent)) + }; + loop { + let size = PARSE_BLOCK.max(filled * 2); + input.time(|| fill_block(&mut reader, &mut block, &mut filled, size))?; + let done = filled < size; + // Parse up to the last line end; the rest starts the next block. + let end = if done { + filled + } else { + match block[..filled].iter().rposition(|&b| b == b'\n') { + Some(i) => i + 1, + None => continue, // one line longer than the block: read more + } + }; + // Waits for the block before, so the batches stay in order. + if let Some(before) = parsing.take() { + let parsed = before + .join() + .unwrap_or_else(|e| std::panic::resume_unwind(e)); + let sent; + (spare, sent) = finish_parsed(parsed)?; + if !sent { + return Ok(()); + } } - Ok(()) - })?; - let done = block.len() < size; - // Parse up to the last line end; the rest starts the next block. - let end = if done { - block.len() - } else { - match block.iter().rposition(|&b| b == b'\n') { - Some(i) => i + 1, - None => continue, // one line longer than the block: read more + // The rest moves to the start of the other block, which is read next. + let rest = filled - end; + if spare.len() < rest { + spare.resize(rest, 0); } - }; - let batches = parser - .clone() - .split_slice_for_parallel_parsing(&block[..end], threads * 4) - .into_par_iter() - .map(|p| { - let mut batch = KeyBatch::default(); - let mut key = Vec::new(); - for q in p { - batch.push(q?.as_ref(), scope, &mut key); - } - Ok(batch.complete()) - }) - .collect::, RdfParseError>>()?; - if handing.time(|| tx.send(batches)).is_err() { - return Ok(()); - } - if done { - return Ok(()); + spare[..rest].copy_from_slice(&block[end..filled]); + let text = std::mem::replace(&mut block, std::mem::take(&mut spare)); + filled = rest; + if done { + // The last block (and a small body's only one, #702) is parsed on + // this thread: there is nothing left to read meanwhile. + let parsed = parse_block(parser.clone(), text, end, threads, scope, tx); + finish_parsed(parsed)?; + return Ok(()); + } + let parser = parser.clone(); + parsing = Some( + threads_scope + .spawn(move || parse_block(parser, text, end, threads, scope, tx)), + ); } - block.drain(..end); - } + }) })? } else { // Turtle, RDF/XML...: this thread parses and writes each term's dictionary key, @@ -1686,8 +1704,13 @@ impl Store { let steps = &self.inner.load.steps; steps.record("read", read); steps.record("read/input", input.0); - // Reading the input in the N-Triples path, and the parser's own reads otherwise. - steps.record("read/parse", read.saturating_sub(input.0 + handing.0)); + // N-Triples and N-Quads blocks are parsed while the next is read; other formats are + // parsed on this thread, between its reads. + if parse.0.is_zero() { + steps.record("read/parse", read.saturating_sub(input.0 + handing.0)); + } else { + steps.record("read/parse", parse.0); + } let added = self.bulk_finish(ids, &mut writer)?; drop(writer); self.entail_after_load()?; @@ -2527,6 +2550,80 @@ impl Store { } } +/// A block of N-Triples or N-Quads parsed on its own thread, with its text to read into again. +struct Parsed { + text: Vec, + result: Result<(), RdfParseError>, + /// Whether the dictionary's thread took the batches (it stops on an error). + sent: bool, + parse: std::time::Duration, + handing: std::time::Duration, +} + +/// Parses `text[..end]` on every core into batches of dictionary keys, and hands them to the +/// dictionary's thread. +fn parse_block( + parser: RdfParser, + text: Vec, + end: usize, + threads: usize, + scope: Option<&labels::Scope>, + tx: &std::sync::mpsc::SyncSender>, +) -> Parsed { + let started = std::time::Instant::now(); + let batches = parser + .split_slice_for_parallel_parsing(&text[..end], threads * 4) + .into_par_iter() + .map(|p| { + let mut batch = KeyBatch::default(); + let mut key = Vec::new(); + for q in p { + batch.push(q?.as_ref(), scope, &mut key); + } + Ok(batch.complete()) + }) + .collect::, RdfParseError>>(); + let parse = started.elapsed(); + let started = std::time::Instant::now(); + let (result, sent) = match batches { + Ok(batches) => (Ok(()), tx.send(batches).is_ok()), + Err(e) => (Err(e), false), + }; + Parsed { + text, + result, + sent, + parse, + handing: started.elapsed(), + } +} + +/// Reads into `block` until `block[..filled]` holds `size` bytes or the input ends. A pipe +/// answers each read with at most 64 KB; `take(…).read_to_end(…)` spent milliseconds per such +/// read on the block's spare room, so a load from a pipe took four times as long as from the +/// file (#775). The room is zeroed once, growing by doubling, and kept from block to block. +fn fill_block( + reader: &mut impl std::io::Read, + block: &mut Vec, + filled: &mut usize, + size: usize, +) -> std::io::Result<()> { + while *filled < size { + if block.len() == *filled { + // A small input stays small: the room starts at 64 KB (#702). + let grow = (*filled).max(64 << 10).min(size - *filled); + block.resize(*filled + grow, 0); + } + match reader.read(&mut block[*filled..]) { + Ok(0) => break, + Ok(n) => *filled += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + Ok(()) +} + /// See [`Store::clean_checkpoint`]. fn clean_checkpoint(disk: &persist::Disk) -> Option<(PathBuf, [u64; 2])> { if disk.log_size() != 0 { @@ -5332,6 +5429,51 @@ impl<'a> QueryableDataset<'a> for Snapshot { mod tests { use super::*; + /// A reader like a pipe: at most 64 KB per read. + struct Piped<'a> { + text: &'a [u8], + reads: usize, + } + + impl std::io::Read for Piped<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.reads += 1; + let n = buf.len().min(64 << 10).min(self.text.len()); + buf[..n].copy_from_slice(&self.text[..n]); + self.text = &self.text[n..]; + Ok(n) + } + } + + #[test] + fn a_block_fills_from_a_pipe_in_few_reads() { + let text: Vec = (0..10 << 20).map(|i| (i % 251) as u8).collect(); + let mut pipe = Piped { + text: &text, + reads: 0, + }; + let (mut block, mut filled) = (Vec::new(), 0); + super::fill_block(&mut pipe, &mut block, &mut filled, 4 << 20).unwrap(); + assert_eq!(&block[..filled], &text[..4 << 20]); + // One read per 64 KB, and no more room than the block. + assert_eq!(pipe.reads, 64); + assert_eq!(block.len(), 4 << 20); + // The rest, then the end of the input. + block.copy_within(1 << 20..filled, 0); + filled -= 1 << 20; + super::fill_block(&mut pipe, &mut block, &mut filled, 16 << 20).unwrap(); + assert_eq!(&block[..filled], &text[1 << 20..]); + assert!(pipe.reads <= 64 + 96 + 2, "{} reads", pipe.reads); + // A small input makes a small block. + let mut pipe = Piped { + text: b" .\n", + reads: 0, + }; + let (mut block, mut filled) = (Vec::new(), 0); + super::fill_block(&mut pipe, &mut block, &mut filled, 64 << 20).unwrap(); + assert_eq!((filled, block.len()), (14, 64 << 10)); + } + /// A subject, predicate or object the rows hide everywhere matches nothing in a view, /// and its estimates and compiled patterns say so, so join orders start there (#204). /// One hidden only on some subjects keeps its estimate and its other quads. diff --git a/docs/store.md b/docs/store.md index 408b5133..020df8d1 100644 --- a/docs/store.md +++ b/docs/store.md @@ -818,8 +818,8 @@ A bulk load records the wall time of each of its steps and the process's peak me | Part | What a thread does in it | |---|---| -| `read/input` | reads the file's next 64 MB block (N-Triples and N-Quads; other formats read as they parse) | -| `read/parse` | the rest of the parsing thread's time: it parses each block on every core and hashes each term's key (it waits for the parsing of the block's parts) | +| `read/input` | reads the input's next 64 MB block, while the block before is parsed (N-Triples and N-Quads; other formats read as they parse) | +| `read/parse` | parses each block on every core and hashes each term's key (N-Triples and N-Quads; other formats: the rest of the parsing thread's time) | | `read/look up` | looks the keys of a block up in the dictionary's mapped files, on the lookup threads (only once the dictionary is past an eighth of `--memory-limit`) | | `read/add terms` | the one thread that numbers the terms: finds or adds each key in the dictionary's table | | `read/ids and sorted runs` | writes each triple's ids to the sorter; past half of `--memory-limit`, sorts each full chunk and writes it out as a run | @@ -859,7 +859,12 @@ the data: 4.5 s at 25M, 10.7 s at 50M (#730). Loading from a pipe (`mkfifo`, `head -n` into it) took about 4.5 times as long, with the parsing thread waiting for its input: 25M triples in 103.6 s instead of 23.7 s, 83 s of it in -`read/input`. +`read/input`. Each read of a pipe gives at most 64 KB, and `read_to_end` spent about 2 ms on the +block's spare room for each. Since #775 the loader reads into a block it zeroed once, and parses +each block while it reads the next, so the pipe's writer never waits for a parse. 25M short +triples (1.8 GB, 4 cores, two runs each): 16.4 and 17.4 s from the file, 17.2 and 17.9 s from a +named pipe, with `read/input` 1.2 s and 4.4 s (it overlaps the parsing now). The peak memory +grows by one block (64 MB). ### Streaming bulk load on all of RINF