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
perf(merge): merge posting lists instead of re-analysing every document (#876) (#901)
xerj-org4878a6121c9e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 278c5e7f1..a0cd0f834 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,67 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Performance+- **Merge copies posting lists instead of re-analysing every document it+ merges** ([#876](https://github.com/xerj-org/xerj/issues/876)). A merged+ segment's postings ARE its inputs' postings with the document ids remapped —+ nothing about them depends on the source text — but the merge rebuilt each+ side-car by walking back to every surviving document's stored `_source`,+ re-extracting its field values and re-running the whole analyzer chain.+ Under size-tiered levelling that re-analyses every document once per level,+ which is why a post-index merge tail could rival the index itself. The merge+ now streams each input's term dictionary, replays the decoded posting lists+ with the doc ids remapped and tombstoned documents skipped, and carries the+ norms and field statistics across.++ Measured on a 100 MiB text corpus force-merged to one segment (2 000+ documents, 32-core box, median of four runs per arm): the merged segment's+ FTS side-car build drops from **3.15 s to 0.85 s (~3.7x)**, and peak RSS+ over the whole force-merge from ~2.8 GiB to ~2.4 GiB. End-to-end force-merge+ time moves less, ~41 s to ~32 s, and is noisy — because after this change the+ merge is dominated by the doc-values column build (7-12 s per batch against+ 0.85 s for FTS), which this change does not touch.++ Everything a query can read out of a merged segment is identical to what+ the old path wrote — every posting list, `doc_freq`, norm byte, `_score`+ and `field_length` — and the `.fst` and `.post` side-cars are byte-for-byte+ identical. Two on-disk representations differ without any query being able+ to tell:++ - The `.norms` array may be SHORTER. Byte 0 spells both "field absent" and+ "field length <= 1", and the reader drops byte-0 entries, so a trailing+ run of such documents cannot be replayed and the dense array stops at the+ last non-zero document instead of at the last document carrying the+ field. A single-token `keyword` field is entirely byte 0, so its `.norms`+ shrinks to its header. Both files load to the same norms table.+ - `.meta`'s `total_term_frequency` for a docs-only (`keyword`) field: a+ document that repeats the same value merges with+ `total_term_frequency = doc_frequency`, because that format never stored+ a per-document frequency and its reader synthesises 1. Nothing outside+ `xerj-fts` reads `total_term_frequency`; `.meta` is otherwise identical,+ `total_field_length` included, so `avgdl` still counts the repeat.++ Two further edges exist only when a merge also DROPS documents: a dropped+ document whose value analysed to zero tokens leaves no trace to reclaim its+ `total_docs` seat, and a dropped docs-only document's length is recovered+ from the quantised norm byte, exact to length 7.++ This also changes one behaviour worth stating plainly: because postings are+ now preserved as written, a merge no longer re-analyses old segments under a+ changed mapping. Editing an analyzer and running `_forcemerge` used to+ rewrite the old documents' terms as a side effect; it no longer does — that+ needs a reindex. A change to a field's POSITION setting is still detected+ and still falls back to the rebuild; an analyzer-only change is not+ detectable and is not re-applied. This matches Lucene's semantics.++ A merge falls back to the old rebuild — same output, old cost — when the+ replay cannot be proved equivalent: an input whose side-cars will not open+ or enumerate, an input carrying documents but no FTS data, or a field whose+ stored position setting disagrees with what the merge would write.+ `Index::merge_reanalysed_document_count()` reports how many documents took+ that fallback, `XERJ_PROF=1` prints a per-batch `merge-batch` phase+ breakdown, and `XERJ_MERGE_FTS_REANALYZE=1` forces every merge back onto the+ old path.+- **`--embed-mode neural`: a long passage no longer pads a whole batch up toits own length** ([#366](https://github.com/xerj-org/xerj/issues/366)). Thebuilt-in Candle encoder tokenized every call with `PaddingStrategy::diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex dfc801d3e..10ad285e4 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -7723,6 +7723,14 @@ pub struct Index {/// Failed writes of `schema.json` during dynamic-mapping evolution./// See [`Index::persist_evolved_schema`] (issue #204).schema_persist_failures: AtomicU64,+ /// #876 — documents a merge re-analysed instead of merging their+ /// postings. Merging is supposed to replay the inputs' posting lists,+ /// which costs nothing per document; this counts the documents that took+ /// the fallback (an input the preflight refused, or+ /// `XERJ_MERGE_FTS_REANALYZE=1`). An index whose merges are silently+ /// paying the old O(text) cost shows it here and nowhere else.+ /// `Arc` because the merge encode runs in `spawn_blocking`.+ merge_fts_reanalysed_docs: Arc<AtomicU64>,}impl Index {@@ -8094,6 +8102,7 @@ impl Index {merge_events: AtomicU64::new(0),merge_scheduling_stopped: std::sync::atomic::AtomicBool::new(false),merge_evaluations: AtomicU64::new(0),+ merge_fts_reanalysed_docs: Arc::new(AtomicU64::new(0)),schema_persist_failures: AtomicU64::new(0),});// #871 — event-driven merge scheduling: the store fires this hook on@@ -8481,6 +8490,7 @@ impl Index {merge_events: AtomicU64::new(0),merge_scheduling_stopped: std::sync::atomic::AtomicBool::new(false),merge_evaluations: AtomicU64::new(0),+ merge_fts_reanalysed_docs: Arc::new(AtomicU64::new(0)),schema_persist_failures: AtomicU64::new(0),});// #871 — event-driven merge scheduling (see `Index::create` and@@ -10527,6 +10537,21 @@ impl Index {.load(std::sync::atomic::Ordering::Relaxed)}+ /// #876 — how many documents this index's merges have re-analysed+ /// rather than merging their postings.+ ///+ /// Merging replays the input segments' posting lists, so the expected+ /// value is zero: a document's postings are built once, at flush, and+ /// every later merge copies them. A non-zero count means some batch fell+ /// back to the old rebuild — an input whose side-cars the preflight in+ /// [`fts_merge_readers`] would not vouch for, or the+ /// `XERJ_MERGE_FTS_REANALYZE` escape hatch — and that index is paying+ /// analysis cost proportional to (corpus size x merge levels).+ pub fn merge_reanalysed_document_count(&self) -> u64 {+ self.merge_fts_reanalysed_docs+ .load(std::sync::atomic::Ordering::Relaxed)+ }+/// ES-style `_forcemerge`: run SYNCHRONOUSLY until the index has at/// most `max_num_segments` segments.///@@ -10668,13 +10693,30 @@ impl Index {// Resolve per-field analyzer configs once for FTS rebuild. See// `build_fts_field_configs` — keyword/numeric fields must use the// `keyword` analyzer or the FST drops their values to stop-words.- let (field_configs, excluded_fts_fields) = {+ let (field_configs, excluded_fts_fields, mapped_field_names) = {let schema = self.schema.read().await;(build_fts_field_configs(&schema.schema),crate::memtable::fts_excluded_fields(&schema.schema),+ // #876 — a side-car whose field name is not a portable+ // filename is stored under a SHA-256 digest. Enumerating a+ // source segment's fields needs the names back, and the+ // mapping is where they live.+ schema+ .schema+ .fields+ .iter()+ .map(|field| field.name.clone())+ .collect::<Vec<String>>(),)};+ // #876 escape hatch, matching `XERJ_MERGE_PARALLELISM`'s precedent:+ // force every merge back onto the re-analysing FTS rebuild. Exists so+ // an operator (and the A/B measurement in the PR) can pin the old+ // behaviour without a rebuild.+ let reanalyse_fts_on_merge = std::env::var("XERJ_MERGE_FTS_REANALYZE")+ .ok()+ .is_some_and(|value| value != "0");// Kept for the legacy "if !text_fields.is_empty()" branch — empty// here because the merge path now indexes ALL source fields, not// just declared text fields. See the merge FTS rebuild block.@@ -10786,6 +10828,8 @@ impl Index {let registry_for_task = Arc::clone(&self.registry);let field_configs_for_task = field_configs.clone();let excluded_fts_fields_for_task = excluded_fts_fields.clone();+ let mapped_field_names_for_task = mapped_field_names.clone();+ let reanalysed_docs_for_task = Arc::clone(&self.merge_fts_reanalysed_docs);let segments_dir_for_task = segments_dir.clone();let dv_skip_for_merge = dv_skip.clone();// #318 — the operator's `compression.level`, resolved once per@@ -10845,6 +10889,40 @@ impl Index {seq_no: u64,}+ // #876 — decide BEFORE the stored-document pass whether this+ // batch's FTS side-car can be MERGED (replay the inputs'+ // posting lists) rather than REBUILT (re-analyse every+ // surviving document). The rebuild needs that pass to collect+ // `fts_input`; the merge does not, and skipping it is most of+ // the win — a merged document's postings are already on disk+ // and already correct, and size-tiered levelling re-derives+ // them O(log N) times.+ //+ // Anything the postings merge cannot reproduce exactly puts+ // the batch back on the rebuild: an unresolvable digest+ // filename component, a segment whose side-cars will not+ // open, a doc-carrying input with no FTS data at all, or a+ // field whose stored shape (positions vs docs-only)+ // contradicts what this writer would emit for it.+ let merge_readers: Option<Vec<xerj_fts::index::FtsIndexReader>> =+ if reanalyse_fts_on_merge {+ None+ } else {+ fts_merge_readers(+ &segments_dir_for_task,+ &metas_for_task,+ &field_configs_for_task,+ &excluded_fts_fields_for_task,+ &mapped_field_names_for_task,+ )+ };+ let merge_postings = merge_readers.is_some();++ // Per-phase attribution of one merge batch, gated on+ // XERJ_PROF, matching the flush path's `XERJ_PROF+ // flush-sidecar` line. The #876 A/B is read off `fts_us`.+ let prof = std::env::var_os("XERJ_PROF").is_some();+let mut min_seq = u64::MAX;let mut max_seq = 0u64;@@ -10898,7 +10976,17 @@ impl Index {// `merged_json_buf` (drained into it below), so the peak// stays ~1× stored size + the fts_input Values, unchanged// from the M5.22 profile.- let mut survivors: Vec<(u64, String, String)> = Vec::new();+ // #876 adds the source coordinates: `(input index, that+ // input's own document ordinal)`. The postings merge needs to+ // know where each surviving document CAME FROM to remap its+ // doc ids, and the global `_seq_no` sort below scrambles the+ // per-input order, so the pair has to ride along.+ let mut survivors: Vec<(u64, String, String, u32, u32)> = Vec::new();+ // One entry per document in each input segment, in that+ // segment's own ordinal order: the merged ordinal it becomes,+ // or `None` if it does not survive.+ let mut doc_maps: Vec<Vec<Option<u32>>> =+ vec![Vec::new(); metas_for_task.len()];// RC4 W2 #14 — union of the inputs' SEQ-AWARE tombstone// sections (ZTB2), max seq per doc. A load-bearing@@ -10909,7 +10997,7 @@ impl Index {// resurrect the older copy.let mut tomb_union: HashMap<String, u64> = HashMap::new();- for meta in &metas_for_task {+ for (source_index, meta) in metas_for_task.iter().enumerate() {min_seq = min_seq.min(meta.min_seq_no);max_seq = max_seq.max(meta.max_seq_no);let seg_path = segments_dir_for_task.join(&meta.seg_path);@@ -11048,7 +11136,11 @@ impl Index {}};- for raw in &raw_docs {+ // The FTS/doc-values ordinal space of a segment is the+ // order of its stored documents, so the map is exactly as+ // long as this vector.+ doc_maps[source_index] = vec![None; raw_docs.len()];+ for (source_ordinal, raw) in raw_docs.iter().enumerate() {let raw_str = raw.get();let id_seq: IdSeq = match serde_json::from_str(raw_str) {Ok(v) => v,@@ -11082,6 +11174,8 @@ impl Index {id_seq.seq_no,id_seq.id.to_string(),raw_str.to_string(),+ source_index as u32,+ source_ordinal as u32,));}// raw_docs + stored_bytes drop here — segment RAM reclaimed.@@ -11090,31 +11184,57 @@ impl Index {// Global insertion-order (_seq_no) sort — see the B1 note// above. seq_nos are unique per surviving doc (stale /// duplicate copies were filtered by the version map).- survivors.sort_unstable_by_key(|(seq, _, _)| *seq);+ survivors.sort_unstable_by_key(|(seq, _, _, _, _)| *seq);// Single sorted stream → all four outputs. `into_iter`// frees each raw String right after its bytes are copied// into `merged_json_buf`, keeping peak memory ~1× stored.- for (seq_no, id_str, raw_str) in survivors {+ for (seq_no, id_str, raw_str, source_index, source_ordinal) in survivors {if !first_doc {merged_json_buf.push(b',');}first_doc = false;merged_json_buf.extend_from_slice(raw_str.as_bytes());live_doc_count += 1;- // Pushed BEFORE the per-doc Value parse that can- // `continue` — the .ids side-car must cover every- // stored doc (alignment invariant, see above).+ // The .ids side-car must cover every stored doc+ // (alignment invariant, see above).ids_pairs.push((seq_no, id_str.clone()));// Per-doc Value parse for FTS / DV builders.- let doc_value: Value = match serde_json::from_str(&raw_str) {- Ok(v) => v,- Err(_) => continue,- };+ //+ // A document whose stored bytes will not re-parse still+ // takes its seat in `fts_input`. These bytes already+ // parsed as a `RawValue` above, so reaching the fallback+ // is close to impossible — but `continue`-ing out of the+ // push (which is what this did) shifts every LATER+ // document's FTS and doc-values ordinal one place off its+ // stored ordinal, and that alignment is what every reader+ // addresses a document by. An empty `_source` indexes and+ // columnises nothing for it, which is the same as the+ // skip minus the shift.+ let doc_value: Value =+ serde_json::from_str(&raw_str).unwrap_or_else(|error| {+ tracing::warn!(+ doc = %id_str,+ "merge: surviving doc failed its re-parse, indexing it empty: {error}"+ );+ Value::Null+ });let source = doc_value.get("_source").cloned().unwrap_or(Value::Null);- let fields =- extract_fts_fields_excluding(&source, &excluded_fts_fields_for_task);+ // The merged FTS/doc-values ordinal is this document's+ // index in `fts_input`.+ doc_maps[source_index as usize][source_ordinal as usize] =+ Some(fts_input.len() as u32);+ // The re-analysis input. `merge_postings` replays the+ // inputs' posting lists instead, so it needs no field+ // values at all — only the `_source` the doc-values+ // builder reads below. An empty `HashMap` allocates+ // nothing.+ let fields = if merge_postings {+ HashMap::new()+ } else {+ extract_fts_fields_excluding(&source, &excluded_fts_fields_for_task)+ };fts_input.push((id_str, fields, source));}@@ -11132,10 +11252,12 @@ impl Index {return None;}};+ let stored_timer = std::time::Instant::now();let encoded = xerj_storage::stored_codec::encode_stored_v2_at_level(&merged_json_buf,merge_zstd_level,);+ let stored_us = stored_timer.elapsed().as_micros();drop(merged_json_buf);if let Err(e) = writer.add_section(SectionType::Stored, &encoded) {tracing::error!("merge ABORTED: failed to add section: {e}");@@ -11192,6 +11314,7 @@ impl Index {m.record_bytes_written(merged_meta.size_bytes);}+ let fts_timer = std::time::Instant::now();// Build FTS side-cars using the parallel per-field builder.// We pre-built `fts_input` during the byte-copy pass above,// so this is just one rayon `add_documents_parallel` call.@@ -11214,8 +11337,34 @@ impl Index {// every bulk request (see `crate::merge_pool`).// Same-pool install here is a no-op re-entry —// the whole batch already runs inside merge_pool.- crate::merge_pool().install(|| {- fts_writer.add_documents_parallel(&fts_input);+ let built = crate::merge_pool()+ .install(|| -> std::result::Result<(), String> {+ match merge_readers.as_ref() {+ // #876 — replay the inputs' postings.+ Some(readers) => {+ let sources: Vec<xerj_fts::index::FtsMergeSource<'_>> =+ readers+ .iter()+ .zip(doc_maps.iter())+ .map(|(reader, doc_map)| {+ xerj_fts::index::FtsMergeSource {+ reader,+ doc_map: doc_map.as_slice(),+ }+ })+ .collect();+ fts_writer+ .merge_from_segments(&sources)+ .map_err(|e| e.to_string())?;+ }+ None => {+ reanalysed_docs_for_task.fetch_add(+ fts_input.len() as u64,+ Ordering::Relaxed,+ );+ fts_writer.add_documents_parallel(&fts_input)+ }+ }if fts_writer.uses_encoded_field_filename_components() {if let Err(e) = store_for_task.ensure_fts_encoded_field_component_format()@@ -11223,7 +11372,7 @@ impl Index {tracing::warn!("merge: encoded FTS filename format preflight failed: {e}");- return;+ return Ok(());}if let Err(e) =fts_writer.publish_encoded_filename_layout()@@ -11231,16 +11380,38 @@ impl Index {tracing::warn!("merge: FTS filename-layout publication failed: {e}");- return;+ return Ok(());}}if let Err(e) = fts_writer.finish() {tracing::warn!("merge: FTS build failed: {e}");}+ Ok(())});+ // LOSS FIREWALL: the preflight already refused every+ // input it could not reproduce exactly, so a failure+ // here means an input's own side-cars contradict+ // themselves. Committing a merged segment whose FTS+ // data is missing would silently stop its documents+ // matching, so abort the batch — the inputs stay+ // live and untouched, exactly as for an unreadable+ // stored section.+ if let Err(message) = built {+ tracing::error!(+ "merge ABORTED: postings merge failed (inputs \+ preserved): {message}"+ );+ failed_for_task.fetch_add(1, Ordering::Relaxed);+ return None;+ }}}+ let fts_us = fts_timer.elapsed().as_micros();+ // Release the inputs' decompressed postings before the+ // doc-values build, which is now the batch's memory peak.+ drop(merge_readers);+// Update version_map so doc → segment_id points to the// merged segment, using each doc's REAL seq_no from// `ids_pairs` (collected during the byte-copy pass).@@ -11273,6 +11444,7 @@ impl Index {// Doc-values side-car — reuse the same `Value`s we// stashed in fts_input above (M5.22).+ let dv_timer = std::time::Instant::now();{let columns = build_doc_value_columns(fts_input.iter().map(|(_, _, v)| Some(v)),@@ -11290,6 +11462,16 @@ impl Index {}}+ let dv_us = dv_timer.elapsed().as_micros();+ if prof {+ eprintln!(+ "XERJ_PROF merge-batch inputs={} docs={live_doc_count} \+ fts={} stored_us={stored_us} fts_us={fts_us} dv_us={dv_us}",+ metas_for_task.len(),+ if merge_postings { "replayed" } else { "reanalysed" },+ );+ }+Some((batch_for_task,merged_meta,@@ -22766,6 +22948,107 @@ fn build_fts_field_configs(schema: &Schema) -> HashMap<String, xerj_fts::index::out}+/// Open a full FTS reader over every input segment of a merge batch, or+/// `None` when this batch has to fall back to re-analysing its documents.+///+/// #876. A merge's output postings ARE its inputs' postings with the doc ids+/// remapped — nothing about them depends on the source text — so the merge+/// should read `.fst`/`.post`/`.meta`/`.norms` rather than re-run the+/// analyzer chain over every surviving document. This is the gate on that+/// path. It says no, and accepts the slow rebuild, whenever the replay could+/// not be proved equivalent:+///+/// * a side-car filename component that is a SHA-256 digest of a field name+/// nobody in the mapping owns — silently omitting the field would drop its+/// postings and stop its terms matching;+/// * an input whose side-cars will not open;+/// * an input that carries documents but has no FTS data to merge (its+/// postings are not on disk, so the only way to give the output an index is+/// to build one);+/// * a field stored with a different position setting than this merge would+/// write for it — a re-encode, not a merge.+///+/// The returned readers hold each input's decompressed postings for the rest+/// of the batch. That is a real allocation, but it replaces `fts_input`'s+/// per-document `FieldValues` — a second copy of every indexed field's TEXT —+/// so the batch's peak working set falls rather than rises.+fn fts_merge_readers(+ segments_dir: &std::path::Path,+ metas: &[xerj_storage::segment::SegmentMeta],+ field_configs: &HashMap<String, xerj_fts::index::FieldIndexConfig>,+ excluded: &std::collections::HashSet<String>,+ mapped_field_names: &[String],+) -> Option<Vec<xerj_fts::index::FtsIndexReader>> {+ let default_store_positions = xerj_fts::index::FieldIndexConfig::default().store_positions;+ // ONE directory scan for the whole batch: a converging index keeps tens of+ // thousands of side-car files here, and this runs per merge batch.+ let segment_ids: Vec<&str> = metas.iter().map(|meta| meta.id.as_str()).collect();+ let per_segment_fields = match xerj_fts::index::segments_indexed_field_names(+ segments_dir,+ &segment_ids,+ mapped_field_names,+ ) {+ Ok(names) => names,+ Err(error) => {+ tracing::info!("merge: cannot enumerate FTS fields, re-analysing this batch: {error}");+ return None;+ }+ };+ let mut readers = Vec::with_capacity(metas.len());+ for (meta, names) in metas.iter().zip(per_segment_fields) {+ // An excluded field (a `dense_vector`, say) must not be resurrected+ // from an older segment that predates the exclusion — the rebuild+ // would not have written it either.+ let names: Vec<String> = names+ .into_iter()+ .filter(|name| !excluded.contains(name))+ .collect();+ if names.is_empty() && meta.doc_count > 0 {+ tracing::info!(+ segment = %meta.id,+ doc_count = meta.doc_count,+ "merge: input segment has documents but no FTS side-cars, re-analysing \+ this batch"+ );+ return None;+ }+ let refs: Vec<&str> = names.iter().map(|name| name.as_str()).collect();+ let reader =+ match xerj_fts::index::FtsIndexReader::open(segments_dir, meta.id.as_str(), &refs) {+ Ok(reader) => reader,+ Err(error) => {+ tracing::info!(+ segment = %meta.id,+ "merge: cannot open FTS side-cars, re-analysing this batch: {error}"+ );+ return None;+ }+ };+ let mismatch = reader+ .indexed_fields()+ .into_iter()+ .find(|field| {+ let expected = field_configs+ .get(*field)+ .map(|config| config.store_positions)+ .unwrap_or(default_store_positions);+ reader.field_has_positions(field) != expected+ })+ .map(|field| field.to_owned());+ if let Some(field) = mismatch {+ tracing::info!(+ segment = %meta.id,+ field,+ "merge: field is stored with a different position setting than this merge \+ would write, re-analysing this batch"+ );+ return None;+ }+ readers.push(reader);+ }+ Some(readers)+}+/// FTS input extraction for the MERGE path.////// Delegates to the flush path's own walkerdiff --git a/engine/crates/xerj-engine/tests/merge_replays_postings.rs b/engine/crates/xerj-engine/tests/merge_replays_postings.rsnew file mode 100644index 000000000..f0185d910--- /dev/null+++ b/engine/crates/xerj-engine/tests/merge_replays_postings.rs@@ -0,0 +1,307 @@+//! #876 — a merge must not re-analyse the documents it merges, and the index+//! it produces must be indistinguishable from the one that did.+//!+//! The merge path used to rebuild every merged segment's FTS side-car by+//! walking back to each surviving document's stored `_source`, re-extracting+//! its field values, and re-running the analyzer chain — recomputing postings+//! that were already on disk and already correct. Under size-tiered levelling+//! that happens to every document once per level, which is why the post-index+//! merge tail rivalled the index itself.+//!+//! Two claims are tested here, and they only mean something together:+//!+//! 1. `Index::merge_reanalysed_document_count()` stays at zero across a+//! forcemerge — the merge really did replay postings. Without this a+//! silently-always-falling-back preflight would look perfect.+//! 2. Every hit and every `_score` is bit-for-bit what the re-analysing merge+//! produces, which the `XERJ_MERGE_FTS_REANALYZE` arm computes in the same+//! process from the same corpus.++use serde_json::{json, Value};+use tempfile::TempDir;+use xerj_common::config::Config;+use xerj_common::types::{FieldConfig, FieldType, Schema};+use xerj_engine::{Engine, Index};+use xerj_query::parse_request;++fn make_engine(dir: &TempDir) -> Engine {+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ Engine::new(config).expect("engine::new")+}++/// `(id, score bits)` per hit: "the same score" has to mean identical, not+/// close, or a merge that quietly moved `avgdl` would slip through.+async fn hits(idx: &Index, query: Value) -> Vec<(String, u32)> {+ let request = parse_request(&json!({ "query": query, "size": 200 })).expect("parse_request");+ idx.search(&request)+ .await+ .unwrap()+ .hits+ .iter()+ .map(|hit| (hit.id.clone(), hit.score.to_bits()))+ .collect()+}++fn queries() -> Vec<Value> {+ vec![+ // Scored text: BM25 over doc_freq, term freq, field length and avgdl+ // — every statistic the merge has to carry.+ json!({"match": {"body": "quick"}}),+ json!({"match": {"body": "otter"}}),+ json!({"match": {"body": "quick otter settled"}}),+ // Positions.+ json!({"match_phrase": {"body": "quick brown"}}),+ // Must NOT match: the two values of a multi-valued field are held+ // apart by the position-increment gap.+ json!({"match_phrase": {"body": "cobalt second"}}),+ // Docs-only (keyword) posting lists.+ json!({"term": {"tags": "tag-3"}}),+ json!({"term": {"colour": "cobalt"}}),+ json!({"match_all": {}}),+ ]+}++const DOC_COUNT: usize = 400;++fn document(index: usize) -> Value {+ const NOUNS: [&str; 6] = ["fox", "hound", "otter", "falcon", "badger", "heron"];+ const COLOURS: [&str; 4] = ["amber", "cobalt", "russet", "verdant"];+ let noun = NOUNS[index % NOUNS.len()];+ json!({+ "body": if index.is_multiple_of(7) {+ json!([+ format!("quick brown {noun} leapt past a quick {noun} and settled at {index}"),+ format!("a second value about {index}"),+ ])+ } else {+ json!(format!(+ "quick brown {noun} leapt past a quick {noun} and settled at {index}"+ ))+ },+ "tags": [format!("tag-{}", index % 11), format!("group-{}", index % 3)],+ "colour": COLOURS[index % COLOURS.len()],+ "rank": index,+ })+}++fn schema() -> Schema {+ let mut schema = Schema::empty();+ schema+ .fields+ .push(FieldConfig::new("body", FieldType::Text));+ schema+ .fields+ .push(FieldConfig::new("tags", FieldType::Keyword));+ schema+ .fields+ .push(FieldConfig::new("colour", FieldType::Keyword));+ schema+ .fields+ .push(FieldConfig::new("rank", FieldType::Long));+ schema+}++/// Ingest the corpus in eight flushes (so the merge has eight inputs), delete+/// and overwrite a slice of it (so the merge has documents to drop and stale+/// copies to skip), then forcemerge to one segment.+async fn seed_and_merge(engine: &Engine, name: &str) -> std::sync::Arc<Index> {+ engine.create_index(name, schema()).unwrap();+ let idx = engine.get_index(name).unwrap();++ for index in 0..DOC_COUNT {+ idx.index_document(Some(index.to_string()), document(index))+ .await+ .unwrap();+ if (index + 1).is_multiple_of(50) {+ idx.flush().await.unwrap();+ }+ }+ // Deleted documents leave tombstones the merge has to honour.+ for index in (0..DOC_COUNT).step_by(11) {+ idx.delete_document(&index.to_string()).await.unwrap();+ }+ // Overwritten documents leave a stale copy in an older segment that the+ // merge has to skip while keeping the new one.+ for index in (3..DOC_COUNT).step_by(37) {+ let mut updated = document(index);+ updated["body"] = json!(format!("revised heron notes for {index}"));+ idx.index_document(Some(index.to_string()), updated)+ .await+ .unwrap();+ }+ idx.flush().await.unwrap();++ let merged = idx.force_merge(1).await.unwrap();+ assert!(merged >= 1, "forcemerge must actually merge something");+ idx+}++#[tokio::test(flavor = "multi_thread")]+async fn a_forcemerge_replays_postings_and_changes_no_hit_or_score() {+ // Arm A: the postings merge (the default).+ let replay_dir = TempDir::new().unwrap();+ let replay_engine = make_engine(&replay_dir);+ let replayed = seed_and_merge(&replay_engine, "replayed").await;+ assert_eq!(+ replayed.merge_reanalysed_document_count(),+ 0,+ "the forcemerge fell back to re-analysing documents, so this test would \+ be comparing the old path against itself"+ );+ let mut replay_hits = Vec::new();+ for query in queries() {+ replay_hits.push(hits(&replayed, query).await);+ }++ // Arm B: the same corpus, merged the old way. The escape hatch is a+ // process-wide env var, so this arm runs after arm A has finished+ // reading, and this test owns its binary.+ std::env::set_var("XERJ_MERGE_FTS_REANALYZE", "1");+ let rebuild_dir = TempDir::new().unwrap();+ let rebuild_engine = make_engine(&rebuild_dir);+ let rebuilt = seed_and_merge(&rebuild_engine, "rebuilt").await;+ std::env::remove_var("XERJ_MERGE_FTS_REANALYZE");+ assert!(+ rebuilt.merge_reanalysed_document_count() > 0,+ "the escape hatch did not put the merge back on the re-analysing path, \+ so the comparison arm is not the old behaviour"+ );++ for (query, expected) in queries().into_iter().zip(replay_hits) {+ let actual = hits(&rebuilt, query.clone()).await;+ assert_eq!(+ actual, expected,+ "a merge that replayed postings returned different hits or scores than \+ one that re-analysed the same documents, for {query}"+ );+ }+}++// ── Measurement ──────────────────────────────────────────────────────────────++/// Peak resident set of this process so far, in MiB (`VmHWM`).+#[cfg(target_os = "linux")]+fn peak_rss_mib() -> u64 {+ std::fs::read_to_string("/proc/self/status")+ .ok()+ .and_then(|status| {+ status+ .lines()+ .find(|line| line.starts_with("VmHWM:"))+ .and_then(|line| line.split_whitespace().nth(1)?.parse::<u64>().ok())+ })+ .map(|kib| kib / 1024)+ .unwrap_or(0)+}+#[cfg(not(target_os = "linux"))]+fn peak_rss_mib() -> u64 {+ 0+}++/// The #876 A/B, as a rerunnable measurement rather than an assertion.+///+/// Run each arm in its OWN process — the peak-RSS figure is a process-wide+/// high-water mark, so two arms in one process would report the larger of+/// them twice:+///+/// ```sh+/// cargo test --release -p xerj-engine --test merge_replays_postings -- \+/// --ignored --nocapture measure_forcemerge_cost+/// XERJ_MERGE_FTS_REANALYZE=1 cargo test --release -p xerj-engine \+/// --test merge_replays_postings -- --ignored --nocapture measure_forcemerge_cost+/// ```+#[tokio::test(flavor = "multi_thread")]+#[ignore = "measurement, not an assertion — see the doc comment for the two commands"]+async fn measure_forcemerge_cost() {+ // Shaped after the corpus in the issue: a few thousand large text+ // documents (~150 MB of source and prose across ~4 700 files), not many+ // small ones. The merge's old cost was proportional to the TEXT, so the+ // document size is the part that has to be realistic.+ let docs: usize = std::env::var("XERJ_876_DOCS")+ .ok()+ .and_then(|value| value.parse().ok())+ .unwrap_or(2_000);+ let words_per_doc: usize = std::env::var("XERJ_876_WORDS")+ .ok()+ .and_then(|value| value.parse().ok())+ .unwrap_or(4_000);+ const WORDS: [&str; 16] = [+ "retrieval",+ "segment",+ "posting",+ "analyzer",+ "tokenizer",+ "merge",+ "compaction",+ "throughput",+ "latency",+ "vector",+ "dictionary",+ "quantised",+ "checkpoint",+ "tombstone",+ "ordinal",+ "normalisation",+ ];++ let arm = if std::env::var("XERJ_MERGE_FTS_REANALYZE").is_ok() {+ "re-analysing merge (old path)"+ } else {+ "postings merge (#876)"+ };++ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("measure", schema()).unwrap();+ let idx = engine.get_index("measure").unwrap();++ let ingest = std::time::Instant::now();+ let mut bytes: u64 = 0;+ for index in 0..docs {+ // A wide vocabulary with a skewed reuse pattern, so the term+ // dictionary is the shape real text produces rather than sixteen+ // words repeated — the postings replay pays for distinct terms and+ // the analyzer pays for tokens, and both have to be represented.+ let body: String = (0..words_per_doc)+ .map(|word| {+ let seed = index * 7919 + word * 104_729;+ format!("{}{}", WORDS[seed % WORDS.len()], seed % 4_096)+ })+ .collect::<Vec<_>>()+ .join(" ");+ bytes += body.len() as u64;+ idx.index_document(+ Some(index.to_string()),+ json!({+ "body": body,+ "tags": [format!("tag-{}", index % 97), format!("group-{}", index % 7)],+ "colour": WORDS[index % WORDS.len()],+ "rank": index,+ }),+ )+ .await+ .unwrap();+ if (index + 1).is_multiple_of(250) {+ idx.flush().await.unwrap();+ }+ }+ idx.flush().await.unwrap();+ let ingest = ingest.elapsed();+ let rss_after_ingest = peak_rss_mib();++ let merge = std::time::Instant::now();+ let merged = idx.force_merge(1).await.unwrap();+ let merge = merge.elapsed();++ eprintln!(+ "#876 {arm}\n docs={docs} text={}MiB ingest={:.2}s batches_merged={merged}\n \+ FORCEMERGE={:.2}s re-analysed_docs={} peak_rss={}MiB (was {}MiB after ingest)",+ bytes / (1024 * 1024),+ ingest.as_secs_f64(),+ merge.as_secs_f64(),+ idx.merge_reanalysed_document_count(),+ peak_rss_mib(),+ rss_after_ingest,+ );+}diff --git a/engine/crates/xerj-fts/src/index.rs b/engine/crates/xerj-fts/src/index.rsindex 0b3670741..49d25f1dd 100644--- a/engine/crates/xerj-fts/src/index.rs+++ b/engine/crates/xerj-fts/src/index.rs@@ -672,9 +672,10 @@ fn index_field_values<'a>(field_len += tokens.len() as u64;}- field_data- .norms- .push((doc_ord, field_len.min(u16::MAX as u64) as u16));+ field_data.norms.push((+ doc_ord,+ norm_u16_to_u8(field_len.min(u16::MAX as u64) as u16),+ ));field_data.stats.total_docs += 1;field_data.stats.total_field_length += field_len;}@@ -709,8 +710,16 @@ struct FieldData {config: FieldIndexConfig,postings: PostingsWriter,stats: FieldStats,- /// (doc_id, field_length) in insertion order- norms: Vec<(u32, u16)>,+ /// `(doc_id, quantised norm byte)` in insertion order.+ ///+ /// The quantisation happens HERE rather than in `write_field_static` so+ /// that the merge path can carry a source segment's norm byte through+ /// verbatim. [`norm_u8_to_u16`] is NOT the inverse of+ /// [`norm_u16_to_u8`] — byte 9 dequantises to length 8, which+ /// re-quantises to byte 8 — so a merge that read lengths back out of a+ /// source segment and re-quantised them would silently change BM25+ /// length normalisation for every merged document.+ norms: Vec<(u32, u8)>,}impl FtsIndexWriter {@@ -969,6 +978,100 @@ impl FtsIndexWriter {}}+ /// Build every field of this segment by REPLAYING the source segments'+ /// postings, instead of re-analysing their documents.+ ///+ /// This is the merge path. `write_field_static` has always taken a+ /// `PostingsWriter`, and `PostingsWriter`'s ingest unit has always been a+ /// (term, doc, position) occurrence — never a document — so nothing in+ /// the segment writer needs an analyzer. The engine's merge nevertheless+ /// walked back to each surviving document's stored JSON, re-extracted its+ /// field values and re-ran the whole analyzer chain, recomputing postings+ /// that were already on disk and already correct. Under size-tiered+ /// levelling that re-analyses every document O(log N) times (#876).+ ///+ /// What this reproduces exactly, and what it does not:+ ///+ /// * **postings** — doc ids (remapped), term frequencies and positions+ /// are replayed verbatim from the source `.post` blobs, so `doc_freq`+ /// and every posting list are identical to a re-analysed merge.+ /// * **norms** — the source's *quantised* byte is carried through+ /// untouched. It cannot be recomputed from `field_length`, because+ /// `norm_u16_to_u8` is lossy and is not invertible. Every byte a+ /// reader can observe is the byte re-analysis would have written, but+ /// the dense array may be SHORTER: byte 0 spells both "field absent"+ /// and "field length <= 1", `load_norms` drops it on read, so a+ /// trailing run of byte-0 documents cannot be replayed and the array+ /// stops at the last non-zero document. A single-token keyword field+ /// is entirely byte 0, so its `.norms` shrinks to its header. Nothing+ /// a query reads changes — both files load to the identical table.+ /// * **field statistics** — `total_docs` / `total_field_length` are+ /// carried from the source `.meta` and reduced by the dropped+ /// documents' contribution. With no dropped documents (the ordinary+ /// merge) they are exact. Two blind spots when documents ARE dropped:+ /// a dropped document whose value analysed to zero tokens leaves no+ /// trace in either the postings or the norms, so its `total_docs` seat+ /// is not reclaimed; and for a docs-only field a dropped document's+ /// length is read back from the quantised norm byte, which is exact+ /// only up to length 7.+ /// * **`total_term_frequency`** of a docs-only field becomes its doc+ /// frequency, because the docs-only `.post` format never stored a+ /// per-document frequency — its reader synthesises `term_freq = 1`.+ /// That is the value every reader of the source segment already sees,+ /// and nothing outside this crate reads `total_term_frequency`.+ ///+ /// Returns `Err` (leaving the writer untouched) when the inputs cannot be+ /// merged this way — a field whose sources disagree about positions, or+ /// whose on-disk shape contradicts the merge-time configuration. The+ /// caller is expected to fall back to re-analysis rather than to fail the+ /// merge.+ pub fn merge_from_segments(&mut self, sources: &[FtsMergeSource<'_>]) -> Result<()> {+ use rayon::prelude::*;++ let mut field_names: Vec<String> = Vec::new();+ let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();+ for source in sources {+ for field in source.reader.indexed_fields() {+ if seen.insert(field) {+ field_names.push(field.to_owned());+ }+ }+ }+ drop(seen);+ // Deterministic field order keeps a merge reproducible run to run.+ field_names.sort_unstable();++ // Snapshot the configs before the parallel pass so the closure never+ // borrows `self.fields` while the results are being inserted.+ let configs: Vec<FieldIndexConfig> = field_names+ .iter()+ .map(|field| {+ self.fields+ .get(field)+ .map(|data| data.config.clone())+ .unwrap_or_default()+ })+ .collect();++ let built: Vec<Result<FieldData>> = field_names+ .par_iter()+ .zip(configs.par_iter())+ .map(|(field, config)| merge_field_from_segments(field, config, sources))+ .collect();++ // Collect every field before mutating anything: a failure must leave+ // the writer exactly as the caller configured it, so the fallback+ // path starts from a clean slate.+ let mut merged: Vec<(String, FieldData)> = Vec::with_capacity(field_names.len());+ for (field, data) in field_names.into_iter().zip(built) {+ merged.push((field, data?));+ }+ for (field, data) in merged {+ self.fields.insert(field, data);+ }+ Ok(())+ }+/// Flush all data to disk and return field stats for the segment manifest.////// Field writes run in parallel via Rayon — each thread owns one field's@@ -1206,8 +1309,8 @@ impl FtsIndexWriter {let max_doc_id: u32 = norms.last().map(|(d, _)| *d).unwrap_or(0);let dense_len = (max_doc_id as usize).saturating_add(1);let mut dense: Vec<u8> = vec![0u8; dense_len];- for (doc_id, norm) in &norms {- dense[*doc_id as usize] = norm_u16_to_u8(*norm);+ for (doc_id, norm_byte) in &norms {+ dense[*doc_id as usize] = *norm_byte;}// Try LZ4 when the dense array is big enough for compression@@ -1234,6 +1337,302 @@ impl FtsIndexWriter {}}+/// One input segment of a postings-level merge.+///+/// See [`FtsIndexWriter::merge_from_segments`].+pub struct FtsMergeSource<'a> {+ /// A full (NOT `open_stats_only`) reader over the source segment.+ pub reader: &'a FtsIndexReader,+ /// Source document ordinal → merged document ordinal, `None` for a+ /// document the merge drops. Exactly one entry per document in the+ /// source segment, in that segment's own ordinal order — which is the+ /// order its stored section holds, the same alignment the doc-values+ /// side-car already relies on.+ pub doc_map: &'a [Option<u32>],+}++/// Build one merged field by replaying every source segment's postings.+fn merge_field_from_segments(+ field: &str,+ config: &FieldIndexConfig,+ sources: &[FtsMergeSource<'_>],+) -> Result<FieldData> {+ let inputs: Vec<&FtsMergeSource<'_>> = sources+ .iter()+ .filter(|source| source.reader.field_stats(field).is_some())+ .collect();++ let Some(first) = inputs.first() else {+ return Ok(FieldData {+ config: config.clone(),+ postings: if config.store_positions {+ PostingsWriter::new()+ } else {+ PostingsWriter::new_no_positions()+ },+ stats: FieldStats::default(),+ norms: Vec::new(),+ });+ };++ // A posting list's on-disk shape decides how it decodes, so every input+ // must agree with every other AND with what this writer would emit.+ // Anything else would be a re-encode, not a merge — the caller+ // re-analyses instead.+ let has_positions = first.reader.field_has_positions(field);+ for source in &inputs {+ if source.reader.field_has_positions(field) != has_positions {+ bail!("FTS merge: sources disagree on positions for field '{field}'");+ }+ }+ if has_positions != config.store_positions {+ bail!(+ "FTS merge: field '{field}' is stored with store_positions={has_positions} but the \+ merge configuration asks for {}",+ config.store_positions+ );+ }++ let mut postings = if has_positions {+ PostingsWriter::new()+ } else {+ PostingsWriter::new_no_positions()+ };+ let mut norms: Vec<(u32, u8)> = Vec::new();+ let mut stats = FieldStats::default();++ for source in &inputs {+ let source_stats = source+ .reader+ .field_stats(field)+ .expect("filtered to the sources that carry this field")+ .clone();+ let doc_count = source.doc_map.len();+ // One flag per source document: which documents the postings mention.+ // A dropped document that no posting mentions had zero tokens, and+ // its `total_docs` seat is unreclaimable — see the method docs.+ let mut had_posting = vec![false; doc_count];+ let mut dropped_token_count: u64 = 0;+ let mut failure: Option<String> = None;++ source.reader.for_each_term(field, |term| {+ let Some(term_postings) = source.reader.lookup_term(field, term) else {+ failure = Some(format!(+ "term '{term}' of field '{field}' is in the FST but not in the .meta"+ ));+ return false;+ };+ let Some(data) = source.reader.postings_data(field, &term_postings) else {+ failure = Some(format!(+ "field '{field}' has no postings bytes for term '{term}' (a stats-only \+ reader cannot be merged)"+ ));+ return false;+ };+ let mut decoded = crate::postings::PostingsReader::new_with_positions(+ data,+ term_postings.doc_frequency,+ has_positions,+ );+ // One run per (source, term), handed to the writer in one call:+ // a per-occurrence hand-off would re-descend the term BTreeMap+ // for every token in the corpus.+ let mut run: Vec<crate::postings::DecodedPosting> =+ Vec::with_capacity(term_postings.doc_frequency as usize);+ while let Some(mut posting) = decoded.next() {+ let ordinal = posting.doc_id as usize;+ if ordinal >= doc_count {+ failure = Some(format!(+ "field '{field}' has a posting for doc {ordinal}, past the {doc_count} \+ documents the caller mapped"+ ));+ return false;+ }+ had_posting[ordinal] = true;+ match source.doc_map[ordinal] {+ Some(merged) => {+ posting.doc_id = merged;+ run.push(posting);+ }+ None => dropped_token_count += posting.term_freq as u64,+ }+ }+ postings.extend_postings(term, run);+ true+ });+ if let Some(message) = failure {+ bail!("FTS merge: {message}");+ }+ // An input that maps no documents puts nothing into the output, so it+ // contributes no statistics either. Any input that DOES have+ // postings while mapping no documents was already refused above.+ if doc_count == 0 {+ continue;+ }++ let mut norm_bytes = vec![0u8; doc_count];+ for (doc_id, byte) in source.reader.field_norm_bytes(field) {+ let ordinal = doc_id as usize;+ if ordinal >= doc_count {+ bail!(+ "FTS merge: field '{field}' has a norm for doc {ordinal}, past the \+ {doc_count} documents the caller mapped"+ );+ }+ norm_bytes[ordinal] = byte;+ }++ let mut dropped_docs: u64 = 0;+ let mut dropped_quantised_length: u64 = 0;+ for (ordinal, &byte) in norm_bytes.iter().enumerate() {+ match source.doc_map[ordinal] {+ // Byte 0 is how the dense norms array spells BOTH "field+ // absent" and "field length 1", and `load_norms` drops it on+ // read, so a byte-0 entry cannot be recovered here and is not+ // pushed. Every byte a reader can observe is therefore the+ // byte a re-analysing writer would have written — but NOT the+ // array's length: re-analysis pushes an entry for every doc+ // that CARRIES the field, byte 0 included, and+ // `write_field_static` sizes the dense array from the last+ // entry. When the highest-ordinal doc carrying the field+ // quantises to 0 (field length <= 1: every single-token+ // keyword field), the replayed `.norms` stops at the last+ // NON-zero doc and is shorter, with the difference being+ // trailing zeros only. `load_norms` filters `b != 0`, so both+ // files load to the identical norms table and no hit, score or+ // `field_length` moves. Pinned by+ // `merge_postings_equivalence.rs::+ // a_single_token_field_replays_an_equivalent_shorter_norms_array`.+ Some(merged) => {+ if byte != 0 {+ norms.push((merged, byte));+ }+ }+ None => {+ if had_posting[ordinal] {+ dropped_docs += 1;+ dropped_quantised_length += norm_u8_to_u16(byte) as u64;+ }+ }+ }+ }++ stats.total_docs += source_stats.total_docs.saturating_sub(dropped_docs);+ // A positioned field knows each dropped document's exact token count+ // (the sum of its term frequencies). A docs-only field does not —+ // its `.post` never stored one — so its dropped length comes from the+ // quantised norm byte, which is exact up to length 7.+ let dropped_length = if has_positions {+ dropped_token_count+ } else {+ dropped_quantised_length+ };+ stats.total_field_length += source_stats+ .total_field_length+ .saturating_sub(dropped_length);+ }++ // The inputs' surviving documents interleave in the merged ordinal space,+ // so a term shared by several of them arrives as several ascending runs.+ postings.sort_postings_by_doc();++ Ok(FieldData {+ config: config.clone(),+ postings,+ stats,+ norms,+ })+}++/// Every field name each of `segment_ids` holds FTS side-cars for, in the same+/// order as `segment_ids`.+///+/// A segment's field set is whatever its documents happened to carry, so it is+/// not derivable from the mapping; the merge path needs it to know which+/// readers to open. A portable field name IS its own filename component and+/// reads straight back; a digest-encoded component is resolved against+/// `known_fields`, and an unresolvable one is an error rather than a silent+/// omission — dropping a field here would drop its postings from the merged+/// segment and silently stop its terms matching.+///+/// Takes the whole batch at once because it costs ONE directory scan. A+/// converging index keeps thousands of segments in this directory (tens of+/// thousands of side-car files), and a merge batch has up to sixteen inputs:+/// scanning per input would re-walk that directory sixteen times per batch.+pub fn segments_indexed_field_names(+ segment_dir: &Path,+ segment_ids: &[&str],+ known_fields: &[String],+) -> Result<Vec<Vec<String>>> {+ let mut encoded: HashMap<String, &str> = HashMap::new();+ for name in known_fields {+ if let Cow::Owned(component) = field_file_component(name) {+ encoded.insert(component, name.as_str());+ }+ }++ let prefixes: Vec<String> = segment_ids.iter().map(|id| format!("{id}.")).collect();+ let mut per_segment: Vec<Vec<String>> = vec![Vec::new(); segment_ids.len()];+ let mut seen: Vec<std::collections::HashSet<String>> =+ vec![std::collections::HashSet::new(); segment_ids.len()];++ let entries = fs::read_dir(segment_dir)+ .with_context(|| format!("listing segment dir {:?}", segment_dir))?;+ for entry in entries {+ let entry = entry.with_context(|| format!("reading segment dir {:?}", segment_dir))?;+ let file_name = entry.file_name();+ let Some(file_name) = file_name.to_str() else {+ continue;+ };+ for (index, prefix) in prefixes.iter().enumerate() {+ let Some(rest) = file_name.strip_prefix(prefix.as_str()) else {+ continue;+ };+ // Only the FST is enumerated: it is the file `FtsIndexReader::open`+ // gates a field's existence on, and taking one extension keeps a+ // four-file family from being counted four times. `.fst.tmp`+ // leftovers fall out here too — their final component is `tmp`.+ let Some((component, extension)) = rest.rsplit_once('.') else {+ break;+ };+ if extension != "fst" || component.is_empty() {+ break;+ }+ let name = if component.starts_with(ENCODED_FIELD_COMPONENT_PREFIX) {+ match encoded.get(component) {+ Some(name) => (*name).to_owned(),+ None => bail!(+ "segment {} has an FTS side-car component that no known field name \+ digests to: {component}",+ segment_ids[index]+ ),+ }+ } else {+ component.to_owned()+ };+ if seen[index].insert(name.clone()) {+ per_segment[index].push(name);+ }+ break;+ }+ }++ for names in &mut per_segment {+ names.sort_unstable();+ }+ Ok(per_segment)+}++/// [`segments_indexed_field_names`] for a single segment.+pub fn segment_indexed_field_names(+ segment_dir: &Path,+ segment_id: &str,+ known_fields: &[String],+) -> Result<Vec<String>> {+ let mut names = segments_indexed_field_names(segment_dir, &[segment_id], known_fields)?;+ Ok(names.pop().unwrap_or_default())+}+const NORMS_MAGIC: &[u8; 4] = b"ZNM1";/// Lucene-style logarithmic norm quantisation: maps a u16 field length@@ -1256,7 +1655,6 @@ fn norm_u16_to_u8(len: u16) -> u8 {}#[inline]-#[allow(dead_code)]fn norm_u8_to_u16(b: u8) -> u16 {if b < 8 {return (b + 1) as u16;@@ -1336,8 +1734,15 @@ struct LoadedField {post_data: PostData,/// Pre-parsed metadata (term postings, field stats) — small, stays owned.meta: FieldMeta,- /// doc_id → field_length lookup (sorted by doc_id).- norms: Vec<(u32, u16)>,+ /// `(doc_id, field_length, quantised norm byte)`, sorted by doc_id.+ ///+ /// The raw byte rides along beside the dequantised length because the+ /// merge path must reproduce the source segment's norms file byte for+ /// byte: `norm_u16_to_u8(norm_u8_to_u16(b)) != b` for most `b`, so+ /// re-quantising the length would move BM25's length normalisation on+ /// every merged document. `(u32, u16, u8)` still occupies 8 bytes+ /// after padding, so this costs no memory over the old `(u32, u16)`.+ norms: Vec<(u32, u16, u8)>,}impl FtsIndexReader {@@ -1574,7 +1979,7 @@ impl FtsIndexReader {Ok(mmap)}- fn load_norms(path: &Path) -> Result<Vec<(u32, u16)>> {+ fn load_norms(path: &Path) -> Result<Vec<(u32, u16, u8)>> {let bytes = fs::read(path).with_context(|| format!("opening norms {:?}", path))?;// V4 M4.7 compact format starts with `NORMS_MAGIC`; legacy starts// with a raw u32 count (whose first byte almost never matches 'Z').@@ -1605,7 +2010,7 @@ impl FtsIndexReader {let mut norms = Vec::new();for (doc_id, &b) in dense.iter().enumerate() {if b != 0 {- norms.push((doc_id as u32, norm_u8_to_u16(b)));+ norms.push((doc_id as u32, norm_u8_to_u16(b), b));}}Ok(norms)@@ -1617,7 +2022,9 @@ impl FtsIndexReader {for _ in 0..count {let doc_id = cur.read_u32::<LittleEndian>()?;let norm = cur.read_u16::<LittleEndian>()?;- norms.push((doc_id, norm));+ // The pre-M4.7 format stored an unquantised length; the byte a+ // writer would emit for it is what a merge must carry forward.+ norms.push((doc_id, norm, norm_u16_to_u8(norm)));}Ok(norms)}@@ -1645,7 +2052,7 @@ impl FtsIndexReader {total += m.as_fst().as_bytes().len() as u64;}total += f.meta.flat_records.len() as u64;- // `norms` is Vec<(u32, u16)>, which pads to 8 bytes per element.+ // `norms` is Vec<(u32, u16, u8)>, which pads to 8 bytes per element.total += (f.norms.len() as u64) * 8;// Legacy ZFM1/ZFM2 keep per-term metadata in a HashMap instead of// the flat array; approximate it rather than walking every entry.@@ -1755,11 +2162,28 @@ impl FtsIndexReader {// Binary search by doc_idloaded.norms- .binary_search_by_key(&doc_id, |(id, _)| *id)+ .binary_search_by_key(&doc_id, |(id, _, _)| *id).ok().map(|idx| loaded.norms[idx].1)}+ /// Every `(doc_id, quantised norm byte)` this field records, ascending by+ /// doc id. Docs whose norm byte is zero are absent — the dense on-disk+ /// array cannot tell "field missing" from "field length 1" (both encode+ /// as byte 0), and neither can this.+ ///+ /// Exists for the merge path: a merged segment must write the SAME norm+ /// byte the source segment holds, and [`Self::field_length`]'s+ /// dequantised `u16` cannot be re-quantised back to it.+ pub fn field_norm_bytes(&self, field: &str) -> impl Iterator<Item = (u32, u8)> + '_ {+ self.fields.get(field).into_iter().flat_map(|loaded| {+ loaded+ .norms+ .iter()+ .map(|(doc_id, _, byte)| (*doc_id, *byte))+ })+ }+/// Stream every term of `field` through `f` in lexicographic order,/// stopping as soon as `f` returns `false`.///diff --git a/engine/crates/xerj-fts/src/lib.rs b/engine/crates/xerj-fts/src/lib.rsindex f0c3d4560..ff2765260 100644--- a/engine/crates/xerj-fts/src/lib.rs+++ b/engine/crates/xerj-fts/src/lib.rs@@ -76,7 +76,8 @@ pub use bm25::{};pub use index::{- FieldIndexConfig, FieldValues, FtsIndexReader, FtsIndexWriter, POSITION_INCREMENT_GAP,+ segment_indexed_field_names, segments_indexed_field_names, FieldIndexConfig, FieldValues,+ FtsIndexReader, FtsIndexWriter, FtsMergeSource, POSITION_INCREMENT_GAP,};pub use postings::{diff --git a/engine/crates/xerj-fts/src/postings.rs b/engine/crates/xerj-fts/src/postings.rsindex df5a91e26..683c767b4 100644--- a/engine/crates/xerj-fts/src/postings.rs+++ b/engine/crates/xerj-fts/src/postings.rs@@ -219,6 +219,80 @@ impl PostingsWriter {);}+ /// Append a whole run of already-decoded postings for `term`.+ ///+ /// This is the merge path's ingest entry point. `add_occurrence` is the+ /// INDEXING entry point: it takes one token at a time because that is+ /// what an analyzer produces. A merge has no analyzer — it has one+ /// [`DecodedPosting`] per (term, document) straight out of a source+ /// segment's posting list — so replaying it occurrence by occurrence+ /// would pay a `BTreeMap<String, _>` descent per TOKEN. Taking the run+ /// in one call pays one descent per (term, source segment) instead:+ /// measured at roughly half the replay's CPU on a 100 MiB corpus, and it+ /// also moves each posting's position vector in rather than copying it.+ ///+ /// Positions are dropped when this writer omits them. `term_freq` is+ /// stored as given — the `.post` format records the frequency and the+ /// position count as separate fields, and a merge must reproduce both+ /// exactly as the source segment had them.+ ///+ /// Two obligations on the caller, both of which a merge satisfies by+ /// construction:+ ///+ /// * a document may appear at most ONCE per term across every run (each+ /// merged ordinal comes from exactly one source document, and a posting+ /// list holds one entry per document), because this appends without+ /// coalescing equal doc ids;+ /// * runs may arrive out of doc order — a merged segment interleaves its+ /// inputs' documents — so [`Self::sort_postings_by_doc`] MUST run before+ /// `encode_term`.+ pub fn extend_postings(&mut self, term: &str, run: Vec<DecodedPosting>) {+ if run.is_empty() {+ return;+ }+ let store_positions = self.store_positions;+ let convert = move |posting: DecodedPosting| RawPosting {+ doc_id: posting.doc_id,+ term_freq: posting.term_freq,+ positions: if store_positions {+ posting.positions+ } else {+ Vec::new()+ },+ };+ match self.postings.get_mut(term) {+ Some(list) => {+ list.reserve(run.len());+ list.extend(run.into_iter().map(convert));+ }+ None => {+ self.postings+ .insert(term.to_owned(), run.into_iter().map(convert).collect());+ }+ }+ }++ /// Restore the ascending-doc-id invariant every posting list must hold+ /// before it is encoded.+ ///+ /// The indexing path never needs this: it walks documents in ordinal+ /// order, so each list is built ascending. The merge path replays+ /// several source segments whose surviving documents interleave in the+ /// merged ordinal space, so a shared term's list arrives as k ascending+ /// runs. `encode_block_doc_ids` delta-encodes with a plain `-`, which+ /// would underflow on an out-of-order pair.+ ///+ /// `sort_by_key` is the stable, run-detecting sort, so k concatenated+ /// ascending runs cost O(n log k), not O(n log n); lists that are already+ /// ordered are detected by the scan below and never sorted at all.+ pub fn sort_postings_by_doc(&mut self) {+ for list in self.postings.values_mut() {+ if list.windows(2).any(|pair| pair[0].doc_id > pair[1].doc_id) {+ list.sort_by_key(|posting| posting.doc_id);+ }+ }+ }+/// Direct `(doc_frequency, total_term_frequency)` lookup for ONE term.////// O(log T + postings(term)) — use this in per-term loops. The segmentdiff --git a/engine/crates/xerj-fts/tests/merge_postings_equivalence.rs b/engine/crates/xerj-fts/tests/merge_postings_equivalence.rsnew file mode 100644index 000000000..6901d5711--- /dev/null+++ b/engine/crates/xerj-fts/tests/merge_postings_equivalence.rs@@ -0,0 +1,691 @@+//! #876 — merging postings must produce the segment a re-analysing merge+//! would have produced.+//!+//! The merge path used to walk back to every surviving document's source+//! text and re-run the analyzer chain over it. `FtsIndexWriter::+//! merge_from_segments` instead replays the source segments' already-built+//! posting lists. That is only allowed to be faster — never different — so+//! every test here builds the SAME merged segment twice, once each way, and+//! compares the two.+//!+//! The comparison is deliberately at the byte level of the side-car files.+//! Hits and BM25 scores are a pure function of those bytes, so equal files are+//! a strictly stronger claim than equal search results; the search comparison+//! is kept anyway because it is the claim the issue actually makes.+//!+//! `.fst`, `.post` and `.meta` are compared byte for byte. (`.meta` holds+//! `total_term_frequency`, which a docs-only field DOES diverge on when a+//! document repeats the same value — no fixture document does, so the byte+//! comparison is sound here, and that divergence has its own test:+//! `a_docs_only_field_carries_its_length_but_not_its_term_frequency`.)+//!+//! `.norms` is compared for the content a reader can observe, because it is+//! knowingly NOT byte-identical: byte 0 spells both "field absent" and "field+//! length <= 1", `load_norms` drops byte-0 entries on read, so a replayed+//! merge cannot reproduce a trailing run of them and writes a SHORTER dense+//! array. The `colour` field in the fixture below is single-token precisely+//! so that case is exercised on every run instead of being accidentally+//! avoided; the exact divergence, and the fact that nothing a query reads+//! moves with it, are pinned by+//! `a_single_token_field_replays_an_equivalent_shorter_norms_array`.++use std::collections::HashMap;+use std::path::Path;+use std::sync::Arc;++use xerj_fts::analyzer::AnalyzerRegistry;+use xerj_fts::index::{+ segment_indexed_field_names, FieldIndexConfig, FieldValues, FtsIndexReader, FtsIndexWriter,+ FtsMergeSource,+};+use xerj_fts::search::{FtsSearcher, PhraseQuery, Query, TermQuery};++const FIELDS: [&str; 4] = ["body", "colour", "tags", "title"];+/// The side-cars a replayed merge must reproduce byte for byte. `.norms` is+/// excluded on purpose and checked by `assert_norms_equivalent` instead — see+/// the module comment.+const EXTENSIONS: [&str; 3] = ["fst", "post", "meta"];++fn registry() -> Arc<AnalyzerRegistry> {+ Arc::new(AnalyzerRegistry::default())+}++fn configure(writer: &mut FtsIndexWriter) {+ writer.configure_field(+ "body",+ FieldIndexConfig {+ analyzer: "standard".to_owned(),+ store_positions: true,+ store_term_vectors: false,+ },+ );+ writer.configure_field(+ "title",+ FieldIndexConfig {+ analyzer: "standard".to_owned(),+ store_positions: true,+ store_term_vectors: false,+ },+ );+ // Keyword fields are docs-only: their posting lists carry neither a+ // frequency nor a position, which is the shape the merge has to preserve.+ writer.configure_field(+ "tags",+ FieldIndexConfig {+ analyzer: "keyword".to_owned(),+ store_positions: false,+ store_term_vectors: false,+ },+ );+ // A SINGLE-TOKEN keyword field. `norm_u16_to_u8` maps length 1 to byte 0,+ // the same byte it uses for "field absent", and the reader drops byte-0+ // entries — so every document's norm here is unrecoverable by a replay and+ // this field's `.norms` is the one side-car the merge cannot reproduce byte+ // for byte. It is in the fixture so that gap is measured, not dodged.+ writer.configure_field(+ "colour",+ FieldIndexConfig {+ analyzer: "keyword".to_owned(),+ store_positions: false,+ store_term_vectors: false,+ },+ );+}++/// 300 documents, wide enough that the hottest terms cross the 128-doc PFOR+/// block boundary (so the merged segment exercises the full-block encoder and+/// its cross-block delta chain, not just the vbyte residual).+const DOC_COUNT: usize = 300;++fn document(index: usize) -> HashMap<String, FieldValues> {+ const NOUNS: [&str; 6] = ["fox", "hound", "otter", "falcon", "badger", "heron"];+ const COLOURS: [&str; 4] = ["amber", "cobalt", "russet", "verdant"];++ let mut fields: HashMap<String, FieldValues> = HashMap::new();++ // `quick` and `brown` land in every document (a >128-posting term);+ // `NOUNS[..]` repeats twice in the same value so term frequencies and+ // position lists are both non-trivial.+ let body = format!(+ "quick brown {noun} leapt past a quick {noun} and settled at {index}",+ noun = NOUNS[index % NOUNS.len()],+ );+ if index.is_multiple_of(7) {+ // Multi-valued text: the second value's positions start after+ // POSITION_INCREMENT_GAP, which a merge must carry through untouched.+ fields.insert(+ "body".to_owned(),+ FieldValues::from_values(vec![body, format!("a second value about {index}")]),+ );+ } else {+ fields.insert("body".to_owned(), FieldValues::One(body));+ }++ fields.insert(+ "tags".to_owned(),+ FieldValues::from_values(vec![+ format!("tag-{}", index % 11),+ format!("colour-{}", COLOURS[index % COLOURS.len()]),+ ]),+ );++ // Exactly one keyword token, on EVERY document — so this field's norm is+ // byte 0 for the highest merged ordinal, which is what makes the replayed+ // `.norms` shorter than the re-analysed one.+ fields.insert(+ "colour".to_owned(),+ FieldValues::One(COLOURS[index % COLOURS.len()].to_owned()),+ );++ // Present on only a third of the documents, so the merged segment has a+ // field whose document set is sparse in the merged ordinal space.+ if index.is_multiple_of(3) {+ fields.insert(+ "title".to_owned(),+ FieldValues::One(format!("Report {index} of the survey")),+ );+ }++ fields+}++/// Deterministic pseudo-shuffle standing in for `_seq_no` order: the engine+/// sorts every batch's survivors by sequence number, so documents from+/// different input segments INTERLEAVE in the merged ordinal space. That is+/// what forces the merge to re-sort each term's posting list.+fn sequence_number(index: usize) -> usize {+ (index * 97) % DOC_COUNT+}++struct Fixture {+ dir: tempfile::TempDir,+ /// Per source segment: the documents it holds, in its own ordinal order.+ segments: Vec<Vec<usize>>,+}++impl Fixture {+ /// Three source segments, round-robin over the document set.+ fn build(survives: impl Fn(usize) -> bool) -> (Self, Vec<usize>) {+ let dir = tempfile::TempDir::new().unwrap();+ let mut segments: Vec<Vec<usize>> = vec![Vec::new(); 3];+ for index in 0..DOC_COUNT {+ segments[index % 3].push(index);+ }++ for (segment, documents) in segments.iter().enumerate() {+ let mut writer = FtsIndexWriter::new(dir.path(), format!("seg-{segment}"), registry());+ configure(&mut writer);+ let batch: Vec<(String, HashMap<String, FieldValues>, ())> = documents+ .iter()+ .map(|index| (index.to_string(), document(*index), ()))+ .collect();+ writer.add_documents_parallel(&batch);+ writer.finish().unwrap();+ }++ // Survivors, in merged (sequence-number) order.+ let mut survivors: Vec<usize> = (0..DOC_COUNT).filter(|index| survives(*index)).collect();+ survivors.sort_by_key(|index| sequence_number(*index));++ (Fixture { dir, segments }, survivors)+ }++ fn path(&self) -> &Path {+ self.dir.path()+ }++ /// The merged segment a RE-ANALYSING merge writes: every surviving+ /// document's field values, fed through the analyzer again.+ fn reanalysed(&self, survivors: &[usize], segment_id: &str) {+ let mut writer = FtsIndexWriter::new(self.path(), segment_id, registry());+ configure(&mut writer);+ let batch: Vec<(String, HashMap<String, FieldValues>, ())> = survivors+ .iter()+ .map(|index| (index.to_string(), document(*index), ()))+ .collect();+ writer.add_documents_parallel(&batch);+ writer.finish().unwrap();+ }++ /// The merged segment a POSTINGS merge writes: no documents, no analyzer,+ /// just the source segments' side-cars and a doc-id remap.+ fn replayed(&self, survivors: &[usize], segment_id: &str) {+ let merged_ordinal: HashMap<usize, u32> = survivors+ .iter()+ .enumerate()+ .map(|(ordinal, index)| (*index, ordinal as u32))+ .collect();++ let readers: Vec<FtsIndexReader> = (0..self.segments.len())+ .map(|segment| {+ FtsIndexReader::open(self.path(), format!("seg-{segment}"), &FIELDS).unwrap()+ })+ .collect();+ let doc_maps: Vec<Vec<Option<u32>>> = self+ .segments+ .iter()+ .map(|documents| {+ documents+ .iter()+ .map(|index| merged_ordinal.get(index).copied())+ .collect()+ })+ .collect();+ let sources: Vec<FtsMergeSource<'_>> = readers+ .iter()+ .zip(doc_maps.iter())+ .map(|(reader, doc_map)| FtsMergeSource {+ reader,+ doc_map: doc_map.as_slice(),+ })+ .collect();++ let mut writer = FtsIndexWriter::new(self.path(), segment_id, registry());+ configure(&mut writer);+ writer.merge_from_segments(&sources).unwrap();+ writer.finish().unwrap();+ }+}++fn sidecar(dir: &Path, segment_id: &str, field: &str, extension: &str) -> Vec<u8> {+ std::fs::read(dir.join(format!("{segment_id}.{field}.{extension}")))+ .unwrap_or_else(|error| panic!("reading {segment_id}.{field}.{extension}: {error}"))+}++fn assert_sidecars_identical(dir: &Path, expected: &str, actual: &str, extensions: &[&str]) {+ for field in FIELDS {+ for extension in extensions {+ let want = sidecar(dir, expected, field, extension);+ let got = sidecar(dir, actual, field, extension);+ assert_eq!(+ want,+ got,+ "field '{field}' side-car .{extension} differs between the re-analysed \+ merge and the replayed merge ({} vs {} bytes)",+ want.len(),+ got.len()+ );+ }+ }+}++/// The declared length of a `.norms` dense array, straight out of the ZNM1+/// header (`"ZNM1"`, u8 encoding, u32 dense_len, u32 payload_len).+fn norms_dense_len(dir: &Path, segment_id: &str, field: &str) -> u32 {+ let bytes = sidecar(dir, segment_id, field, "norms");+ assert!(+ bytes.len() >= 13 && &bytes[..4] == b"ZNM1",+ "{segment_id}.{field}.norms is not in the ZNM1 format this test reads"+ );+ u32::from_le_bytes(bytes[5..9].try_into().unwrap())+}++/// `.norms` is the one side-car a replay cannot reproduce byte for byte, so it+/// is compared for what a reader can actually see instead.+///+/// The replayed array is allowed to be SHORTER — byte 0 means both "absent"+/// and "length <= 1", `load_norms` drops those entries, so the replay stops at+/// the last non-zero document — but every norm byte, every dequantised+/// `field_length` and the field statistics behind `avgdl` must match exactly.+/// A shorter array with an identical live table differs only in trailing+/// zeros, which is precisely what no query can observe.+fn assert_norms_equivalent(dir: &Path, expected: &str, actual: &str, doc_count: u32) {+ let want_reader = FtsIndexReader::open(dir, expected, &FIELDS).unwrap();+ let got_reader = FtsIndexReader::open(dir, actual, &FIELDS).unwrap();+ for field in FIELDS {+ let want: Vec<(u32, u8)> = want_reader.field_norm_bytes(field).collect();+ let got: Vec<(u32, u8)> = got_reader.field_norm_bytes(field).collect();+ assert_eq!(+ want, got,+ "field '{field}': the norm bytes a reader loads differ between the \+ re-analysed merge and the replayed merge"+ );+ for doc_id in 0..doc_count {+ assert_eq!(+ want_reader.field_length(field, doc_id),+ got_reader.field_length(field, doc_id),+ "field '{field}': length of merged doc {doc_id} differs"+ );+ }+ let want_len = norms_dense_len(dir, expected, field);+ let got_len = norms_dense_len(dir, actual, field);+ assert!(+ got_len <= want_len,+ "field '{field}': the replayed .norms dense array ({got_len}) may be \+ shorter than the re-analysed one ({want_len}) but never longer — \+ a longer one would mean the replay invented a document"+ );+ }+}++fn hits(dir: &Path, segment_id: &str, query: &Query) -> Vec<(u32, u32)> {+ let reader = Arc::new(FtsIndexReader::open(dir, segment_id, &FIELDS).unwrap());+ let searcher = FtsSearcher::new(reader, registry());+ searcher+ .search(query, 500, false)+ .unwrap()+ .into_iter()+ // Compare the score's exact bit pattern: "same BM25 score" means+ // identical, not close.+ .map(|hit| (hit.doc_id, hit.score.to_bits()))+ .collect()+}++fn queries() -> Vec<Query> {+ vec![+ Query::Term(TermQuery::new("body", "quick")),+ Query::Term(TermQuery::new("body", "otter")),+ Query::Phrase(PhraseQuery::new(+ "body",+ vec!["quick".to_owned(), "brown".to_owned()],+ )),+ // Spans the position-increment gap between two values of the same+ // multi-valued field: it must match NOTHING, before and after.+ Query::Phrase(PhraseQuery::new(+ "body",+ vec!["17".to_owned(), "a".to_owned()],+ )),+ Query::Term(TermQuery::new("tags", "tag-3")),+ Query::Term(TermQuery::new("tags", "colour-cobalt")),+ // The single-token field whose `.norms` the replay cannot reproduce:+ // its hits and its BM25 scores must be identical anyway.+ Query::Term(TermQuery::new("colour", "cobalt")),+ Query::Term(TermQuery::new("title", "survey")),+ Query::MatchAll,+ ]+}++fn assert_searches_identical(dir: &Path, expected: &str, actual: &str) {+ for query in queries() {+ let want = hits(dir, expected, &query);+ let got = hits(dir, actual, &query);+ assert_eq!(+ want, got,+ "hit list / scores differ for {query:?} between the re-analysed merge and \+ the replayed merge"+ );+ }+}++/// `.fst`, `.post` and `.meta` byte for byte; `.norms` for everything a+/// reader can observe (see `assert_norms_equivalent`).+#[test]+fn a_merge_with_no_deletes_reproduces_the_re_analysed_segment() {+ let (fixture, survivors) = Fixture::build(|_| true);+ assert_eq!(survivors.len(), DOC_COUNT);++ fixture.reanalysed(&survivors, "merged-reanalysed");+ fixture.replayed(&survivors, "merged-replayed");++ assert_sidecars_identical(+ fixture.path(),+ "merged-reanalysed",+ "merged-replayed",+ &EXTENSIONS,+ );+ assert_norms_equivalent(+ fixture.path(),+ "merged-reanalysed",+ "merged-replayed",+ survivors.len() as u32,+ );+ assert_searches_identical(fixture.path(), "merged-reanalysed", "merged-replayed");+}++/// Same comparison as above, with a fifth of the documents gone.+#[test]+fn a_merge_that_drops_documents_reproduces_the_re_analysed_segment() {+ // Every fifth document is deleted or superseded, so the merge must skip+ // it, close the ordinal gap it leaves, and reclaim its share of the+ // field-length statistics.+ let (fixture, survivors) = Fixture::build(|index| !index.is_multiple_of(5));+ assert_eq!(survivors.len(), DOC_COUNT - DOC_COUNT / 5);++ fixture.reanalysed(&survivors, "dropped-reanalysed");+ fixture.replayed(&survivors, "dropped-replayed");++ assert_sidecars_identical(+ fixture.path(),+ "dropped-reanalysed",+ "dropped-replayed",+ &EXTENSIONS,+ );+ assert_norms_equivalent(+ fixture.path(),+ "dropped-reanalysed",+ "dropped-replayed",+ survivors.len() as u32,+ );+ assert_searches_identical(fixture.path(), "dropped-reanalysed", "dropped-replayed");+}++#[test]+fn field_statistics_survive_a_merge_that_drops_documents() {+ // Guards the number BM25 length-normalisation actually reads: avgdl =+ // total_field_length / total_docs. A merge that lost either would still+ // return the same hit SET while silently re-ranking it.+ let (fixture, survivors) = Fixture::build(|index| !index.is_multiple_of(5));+ fixture.reanalysed(&survivors, "stats-reanalysed");+ fixture.replayed(&survivors, "stats-replayed");++ let expected = FtsIndexReader::open(fixture.path(), "stats-reanalysed", &FIELDS).unwrap();+ let actual = FtsIndexReader::open(fixture.path(), "stats-replayed", &FIELDS).unwrap();+ for field in FIELDS {+ let want = expected.field_stats(field).unwrap();+ let got = actual.field_stats(field).unwrap();+ assert_eq!(+ (want.total_docs, want.total_field_length),+ (got.total_docs, got.total_field_length),+ "field '{field}' statistics diverged across the merge"+ );+ for doc_id in 0..survivors.len() as u32 {+ assert_eq!(+ expected.field_length(field, doc_id),+ actual.field_length(field, doc_id),+ "field '{field}' length of merged doc {doc_id} diverged"+ );+ }+ }+}++#[test]+fn merging_needs_no_documents_only_the_segments() {+ // The point of the change, stated as a test: `merge_from_segments` is+ // handed readers and a doc-id map — never a document, never an analyzer+ // input — and still produces a searchable segment.+ let (fixture, survivors) = Fixture::build(|_| true);+ fixture.replayed(&survivors, "sourceless");++ let found = hits(+ fixture.path(),+ "sourceless",+ &Query::Term(TermQuery::new("body", "quick")),+ );+ assert_eq!(+ found.len(),+ DOC_COUNT,+ "every document should still match the term that appears in all of them"+ );+}++#[test]+fn side_car_field_names_read_back_from_the_segment_directory() {+ let (fixture, _survivors) = Fixture::build(|_| true);+ let names = segment_indexed_field_names(fixture.path(), "seg-0", &[]).unwrap();+ let mut expected: Vec<String> = FIELDS.iter().map(|field| (*field).to_owned()).collect();+ expected.sort();+ assert_eq!(names, expected);+}++#[test]+fn an_unresolvable_digest_component_is_refused_not_skipped() {+ // A field name that cannot be a portable filename is stored under a+ // SHA-256 digest. If the caller cannot tell the merge which name that+ // digest belongs to, enumerating must fail loudly: quietly omitting the+ // field would drop its postings out of the merged segment and stop its+ // terms matching, with nothing in the log.+ let dir = tempfile::TempDir::new().unwrap();+ let unsafe_field = "weird/field:name";+ let mut writer = FtsIndexWriter::new(dir.path(), "seg-encoded", registry());+ writer.configure_field(unsafe_field, FieldIndexConfig::default());+ let batch: Vec<(String, HashMap<String, FieldValues>, ())> = vec![(+ "1".to_owned(),+ HashMap::from([(+ unsafe_field.to_owned(),+ FieldValues::One("hello world".to_owned()),+ )]),+ (),+ )];+ writer.add_documents_parallel(&batch);+ writer.publish_encoded_filename_layout().unwrap();+ writer.finish().unwrap();++ assert!(+ segment_indexed_field_names(dir.path(), "seg-encoded", &[]).is_err(),+ "an unknown digest component must be an error"+ );+ let known = vec![unsafe_field.to_owned()];+ assert_eq!(+ segment_indexed_field_names(dir.path(), "seg-encoded", &known).unwrap(),+ known,+ "a digest component must resolve once the caller supplies the name"+ );+}++#[test]+fn a_docs_only_field_carries_its_length_but_not_its_term_frequency() {+ // The one place a replayed merge is knowingly NOT byte-identical, pinned+ // so it cannot drift further. A docs-only (`keyword`) posting list never+ // stored a per-document frequency — its reader synthesises 1 — so a+ // document that repeats the same keyword value merges with ttf = df.+ // Everything a query can observe is unchanged: the doc frequency, the+ // posting list bytes, the norm, and the field-length statistics all+ // survive, because `total_field_length` is carried from the source .meta+ // rather than recounted from the postings.+ let dir = tempfile::TempDir::new().unwrap();+ let fields = HashMap::from([(+ "tags".to_owned(),+ FieldValues::from_values(vec!["dup".to_owned(), "dup".to_owned(), "solo".to_owned()]),+ )]);+ let batch: Vec<(String, HashMap<String, FieldValues>, ())> =+ vec![("1".to_owned(), fields.clone(), ())];++ let mut source = FtsIndexWriter::new(dir.path(), "dup-source", registry());+ configure(&mut source);+ source.add_documents_parallel(&batch);+ source.finish().unwrap();++ let mut reference = FtsIndexWriter::new(dir.path(), "dup-reanalysed", registry());+ configure(&mut reference);+ reference.add_documents_parallel(&batch);+ reference.finish().unwrap();++ let reader = FtsIndexReader::open(dir.path(), "dup-source", &FIELDS).unwrap();+ let doc_map = [Some(0u32)];+ let mut merged = FtsIndexWriter::new(dir.path(), "dup-replayed", registry());+ configure(&mut merged);+ merged+ .merge_from_segments(&[FtsMergeSource {+ reader: &reader,+ doc_map: &doc_map,+ }])+ .unwrap();+ merged.finish().unwrap();++ // Query-visible state: identical.+ for extension in ["fst", "post", "norms"] {+ assert_eq!(+ sidecar(dir.path(), "dup-reanalysed", "tags", extension),+ sidecar(dir.path(), "dup-replayed", "tags", extension),+ "docs-only .{extension} must survive a repeated value byte for byte"+ );+ }+ let expected = FtsIndexReader::open(dir.path(), "dup-reanalysed", &FIELDS).unwrap();+ let actual = FtsIndexReader::open(dir.path(), "dup-replayed", &FIELDS).unwrap();+ assert_eq!(+ expected.field_stats("tags").unwrap().total_field_length,+ actual.field_stats("tags").unwrap().total_field_length,+ "the field length behind avgdl must count the repeat"+ );+ assert_eq!(+ expected.lookup_term("tags", "dup").unwrap().doc_frequency,+ actual.lookup_term("tags", "dup").unwrap().doc_frequency,+ );++ // The known, documented divergence.+ assert_eq!(+ expected+ .lookup_term("tags", "dup")+ .unwrap()+ .total_term_frequency,+ 2,+ "re-analysis counts the repeated keyword value twice"+ );+ assert_eq!(+ actual+ .lookup_term("tags", "dup")+ .unwrap()+ .total_term_frequency,+ 1,+ "a replayed docs-only posting can only report the frequency its \+ on-disk format kept, which is one per document"+ );+}++#[test]+fn a_single_token_field_replays_an_equivalent_shorter_norms_array() {+ // The SECOND place a replayed merge is knowingly not byte-identical,+ // pinned so it cannot drift and so it cannot silently stop being covered.+ //+ // `norm_u16_to_u8` returns byte 0 for length 0 AND for length 1, and+ // `load_norms` treats byte 0 as "no entry". Re-analysis pushes a norm for+ // every document that CARRIES the field - byte 0 included - and+ // `write_field_static` sizes the dense array from the last such entry, so+ // it writes one byte per document up to the highest one carrying the+ // field. A replay has no byte-0 entries to push, so its array stops at+ // the last NON-zero document; for a field that is single-token everywhere+ // that is no document at all, and the array collapses to one byte.+ //+ // The difference is trailing zeros. Both files load to the same (empty)+ // norms table, so `field_length`, `_score` and the hit list are unchanged+ // - which is what `assert_norms_equivalent` and `assert_searches_identical`+ // check on every merge test above. This test states the mechanism+ // directly: the fixture really is byte-0 throughout, the replayed array+ // really is shorter, and nothing observable moves.+ let (fixture, survivors) = Fixture::build(|_| true);+ fixture.reanalysed(&survivors, "norms-reanalysed");+ fixture.replayed(&survivors, "norms-replayed");++ // Precondition: `colour` really is the byte-0 case. If a future fixture+ // change gave it two tokens, this assertion fails rather than quietly+ // turning the test into a no-op - which is exactly how this case escaped+ // the original suite.+ let source = FtsIndexReader::open(fixture.path(), "seg-0", &FIELDS).unwrap();+ assert_eq!(+ source.field_norm_bytes("colour").count(),+ 0,+ "'colour' must analyse to one token per document (norm byte 0) for this \+ test to be testing anything"+ );+ assert!(+ source.field_stats("colour").unwrap().total_docs > 0,+ "'colour' must actually be indexed in the source segment"+ );++ // The divergence, stated exactly: re-analysis sizes the array from the+ // last document carrying the field, the replay from the last non-zero one.+ let reanalysed_len = norms_dense_len(fixture.path(), "norms-reanalysed", "colour");+ let replayed_len = norms_dense_len(fixture.path(), "norms-replayed", "colour");+ assert_eq!(+ reanalysed_len,+ survivors.len() as u32,+ "re-analysis writes one norm byte per document carrying the field"+ );+ assert_eq!(+ replayed_len, 1,+ "a replay with no non-zero norm has nothing to size the array from"+ );++ // ...and nothing a reader can see moves with it.+ let expected = FtsIndexReader::open(fixture.path(), "norms-reanalysed", &FIELDS).unwrap();+ let actual = FtsIndexReader::open(fixture.path(), "norms-replayed", &FIELDS).unwrap();+ assert_eq!(expected.field_norm_bytes("colour").count(), 0);+ assert_eq!(actual.field_norm_bytes("colour").count(), 0);+ for doc_id in 0..survivors.len() as u32 {+ assert_eq!(+ expected.field_length("colour", doc_id),+ actual.field_length("colour", doc_id),+ "merged doc {doc_id} field length diverged"+ );+ }+ assert_eq!(+ expected.field_stats("colour").unwrap().total_docs,+ actual.field_stats("colour").unwrap().total_docs,+ );+ assert_eq!(+ expected.field_stats("colour").unwrap().total_field_length,+ actual.field_stats("colour").unwrap().total_field_length,+ );+ // The other three side-cars stay byte for byte identical for this field.+ for extension in EXTENSIONS {+ assert_eq!(+ sidecar(fixture.path(), "norms-reanalysed", "colour", extension),+ sidecar(fixture.path(), "norms-replayed", "colour", extension),+ "single-token keyword .{extension} must survive the merge byte for byte"+ );+ }+ assert_eq!(+ hits(+ fixture.path(),+ "norms-reanalysed",+ &Query::Term(TermQuery::new("colour", "cobalt"))+ ),+ hits(+ fixture.path(),+ "norms-replayed",+ &Query::Term(TermQuery::new("colour", "cobalt"))+ ),+ "hits and scores over a single-token field must be identical despite \+ the shorter .norms"+ );+}