AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
Cut cold first-query search latency (#2422) (#2443)
xerj-org085d1e53ee25
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 20fa3b994..901b8d0ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -105,6 +105,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the file's prepared records are safely on disk; resume and crash recoverystill replay from the verified prepared records. On a 344 MB test corpus thestate directory went from 503 MB to 242 MB after a sync (#2421).+- `xerj search` checks whether the index is stale while the search runs+ instead of after it. The check reads the autoindex catalog, which cost about+ 0.3 s on the first search after a restart, and that time was added to every+ cold search (#2422).+- Cold searches read stored fields about 6x faster. Picking a few hits+ out of a stored segment read the compressed data one byte at a time; it+ now reads it in 64 KB chunks. Loading one hit from a 20,000-document+ segment went from 1.3 s to 0.2 s, with the same results (#2422).+- Loading a whole segment's stored documents, which a search that returns+ full `_source` does the first time it touches a segment, is about 1.7x+ faster. The stored columns are now unpacked side by side instead of one+ after another, and the documents are rebuilt in parallel. On a 100 MB+ segment with embeddings this went from 0.41 s to 0.24 s, with identical+ output (#2422).- The first searches after a restart, or after a segment left the cache,no longer read every stored document to return a page of hits. When therequest names its `_source` fields (as `xerj search` does), only thediff --git a/engine/crates/xerj-autoindex/src/search.rs b/engine/crates/xerj-autoindex/src/search.rsindex d6a8179b2..c707ba946 100644--- a/engine/crates/xerj-autoindex/src/search.rs+++ b/engine/crates/xerj-autoindex/src/search.rs@@ -802,6 +802,21 @@ fn parse_search_cli(}/// Entry point for the `search` subcommand. Returns a process exit code.+/// Start the staleness check on its own thread so it overlaps the search.+/// The check uses its own blocking client with a short timeout.+fn spawn_staleness_check(+ url: &str,+ api_key: Option<&str>,+ prefix: &str,+) -> std::thread::JoinHandle<Option<staleness::StalenessHint>> {+ let (url, api_key, prefix) = (+ url.to_string(),+ api_key.map(str::to_string),+ prefix.to_string(),+ );+ std::thread::spawn(move || staleness::check(&url, api_key.as_deref(), &prefix))+}+pub fn run_search_cli() -> i32 {let url = std::env::var("XERJ_URL").ok()@@ -924,6 +939,12 @@ pub fn run_search_cli() -> i32 {if code_corpus && k > 0 {body["size"] = json!(search_fetch_size(k));}+ // The catalog read and mtime walk run beside the query instead of after+ // it. On a cold node the catalog's sorted run lookup was ~0.26 s on top+ // of the search (#2422). A failed search exits without waiting for it.+ // A missing catalog, a remote folder, or a check that hits its cap leaves+ // the response unchanged (#2345).+ let stale = spawn_staleness_check(&url, api_key.as_deref(), &prefix);let mut resp = match es.search_without_savings(&pattern, &body) {Ok(v) => v,Err(e) => {@@ -941,10 +962,7 @@ pub fn run_search_cli() -> i32 {// header cite the matched line. `xerj code --json` is the raw server// body and does not share this hit post-pass.xerj_common::xccode::passage::annotate_search_match_lines(&mut resp, &query);- // After the query, so a failed search does not pay for the catalog read.- // A missing catalog, a remote folder, or a check that hits its cap leaves- // the response unchanged (#2345).- let hint = staleness::check(&url, api_key.as_deref(), &prefix);+ let hint = stale.join().ok().flatten();if as_json {if let Some(hint) = &hint {staleness::attach(&mut resp, hint);@@ -1019,6 +1037,38 @@ pub fn run_search_cli() -> i32 {#[cfg(test)]mod tests {use super::*;++ /// The CLI's catalog read must overlap the query, not follow it (#2422).+ /// A catalog that answers after 600 ms must not hold up the caller.+ #[test]+ fn staleness_check_runs_beside_the_search_instead_of_after_it() {+ use std::io::{Read, Write};+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let server = std::thread::spawn(move || {+ let (mut sock, _) = listener.accept().unwrap();+ let mut buf = [0u8; 8192];+ let _ = sock.read(&mut buf);+ std::thread::sleep(std::time::Duration::from_millis(600));+ let body = r#"{"hits":{"hits":[]}}"#;+ let _ = write!(+ sock,+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ });+ let started = std::time::Instant::now();+ let handle = spawn_staleness_check(&url, None, "sr");+ assert!(+ started.elapsed() < std::time::Duration::from_millis(300),+ "starting the check blocked for {:?}",+ started.elapsed()+ );+ // No run doc in the catalog, so no hint, once it has answered.+ assert!(handle.join().unwrap().is_none());+ assert!(started.elapsed() >= std::time::Duration::from_millis(500));+ server.join().unwrap();+ }use xerj_common::code_query::normalize_code_search_query;/// `My_Proj` is stored as `my-proj-*`. Searching the typed charactersdiff --git a/engine/crates/xerj-storage/src/stored_codec.rs b/engine/crates/xerj-storage/src/stored_codec.rsindex da98d6fe3..677d40eab 100644--- a/engine/crates/xerj-storage/src/stored_codec.rs+++ b/engine/crates/xerj-storage/src/stored_codec.rs@@ -130,6 +130,19 @@ where.is_break()}+/// Read buffer for the streaming JSON column parsers (#2422).+pub(crate) const JSON_STREAM_READ_BUFFER: usize = 64 * 1024;++/// Buffer a reader before `serde_json::Deserializer::from_reader`, which+/// pulls ONE byte per `read` call. Over zstd's streaming `Decoder` that was+/// one `ZSTD_decompressStream` call per byte of column JSON: hydrating one+/// row of a 20k-row, 87 MB stored section took ~1.3 s, five times the full+/// decode it exists to avoid. Buffering keeps the bounded memory of+/// streaming (one 64 KiB buffer) and drops that cost to the parse itself.+pub(crate) fn buffered_json_stream<R: std::io::Read>(reader: R) -> std::io::BufReader<R> {+ std::io::BufReader::with_capacity(JSON_STREAM_READ_BUFFER, reader)+}+// ── V1: flat LZ4 over JSON (legacy) ───────────────────────────────────────/// Magic prefix for LZ4-compressed stored sections (v1, pre-columnar).@@ -1103,6 +1116,40 @@ fn zstd_frame_content_size(payload: &[u8], context: &str) -> Result<Option<u64>>.map_err(|_| StorageError::Other(anyhow::anyhow!("{context} zstd frame header is invalid")))}+/// Largest output `zstd_decode_presized` reserves up front from a frame+/// header. A header is untrusted input; above this the decode falls back to+/// growing the buffer as data actually arrives.+const ZSTD_PRESIZE_CAP: u64 = 1 << 30;++/// Decode a zstd column payload into a buffer sized from the frame header+/// (#2422). `zstd::decode_all` has no size hint, so a 50 MB embedding column+/// grew its buffer by repeated reallocation and copying (13.75% of a cold+/// search's CPU was `rallocx`). Payloads that are not exactly one frame with+/// a declared size, or that declare more than `ZSTD_PRESIZE_CAP`, keep the+/// `decode_all` path, as does any frame the one-shot decode rejects, so the+/// output and the errors are those of `decode_all`.+fn zstd_decode_presized(frame: &[u8]) -> std::io::Result<Vec<u8>> {+ let single_frame =+ zstd::zstd_safe::find_frame_compressed_size(frame).is_ok_and(|size| size == frame.len());+ let declared = zstd::zstd_safe::get_frame_content_size(frame)+ .ok()+ .flatten();+ if let (true, Some(size)) = (single_frame, declared) {+ if size <= ZSTD_PRESIZE_CAP {+ let mut out = Vec::new();+ if out.try_reserve_exact(size as usize).is_ok() {+ let decoded = zstd::bulk::Decompressor::new().and_then(|mut decompressor| {+ decompressor.decompress_to_buffer(frame, &mut out)+ });+ if decoded.is_ok() && out.len() as u64 == size {+ return Ok(out);+ }+ }+ }+ }+ zstd::decode_all(frame)+}+fn decode_zstd_exact(payload: &[u8], expected: usize, context: &str) -> Result<Vec<u8>> {if zstd_frame_content_size(payload, context)?.is_some_and(|size| size != expected as u64) {return Err(StorageError::Other(anyhow::anyhow!(@@ -1679,7 +1726,7 @@ fn parse_typed_vector_reader<R: std::io::Read>() -> Result<std::result::Result<Option<StoredVectorRows>, ()>> {use serde::de::Deserializer as _;let cancelled = std::cell::Cell::new(false);- let mut deserializer = serde_json::Deserializer::from_reader(reader);+ let mut deserializer = serde_json::Deserializer::from_reader(buffered_json_stream(reader));let value = match deserializer.deserialize_seq(TypedVectorRowsVisitor {expected_rows: num_docs,column_index,@@ -1821,7 +1868,7 @@ fn parse_typed_chunk_reader<R: std::io::Read>(}}let cancelled = std::cell::Cell::new(false);- let mut deserializer = serde_json::Deserializer::from_reader(reader);+ let mut deserializer = serde_json::Deserializer::from_reader(buffered_json_stream(reader));let value = match deserializer.deserialize_seq(Visitor {rows: num_docs,column: column_index,@@ -2007,11 +2054,9 @@ fn decode_stored_v2(body: &[u8], present_nulls: &[(u32, u32)]) -> Result<Vec<u8>.map_err(|e| StorageError::Other(anyhow::anyhow!("v2 num_cols: {e}")))?as usize;- // First pass: decode each column into Vec<Value>. Store the name- // alongside so we can re-assemble the docs.- let mut col_names: Vec<String> = Vec::with_capacity(num_cols);- let mut col_data: Vec<Vec<serde_json::Value>> = Vec::with_capacity(num_cols);-+ // First pass: walk the column directory, then decode each column into+ // Vec<Value>. Store the name alongside so we can re-assemble the docs.+ let mut entries: Vec<(String, ColCodec, &[u8])> = Vec::with_capacity(num_cols.min(4096));for _ in 0..num_cols {let name_len = cur.read_u16::<LittleEndian>()@@ -2041,50 +2086,63 @@ fn decode_stored_v2(body: &[u8], present_nulls: &[(u32, u32)]) -> Result<Vec<u8>}let payload = &body[pos..pos + payload_len];cur.set_position((pos + payload_len) as u64);-- let values = match codec {- ColCodec::RawJson => decode_raw_json(payload)?,- ColCodec::Lz4Json => decode_lz4_json(payload)?,- ColCodec::Constant => decode_constant(payload, num_docs)?,- ColCodec::DictBitpack => decode_dict_bitpack(payload, num_docs)?,- ColCodec::TypedInt => decode_typed_int(payload, num_docs)?,- // CROSS_DEP and COPY_OF both require their source column to be- // materialised first. We emit a placeholder here and revisit- // both in the deferred fixpoint below — COPY_OF is written with- // an earlier pass-1 source by construction, but decode treats a- // crafted segment's references the same way instead of trusting- // that.- ColCodec::CopyOf | ColCodec::CrossDep => {- let (key, value) = match codec {- ColCodec::CopyOf => (- "__deferred_copy_of__",- serde_json::Value::Number((copy_of_source_index(payload)? as u64).into()),- ),- _ => (- "__deferred_cross_dep__",- serde_json::Value::Array(- payload- .iter()- .map(|b| serde_json::Value::Number((*b).into()))- .collect(),- ),- ),- };- col_names.push(name);- col_data.push(Vec::new());- col_data- .last_mut()- .unwrap()- .push(serde_json::Value::Object({+ entries.push((name, codec, payload));+ }++ // #2422: the columns are independent zstd/JSON streams, so decode them+ // in parallel. One embedding column (`*_vector_chunks`) is ~30% of a+ // 100 MB autoindex section's decode; serially every other column queued+ // behind it on the first (cold) search of a segment. Errors surface in+ // column order, as the serial loop reported them.+ let decoded: Vec<Result<Vec<serde_json::Value>>> = {+ use rayon::prelude::*;+ entries+ .par_iter()+ .map(|(_, codec, payload)| {+ let payload = *payload;+ Ok(match codec {+ ColCodec::RawJson => decode_raw_json(payload)?,+ ColCodec::Lz4Json => decode_lz4_json(payload)?,+ ColCodec::Constant => decode_constant(payload, num_docs)?,+ ColCodec::DictBitpack => decode_dict_bitpack(payload, num_docs)?,+ ColCodec::TypedInt => decode_typed_int(payload, num_docs)?,+ // CROSS_DEP and COPY_OF both require their source column+ // to be materialised first. We emit a placeholder here+ // and revisit both in the deferred fixpoint below —+ // COPY_OF is written with an earlier pass-1 source by+ // construction, but decode treats a crafted segment's+ // references the same way instead of trusting that.+ ColCodec::CopyOf | ColCodec::CrossDep => {+ let (key, value) = match codec {+ ColCodec::CopyOf => (+ "__deferred_copy_of__",+ serde_json::Value::Number(+ (copy_of_source_index(payload)? as u64).into(),+ ),+ ),+ _ => (+ "__deferred_cross_dep__",+ serde_json::Value::Array(+ payload+ .iter()+ .map(|b| serde_json::Value::Number((*b).into()))+ .collect(),+ ),+ ),+ };let mut m = serde_json::Map::new();m.insert(key.into(), value);- m- }));- continue;- }- };+ vec![serde_json::Value::Object(m)]+ }+ })+ })+ .collect()+ };+ let mut col_names: Vec<String> = Vec::with_capacity(entries.len());+ let mut col_data: Vec<Vec<serde_json::Value>> = Vec::with_capacity(entries.len());+ for ((name, _, _), values) in entries.into_iter().zip(decoded) {col_names.push(name);- col_data.push(values);+ col_data.push(values?);}// Second pass: resolve deferred CROSS_DEP columns now that the pass-1@@ -2199,45 +2257,95 @@ fn decode_stored_v2(body: &[u8], present_nulls: &[(u32, u32)]) -> Result<Vec<u8>))})?;out.push(b'[');- for d in 0..num_docs {- if d > 0 {- out.push(b',');+ // #2422: rows are independent, so serialise them in parallel row chunks+ // and append the chunks in order — byte-identical to the serial loop.+ // Each cell is moved out of `col_data` (it is used exactly once) instead+ // of cloned: the clone of every embedding array was half the reassembly+ // cost, and moving lets each row's memory go as soon as it is written.+ // Chunks are produced in bounded waves so the transient buffers stay a+ // small fraction of the output rather than a second full copy (#950).+ const ROWS_PER_CHUNK: usize = 256;+ let n_chunks = num_docs.div_ceil(ROWS_PER_CHUNK);+ let mut per_chunk: Vec<Vec<&mut [serde_json::Value]>> = (0..n_chunks)+ .map(|_| Vec::with_capacity(col_data.len()))+ .collect();+ for column in col_data.iter_mut() {+ let mut rest: &mut [serde_json::Value] = column.as_mut_slice();+ for chunk_cols in per_chunk.iter_mut() {+ let take = ROWS_PER_CHUNK.min(rest.len());+ let (head, tail) = std::mem::take(&mut rest).split_at_mut(take);+ chunk_cols.push(head);+ rest = tail;}- let mut source_map = serde_json::Map::new();- for (cix, name) in col_names.iter().enumerate() {- if cix == id_col_ix || cix == seq_col_ix {- continue;- }- let v = col_data[cix]- .get(d)- .cloned()- .unwrap_or(serde_json::Value::Null);- if !v.is_null() {- source_map.insert(name.clone(), v);- } else if present_null_set.contains(&(d as u32, cix as u32)) {- // Present explicit null (#415): re-insert in column order, as- // opposed to an absent field, which stays dropped.- source_map.insert(name.clone(), serde_json::Value::Null);+ }+ let wave = rayon::current_num_threads().max(1) * 2;+ let mut chunks = per_chunk.into_iter().enumerate();+ let mut done_chunks = 0usize;+ loop {+ let batch: Vec<(usize, Vec<&mut [serde_json::Value]>)> =+ chunks.by_ref().take(wave).collect();+ if batch.is_empty() {+ break;+ }+ let bufs: Vec<Result<Vec<u8>>> = {+ use rayon::prelude::*;+ batch+ .into_par_iter()+ .map(|(chunk_ix, mut cols)| {+ let start = chunk_ix * ROWS_PER_CHUNK;+ let end = (start + ROWS_PER_CHUNK).min(num_docs);+ let mut buf = Vec::new();+ for d in start..end {+ let local = d - start;+ let mut cell = |cix: usize| {+ cols[cix]+ .get_mut(local)+ .map(std::mem::take)+ .unwrap_or(serde_json::Value::Null)+ };+ if d > 0 {+ buf.push(b',');+ }+ let mut source_map = serde_json::Map::new();+ for (cix, name) in col_names.iter().enumerate() {+ if cix == id_col_ix || cix == seq_col_ix {+ continue;+ }+ let v = cell(cix);+ if !v.is_null() {+ source_map.insert(name.clone(), v);+ } else if present_null_set.contains(&(d as u32, cix as u32)) {+ // Present explicit null (#415): re-insert in+ // column order, as opposed to an absent+ // field, which stays dropped.+ source_map.insert(name.clone(), serde_json::Value::Null);+ }+ }+ let mut doc = serde_json::Map::new();+ doc.insert("_id".into(), cell(id_col_ix));+ doc.insert("_seq_no".into(), cell(seq_col_ix));+ doc.insert("_source".into(), serde_json::Value::Object(source_map));+ serde_json::to_writer(&mut buf, &serde_json::Value::Object(doc)).map_err(+ |e| StorageError::Other(anyhow::anyhow!("v2 reassemble: {e}")),+ )?;+ }+ Ok(buf)+ })+ .collect()+ };+ for buf in bufs {+ out.extend_from_slice(&buf?);+ }+ // After the first wave, size the output from the bytes actually+ // produced so far instead of doubling (and copying) up to ~100 MB.+ if done_chunks == 0 && n_chunks > wave {+ let estimate = out.len() / wave.min(n_chunks) * n_chunks;+ let estimate = estimate + estimate / 16;+ if estimate > out.capacity() {+ let _ = out.try_reserve_exact(estimate - out.len());}}- let mut doc = serde_json::Map::new();- doc.insert(- "_id".into(),- col_data[id_col_ix]- .get(d)- .cloned()- .unwrap_or(serde_json::Value::Null),- );- doc.insert(- "_seq_no".into(),- col_data[seq_col_ix]- .get(d)- .cloned()- .unwrap_or(serde_json::Value::Null),- );- doc.insert("_source".into(), serde_json::Value::Object(source_map));- serde_json::to_writer(&mut out, &serde_json::Value::Object(doc))- .map_err(|e| StorageError::Other(anyhow::anyhow!("v2 reassemble: {e}")))?;+ done_chunks += wave;}out.push(b']');Ok(out)@@ -2845,7 +2953,7 @@ fn decode_dict_bitpack(payload: &[u8], num_docs: usize) -> Result<Vec<serde_json"dict bitpack truncated")));}- let dict_json = zstd::decode_all(&payload[pos..pos + dict_zstd_len])+ let dict_json = zstd_decode_presized(&payload[pos..pos + dict_zstd_len]).map_err(|e| StorageError::Other(anyhow::anyhow!("dict zstd decode: {e}")))?;let entries: Vec<serde_json::Value> = serde_json::from_slice(&dict_json).map_err(|e| StorageError::Other(anyhow::anyhow!("dict json decode: {e}")))?;@@ -3114,7 +3222,7 @@ fn decode_cross_dep(fn decode_raw_json(payload: &[u8]) -> Result<Vec<serde_json::Value>> {let frame = decode_raw_payload(payload)?;- let raw = zstd::decode_all(frame)+ let raw = zstd_decode_presized(frame).map_err(|e| StorageError::Other(anyhow::anyhow!("raw zstd decode: {e}")))?;serde_json::from_slice(&raw).map_err(|e| StorageError::Other(anyhow::anyhow!("raw json decode: {e}")))@@ -5247,4 +5355,77 @@ mod tests {let actual = decode_stored(&encoded).unwrap().len() as u64;assert!(bound >= actual, "bound {bound} < actual {actual}");}++ /// #2422: the columnar decode runs its columns and its row chunks in+ /// parallel. The result must stay byte-identical to the input across+ /// several row chunks and waves, with present nulls (#415), absent+ /// fields, embedding arrays and strings that need escaping.+ #[test]+ fn v2_parallel_decode_is_byte_identical_across_row_chunks() {+ let mut docs: Vec<serde_json::Value> = Vec::new();+ for i in 0..9000u64 {+ let mut source = serde_json::Map::new();+ source.insert("a".into(), json!(["x", "y", "z"][(i % 3) as usize]));+ // Doc 0 carries every field, so the decoder's first-seen column+ // order matches each document's key order.+ if i % 7 == 3 {+ source.insert("b".into(), serde_json::Value::Null);+ } else if i % 5 != 4 {+ source.insert("b".into(), json!(i * 3));+ }+ if i % 11 != 10 {+ source.insert("c".into(), json!(format!("line \"{i}\"\n\ttab")));+ }+ source.insert(+ "vec".into(),+ // Eighths are exact in f32, which the stored vector path keeps.+ json!((0..8).map(|k| (i * 8 + k) as f64 / 8.0).collect::<Vec<_>>()),+ );+ docs.push(json!({ "_id": i.to_string(), "_seq_no": i, "_source": source }));+ }+ let raw = serde_json::to_vec(&docs).unwrap();+ let encoded = encode_stored_v2(&raw);+ assert!(+ is_columnar_stored_magic(&encoded) || &encoded[..4] == STORED_V3_MAGIC,+ "fixture must take the columnar codec"+ );+ let decoded = decode_stored(&encoded).unwrap();+ assert!(decoded == raw, "parallel columnar decode changed the bytes");+ }++ /// #2422: `zstd_decode_presized` must return exactly what+ /// `zstd::decode_all` does, including for frames without a declared+ /// size and for concatenated frames, which keep the `decode_all` path.+ #[test]+ fn presized_zstd_decode_matches_decode_all() {+ let data: Vec<u8> = (0..200_000u32)+ .flat_map(|i| (i % 251).to_le_bytes())+ .collect();+ let sized = zstd::bulk::compress(&data, 3).unwrap();+ assert!(zstd::zstd_safe::get_frame_content_size(&sized)+ .unwrap()+ .is_some());+ let mut unsized_frame = Vec::new();+ {+ let mut encoder = zstd::stream::write::Encoder::new(&mut unsized_frame, 3).unwrap();+ encoder.include_contentsize(false).unwrap();+ std::io::Write::write_all(&mut encoder, &data).unwrap();+ encoder.finish().unwrap();+ }+ assert!(zstd::zstd_safe::get_frame_content_size(&unsized_frame)+ .unwrap()+ .is_none());+ let mut concatenated = sized.clone();+ concatenated.extend_from_slice(&sized);+ for frame in [&sized, &unsized_frame, &concatenated] {+ assert_eq!(+ zstd_decode_presized(frame).unwrap(),+ zstd::decode_all(frame.as_slice()).unwrap()+ );+ }+ let mut corrupt = sized.clone();+ let mid = corrupt.len() / 2;+ corrupt.truncate(mid);+ assert!(zstd_decode_presized(&corrupt).is_err());+ }}diff --git a/engine/crates/xerj-storage/src/stored_codec/row_hydration.rs b/engine/crates/xerj-storage/src/stored_codec/row_hydration.rsindex 667156be5..d52a1a316 100644--- a/engine/crates/xerj-storage/src/stored_codec/row_hydration.rs+++ b/engine/crates/xerj-storage/src/stored_codec/row_hydration.rs@@ -175,7 +175,7 @@ fn select_json_rows<R: std::io::Read>(checkpoint: &mut dyn FnMut(StoredDecodeCheckpoint) -> std::ops::ControlFlow<()>,) -> Result<std::result::Result<Vec<serde_json::Value>, ()>> {let cancelled = Cell::new(false);- let mut deserializer = serde_json::Deserializer::from_reader(reader);+ let mut deserializer = serde_json::Deserializer::from_reader(buffered_json_stream(reader));let values = match deserializer.deserialize_seq(SelectedRowsVisitor {selected,expected_rows,@@ -873,6 +873,50 @@ mod tests {)}+ /// #2422: `select_json_rows` reads its column through a buffer.+ /// `serde_json`'s reader pulls one byte per `read`, and over zstd's+ /// streaming decoder every `read` was a `ZSTD_decompressStream` call, so+ /// one selected row of a large column cost one zstd call per byte.+ #[test]+ fn selected_rows_read_the_column_in_large_chunks_not_byte_by_byte() {+ struct CountingReader<'a> {+ inner: &'a [u8],+ reads: &'a Cell<usize>,+ }+ impl std::io::Read for CountingReader<'_> {+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {+ self.reads.set(self.reads.get() + 1);+ self.inner.read(buf)+ }+ }+ let rows: Vec<_> = (0..4096)+ .map(|i| json!({"row": i, "text": "x".repeat(200)}))+ .collect();+ let column = serde_json::to_vec(&rows).unwrap();+ let reads = Cell::new(0);+ let selected = select_json_rows(+ CountingReader {+ inner: &column,+ reads: &reads,+ },+ &[7, 4000],+ rows.len(),+ "test json",+ 0,+ &mut |_| std::ops::ControlFlow::Continue(()),+ )+ .unwrap()+ .unwrap();+ assert_eq!(selected, vec![rows[7].clone(), rows[4000].clone()]);+ let chunk_reads = column.len().div_ceil(JSON_STREAM_READ_BUFFER) + 2;+ assert!(+ reads.get() <= chunk_reads,+ "{} reads for a {} byte column; a byte-at-a-time parse makes one per byte",+ reads.get(),+ column.len()+ );+ }+#[test]fn raw_and_lz4_select_rows_and_reject_trailing_json() {for codec in [ColCodec::RawJson, ColCodec::Lz4Json] {