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
fix(build): run x86_64 releases on CPUs without AVX2 (#2161) (#2253)
xerj-org8c05ed5c8700
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 27fdbd1bb..3f63e272a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- x86_64 release binaries no longer require AVX2. The build baseline is+ `x86-64-v2` (SSE4.2). The HNSW eight-accumulator dot product — the kernel+ `x86-64-v3` was actually vectorizing — compiles an AVX2+FMA variant and+ selects it at runtime when the CPU has both features; the scalar+ compilation is bit-identical. Installers install on CPUs without AVX2+ instead of refusing. `XERJ_SKIP_CPU_CHECK` is gone+ ([#2161](https://github.com/xerj-org/xerj/issues/2161)).+- `xerj corpus index` killed mid-index resumes that build's journal instead ofstarting a legacy index under a new prefix. When the journal still has ageneration in progress, indexing continues at the uncommitted operations anddiff --git a/README.md b/README.mdindex 8667b7db9..2e5599346 100644--- a/README.md+++ b/README.md@@ -197,10 +197,9 @@ irm https://xerj.org/get.ps1 | iex```One static binary, no JVM, no dependencies. Prebuilt for Linux, macOS and Windows on x86-64-and arm64. The x86-64 builds need a CPU with AVX2, BMI2 and FMA (x86-64-v3: Intel Haswell-2013 and later, AMD Excavator/Zen and later); on an older CPU they stop at launch with an-illegal-instruction error, so the installer checks before downloading and tells you to-[build from source](#build-from-source) instead. It speaks the Elasticsearch API, so existing+and arm64. The x86-64 builds target x86-64-v2 (SSE4.2: Intel Nehalem 2008 and later, AMD+Bulldozer and later) and use AVX2 and FMA at runtime when the CPU has them, so a pre-Haswell+machine runs the same binary. It speaks the Elasticsearch API, so existingclients, dashboards and tooling work against it unchanged.First commands after install (the installer prints where `xerj` landed; add it to your PATH@@ -593,13 +592,13 @@ cargo build --release -p xerj-server./target/release/xerj --insecure --data-dir ~/xerj-data```-The x86-64 release builds target `x86-64-v3` (AVX2, BMI2, FMA; set per target in-`engine/.cargo/config.toml`), which is why the prebuilt binaries crash at launch on CPUs older-than Intel Haswell (2013) or AMD Excavator/Zen. `RUSTFLAGS` overrides that file, so on such a-CPU build with a lower baseline instead of installing the prebuilt binary:+The x86-64 release builds target `x86-64-v2` (SSE4.2; set per target in+`engine/.cargo/config.toml`). The HNSW dot-product kernel also compiles an AVX2+FMA+variant and selects it at runtime when the CPU has both features. `RUSTFLAGS` overrides+that file, so a local build can opt into the host CPU:```sh-RUSTFLAGS="-C target-cpu=x86-64-v2" cargo build --release -p xerj-server+RUSTFLAGS="-C target-cpu=native" cargo build --release -p xerj-server```To run the conformance suite against a running server:diff --git a/engine/.cargo/config.toml b/engine/.cargo/config.tomlindex 9f627aa56..eb6221938 100644--- a/engine/.cargo/config.toml+++ b/engine/.cargo/config.toml@@ -5,20 +5,24 @@# host's x86 features (e.g. `znver4`) into every invocation,# including aarch64 ones, which rejected the flag with "unknown# processor znver4". Release binaries must also be portable across-# machines, so we pin to a generic mid-range baseline per-arch:+# machines, so we pin to a generic baseline per-arch:#-# x86_64 → `x86-64-v3` (Haswell+, SSE4.2/AVX2/BMI1/BMI2/F16C) —-# the Rust portable baseline for modern (>=2013) x86.+# x86_64 → `x86-64-v2` (Nehalem+, SSE4.2/POPCNT, no AVX/AVX2).+# Pre-Haswell CPUs, some Atom/Celeron/Pentium parts, and+# VMs that hide AVX2 can run the binary (#2161). The HNSW+# dot-product kernel compiles an AVX2+FMA variant and+# selects it at runtime when the CPU has both features, so+# Haswell and newer keep that kernel's v3 speed.# aarch64 → default (ARMv8-A) — universally available.## To re-enable target-cpu=native locally:# export RUSTFLAGS="-C target-cpu=native"# (env RUSTFLAGS takes precedence over this file.)[target.x86_64-unknown-linux-gnu]-rustflags = ["-C", "target-cpu=x86-64-v3"]+rustflags = ["-C", "target-cpu=x86-64-v2"][target.x86_64-unknown-linux-musl]-rustflags = ["-C", "target-cpu=x86-64-v3"]+rustflags = ["-C", "target-cpu=x86-64-v2"][target.aarch64-unknown-linux-gnu]rustflags = []@@ -27,7 +31,7 @@ rustflags = []rustflags = [][target.x86_64-apple-darwin]-rustflags = ["-C", "target-cpu=x86-64-v3"]+rustflags = ["-C", "target-cpu=x86-64-v2"][target.aarch64-apple-darwin]# `ring 0.17.14` has a compile-time assertion@@ -38,7 +42,7 @@ rustflags = ["-C", "target-cpu=x86-64-v3"]rustflags = ["-C", "target-cpu=apple-m1"][target.x86_64-pc-windows-msvc]-rustflags = ["-C", "target-cpu=x86-64-v3"]+rustflags = ["-C", "target-cpu=x86-64-v2"][target.aarch64-pc-windows-msvc]rustflags = []diff --git a/engine/crates/xerj-vector/src/distance.rs b/engine/crates/xerj-vector/src/distance.rsindex 58719cf60..ebd4d4deb 100644--- a/engine/crates/xerj-vector/src/distance.rs+++ b/engine/crates/xerj-vector/src/distance.rs@@ -1,7 +1,11 @@//! Distance metrics for vector similarity search.//!-//! All functions are written with explicit loops that the compiler can-//! auto-vectorize with SSE/AVX/NEON, avoiding any unsafe code.+//! These are single-accumulator loops. LLVM does not reassociate f32+//! addition, so `x86-64-v3` does not vectorize them (measured: the+//! assembly stays scalar `mulss`/`addss`, and a v3 build is not faster+//! than v2). The beam-search hot path is the eight-accumulator kernel in+//! `hnsw`, which dispatches to AVX2 at runtime. Widening the reductions+//! here would change bits that callers treat as exact.use serde::{Deserialize, Serialize};@@ -34,7 +38,6 @@ pub fn cosine(a: &[f32], b: &[f32]) -> f32 {let mut norm_a = 0.0f32;let mut norm_b = 0.0f32;- // Single-pass — compiler will auto-vectorize this loopfor (&ai, &bi) in a.iter().zip(b.iter()) {dot += ai * bi;norm_a += ai * ai;@@ -164,22 +167,40 @@ mod tests {// Should not panic, returns 0assert_eq!(cosine(&a, &b), 0.0);}-}-// TODO(v1.0.2): Add explicit SIMD implementations with runtime dispatch.-//-// Current: pure Rust loops, compiler auto-vectorizes to SSE2/NEON.-// Target: explicit AVX2 (x86_64) + NEON (aarch64) + SVE2 (Graviton3+)-// via `pulp` crate or `std::arch` intrinsics.-//-// Expected speedup: 3-10× on kNN search hot path.-//-// ARM-specific notes:-// - NEON: 128-bit SIMD, available on all ARMv8 (Graviton2+)-// - SVE/SVE2: scalable vector extension, 128-2048 bit, Graviton3+-// - LSE atomics: better fetch_add/CAS on high-core-count ARM-//-// #[cfg(target_arch = "x86_64")]-// mod avx2 { ... }-// #[cfg(target_arch = "aarch64")]-// mod neon { ... }+ /// The committed x86_64 rustflags must not force AVX2. Release builds+ /// pin `x86-64-v2` and pick AVX2 up at runtime in the HNSW kernel.+ /// `RUSTFLAGS` can still override this file for a local native build;+ /// this test locks the file, not the ambient flags.+ #[test]+ fn x86_64_release_baseline_is_v2_not_v3() {+ let config = include_str!("../../../.cargo/config.toml");+ let code = config+ .lines()+ .filter(|line| {+ let trimmed = line.trim();+ !trimmed.is_empty() && !trimmed.starts_with('#')+ })+ .collect::<Vec<_>>()+ .join("\n");+ assert!(+ !code.contains("x86-64-v3"),+ "non-comment rustflags must not force x86-64-v3:\n{code}"+ );+ for target in [+ "x86_64-unknown-linux-gnu",+ "x86_64-unknown-linux-musl",+ "x86_64-apple-darwin",+ "x86_64-pc-windows-msvc",+ ] {+ let section = code+ .split("[target.")+ .find(|part| part.starts_with(target))+ .unwrap_or_else(|| panic!("missing [target.{target}]"));+ assert!(+ section.contains("target-cpu=x86-64-v2"),+ "{target} must pin x86-64-v2, section was:\n{section}"+ );+ }+ }+}diff --git a/engine/crates/xerj-vector/src/hnsw.rs b/engine/crates/xerj-vector/src/hnsw.rsindex f22299626..a3c8385f6 100644--- a/engine/crates/xerj-vector/src/hnsw.rs+++ b/engine/crates/xerj-vector/src/hnsw.rs@@ -81,15 +81,17 @@ fn corrupt(msg: &str) -> XerjError {/// Dot product with eight independent accumulators.///-/// A single-accumulator `for` loop is a strict serial FP dependency chain-/// that rustc must NOT auto-vectorize (float addition is not associative),-/// so the beam search was spending ~5 ns/dim in scalar fmadds. Eight-/// independent chains let LLVM keep multiple SIMD lanes busy; the exact-/// f32 sum differs from the serial order only in rounding, which is fine-/// here — graph distances only decide beam ORDER and callers rescore-/// exact similarities downstream.-#[inline]-fn dot_unrolled(a: &[f32], b: &[f32]) -> f32 {+/// A single-accumulator `for` loop is a strict serial f32 dependency chain.+/// LLVM will not reassociate it, so it stays scalar even at `x86-64-v3`.+/// Eight independent chains are what the beam-search inner loop actually+/// vectorizes. The release baseline is `x86-64-v2` (no AVX2; #2161), and+/// the same source is compiled again in [`dot_avx2`] with AVX2 and FMA+/// enabled. Rust does not contract `acc += x * y` into an FMA, so the two+/// compilations are bit-identical; only the instruction width changes.+/// Callers rescore exact similarities downstream — this value only orders+/// the beam.+#[inline(always)]+fn dot_scalar(a: &[f32], b: &[f32]) -> f32 {let mut acc = [0.0f32; 8];// `as_chunks::<8>()` yields the same 8-wide windows + remainder as// `chunks_exact(8)` (the `x`/`y` are now `&[f32; 8]`, so the fixed@@ -114,6 +116,36 @@ fn dot_unrolled(a: &[f32], b: &[f32]) -> f32 {s}+/// [`dot_scalar`] compiled with AVX2 and FMA available to LLVM.+///+/// # Safety+///+/// The current CPU must support both AVX2 and FMA. The `*_avx2` entry+/// points check `is_x86_feature_detected` before calling in.+#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+#[target_feature(enable = "avx2,fma")]+#[inline]+unsafe fn dot_avx2(a: &[f32], b: &[f32]) -> f32 {+ dot_scalar(a, b)+}++/// `AVX2 == true` selects [`dot_avx2`]. That monomorphization is only+/// reached from a `#[target_feature(enable = "avx2,fma")]` wrapper.+#[inline(always)]+fn dot<const AVX2: bool>(a: &[f32], b: &[f32]) -> f32 {+ // `AVX2` is read on every architecture so the const parameter is used+ // when the x86 block below is compiled out.+ if AVX2 && cfg!(any(target_arch = "x86", target_arch = "x86_64")) {+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ {+ // SAFETY: the corresponding `*_avx2` wrapper checked both features+ // and carries `target_feature(enable = "avx2,fma")`.+ return unsafe { dot_avx2(a, b) };+ }+ }+ dot_scalar(a, b)+}+// ─────────────────────────────────────────────────────────────────────────────// Parameters// ─────────────────────────────────────────────────────────────────────────────@@ -379,7 +411,7 @@ fn query_inverse(graph: &impl GraphStorageRead, query: &[f32]) -> f32 {}#[inline(always)]-fn slot_distance(+fn slot_distance<const AVX2: bool>(graph: &impl GraphStorageRead,query: &[f32],query_inverse_norm: f32,@@ -388,7 +420,7 @@ fn slot_distance(let vector = graph.vector(slot);match graph.metric() {DistanceMetric::Cosine => {- 1.0 - dot_unrolled(query, vector) * query_inverse_norm * graph.inverse_norm(slot)+ 1.0 - dot::<AVX2>(query, vector) * query_inverse_norm * graph.inverse_norm(slot)}metric => compute_distance(metric, query, vector),}@@ -400,16 +432,46 @@ fn greedy_layer(query_inverse_norm: f32,start: u32,layer: usize,+) -> (u32, f32) {+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ {+ if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {+ // SAFETY: both features are present; `greedy_layer_avx2` enables them.+ return unsafe { greedy_layer_avx2(graph, query, query_inverse_norm, start, layer) };+ }+ }+ greedy_layer_impl::<false>(graph, query, query_inverse_norm, start, layer)+}++#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+#[target_feature(enable = "avx2,fma")]+unsafe fn greedy_layer_avx2(+ graph: &impl GraphStorageRead,+ query: &[f32],+ query_inverse_norm: f32,+ start: u32,+ layer: usize,+) -> (u32, f32) {+ greedy_layer_impl::<true>(graph, query, query_inverse_norm, start, layer)+}++#[inline(always)]+fn greedy_layer_impl<const AVX2: bool>(+ graph: &impl GraphStorageRead,+ query: &[f32],+ query_inverse_norm: f32,+ start: u32,+ layer: usize,) -> (u32, f32) {let mut best = start;- let mut best_distance = slot_distance(graph, query, query_inverse_norm, start);+ let mut best_distance = slot_distance::<AVX2>(graph, query, query_inverse_norm, start);loop {let mut improved = false;if layer >= graph.layer_count(best) {break;}for &neighbor in graph.neighbors(best, layer) {- let distance = slot_distance(graph, query, query_inverse_norm, neighbor);+ let distance = slot_distance::<AVX2>(graph, query, query_inverse_norm, neighbor);if distance < best_distance {best_distance = distance;best = neighbor;@@ -432,6 +494,48 @@ fn beam<G, A>(layer: usize,admit: &A,) -> Vec<(f32, u32)>+where+ G: GraphStorageRead,+ A: Fn(u32) -> bool + ?Sized,+{+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ {+ if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {+ // SAFETY: both features are present; `beam_avx2` enables them.+ return unsafe { beam_avx2(graph, query, query_inverse_norm, entry, ef, layer, admit) };+ }+ }+ beam_impl::<G, A, false>(graph, query, query_inverse_norm, entry, ef, layer, admit)+}++#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+#[target_feature(enable = "avx2,fma")]+unsafe fn beam_avx2<G, A>(+ graph: &G,+ query: &[f32],+ query_inverse_norm: f32,+ entry: u32,+ ef: usize,+ layer: usize,+ admit: &A,+) -> Vec<(f32, u32)>+where+ G: GraphStorageRead,+ A: Fn(u32) -> bool + ?Sized,+{+ beam_impl::<G, A, true>(graph, query, query_inverse_norm, entry, ef, layer, admit)+}++#[inline(always)]+fn beam_impl<G, A, const AVX2: bool>(+ graph: &G,+ query: &[f32],+ query_inverse_norm: f32,+ entry: u32,+ ef: usize,+ layer: usize,+ admit: &A,+) -> Vec<(f32, u32)>whereG: GraphStorageRead,A: Fn(u32) -> bool + ?Sized,@@ -449,7 +553,7 @@ whereseen}- let entry_distance = slot_distance(graph, query, query_inverse_norm, entry);+ let entry_distance = slot_distance::<AVX2>(graph, query, query_inverse_norm, entry);let mut candidates: BinaryHeap<Reverse<(ordered_float::OrderedFloat, u32)>> =BinaryHeap::with_capacity(ef * 4);let mut results: BinaryHeap<(ordered_float::OrderedFloat, u32)> =@@ -484,7 +588,7 @@ whereif test_and_set(&mut visited, neighbor) {continue;}- let distance = slot_distance(graph, query, query_inverse_norm, neighbor);+ let distance = slot_distance::<AVX2>(graph, query, query_inverse_norm, neighbor);let farthest = results.peek().map(|&(distance, _)| distance.0)@@ -513,6 +617,32 @@ fn select_diverse(graph: &impl GraphStorageRead,candidates: &[(f32, u32)],max_neighbors: usize,+) -> Vec<(f32, u32)> {+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ {+ if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {+ // SAFETY: both features are present; `select_diverse_avx2` enables them.+ return unsafe { select_diverse_avx2(graph, candidates, max_neighbors) };+ }+ }+ select_diverse_impl::<false>(graph, candidates, max_neighbors)+}++#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+#[target_feature(enable = "avx2,fma")]+unsafe fn select_diverse_avx2(+ graph: &impl GraphStorageRead,+ candidates: &[(f32, u32)],+ max_neighbors: usize,+) -> Vec<(f32, u32)> {+ select_diverse_impl::<true>(graph, candidates, max_neighbors)+}++#[inline(always)]+fn select_diverse_impl<const AVX2: bool>(+ graph: &impl GraphStorageRead,+ candidates: &[(f32, u32)],+ max_neighbors: usize,) -> Vec<(f32, u32)> {let mut sorted = candidates.to_vec();sorted.sort_unstable_by(|left, right| left.0.partial_cmp(&right.0).unwrap());@@ -524,7 +654,7 @@ fn select_diverse(let vector = graph.vector(candidate);let inverse_norm = graph.inverse_norm(candidate);let diverse = kept.iter().all(|&(_, retained)| {- slot_distance(graph, vector, inverse_norm, retained) >= candidate_distance+ slot_distance::<AVX2>(graph, vector, inverse_norm, retained) >= candidate_distance});if diverse {kept.push((candidate_distance, candidate));@@ -534,6 +664,32 @@ fn select_diverse(}fn backlink_distances(graph: &impl GraphStorageRead, base: u32, layer: usize) -> Vec<(f32, u32)> {+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ {+ if std::is_x86_feature_detected!("avx2") && std::is_x86_feature_detected!("fma") {+ // SAFETY: both features are present; `backlink_distances_avx2` enables them.+ return unsafe { backlink_distances_avx2(graph, base, layer) };+ }+ }+ backlink_distances_impl::<false>(graph, base, layer)+}++#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+#[target_feature(enable = "avx2,fma")]+unsafe fn backlink_distances_avx2(+ graph: &impl GraphStorageRead,+ base: u32,+ layer: usize,+) -> Vec<(f32, u32)> {+ backlink_distances_impl::<true>(graph, base, layer)+}++#[inline(always)]+fn backlink_distances_impl<const AVX2: bool>(+ graph: &impl GraphStorageRead,+ base: u32,+ layer: usize,+) -> Vec<(f32, u32)> {let vector = graph.vector(base);let inverse_norm = graph.inverse_norm(base);graph@@ -541,7 +697,7 @@ fn backlink_distances(graph: &impl GraphStorageRead, base: u32, layer: usize) ->.iter().map(|&neighbor| {(- slot_distance(graph, vector, inverse_norm, neighbor),+ slot_distance::<AVX2>(graph, vector, inverse_norm, neighbor),neighbor,)})@@ -1151,7 +1307,7 @@ impl HnswIndex {let ep = graph.entry_slot()?;let q_inv = query_inverse(&graph, query);let mut curr = ep;- let mut curr_dist = slot_distance(&graph, query, q_inv, curr);+ let mut curr_dist = slot_distance::<false>(&graph, query, q_inv, curr);for layer in (1..=graph.entry_layer()).rev() {let (s, d) = greedy_layer(&graph, query, q_inv, curr, layer);curr = s;@@ -1434,7 +1590,7 @@ mod tests {let vector = &graph.vectors[start..start + graph.dim];match graph.metric {DistanceMetric::Cosine => {- 1.0 - dot_unrolled(query, vector)+ 1.0 - dot_scalar(query, vector)* query_inverse_norm* graph.inv_norms[slot as usize]}@@ -1991,4 +2147,83 @@ mod tests {"recall@10 regression: got {recall:.3}, expected >= 0.9");}++ /// The AVX2 compilation of the beam-search dot product must return the+ /// same bits as the scalar compilation. Lengths cover the 8-wide chunk,+ /// the remainder, and an unaligned window.+ #[test]+ fn avx2_dot_matches_scalar_bits() {+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]+ {+ if !std::is_x86_feature_detected!("avx2") || !std::is_x86_feature_detected!("fma") {+ return;+ }+ let mut state = 0xC0FFEE_u64;+ let mut next = || {+ state = state.wrapping_mul(6364136223846793005).wrapping_add(1);+ let unit = ((state >> 33) as u32 as f32) / 2147483648.0;+ unit * 4.0 - 2.0+ };+ let mut data = Vec::with_capacity(2048);+ for _ in 0..2048 {+ data.push(next());+ }+ data[3] = 0.0;+ data[4] = -0.0;+ data[10] = 1.0e20;+ data[11] = -1.0e-20;+ for &len in &[0usize, 1, 7, 8, 9, 15, 16, 17, 31, 32, 63, 64, 768] {+ for &off in &[0usize, 1] {+ if off + len * 2 > data.len() {+ continue;+ }+ let a = &data[off..off + len];+ let b = &data[off + len..off + len * 2];+ let scalar = dot_scalar(a, b);+ // SAFETY: the feature check above succeeded.+ let avx = unsafe { dot_avx2(a, b) };+ assert_eq!(+ scalar.to_bits(),+ avx.to_bits(),+ "len {len} off {off}: scalar {scalar} avx2 {avx}"+ );+ }+ }+ }+ }++ /// Production search (AVX2 kernel on this host, scalar otherwise) must+ /// agree bit-for-bit with the scalar eight-accumulator formula.+ #[test]+ fn search_cosine_distance_matches_scalar_dot() {+ let dim = 32usize;+ let idx = make_index(dim);+ let mut state = 0xA11CE_u64;+ let mut next = || {+ state = state.wrapping_mul(6364136223846793005).wrapping_add(1);+ (((state >> 33) as u32) as f32) / 2147483648.0 * 2.0 - 1.0+ };+ let mut vecs = Vec::new();+ for i in 0..40u64 {+ let v: Vec<f32> = (0..dim).map(|_| next()).collect();+ idx.insert(i, v.clone()).unwrap();+ vecs.push(v);+ }+ let q = vecs[0].clone();+ let q_norm = q.iter().map(|x| x * x).sum::<f32>().sqrt();+ let q_inv = if q_norm > 0.0 { 1.0 / q_norm } else { 0.0 };+ let hits = idx.search(&q, 8, 64).unwrap();+ assert!(!hits.is_empty());+ for (id, dist) in hits {+ let v = &vecs[id as usize];+ let n = v.iter().map(|x| x * x).sum::<f32>().sqrt();+ let inv = if n > 0.0 { 1.0 / n } else { 0.0 };+ let expect = 1.0 - dot_scalar(&q, v) * q_inv * inv;+ assert_eq!(+ dist.to_bits(),+ expect.to_bits(),+ "id {id}: search {dist} scalar {expect}"+ );+ }+ }}diff --git a/landing/docs/install.html b/landing/docs/install.htmlindex f650a803c..ff8ca12d8 100644--- a/landing/docs/install.html+++ b/landing/docs/install.html@@ -241,7 +241,7 @@<li><strong>OS:</strong> Linux (any distro — the Linux build is fully static musl, Alpine included), macOS (Apple Silicon arm64 / Intel x86_64), or Windows 10+ (x64 / ARM64).</li><li><strong>RAM:</strong> 400 MB idle. 2 GB working set per active index. Scales linearly with segment resident set.</li><li><strong>Disk:</strong> Any fs that supports <code class="inline">fsync</code> and mmap. Prefer SSD.</li>- <li><strong>CPU:</strong> x86_64 with AVX2, BMI2 and FMA (x86-64-v3: Intel Haswell 2013 and later, AMD Excavator/Zen and later), or arm64 with NEON. The x86_64 release builds are compiled for that baseline and stop at launch with an illegal-instruction error on older CPUs; both installers check the CPU before downloading and refuse with the reason. On such a CPU, <a href="https://github.com/xerj-org/xerj#build-from-source">build from source</a> with <code class="inline">RUSTFLAGS="-C target-cpu=x86-64-v2"</code>.</li>+ <li><strong>CPU:</strong> x86_64 with SSE4.2 (x86-64-v2: Intel Nehalem 2008 and later, AMD Bulldozer and later), or arm64 with NEON. The x86_64 release builds use that baseline and run AVX2 and FMA at runtime when the CPU has them, so a pre-Haswell CPU runs the same binary.</li><li><strong>Open files:</strong> 65536 ulimit is sufficient for most deployments.</li></ul>@@ -254,7 +254,7 @@<p>Both installers verify <strong>fail-closed</strong>: each computes the archive's own SHA-256 and compares it against the published digest, and if the checksum cannot be downloaded, or no SHA-256 tool (<code class="inline">sha256sum</code>, <code class="inline">shasum</code>, <code class="inline">openssl</code>, <code class="inline">busybox</code>…) can be found, the installer stops rather than installing an unverified binary.</p><p>On Linux the one-liner installs the <strong>static musl</strong> build by default — it runs on any distro including Alpine and has no glibc-version floor. Ask for the glibc build explicitly if you need it:</p><pre class="code">$ curl -fsSL https://xerj.org/get | XERJ_LIBC=gnu sh</pre>- <p>Other environment overrides: <code class="inline">XERJ_VERSION</code> (install a specific tag), <code class="inline">XERJ_INSTALL_DIR</code> (default <code class="inline">~/.local/bin</code> on Linux and macOS, <code class="inline">%LOCALAPPDATA%\Programs\xerj</code> on Windows), <code class="inline">XERJ_REPO</code>, <code class="inline">XERJ_SKIP_CPU_CHECK=1</code> (install an x86_64 build even when the CPU does not advertise AVX2; it will crash at launch if the hardware really lacks it).</p>+ <p>Other environment overrides: <code class="inline">XERJ_VERSION</code> (install a specific tag), <code class="inline">XERJ_INSTALL_DIR</code> (default <code class="inline">~/.local/bin</code> on Linux and macOS, <code class="inline">%LOCALAPPDATA%\Programs\xerj</code> on Windows), <code class="inline">XERJ_REPO</code>.</p><h2>Manual download</h2><p>Every release publishes eight targets, each with a <code class="inline">.sha256</code> alongside: <code class="inline">x86_64</code>/<code class="inline">aarch64</code> × <code class="inline">unknown-linux-musl</code> (static, any distro), <code class="inline">unknown-linux-gnu</code>, <code class="inline">apple-darwin</code>, and <code class="inline">pc-windows-msvc</code> (.zip).</p>diff --git a/landing/get b/landing/getindex 8533db951..e2886a4cf 100644--- a/landing/get+++ b/landing/get@@ -15,10 +15,9 @@# install without verifying SHA-256. Only useful on a# box with no hashing tool at all; you are choosing to# run an unverified binary.-# XERJ_SKIP_CPU_CHECK=1 install an x86_64 build even when this CPU does-# not advertise AVX2/BMI2/FMA (see "CPU feature-# floor" below). The binary will crash at launch if-# the hardware really lacks them.+#+# x86_64 binaries target x86-64-v2 and use AVX2/FMA at runtime when the CPU+# has them. The installer does not refuse a CPU (#2161).# =============================================================================set -eu@@ -88,45 +87,9 @@ if [ "$os" = "Darwin" ] && [ "$cpu" = "x86_64" ] \cpu="aarch64"fi-# --- CPU feature floor (x86_64 only) ------------------------------------------# Every x86_64 release binary is built with `-C target-cpu=x86-64-v3`-# (engine/.cargo/config.toml), so it executes AVX2/BMI2/FMA instructions-# unconditionally. On a CPU without them — Intel before Haswell (2013), AMD-# before Excavator/Zen, some Atom/Celeron/Pentium parts, VMs that hide the-# flags — the process dies at launch with "Illegal instruction" and prints-# nothing (#2161, field report #2158). Refuse here, before the download, and-# say why. The arm64 builds have no such floor (ARMv8-A baseline).-#-# Only positive evidence fails the check: a readable feature list that lacks-# a feature. When the list cannot be read at all (no /proc/cpuinfo, no-# sysctl) the check is skipped, not failed. XERJ_SKIP_CPU_CHECK=1 bypasses it.-if [ "$cpu" = "x86_64" ] && [ "${XERJ_SKIP_CPU_CHECK:-}" != "1" ]; then- missing=''- if [ "$os" = "Darwin" ]; then- # hw.optional.* answers 1/0 per feature, nothing when the key is unknown.- for f in avx1_0 avx2_0 bmi1 bmi2 f16c fma; do- [ "$(sysctl -n "hw.optional.$f" 2>/dev/null)" = "0" ] && missing="$missing $f"- done- elif [ -r /proc/cpuinfo ]; then- # Linux, and the /proc emulation of Git Bash / MSYS / Cygwin on Windows.- # The flag names are the kernel's: LZCNT is advertised as `abm`.- flags=$(sed -n 's/^flags[[:space:]]*:[[:space:]]*//p' /proc/cpuinfo | head -n1)- if [ -n "$flags" ]; then- for f in avx avx2 bmi1 bmi2 f16c fma abm movbe xsave; do- case " $flags " in *" $f "*) ;; *) missing="$missing $f" ;; esac- done- fi- fi- if [ -n "$missing" ]; then- die "this CPU lacks${missing} — the x86_64 release binaries are built for x86-64-v3- (AVX2/BMI2/FMA: Intel Haswell 2013+, AMD Excavator/Zen+) and crash at launch with- 'Illegal instruction' without them (https://github.com/${REPO}/issues/2161).- Build for this CPU instead: RUSTFLAGS='-C target-cpu=x86-64-v2' cargo build --release -p xerj-server- (https://github.com/${REPO}#build-from-source)- To install the prebuilt binary anyway (e.g. a sandbox hides flags the hardware has):- XERJ_SKIP_CPU_CHECK=1"- fi-fi+# x86_64 release binaries are built for x86-64-v2 (engine/.cargo/config.toml)+# and select AVX2/FMA at runtime when the CPU has them, so a pre-Haswell+# machine can install the same artifact (#2161). No feature check here.if [ "$os" = "Linux" ]; thencase "${XERJ_LIBC:-musl}" inmusl) ;; # the default set abovediff --git a/landing/get.ps1 b/landing/get.ps1index 9c9844289..670376bdb 100644--- a/landing/get.ps1+++ b/landing/get.ps1@@ -11,9 +11,9 @@# XERJ_INSTALL_DIR=path install location (default: %LOCALAPPDATA%\Programs\xerj)# XERJ_REPO=owner/name source repo (default: xerj-org/xerj)# XERJ_NO_PATH=1 do not add the install dir to the user PATH-# XERJ_SKIP_CPU_CHECK=1 install the x64 build even when this CPU does not-# advertise AVX2 (see "CPU feature floor" below). It-# will crash at launch if the hardware really lacks it.+#+# x64 binaries target x86-64-v2 and use AVX2/FMA at runtime when the CPU has+# them. The installer does not refuse a CPU (#2161).## Works on Windows PowerShell 5.1 and PowerShell 7+.#@@ -56,53 +56,9 @@}$target = "$cpu-pc-windows-msvc"- # --- CPU feature floor (x64 only) -------------------------------------------- # Every x64 release binary is built with `-C target-cpu=x86-64-v3`- # (engine/.cargo/config.toml), so it executes AVX2/BMI2/FMA instructions- # unconditionally. On a CPU without them - Intel before Haswell (2013), AMD- # before Excavator/Zen, some Atom/Celeron/Pentium parts, VMs that hide the- # flags - xerj.exe dies at launch with STATUS_ILLEGAL_INSTRUCTION- # (0xc000001d) and prints nothing (#2161, field report #2158). Refuse here,- # before the download, and say why. The ARM64 build has no such floor.- #- # Only positive evidence fails the check; when the features cannot be read- # it is skipped, not failed. $env:XERJ_SKIP_CPU_CHECK=1 bypasses it.- if ($cpu -eq 'x86_64' -and $env:XERJ_SKIP_CPU_CHECK -ne '1') {- $missing = @()- try {- if ($PSVersionTable.PSVersion.Major -ge 7) {- # PowerShell 7+ (.NET Core 3.0+): CPUID-backed, independent of the OS build.- foreach ($f in 'Avx', 'Avx2', 'Bmi1', 'Bmi2', 'Fma', 'Lzcnt') {- $t = "System.Runtime.Intrinsics.X86.$f" -as [type]- if ($t -and -not $t::IsSupported) { $missing += $f.ToLower() }- }- } else {- # Windows PowerShell 5.1 (.NET Framework has no intrinsics API):- # kernel32!IsProcessorFeaturePresent(PF_AVX2_INSTRUCTIONS_AVAILABLE = 40).- # That constant exists since Windows 10 version 2004 (build 19041);- # older builds answer 0 whatever the hardware, so skip them.- $build = [int](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').CurrentBuildNumber- if ($build -ge 19041) {- if (-not ('XerjInstaller.Cpu' -as [type])) {- Add-Type -Namespace 'XerjInstaller' -Name 'Cpu' -MemberDefinition @'-[DllImport("kernel32.dll")] public static extern bool IsProcessorFeaturePresent(int feature);-'@- }- if (-not [XerjInstaller.Cpu]::IsProcessorFeaturePresent(40)) { $missing += 'avx2' }- }- }- } catch {- $missing = @() # could not read the features: do not guess- }- if ($missing.Count -gt 0) {- Fail ("this CPU lacks $($missing -join ', ') - the x64 release binaries are built for x86-64-v3 " +- "(AVX2/BMI2/FMA: Intel Haswell 2013+, AMD Excavator/Zen+) and crash at launch with " +- "STATUS_ILLEGAL_INSTRUCTION without them (https://github.com/$Repo/issues/2161). " +- "Build for this CPU instead: `$env:RUSTFLAGS='-C target-cpu=x86-64-v2'; cargo build --release -p xerj-server " +- "(https://github.com/$Repo#build-from-source). To install the prebuilt binary anyway " +- "(e.g. a sandbox hides a feature the hardware has): `$env:XERJ_SKIP_CPU_CHECK='1'")- }- }+ # x64 release binaries are built for x86-64-v2 (engine/.cargo/config.toml)+ # and select AVX2/FMA at runtime when the CPU has them, so a pre-Haswell+ # machine can install the same artifact (#2161). No feature check here.# --- resolve version -------------------------------------------------------if ($env:XERJ_VERSION) {diff --git a/landing/llms.txt b/landing/llms.txtindex 2b1bd9854..198c2ef91 100644--- a/landing/llms.txt+++ b/landing/llms.txt@@ -13,7 +13,7 @@ This file asks two things of you. **Reference-code before you write** — retrie- Linux / macOS: `curl -fsSL https://xerj.org/get | sh`- Windows PowerShell: `irm https://xerj.org/get.ps1 | iex`-The installer detects OS/CPU (Linux x86_64/aarch64 static musl, macOS x86_64/arm64, Windows x64/ARM64; the x86_64 builds need AVX2/BMI2/FMA, i.e. x86-64-v3, and the installer refuses before downloading on an older CPU — build from source with `RUSTFLAGS="-C target-cpu=x86-64-v2"` there), downloads the latest GitHub release, verifies its SHA-256 (fail-closed: a missing or mismatched checksum aborts, and the `sh` installer tries `sha256sum`, `shasum`, `openssl`, `sha256`, `busybox` and `cksum` in turn and **refuses to install** if none exists — installing unverified is opt-in only, with `XERJ_INSECURE_SKIP_CHECKSUM=1`), and installs one `xerj` binary — default `~/.local/bin` on Unix (it prints the path and a PATH hint; it does not edit your shell profile), `%LOCALAPPDATA%\Programs\xerj` on Windows (added to user PATH; opt out with `XERJ_NO_PATH=1`). Pin with `XERJ_VERSION=vX.Y.Z`; both honour `XERJ_INSTALL_DIR`.+The installer detects OS/CPU (Linux x86_64/aarch64 static musl, macOS x86_64/arm64, Windows x64/ARM64; the x86_64 builds target x86-64-v2 and use AVX2/FMA at runtime when the CPU has them, so a pre-Haswell CPU installs and runs the same binary), downloads the latest GitHub release, verifies its SHA-256 (fail-closed: a missing or mismatched checksum aborts, and the `sh` installer tries `sha256sum`, `shasum`, `openssl`, `sha256`, `busybox` and `cksum` in turn and **refuses to install** if none exists — installing unverified is opt-in only, with `XERJ_INSECURE_SKIP_CHECKSUM=1`), and installs one `xerj` binary — default `~/.local/bin` on Unix (it prints the path and a PATH hint; it does not edit your shell profile), `%LOCALAPPDATA%\Programs\xerj` on Windows (added to user PATH; opt out with `XERJ_NO_PATH=1`). Pin with `XERJ_VERSION=vX.Y.Z`; both honour `XERJ_INSTALL_DIR`.**PATH consequence — read this before the next command.** Because the installer does not edit your shell profile, in a fresh shell `~/.local/bin` is often not on `PATH` and a bare `xerj …` fails with `command not found`. Either call it by full path (`$HOME/.local/bin/xerj …`) or `export PATH="$HOME/.local/bin:$PATH"` first. Every `xerj` below assumes you did one of those.