From 917cb26186725720ac49c75df0893bf8a4205bef Mon Sep 17 00:00:00 2001 From: Eric Coissac Date: Tue, 1 Dec 2026 16:58:07 +0100 Subject: [PATCH] refactor: rename project from obikmer to obiskim Update the project name, binary, and all associated documentation, scripts, and configuration files from `obikmer` to `obiskim`. This change ensures consistency across the codebase, including lock files, VCF outputs, benchmark targets, and user-facing documentation. - Update `mkdocs.yml` and `.crate-kit/VERSION` to reflect the new project name and version 0.3.4. - Rename all references in `DevDocMD/` documentation, including architecture, implementation, and theory sections, from `obikmer` to `obiskim`. - Update `UserDocMD/` files to use `.obiskim.lock` and `.obiskim.gate` for lock files, and update VCF contig IDs to `obiskim__`. - Modify `benchmark/` scripts and Makefiles to use `obiskim` binary names and `obiskim_dist/` directories for distribution and comparison tasks. - Update `prompts/` files to reference the `obiskim` repository and commands instead of `obikmer`. - Rename temporary directories in `scripts/` smoke tests from `obikmer_*` to `obiskim_*`. - Update `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` to use `obiskim` in VCF source identifiers and assertions. - Update `src/obiskim/Cargo.toml` version to 1.4.9 and update `src/obiskim/src/cmd/phylo/args/outputs.rs` documentation. - Update `src/obisys/src/lock.rs` to use `.obiskim.lock`, `.obiskim.gate`, and `.obiskim.promote` file names. --- .crate-kit/VERSION | 2 +- .../architecture/hot_resume_memoization.md | 2 +- DevDocMD/architecture/query.md | 28 +++++----- DevDocMD/architecture/query.refs.md | 2 +- DevDocMD/architecture/siblings.md | 2 +- .../implementation/benchmark_query_testing.md | 8 +-- .../evidence_elimination.refs.md | 6 +-- DevDocMD/implementation/filtering.md | 22 ++++---- DevDocMD/implementation/merge.md | 6 +-- DevDocMD/implementation/merge_parallelism.md | 4 +- DevDocMD/implementation/merge_scaling.md | 2 +- DevDocMD/implementation/mphf_batch_queries.md | 10 ++-- DevDocMD/implementation/obipipeline.md | 2 +- .../implementation/partition_layer_cache.md | 34 ++++++------ DevDocMD/implementation/pipeline.md | 4 +- DevDocMD/implementation/select.md | 14 ++--- DevDocMD/index.md | 4 +- DevDocMD/index.refs.md | 4 +- DevDocMD/installation.md | 12 ++--- DevDocMD/theory/entropy.refs.md | 2 +- DevDocMD/theory/evolutionary_distances.md | 52 +++++++++---------- DevDocMD/theory/indexing.refs.md | 2 +- .../theory/sibling_partition_unification.md | 2 +- ReleaseNotes/version-1.4.9.md | 27 ++++++++++ UserDocMD/formats/index_layout.md | 4 +- UserDocMD/formats/vcf.md | 14 ++--- benchmark/Makefile | 34 ++++++------ benchmark/README.md | 4 +- benchmark/compare_all_dist.py | 28 +++++----- benchmark/simulate_one.sh | 2 +- benchmark/simulate_query_one.sh | 2 +- benchmark/simulate_skim.sh | 2 +- benchmark/verify_count.py | 8 +-- benchmark/verify_merge_count.py | 8 +-- benchmark/verify_merge_presence.py | 8 +-- benchmark/verify_presence.py | 8 +-- mkdocs.yml | 2 +- prompts/merge_mmap_refactor.md | 10 ++-- prompts/obi-migration.md | 14 ++--- prompts/pack_optimization.md | 4 +- scripts/merge_report.py | 4 +- scripts/pseudo_alignment_nesting.py | 2 +- scripts/smoke_test_index.sh | 2 +- scripts/smoke_test_merge.sh | 2 +- .../src/siblings/algorithms/alignment_vcf.rs | 14 ++--- src/obiskim/Cargo.toml | 2 +- src/obiskim/src/cmd/phylo/args/outputs.rs | 2 +- src/obisys/src/lock.rs | 12 ++--- 48 files changed, 236 insertions(+), 209 deletions(-) create mode 100644 ReleaseNotes/version-1.4.9.md diff --git a/.crate-kit/VERSION b/.crate-kit/VERSION index ccd34e0b..89624c20 100644 --- a/.crate-kit/VERSION +++ b/.crate-kit/VERSION @@ -1 +1 @@ -0.3.3+0.1.1 +0.3.4+0.1.1 diff --git a/DevDocMD/architecture/hot_resume_memoization.md b/DevDocMD/architecture/hot_resume_memoization.md index d737c1a9..75c27613 100644 --- a/DevDocMD/architecture/hot_resume_memoization.md +++ b/DevDocMD/architecture/hot_resume_memoization.md @@ -37,7 +37,7 @@ Reproduced on the 1x testbed (20 genomes, 512 layers): derived annexes deleted, **Not covered.** The builders outside that path still write at their final name: `PersistentCompactIntVecBuilder`, the int/sparse matrix builders, `EliasFanoBuilder`, `TempBitVecBuilder`/`TempCompactIntVecBuilder` (temporary by nature) and the index-construction files that use them. The same reasoning applies to them as soon as a stage built on them has to be resumed; not audited. The in-memory overlap accumulator is still lost on a kill (a sweep restarts), now without leaving a corrupt file. -**`obiksession` crate** (`src/obiksession/`): `Session` (named directory, opaque parameter blob checked on open, whole-lifetime `DirLock`, artifacts checksummed with xxh3 and mmap-restored) and `Memoize` (`get_or_compute[_with_key]`, `invalidate`, `cached_keys`, `MemoKey` from `Debug` + xxh3, the `session_memoize!` macro). Compiles, 15 tests pass, **no caller**: `obikmer` lists the dependency without using it. `phylo --session` exits with an error (`cmd/phylo/mod.rs:271`) since `session_cache.rs` (the consumer tied to `PairwiseTally`/`PartitionDispersion`/`SnpAlignment`) was removed. `sample_index(skip_layers)` remains as a seam, never called with a non-zero value. +**`obiksession` crate** (`src/obiksession/`): `Session` (named directory, opaque parameter blob checked on open, whole-lifetime `DirLock`, artifacts checksummed with xxh3 and mmap-restored) and `Memoize` (`get_or_compute[_with_key]`, `invalidate`, `cached_keys`, `MemoKey` from `Debug` + xxh3, the `session_memoize!` macro). Compiles, 15 tests pass, **no caller**: `obiskim` lists the dependency without using it. `phylo --session` exits with an error (`cmd/phylo/mod.rs:271`) since `session_cache.rs` (the consumer tied to `PairwiseTally`/`PartitionDispersion`/`SnpAlignment`) was removed. `sample_index(skip_layers)` remains as a seam, never called with a non-zero value. **Previous design and why it missed the goal** (`theory/evolutionary_distances.md`, section "Explicit `--session`"): one session per *exact* parameter tuple (changing `--n-sites` made another session), artifacts specific to the sampling result, resume only inside the draw (checkpoint every 8 layers or 30 s). Reuse across commands existed only for the sample. An exhaustive-sample cache from which smaller samples would be drawn was proposed and never done. User judgement: this version did not answer the objective. diff --git a/DevDocMD/architecture/query.md b/DevDocMD/architecture/query.md index b7b73ff6..1f50a59c 100644 --- a/DevDocMD/architecture/query.md +++ b/DevDocMD/architecture/query.md @@ -203,7 +203,7 @@ Genome keys follow the iteration order of `meta.genomes`. ## CLI ``` -obikmer query [--detail] [--mismatch] [--count-missing] +obiskim query [--detail] [--mismatch] [--count-missing] [--force-presence] [--presence-threshold ] [-z ] [-T ] [--chunk-size ] [ ...] @@ -259,7 +259,7 @@ replacing the `CanonicalKmer` key by the resolved `slot` (compact integer, and e **7. Partition-level parallelism is currently absent — and a NUMA-aware mechanism for exactly this already exists, unused, in `obikindex`.** `process_chunk`'s partition loop (`query.rs:250-278`, `for (part_idx, part_sks) in by_part.iter().enumerate()`) processes every partition of a chunk sequentially on the single worker thread that owns that chunk. This is a parallelism axis on its own, independent of the column question below. More importantly: `docmd/architecture/numa_partition_runner.md` and `numa_worker_pools.md` document `PartitionRunner` (`obikindex/src/numa.rs`), **already implemented** and already used by `merge.rs`, `index.rs` (`build_layers`), `select.rs`, `reindex.rs`, `rebuild.rs` — one controller thread per NUMA node, a Rayon pool pinned to that node's CPUs (`hwlocality`, `numa` feature, default-on in `obikindex/Cargo.toml`), adaptive worker activation driven by *both* a CPU-efficiency signal and an I/O-throughput signal (`CpuSample`/`IoSample`, `/proc/self/io` on Linux). It exists precisely because a naive `into_par_iter()` on the global Rayon pool measurably degrades ×60 on this codebase's own 192-core/8-NUMA reference machine (`numa_worker_pools.md`, § Problem) once workers contend for cross-socket memory bandwidth on shared mmap'd/hashed structures — exactly the shape of the matrix-column scan in point 8 below. -`obikmer` already depends on `obikindex` (`obikmer/Cargo.toml`, for `KmerIndex`), so `PartitionRunner` is directly reachable from `cmd/query.rs` — no new dependency. Both the partition-level loop and (see point 8) the genome-column scan should be driven through it rather than through ad-hoc `rayon::into_par_iter()`, to avoid reproducing the already-measured-and-fixed contention problem. Also relevant: the "CPU-only signal stalls on I/O-bound stages" issue documented for `pack_matrices` (mmap-heavy, page-fault-bound) applies just as much to a column-major mmap scan over persistent matrices — reuse the existing dual CPU/IO activation signal rather than re-deriving one. +`obiskim` already depends on `obikindex` (`obiskim/Cargo.toml`, for `KmerIndex`), so `PartitionRunner` is directly reachable from `cmd/query.rs` — no new dependency. Both the partition-level loop and (see point 8) the genome-column scan should be driven through it rather than through ad-hoc `rayon::into_par_iter()`, to avoid reproducing the already-measured-and-fixed contention problem. Also relevant: the "CPU-only signal stalls on I/O-bound stages" issue documented for `pack_matrices` (mmap-heavy, page-fault-bound) applies just as much to a column-major mmap scan over persistent matrices — reuse the existing dual CPU/IO activation signal rather than re-deriving one. > > **Correction from implementation (Phase 4 below)**: this turned out not to be viable as described. `PartitionRunner::run()`'s actual body spawns roughly one OS thread per worker slot across every NUMA node **on every call** (confirmed by reading `numa.rs`, not just its doc comments) — fine for the one-call-per-command-invocation batch usage in `merge`/`build_layers`, but `query_partition_with` runs once per `(chunk, partition)`, far too frequently to absorb that spawn cost. Partition-level parallelism via `PartitionRunner` is deferred, not implemented. See Phase 4's "What did not ship, and why" for the detail. @@ -285,7 +285,7 @@ None of this is implemented yet — parked here as a coherent roadmap while the ## Implementation plan -Concrete, phased translation of the roadmap above. Phases 0–2 are small, independent, low-risk, and each individually testable against current `query` output — land them first, in order, and measure on the reference 192-core/8-NUMA machine before deciding whether phases 3–5 (the staged/sparse engine, the larger structural payoff) are still worth their cost. Phases 3–5 are one coordinated change spanning `obikmer`, `obikindex::partition`, and `obicompactvec` — they should not be split across releases mid-way, because the intermediate state (e.g. k-mer-level dedup feeding the old dense `KmerResults`) has no correctness or performance benefit on its own. Phase 6 is unrelated to phases 0–5 and can happen any time, independently, if `rapidgzip-rs` is validated (see [chunkreader.md](../implementation/chunkreader.md#future-work--parallel-gzip-decompression-in-xopen)). +Concrete, phased translation of the roadmap above. Phases 0–2 are small, independent, low-risk, and each individually testable against current `query` output — land them first, in order, and measure on the reference 192-core/8-NUMA machine before deciding whether phases 3–5 (the staged/sparse engine, the larger structural payoff) are still worth their cost. Phases 3–5 are one coordinated change spanning `obiskim`, `obikindex::partition`, and `obicompactvec` — they should not be split across releases mid-way, because the intermediate state (e.g. k-mer-level dedup feeding the old dense `KmerResults`) has no correctness or performance benefit on its own. Phase 6 is unrelated to phases 0–5 and can happen any time, independently, if `rapidgzip-rs` is validated (see [chunkreader.md](../implementation/chunkreader.md#future-work--parallel-gzip-decompression-in-xopen)). Instrumentation is deliberately sequenced *before* the I/O fix (reordering the roadmap's own listed order), because every later phase's justification rests on a measurement ("to be measured, not assumed" appears throughout the roadmap above) — without it, phases 3–5 would be undertaken on faith. @@ -295,7 +295,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the **Debug logging.** Every phase that changes an algorithmic choice (not phase 0, which *is* the logging) adds `tracing::debug!`/`trace!` at points that let a cluster run's logs answer "did this help": counts, ratios, and timings that quantify the specific claim that phase makes — e.g. phase 3 must log how many MPHF `find` calls were saved by k-mer-level dedup (the whole justification for that phase), phase 4 must log per-column scan timings, phase 5 must log actual retained-memory / sparsity ratios achieved. Prefer one structured `debug!` per chunk (fields, not prose) over free-text — the cluster logs will be the only evidence available for judging these choices, so they need to be grep/awk-able, not just readable. -**Unit tests.** This project's convention (`obiread`, `obikseq`, `obidebruinj`, `obicompactvec`, `obikindex::layer`, `obiskio`, `obifastwrite`) is `#[cfg(test)] #[path = "tests/.rs"] mod tests;` at the bottom of the source file, with the actual test code in a sibling `src/tests/.rs`. Neither `obikmer` nor `obikindex::partition` (the two crates phases 3 and 5 touch most) currently have a `src/tests/` directory at all — this needs creating, following the existing pattern exactly, not inventing a new one. +**Unit tests.** This project's convention (`obiread`, `obikseq`, `obidebruinj`, `obicompactvec`, `obikindex::layer`, `obiskio`, `obifastwrite`) is `#[cfg(test)] #[path = "tests/.rs"] mod tests;` at the bottom of the source file, with the actual test code in a sibling `src/tests/.rs`. Neither `obiskim` nor `obikindex::partition` (the two crates phases 3 and 5 touch most) currently have a `src/tests/` directory at all — this needs creating, following the existing pattern exactly, not inventing a new one. **Workflow (`jj`).** Work happens in a fresh `jj` commit, easy to abandon. `jj new` between phases is reasonable where it helps isolate a phase for review, but only when the working copy compiles at that point (project convention) — phase 3's internal sub-steps (batch dedup change, then `query_layer.rs` split, then the new return shape) will likely not each compile independently since they're one coupled change, so treat "commit boundary" and "plan phase boundary" as related but not forced to match 1:1; use judgement per phase rather than mechanically splitting on every bullet. @@ -303,9 +303,9 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the **Goal**: make core utilization, throughput, and per-stage timing visible on a real run, so phases 1–5 can be justified with numbers instead of assumption. -- `obikmer/src/cmd/query.rs`: wrap `run()`'s main loop with `obisys::Reporter`/`Stage::start("query")`/`.stop()`, printed at the end via `rep.print()` — same pattern as `index.rs`/`filter.rs`. +- `obiskim/src/cmd/query.rs`: wrap `run()`'s main loop with `obisys::Reporter`/`Stage::start("query")`/`.stop()`, printed at the end via `rep.print()` — same pattern as `index.rs`/`filter.rs`. - Add an `obisys::spinner("query")` progress bar around the `pipe.apply(...)` loop, with an EMA throughput readout (bases/s or k-mers/s, mirroring `steps::scatter`'s `ema_rate` computation, `scatter.rs:88-118`) and live gauges for "chunks in flight" / "workers busy" — reuse the `AtomicU32` counter pattern from `scatter.rs` (`flat_active`, `transform_active`) rather than inventing a new one. -- Add `max_open_files: Option` to `QueryArgs` and a `effective_max_open()` method mirroring `CommonArgs::effective_max_open()` (`obikmer/src/cli.rs:90-94`) — needed by phase 1's `throttle()` call. (`QueryArgs` can't just embed `CommonArgs` — it doesn't take `kmer_size`/`minimizer_size`/`partitions`/`level_max`/`theta` from the CLI, those come from the index metadata — so this is a small standalone addition, not a flatten.) +- Add `max_open_files: Option` to `QueryArgs` and a `effective_max_open()` method mirroring `CommonArgs::effective_max_open()` (`obiskim/src/cli.rs:90-94`) — needed by phase 1's `throttle()` call. (`QueryArgs` can't just embed `CommonArgs` — it doesn't take `kmer_size`/`minimizer_size`/`partitions`/`level_max`/`theta` from the CLI, those come from the index metadata — so this is a small standalone addition, not a flatten.) - Add one structured `debug!` per `process_chunk` call: chunk byte size, sequence count, s-mer count, wall time, and (once later phases exist) the fields they add — this single log line is the baseline every later phase's own logging gets compared against. - **Validation**: none needed beyond "the numbers appear and look sane" — this phase changes no query logic or output. - **Deliverable used by every phase below**: a before/after throughput and core-utilization measurement on the reference machine. @@ -314,7 +314,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the **Goal**: file opening, decompression, and chunk-boundary parsing run across the `n_workers` pool instead of serially in the pipe's dedicated source thread. -- `obikmer/src/cmd/query.rs`: +- `obiskim/src/cmd/query.rs`: - Replace the `paths.into_iter().flat_map(read_sequence_chunks_sized(...))` construction (current `run()`, building `all_chunks`) with `obipipeline::throttle(paths.into_iter(), args.effective_max_open())`, passed as the pipe's `input`. - Add a new `QueryData::Path(PathBuf)` variant (alongside `Chunk`/`Output`) to carry the throttled path through the pipe's type-erasure mechanism. - Add a new **first** pipe stage, `Flat`/fallible (`||?`), modeled on `scatter.rs:60-86` and `superkmer.rs:54-65`: given a `Throttled`, call `read_sequence_chunks_sized(path, chunk_bytes)` and yield each `Rope` chunk, keeping `pw.guard` alive until the file's iterator is exhausted (reuse or adapt `scatter.rs`'s `GuardedIter` wrapper — same lifetime problem, same fix). @@ -328,7 +328,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the **Goal**: `chunk_bytes` reflects actual per-chunk memory (`O(n_genomes)`), not a fixed multiplier. -- `obikmer/src/cmd/query.rs`, `run()`: `n_genomes` and `args.detail` are already computed above the `chunk_bytes` calculation (`n_genomes` at the top of `run()`, before line 407 in the current file) — reorder if needed, then replace: +- `obiskim/src/cmd/query.rs`, `run()`: `n_genomes` and `args.detail` are already computed above the `chunk_bytes` calculation (`n_genomes` at the top of `run()`, before line 407 in the current file) — reorder if needed, then replace: ```rust let computed = avail / (n_workers as u64 * 16); ``` @@ -342,7 +342,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the **Goal**: replace superkmer-level dedup with k-mer-level dedup (roadmap point 5), and split the fused MPHF-find/matrix-fetch (point 4) so stage 1's output is bucketed by layer and MPHF slot (point 6). -- `obikmer/src/cmd/query.rs`: +- `obiskim/src/cmd/query.rs`: - Replace `QueryBatch::from_records`'s dedup map (`HashMap>`, current `query.rs:112`) with a per-partition `HashMap>`, built in the same `SuperKmerIter` pass: superkmer construction and partition routing (`part_idx` from the superkmer's minimizer hash) are unchanged, only the granularity of what gets deduplicated changes — each `CanonicalKmer` within a superkmer is inserted individually instead of the whole superkmer being the dedup key. - **Verified**: `CanonicalKmer` (`obikseq/src/kmer.rs:390`, `pub type CanonicalKmer = CanonicalKmerOf`) — the underlying `CanonicalKmerOf` derives `Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash` (`kmer.rs:269`). Usable as a `HashMap`/`HashSet` key as-is, no change needed. - `obikindex/src/partition/query_layer.rs`: @@ -351,7 +351,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the - New return shape for the partition-level query, replacing today's `on_hit(sk_idx, kmer_idx, row)` callback: `HashMap>>` (roadmap point 6) — built directly from the k-mer dedup map's `Vec<(seq_idx,pos)>` values, keyed by the resolved slot instead of the k-mer. - **This phase alone has no throughput benefit yet** (matrix fetch still happens, just deferred) beyond the k-mer-level dedup itself (fewer MPHF calls when queries have overlapping/repeated k-mers) — its purpose is to produce the input phase 4 needs. Land phase 3+4 together, not phase 3 alone, per the "don't split 3–5 across releases" note above. - Log, per chunk: total k-mer occurrences vs. unique `CanonicalKmer` count (the dedup ratio — the entire justification for this phase) and the resulting MPHF `find` call count. If the dedup ratio is close to `1.0` on real query data (little redundancy), that's the cluster run telling us this phase wasn't worth it — the logging needs to be able to say that, not just confirm the happy path. -- **Unit tests**: create `obikmer/src/cmd/tests/query.rs` (new `src/tests/` dir for this crate, following the project's `#[cfg(test)] #[path = "tests/query.rs"] mod tests;` convention) and `obikindex/src/partition/tests/query_layer.rs` (likewise new for this crate). Cover: the k-mer-level dedup map construction on synthetic sequences with known repeated/overlapping k-mers (assert unique-kmer count and occurrence lists); the `find_slot`/bucket-by-layer-and-slot construction against a small hand-built `QueryLayer` fixture, asserting the `(layer_idx, slot, seq_idx, pos)` tuples match what the old per-occurrence loop would have produced. +- **Unit tests**: create `obiskim/src/cmd/tests/query.rs` (new `src/tests/` dir for this crate, following the project's `#[cfg(test)] #[path = "tests/query.rs"] mod tests;` convention) and `obikindex/src/partition/tests/query_layer.rs` (likewise new for this crate). Cover: the k-mer-level dedup map construction on synthetic sequences with known repeated/overlapping k-mers (assert unique-kmer count and occurrence lists); the `find_slot`/bucket-by-layer-and-slot construction against a small hand-built `QueryLayer` fixture, asserting the `(layer_idx, slot, seq_idx, pos)` tuples match what the old per-occurrence loop would have produced. ### Phase 4 — Column-major matrix fetch (roadmap points 7–8) — implemented, NUMA parallelism deferred @@ -360,7 +360,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the **What shipped:** - `obicompactvec`: the per-column accessors this phase needed **already existed** — `PersistentCompactIntMatrix::col_view(c)` and `PersistentBitMatrix::col_view(c)` are public, and `IntSliceView::get(slot)`/`BitSliceView::get(slot)` are public — the original plan underestimated how much of this plumbing the pairwise-distance code (`dump`/`select`/`stats`) had already required. The one real gap: `PersistentBitMatrix::col_view()` panics on the `Implicit` variant (the documented mono-genome fast path, `bitmatrix.rs`). Added `PersistentBitMatrix::get(c, slot) -> u32` (`bitmatrix.rs`), a non-panicking column-major point lookup that returns `1` for `Implicit` regardless of `c` — the smallest surface needed, not a new `col_get` API from scratch. - `obikindex/src/partition/query_layer.rs`: `query_partition_with` is now two explicit stages, matching roadmap points 6–8: **stage 1** (MPHF-only, per unique k-mer, bucket hits by `(layer_idx, slot)`, emits `QueryHit::Found`) then **stage 2** (per layer with ≥1 hit, column-major: for each genome column `g` in `0..layer.n_cols().min(n_genomes)`, scan that layer's bucketed slots and call `col_value(g, slot)`, emitting `QueryHit::Value(descs, g, value)` on nonzero). `QueryHit` is a single enum delivered through one `FnMut(QueryHit)` callback — an earlier two-closure design (`on_found` + `on_value`) didn't borrow-check, since the caller's single mutable accumulator (`KmerResults`) can't be captured by two separate `FnMut` closures passed to the same call. -- `obikmer/src/cmd/query.rs`: `KmerResults::set` (row-major, whole-row-at-once) replaced by `mark_found` (stage 1: flag a position as indexed, independent of any genome's value) and `set_one` (stage 2: write one genome's value at one position). `QueryStats` extended with `n_columns_scanned`/`n_col_get_calls`, logged per chunk. +- `obiskim/src/cmd/query.rs`: `KmerResults::set` (row-major, whole-row-at-once) replaced by `mark_found` (stage 1: flag a position as indexed, independent of any genome's value) and `set_one` (stage 2: write one genome's value at one position). `QueryStats` extended with `n_columns_scanned`/`n_col_get_calls`, logged per chunk. - Total `get()`-equivalent calls are unchanged from the row-major version (`n_hits × n_cols` in the worst case, confirmed by `n_col_get_calls` in the debug log) — the win is locality (sequential access within one layer's column at a time, across `mmap`'d regions, instead of jumping across all columns per hit), exactly as predicted. **What did not ship, and why — `PartitionRunner` is architecturally the wrong tool here:** @@ -375,14 +375,14 @@ The column-major loop in stage 2 is therefore a **plain sequential loop** for no **Goal**: replace the dense `KmerResults`/`win_min` sliding-window scan with one operating on phase 4's sparse per-genome output. -- `obikmer/src/cmd/query.rs`, `process_chunk`: +- `obiskim/src/cmd/query.rs`, `process_chunk`: - Remove `KmerResults` (`query.rs:157-202`) and the dense `win_min` allocation (`query.rs:290-291`, sized `max_n_kmers × n_genomes`). - Keep a lightweight dense `in_index: Vec` per chunk (sized `total_kmers`, independent of `n_genomes`) from phase 3's stage 1 — still needed for `kmer_missing` bookkeeping (leftmost-s-mer-of-window membership test), which phase 4's sparse structure doesn't carry (a k-mer with no genome hit has no entry there at all). - New per-`(seq_idx, genome)` scan: for each genome's `Vec<(seq_idx, pos, count)>` (sorted, per phase 4), group by `seq_idx` (contiguous after sort), then within each sequence's positions detect runs of `pos, pos+1, pos+2, ...` of length ≥ `z`; within each run, the existing monotone-deque window-minimum logic (`query.rs`'s current `dq` loop, conceptually unchanged) applies — but the deque now only scans real entries in the run, never zero-filled gaps. - Update `SeqAcc` accumulation and `emit_batch` to consume this per-genome sparse iteration instead of `results.val`/`results.is_in_index`. - `--detail`/`cov`: build sparsely during the same scan (only positions with a confirmed contribution get an entry), densify into the `[u32]` JSON array only in `emit_batch`, only for genomes/sequences actually being serialized (per roadmap point 9's note, `query.rs:304-308`'s current dense allocation goes away). - Log, per chunk: total sparse entries retained vs. what the old dense `KmerResults` would have allocated (`total_smers × n_genomes`) — the sparsity ratio is this phase's entire reason for existing, so it must be directly visible in the logs, not inferred from process RSS. Also log the run-detection stats (number of runs found, average run length) — a low average run length relative to `z` would mean most positions still fail to form a full window, worth knowing. -- **Unit tests**: `obikmer/src/cmd/tests/query.rs` (extended from phase 3) — the property test described below is the primary deliverable here, not an afterthought; write it as an actual `#[test]` (or a small internal fuzz/property-style loop over randomized fixtures if a property-testing crate isn't already a dependency — check before adding one, per this project's dependency-approval rule) rather than a one-off manual comparison. +- **Unit tests**: `obiskim/src/cmd/tests/query.rs` (extended from phase 3) — the property test described below is the primary deliverable here, not an afterthought; write it as an actual `#[test]` (or a small internal fuzz/property-style loop over randomized fixtures if a property-testing crate isn't already a dependency — check before adding one, per this project's dependency-approval rule) rather than a one-off manual comparison. - **Validation — this is the correctness-critical phase**: property-test comparing old (dense, pre-phase-3) and new (sparse) implementations on the same randomized input/index fixtures, asserting identical `kmer_count`, `kmer_missing`, `kmer_strict_matches`, and (with `--detail`) `coverage` for every sequence. Keep both implementations compiled side by side (behind a debug-only flag or a temporary parallel code path) only for the duration of this validation; delete the dense path once parity is confirmed — per this project's own convention, superseded code is not kept "just in case." - **Update `docmd/architecture/query.md` itself**: once this phase lands, the "Findere z-window filter" section (which currently — correctly — describes the dense deque-over-`0..n_smers` scan) needs another pass to describe the sparse run-detection algorithm instead, as already flagged when this phase was discussed. @@ -391,7 +391,7 @@ The column-major loop in stage 2 is therefore a **plain sequential loop** for no - New `sparse_findere_for_genome(hits, z, presence, threshold) -> (Vec, n_runs, total_run_len)` (`query.rs`): sorts one genome's raw hits by `(seq_idx, pos)`, detects maximal runs of consecutive `pos` within one sequence, runs the same monotone-deque window-minimum as before but scoped to each run (run-relative indices for eviction, absolute `pos` for computing `pos_out`). Presence/count adjustment (`u32::from(win_min >= threshold)` vs. raw) is applied inside this function, once per confirmed hit, rather than later during accumulation. - `process_chunk` restructured into three passes after the partition loop: (1) run `sparse_findere_for_genome` per genome, collecting `confirmed_by_genome` and run-detection stats; (2) accumulate `genome_totals` directly from `confirmed_by_genome` and mark a `confirmed_any: Vec` (sized `total_kmers_out`, not `× n_genomes`); (3) a position-only pass (`O(total_kmers_out)`, no genome factor) computing `kmer_count`/`kmer_missing` from `confirmed_any` + `SmerIndex`. `cov` (`--detail`) is populated by re-scanning `confirmed_by_genome` — only when `--detail` is actually set, otherwise skipped entirely. - Debug log added (`"sparse Findere"`): `n_dense_would_be` (`n_occurrences × n_genomes` — what the deleted dense path would have allocated), `n_sparse_entries` (what's actually retained), `n_runs`/`avg_run_len` (per the plan's ask, to see whether hits mostly fail to form complete windows). -- **Unit tests**: `sparse_findere_matches_dense_reference_on_random_inputs` (`obikmer/src/cmd/tests/query.rs`) — 200 randomized cases (sequence count/length, `z`, presence/count mode, threshold, hit density from sparse to fully-dense) comparing `sparse_findere_for_genome` against `dense_reference_findere`, a faithful reimplementation of the deleted dense algorithm kept only as a test-local correctness oracle (no property-testing crate added — checked first, none was a workspace dependency; a small `std`-only xorshift64 PRNG stands in for one, deterministic and dependency-free). All 200 cases pass. +- **Unit tests**: `sparse_findere_matches_dense_reference_on_random_inputs` (`obiskim/src/cmd/tests/query.rs`) — 200 randomized cases (sequence count/length, `z`, presence/count mode, threshold, hit density from sparse to fully-dense) comparing `sparse_findere_for_genome` against `dense_reference_findere`, a faithful reimplementation of the deleted dense algorithm kept only as a test-local correctness oracle (no property-testing crate added — checked first, none was a workspace dependency; a small `std`-only xorshift64 PRNG stands in for one, deterministic and dependency-free). All 200 cases pass. - **Functional validation performed**: full workspace build + `cargo test --workspace`, zero failures. End-to-end against real indexes: baseline output (no flags) unchanged from pre-phase-5 recorded values on the same fixtures; `--count-missing` correct (`kmer_missing: 0` on a self-match); `--detail` correct — coverage array length matches `kmer_count`, and critically, re-ran the two-genome cross-contamination check from phase 4 with `--detail --count-missing`: `genomeA` reads show coverage sum `106` for `genomeA` and `0` for `genomeB` (and vice versa) — confirms the sparse-to-dense `cov` reconstruction doesn't leak across genomes either, not just the scalar `kmer_strict_matches` path. - This phase's roadmap item ("update the Findere z-window filter section") — done, see above; the "Algorithm" section's pseudocode was also updated, since it still named `KmerResults`/`SKDesc` from before phases 3–4. diff --git a/DevDocMD/architecture/query.refs.md b/DevDocMD/architecture/query.refs.md index d281c78c..bc386547 100644 --- a/DevDocMD/architecture/query.refs.md +++ b/DevDocMD/architecture/query.refs.md @@ -3,7 +3,7 @@ ## Code couvert -- `obikmer/src/cmd/query.rs` — commande query, format de sortie +- `obiskim/src/cmd/query.rs` — commande query, format de sortie - `obikindex/src/partition/query_layer.rs` — routage de la requête à travers les partitions - `obiread/src/lib.rs` — lecture des séquences d'entrée pour la requête diff --git a/DevDocMD/architecture/siblings.md b/DevDocMD/architecture/siblings.md index a9e32377..1456cd5d 100644 --- a/DevDocMD/architecture/siblings.md +++ b/DevDocMD/architecture/siblings.md @@ -140,7 +140,7 @@ operations with no cross-invocation sharing concern: `build_sibling_annex`, `shannon_entropy_csv`, `sibling_family_size_histogram`/`sibling_annex_stats`, `family_overlap`. The sampled SNP path (`sampled_scan`, `AlignmentReducer`, `PairwiseReducer`, `distance_matrix`, `SankoffBundle`) is **not** wrapped in -trait methods — the CLI (`obikmer::cmd::phylo`) composes them directly, +trait methods — the CLI (`obiskim::cmd::phylo`) composes them directly, because it alone knows the union of reducers a given invocation needs (`--pseudo-alignment`/Sankoff group/`snp-*` `--distance` can combine in one call). A per-output trait method would have to either duplicate that diff --git a/DevDocMD/implementation/benchmark_query_testing.md b/DevDocMD/implementation/benchmark_query_testing.md index cb9c358c..308952bc 100644 --- a/DevDocMD/implementation/benchmark_query_testing.md +++ b/DevDocMD/implementation/benchmark_query_testing.md @@ -2,8 +2,8 @@ `benchmark/Makefile` exercises indexing, merge, and phylo distance reconstruction against simulated bacterial genomes. It now also covers -`obikmer query` — the read-matching path — and the sparse packed -presence-matrix format (`obikmer pack --sparse`), previously untested by +`obiskim query` — the read-matching path — and the sparse packed +presence-matrix format (`obiskim pack --sparse`), previously untested by this pipeline. ## Motivation @@ -42,7 +42,7 @@ without duplicating the exhaustive per-specimen coverage ## Sparse global index `global_index_presence_sparse/` is built by `pack_sparse.sh`: copy -`global_index_presence/` wholesale, then `obikmer pack --sparse` in place. +`global_index_presence/` wholesale, then `obiskim pack --sparse` in place. This works directly because `merge`'s pack stage (`merge.rs:252`, `pack_matrices(false)`) keeps the per-genome column files on disk after dense-packing — `pack_sparse_bit_matrix` (`obicompactvec/src/bitmatrix/sparse.rs:447`) @@ -52,7 +52,7 @@ afterward. No separate merge run needed. ## Query runs -`query_one.sh dense|sparse SPECIMEN` runs `obikmer query --count-missing` +`query_one.sh dense|sparse SPECIMEN` runs `obiskim query --count-missing` against `global_index_presence` or `global_index_presence_sparse`, output gzipped to `query_{dense,sparse}/SPECIMEN.fasta.gz`, Reporter wall/RSS captured to `stats/query_{dense,sparse}/SPECIMEN.stats` (same diff --git a/DevDocMD/implementation/evidence_elimination.refs.md b/DevDocMD/implementation/evidence_elimination.refs.md index b5a17e28..fc8d2378 100644 --- a/DevDocMD/implementation/evidence_elimination.refs.md +++ b/DevDocMD/implementation/evidence_elimination.refs.md @@ -7,9 +7,9 @@ - `obikindex/src/layer/mphf_layer.rs` — build_approx_evidence(dir, b, z), find_approx() - `obikindex/src/layer/meta.rs` — EvidenceKind::Approx { b, z }, LayerMeta - `obikindex/src/reindex.rs` — KmerIndex::reindex(), conversion exact↔approx en place -- `obikmer/src/cmd/reindex.rs` — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size -- `obikmer/src/cmd/index.rs` — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp -- `obikmer/src/cmd/estimate.rs` — commande estimate (dry-run des paramètres) +- `obiskim/src/cmd/reindex.rs` — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size +- `obiskim/src/cmd/index.rs` — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp +- `obiskim/src/cmd/estimate.rs` — commande estimate (dry-run des paramètres) ## Notes diff --git a/DevDocMD/implementation/filtering.md b/DevDocMD/implementation/filtering.md index 518d1e17..5a05976e 100644 --- a/DevDocMD/implementation/filtering.md +++ b/DevDocMD/implementation/filtering.md @@ -206,7 +206,7 @@ Keep k-mers specific to *Betula nana* — present in at least 2 *B. nana* genome and absent from every other genome in the index: ```sh -obikmer filter src --output dst \ +obiskim filter src --output dst \ --ingroup "species=Betula_nana" \ --outgroup "*" \ --min-count 2 \ @@ -217,7 +217,7 @@ Keep k-mers found in at least 2 *Betula nana* genomes and absent from all other *Betula*: ```sh -obikmer filter src --output dst \ +obiskim filter src --output dst \ --ingroup "species=Betula_nana" \ --outgroup "genus=Betula" \ --min-count 2 \ @@ -228,7 +228,7 @@ Use taxonomic paths — keep k-mers present in ≥ 50 % of the *Betula* clade and in fewer than 10 % of everything outside *Betulaceae*: ```sh -obikmer filter src --output dst \ +obiskim filter src --output dst \ --ingroup "taxon~/Betulaceae/Betula" \ --outgroup "taxon!~/Betulaceae" \ --min-frac 0.5 \ @@ -238,7 +238,7 @@ obikmer filter src --output dst \ Multiple outgroup predicates (OR): exclude k-mers present in *Alnus* or *Carpinus*: ```sh -obikmer filter src --output dst \ +obiskim filter src --output dst \ --ingroup "genus=Betula" \ --outgroup "genus=Alnus" \ --outgroup "genus=Carpinus" \ @@ -249,7 +249,7 @@ Noise-tolerant core — keep k-mers present in *all but one* ingroup genome (`-1` = `n−1`) and absent from *all but one* of the outgroup: ```sh -obikmer filter src --output dst \ +obiskim filter src --output dst \ --ingroup "genus=Betula" \ --outgroup "*" \ --min-count -1 \ @@ -259,7 +259,7 @@ obikmer filter src --output dst \ To dump only k-mers specific to *Betula nana*: ```sh -obikmer dump myindex \ +obiskim dump myindex \ --ingroup "species=Betula_nana" \ --outgroup "*" \ --min-count 1 \ @@ -269,7 +269,7 @@ obikmer dump myindex \ To enumerate unitigs of the *Betula*-specific subgraph: ```sh -obikmer unitig myindex \ +obiskim unitig myindex \ --ingroup "genus=Betula" \ --outgroup "*" \ --min-count 2 \ @@ -285,8 +285,8 @@ Iteration terminates immediately — subsequent partitions and layers are not sc Useful for quick inspection of large indexes without loading the entire dataset. ```sh -obikmer dump myindex --head 100 -obikmer dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1 +obiskim dump myindex --head 100 +obiskim dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1 ``` ### `phylo --presence-threshold N` @@ -296,7 +296,7 @@ This option is independent of the `--presence-threshold` used in filtering. ```sh # Jaccard treating kmers with count ≥ 2 as present -obikmer phylo myindex --metric jaccard --presence-threshold 2 +obiskim phylo myindex --metric jaccard --presence-threshold 2 ``` This parameter has no effect on presence/absence indexes (where values are already 0/1) or on metrics other than Jaccard. @@ -309,7 +309,7 @@ This parameter has no effect on presence/absence indexes (where values are alrea once before any iteration; each k-mer row evaluation is a simple index lookup and counter. -- **`obikmer::cmd::predicate::FilterArgs`** — shared `clap` argument group +- **`obiskim::cmd::predicate::FilterArgs`** — shared `clap` argument group embedded via `#[command(flatten)]` in `FilterArgs`, `DumpArgs`, and `UnitigArgs`. `FilterArgs::build_filters()` returns a ready-to-use filter list. diff --git a/DevDocMD/implementation/merge.md b/DevDocMD/implementation/merge.md index a3d8d5ec..06d8ba82 100644 --- a/DevDocMD/implementation/merge.md +++ b/DevDocMD/implementation/merge.md @@ -2,7 +2,7 @@ ## Purpose -`obikmer merge` combines multiple existing kmer indexes into a single index. The result contains all kmers from all sources, with per-genome presence/absence or count data for every genome across every layer. +`obiskim merge` combines multiple existing kmer indexes into a single index. The result contains all kmers from all sources, with per-genome presence/absence or count data for every genome across every layer. --- @@ -64,7 +64,7 @@ Check all sources against the constraints above. Abort on any mismatch. ### 2. Bootstrap output from the base source -The base is chosen by `choose_base` (`merge.rs`): the source with the largest total `unitigs.bin` size (restricted to approximate-evidence sources when the output must be approximate). It is not necessarily `sources[0]`, and the genome columns follow the base first. Because `obikmer index` is not byte-reproducible (unitig segmentation varies), two near-equal sources can swap roles between runs. Its directory is copied to `output` (hard links for files `merge_partition` never rewrites, see below). Immediately after the copy: +The base is chosen by `choose_base` (`merge.rs`): the source with the largest total `unitigs.bin` size (restricted to approximate-evidence sources when the output must be approximate). It is not necessarily `sources[0]`, and the genome columns follow the base first. Because `obiskim index` is not byte-reproducible (unitig segmentation varies), two near-equal sources can swap roles between runs. Its directory is copied to `output` (hard links for files `merge_partition` never rewrites, see below). Immediately after the copy: - `index.meta` is rewritten with the final genome list (all sources, possibly renamed) and the effective evidence kind. - In `Presence` mode, any `counts/` directories inherited from source_0 are removed. @@ -185,7 +185,7 @@ index.meta ← complete genome list + evidence kind written at ## Known issue (not yet fixed, 2026-08-28) -Merging an index against itself — literally the same directory passed twice as separate source arguments (e.g. `obikmer merge -o out IDX IDX --rename-duplicates`) — panics deep in the MPHF's rank-select structure (`common_traits::select_in_word`, `assertion failed: rank < self.count_ones()`), inside `MphfLayer::find` called from `merge_partition`'s "is this source kmer already in dst" check against the bootstrap-copied `dst_layers`. Root cause not identified; ruled out so far: +Merging an index against itself — literally the same directory passed twice as separate source arguments (e.g. `obiskim merge -o out IDX IDX --rename-duplicates`) — panics deep in the MPHF's rank-select structure (`common_traits::select_in_word`, `assertion failed: rank < self.count_ones()`), inside `MphfLayer::find` called from `merge_partition`'s "is this source kmer already in dst" check against the bootstrap-copied `dst_layers`. Root cause not identified; ruled out so far: - **Not an empty-new-layer issue**: a source contributing zero new kmers (verified both as the sole additional source and as a third, fully-redundant source in a 3-way merge) is handled correctly — no layer is created for it, no crash, exit 0. - **Not caused by the hard-link change above**: verified via checksum that a normal (two distinct sources) merge leaves every source file byte-identical. diff --git a/DevDocMD/implementation/merge_parallelism.md b/DevDocMD/implementation/merge_parallelism.md index fddd40e4..b7a84e8b 100644 --- a/DevDocMD/implementation/merge_parallelism.md +++ b/DevDocMD/implementation/merge_parallelism.md @@ -2,7 +2,7 @@ ## Problem observed -Running `obikmer merge` over 109 indexes (108 sources + 1 bootstrap) on a 192-core machine +Running `obiskim merge` over 109 indexes (108 sources + 1 bootstrap) on a 192-core machine produces a fatal OOM during the `merge_partitions` stage: ``` @@ -58,7 +58,7 @@ Plausible for the largest partition of 108 Salix/Betula sources (~450 Mbp each). ## Partition size distribution -`obikmer utils --partition-stats` measures the sum of `unitigs.bin` file sizes +`obiskim utils --partition-stats` measures the sum of `unitigs.bin` file sizes per partition across all source indexes (pure `stat()` syscalls, negligible cost). Observed on a 9-genome pilot (256 partitions): diff --git a/DevDocMD/implementation/merge_scaling.md b/DevDocMD/implementation/merge_scaling.md index 4b1b63d5..ffe19d12 100644 --- a/DevDocMD/implementation/merge_scaling.md +++ b/DevDocMD/implementation/merge_scaling.md @@ -38,4 +38,4 @@ Merge discovers values **column by column** (source by source), in **random slot ## Related findings - The module header of `bitmatrix/sparse.rs` says "not used by any production code path yet". This is stale: `finalize_indexed` packs to sparse by default. -- The new layer of a merge is not byte-reproducible run to run: unitig segmentation varies, so the MPHF, evidence and matrix row order vary with it (measured 2026-11-17, `layer_1/*` differs in all 256 partitions; `layer_0` and metadata are identical). `obikmer index` shows the same behaviour. Merge oracles therefore compare sorted dumps, not file hashes. Where the non-determinism originates (parallel graph fill or unitig walk) is not established. +- The new layer of a merge is not byte-reproducible run to run: unitig segmentation varies, so the MPHF, evidence and matrix row order vary with it (measured 2026-11-17, `layer_1/*` differs in all 256 partitions; `layer_0` and metadata are identical). `obiskim index` shows the same behaviour. Merge oracles therefore compare sorted dumps, not file hashes. Where the non-determinism originates (parallel graph fill or unitig walk) is not established. diff --git a/DevDocMD/implementation/mphf_batch_queries.md b/DevDocMD/implementation/mphf_batch_queries.md index 40466f8f..0895597d 100644 --- a/DevDocMD/implementation/mphf_batch_queries.md +++ b/DevDocMD/implementation/mphf_batch_queries.md @@ -112,8 +112,8 @@ About −5 % wall and −5.5 % CPU, ranges non-overlapping **[measured]**. All o Prerequisites: the simulated reads (`benchmark/run/simulated_data/`) and query reads (`benchmark/run/query_data/`) produced by `gmake simulate simulate_query`; macOS BSD `time -l` and `md5 -q` (the script uses both), Python 3. -1. Build the binary to measure and **copy it** under a name that identifies it (cargo overwrites `target/release/obikmer`): `cp src/target/release/obikmer benchmark/run/bench_mphf/obikmer_