Compare commits

...
178 Commits
Author SHA1 Message Date
Eric Coissac 917cb26186 refactor: rename project from obikmer to obiskim
Release / create-release (push) Successful in 32s
Release / build-linux-x86_64 (push) Successful in 6m18s
Release / build-macos-arm64 (push) Failing after 12s
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_<partition>_<layer>`.
- 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.
2026-12-01 18:17:47 +01:00
Eric Coissac 42d5b881ec refactor: rename obikmer to obiskim
Rename the `obikmer` binary, crate, and documentation to `obiskim`. This change updates all references in source code, build scripts, CI workflows, and user documentation to reflect the new tool name.

- Move `src/obikmer` to `src/obiskim`, renaming the package and binary in `Cargo.toml` and updating `main.rs` and `cli.rs` to use the new name.
- Update `src/Cargo.toml` and `src/Cargo.lock` to replace the `obikmer` workspace member with `obiskim`.
- Update `Makefile` targets (`build`, `release`, `debug`, `profile-build`) and variables (`CARGO_TOML`, `bump-version`) to build and manage `obiskim`.
- Update `.gitea/workflows/release.yml` to build and upload `obiskim` artifacts for Linux and macOS.
- Rename all files in `src/obiskim/src/cmd/` from `obikmer` to `obiskim` paths, updating error messages and help text in `index/mod.rs`, `phylo/args/mod.rs`, and `phylo/tnt.rs`.
- Update documentation in `UserDocMD/` (including `index.md`, `installation.md`, `architecture.md`, and usage guides) to reference `obiskim` commands and behavior.
- Update `benchmark/` scripts and Python verification tools to use `obiskim` binary paths and arguments.
- Update `scripts/` (including `smoke_test_*.sh`, `bench_merge_oracle.sh`, and Docker debug scripts) to test and build `obiskim`.
- Update comments and error messages in library crates (`obicompactvec`, `obifastwrite`, `obikentropy`, `obikfilter`, `obikindex`, `obikindexer`, `obikphylo`, `obikselect`, `obikseq`, `obiread`, `obisys`) to reference `obiskim`.
2026-12-01 18:15:13 +01:00
Eric Coissac a71e59d6f0 refactor: modernize iteration patterns and add sparse matrix support
Update bitvector and matrix operations to use iterator-based loops, `as_chunks`, and direct references instead of index-based access. Introduce `Sparse` variants for persistent bit and integer matrices, including logic to detect and migrate stale columnar formats. Add `is_empty` methods to various data structures and implement `Default` for `PartitionRunner`.

- Add `Sparse` variants to `PersistentBitMatrix` and `PersistentIntMatrix` enums, with auto-detection logic to migrate stale columnar files (`matrix.pbmx`, `matrix.pcmx`) to the new sparse format by rebuilding from columnar data.
- Refactor bit manipulation functions (`or_where`, `and_where`, `xor_where`) in `bitvec.rs` to use direct references (`*word`) instead of indexed access (`words[wi]`), and update remainder handling in `set_last_word`.
- Update `read_int_window` and `read_bit_window` in sparse matrix modules to use `as_chunks::<8>()` for efficient byte-to-u64 conversion, replacing `chunks_exact` and `try_into`.
- Modify `inc_predicate_fast` in `builder.rs` to iterate over `primary.iter_mut().zip(col.primary_bytes())` for incrementing values, avoiding index-based access.
- Add `is_empty` methods to `Evidence`, `FamilyScalarAnnex`, and `RopeCursor` to check for zero-length or empty states.
- Implement `Default` for `PartitionRunner` in `obisys`, delegating to `Self::new()`.
- Refactor multiple test functions across `obicompactvec`, `obikmer`, `obikphylo`, `obikquery`, and `obiskio` to use `enumerate()`, `iter()`, and `take()` instead of index-based loops, improving idiomatic Rust patterns.
- Update `merge_partition` in `obikmerge` to use `clamp(4, 16)` for worker count calculation instead of chained `min`/`max` calls.
- Add `#[allow(clippy::large_enum_variant)]` to `KmerLayer` and `#[allow(clippy::too_many_arguments)]` to subsample functions, with updated documentation clarifying layer types and argument independence.
- Refactor `write_sankoff_phyg` and `write_sample_stats` in `obikmer` to use iterator methods (`take`, `copied`, `enumerate`) for processing matrices and labels.
- Update `build_emax` and `build_log_nwords` in `obikentropy` to use `enumerate` and direct cell references, and add `WS_MAX` constant and comments in `table.rs`.
- Modify `push_warmup_increments` in `obikentropy` to accept a fixed-size array `[u64; 6]` instead of individual arguments, updating `push` accordingly.
- Refactor `resolve_partition_batch` and `query_partition_with` in `obikphylo` and `obikquery` to iterate over `by_layer.iter_mut().enumerate().take(n_layer)`, using direct bucket references.
- Update `ascii_histogram` in `obikmer` to use `checked_div` and `unwrap_or(0)` for bar length calculation, replacing conditional checks.
- Refactor `from_ascii` in `obikseq` to iterate over references `&base in &ascii[..k]` instead of indices, and update related tests to use `#[test]` attributes and new type aliases.
2026-12-01 17:43:44 +01:00
Eric Coissac f022d83394 refactor: modernize arithmetic, control flow, and error handling
Replace manual ceiling division with `div_ceil`, update `map_or` patterns to `is_some_and`/`is_ok_and`, and simplify error handling across the codebase. Move the `default` function for `GraphDeBruijn` from the index layer module to the De Bruijn graph module.

- Move `default` from `src/obikindex/src/layer/meta.rs` to `src/obidebruinj/src/debruijn/graph.rs` and implement `Default` for `GraphDeBruijn`
- Simplify `IndexBuilder::state`, `KmerIndex::genomes`, and `n_layers_per_partition` in `src/obikindex` by removing redundant `Ok` wrappers
- Replace manual ceiling division with `div_ceil` in `src/obikindex/src/layer/fingerprint.rs` for data slicing and byte calculations
- Update `Mphf` operations in `src/obikindex/src/layer/mphf_layer.rs` to use `mmap`, `load_full`, and `store` directly, and switch size calculations to `div_ceil`
- Refine `IndexMode` in `src/obikindex/src/layer/meta.rs` to derive `Default` with `#[default]` on `Exact`
- Update `count_partition` in `src/obikindexer/src/algorithms/counter/count.rs` to use `io::Error::other` with string conversion for error mapping
- Switch `optimal_buckets` in `src/obikindexer/src/algorithms/dereplicator/dereplicate.rs` to use `div_ceil` for average sequence bytes and bucket estimation
- Replace `max_or` and `map_or` with `is_none_or` and direct checks in `src/obikindexer/src/extensions/private_builder.rs` for layer building and artifact removal
- Enforce odd k-mer and minimizer sizes in `src/obikmer/src/cli.rs` using `is_multiple_of` and update validation ranges
- Update `resolve_approx_params` in `src/obikmer/src/cmd/index/mod.rs` to use `div_ceil` for parameter calculations
- Add documentation for `DistanceArg` in `src/obikmer/src/cmd/phylo/values.rs` and clean up test modules
- Refactor median calculation in `src/obikmer/src/cmd/utils/partition_stats.rs` to explicitly handle even and odd lengths
- Replace `g.len() > 0` with `!g.is_empty()` in `src/obikmerge/src/partition_merge/mod.rs`
- Use `isolate_lowest_one` in `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` for diploid allele calculation
- Add documentation for `family_entropy` in `src/obikphylo/src/siblings/algorithms/entropy.rs` and remove empty test blocks
- Replace `map_or` with `is_some_and` in `src/obikquery/src/findere.rs` and `src/obikquery/src/tests/findere.rs` for deque pruning logic
- Simplify `remove_if_exists` in `src/obikrebuild/src/reindex.rs` to warn only on non-`NotFound` errors
- Store `mime_type` by value in `src/obikrope/src/rope.rs` and update `mime_type` and `split_off` accordingly
- Replace manual ceiling division with `div_ceil` in `src/obikseq/src/packed_seq.rs` for byte length and iteration logic
- Update `build_dec4` in `src/obikseq/src/encoding.rs` to use a string slice literal for the decode table
- Refactor `revcomp4` in `src/obikseq/src/revcomp_lookup.rs` to use `rotate_left` for nibble swapping
- Simplify `run` in `src/obipipeline/src/scheduler/pool.rs` to use `if let Ok` for delta handling
- Simplify MIME type checking in `src/obiread/src/chunk.rs` and update error handling for unsupported formats
- Replace `map_or` with `is_ok_and` in `src/obiread/src/mimetype.rs` for FASTA/FASTQ detection
- Update `normalize_fastq` and related functions in `src/obiread/src/normalize.rs` to handle `Result` returns from cursor reads
- Simplify `skip_line` in `src/obiread/src/record.rs` to check `Ok` results directly
- Simplify test assertions in `src/obiread/src/tests/chunk.rs` by removing unnecessary closures
- Update `http_reader` in `src/obiread/src/xopen.rs` to map errors to `io::Error::other` and refine `expand_tilde` logic
- Refactor minimizer change detection in `src/obiskbuilder/src/iter.rs` and `src/obiskbuilder/src/stream_iter.rs` to explicitly check `Some` and inequality
- Update `push` in `src/obiskbuilder/src/rolling_stat.rs` to use `is_some_and` for hash and position checks
- Replace manual ceiling division with `div_ceil` in `src/obiskbuilder/src/scratch.rs` for buffer slicing
- Update `next` in `src/obiskio/src/unitig_index/kmer_iter.rs` to use `div_ceil` for byte length calculation
- Replace manual ceiling division with `div_ceil` in `src/obiskio/src/unitig_index/kmer_raw.rs` for byte extraction
- Update `src/obiskio/src/unitig_index/reader.rs` to use `div_ceil` for byte lengths and direct comparison for magic bytes
- Replace manual ceiling division with `div_ceil` in `src/obiskio/src/unitig_index/writer.rs` for chunk and index writing
- Simplify CPU set mapping in `src/obisys/src/numa/topology.rs` by removing explicit type annotations
- Update `stop` in `src/obisys/src/stage.rs` to use direct delta comparisons for fault counts
- Refine `matches` in `src/obitaxonomy/src/segment_pattern.rs` to check for inequality when rank is `None`
2026-12-01 17:38:49 +01:00
Eric Coissac ed0d563995 refactor: overhaul compact vector storage, phylo algorithms, and CLI interfaces
Refactor the core compact vector library to support sparse matrices, overflow handling, and improved distance metrics. Update phylogenetic algorithms to handle ambiguity policies and quartet conventions, and standardize error handling and CLI argument parsing across all tools.

- `src/obicompactvec`: Add support for sparse bit matrices and overflow handling in compact vectors; update distance metrics (Jaccard, Bray, Euclidean) to accept explicit sums and thresholds; add `transpose` module and refine `PersistentBitMatrix`/`PersistentSparseBitMatrix` APIs.
- `src/obicompactvec/src/bitmatrix`: Implement `PersistentSparseBitMatrix` and `PersistentSparseBitMatrixBuilder`; update pairwise distance calculations to handle implicit and sparse types; add `partial_group_presence_count` for group operations.
- `src/obicompactvec/src/tests`: Update tests to use new sparse matrix APIs, explicit `.close().unwrap()` chains, and refined assertions for distance symmetry and diagonal checks.
- `src/obidebruinj`: Refactor De Bruijn graph traversal to use atomic fetch-or for visited masks and explicit direction checks in `unitig_nucleotides` and `for_each_unitig`.
- `src/obifastwrite`: Update `annotation` to accept slice of tuples; refine `write_scatter` and `write_count` output structures; improve ID extraction in `different_sequences_different_id`.
- `src/obikdump`: Refactor `dump` and `write_unitigs` to use parallel iterators (`rayon::into_par_iter`) and updated `IndexCache` imports for kmer partitioning.
- `src/obikentropy`: Update `emit_f64_2d` formatting; refine entropy tests to use `Kmer::from_ascii` directly and multi-line assertions for range checks.
- `src/obikfilter`: Add `MinComplexity` filter; update `passes` logic for ingroup/outgroup counts with explicit threshold checks; refactor `filter_partition` to use closures for kmer insertion.
- `src/obikidxcache`: Update `iter_partition` and `iter_indexed` to handle explicit partition arguments and collect layer cache keys before iteration.
- `src/obikindex`: Refactor `IndexBuilder` and `KmerIndex` to explicitly initialize `meta` and `lock`; update `OKIError` to include static context and string details; add `TypedLayer` row presence histogram support.
- `src/obikindexer`: Update `build_index_layer` to handle zero layers and flatten `mphf1.bin` loading; refactor `graph_pipeline` to explicitly define transformations and sinks for `KmerGraphData`.
- `src/obikmer`: Refactor CLI commands (`annotate`, `convert`, `dump`, `filter`, `pack`, `select`, `unitig`) to use explicit error handling with `unwrap_or_else` and updated metadata access; add `query` and `select` modules.
- `src/obikmer/src/cmd/phylo`: Update phylogenetic output writers (`iqtree`, `phyg`, `phylip`, `sankoff`, `tnt`) to handle explicit genome indices, sites, and alignment structures; add `shared` module for shared kmer writing.
- `src/obikmerge`: Refactor `merge` to validate source compatibility with specific error messages; update pass 2 logic to stream layer unitigs to column builders.
- `src/obikphylo`: Overhaul distance metrics to support ambiguity policies and quartet conventions; update `SnpAlignment` to include sites; refactor sibling algorithms to handle masking, entropy, and pair weights explicitly.
- `src/obikphylo/src/siblings`: Update `alignment`, `cardcomp`, `entropy`, `masking`, and `pairwise` algorithms to use explicit policy arguments and refined assertions; add `sample_stats` and `subsample` modules.
- `src/obikphylo/src/tree`: Refactor `neighbor_joining` and `upgma` to explicitly handle node creation, edge finding, and label cloning.
- `src/obikquery`: Add `partition_kmers`, `query_layer`, and `smer_index` modules; update `process_chunk` to use explicit iterator chaining for statistics; refine `from_records` to push kmer descriptions.
- `src/obikrebuild`: Refactor `compact_partition` and `reindex` to use explicit block structures and updated error mapping for metadata evidence.
- `src/obikselect`: Update `build_output_cols` to handle group operations and default aggregation; refine `select_partition` to explicitly pass thresholds and presence flags.
- `src/obikseq`: Update `Kmer` push methods to use bitwise operations with `PhantomData`; refine `PackedSeq` initialization and error handling; add `RoutableSuperKmer` to public API.
- `src/obiksession`: Update `Session` to accept `force` parameter for opening; refine `Memoize` to use `get_or_compute_with_key` and explicit byte conversion.
- `src/obikstats`: Refactor `SharingNullModel` to directly construct probability vectors; update tests to use fixed `SharingSpectrum` definitions.
- `src/obipipeline`: Refactor scheduler macros to wrap transformations in `Box<dyn Fn>` with `Send + Sync`; update `Pipe` and `Pool` to handle explicit error signaling and stage indexing.
- `src/obiread`: Add `text/gbff` MIME type; update `read_sequence_chunks_sized` to use explicit `SeqChunkIter` constructors; refine `SeqRecord` initialization.
- `src/obiskbuilder`: Add `stream_iter` module for streaming superkmer iteration; update benchmarks to use direct `.count()` calls.
- `src/obiskio`: Refactor `SKError` to include static context and string details; update `UnitigFileReader`/`Writer` to use explicit error mapping and block offset handling.
- `src/obisys`: Refactor `DirLock` to use explicit `acquire_mode` and `promote`/`demote` logic; update `LockSlot` to handle exclusive/shared states with mutexes; refine `NodeConfig` and `effective_parallelism` tracing.
- `src/obitaxonomy`: Refactor `TaxPath` and `TaxPattern` parsing to handle segments and ranks explicitly; update error messages to include segment information; add `segment` and `segment_pattern` modules.
2026-12-01 17:34:15 +01:00
Eric Coissac 8159137f8b chore: add crate-kit build system and CeCILL license
Introduce the `.crate-kit` infrastructure to standardize build, testing,
and release workflows using Jujutsu and Cargo. Add CeCILL-2.1 license
files and update all workspace crate manifests with license and repository
metadata.

- Add `.crate-kit/` directory with `VERSION`, `crate.mk`, `dev-patch.mk`,
  `jj.mk`, and `org.mk` to define build targets, Jujutsu helpers, and
  registry configuration for the workspace.
- Add 21 shell scripts in `.crate-kit/scripts/` for API tracking,
  dependency checking, version bumping, publishing, tagging, and wiki
  generation, including `common.sh` with shared utility functions.
- Add `scripts/jj-tag.sh` to support tagging commits with version strings
  derived from the current crate version.
- Add `LICENSE` and `LICENSE.en` files containing the CeCILL-2.1 free
  software license agreement in French and English.
- Update `Makefile` with new targets for building, testing, formatting,
  CI, and releasing, integrating with `.crate-kit` scripts and updating
  the wiki directory path to `obiskim`.
- Update `.gitignore` to ignore `.cargo/config.toml` files generated by
  the development patch system.
- Add `license = "CECILL-2.1"` and
  `repository = "https://forge.metabarcoding.org/obi/obiskim"` to all
  `Cargo.toml` files in the workspace, including `obicompactvec`,
  `obidebruinj`, `obifastwrite`, `obikalgorithm`, `obikdump`,
  `obikentropy`, `obikfilter`, `obikidxcache`, `obikindex`,
  `obikindexer`, `obikmer`, `obikmerge`, `obikphylo`, `obikquery`,
  `obikrebuild`, `obikrope`, `obikselect`, `obikseq`, `obiksession`,
  `obikstats`, `obipipeline`, `obiread`, `obiskbuilder`, `obiskio`,
  `obisys`, and `obitaxonomy`.
- Update `src/obikrope/Cargo.toml` to use `criterion2` version 3 with
  the `cargo_bench_support` feature.
- Update `src/obikseq/Cargo.toml` to replace the "OnceLock-based params"
  feature with a new feature description involving thread-local storage.
- Update `src/Cargo.lock` to reflect the version bump of `obikmer` from
  1.4.7 to 1.4.8.
2026-12-01 17:18:34 +01:00
coissac 58e57ceae5 Merge pull request 'refactor: remove migrate-mphf tool and update sibling annex handling' (#84) from push-rstmlzzlxuzq into main
Reviewed-on: OBIKmers/obikmer#84
2026-12-01 09:36:34 +00:00
Eric Coissac b95348b226 refactor: remove migrate-mphf tool and update sibling annex handling
ci.yml / build (pull_request) Successful in 4m10s
Release / create-release (push) Successful in 26s
Release / build-linux-x86_64 (push) Successful in 6m22s
Release / build-macos-arm64 (push) Successful in 2m23s
Remove the `migrate-mphf` tool entirely, as its functionality is no longer needed or has been superseded. Update the `phylo` sibling annex logic to build missing annexes on demand under an exclusive lock, ensuring safe concurrent access. Adjust documentation and CI workflows to reflect the removal of the migration tool and clarify sibling annex behavior.

- Delete the entire `tools/migrate-mphf` directory, including `Cargo.toml`, `Cargo.lock`, and source files (`main.rs`, `layer.rs`, `plan.rs`, `data.rs`, `commit.rs`, `old.rs`, `verify.rs`, `util.rs`), removing functions such as `convert`, `build`, `permute_all`, `finish`, and `check`.
- Update `.gitignore` to remove patterns for `tools/migrate-mphf/target`, `data-stress`, `*.fasta`, and `*.fasta.gz`.
- Modify `Makefile` to remove the `migrate-mphf` and `clean-migrate-mphf` phony targets and associated build commands.
- Update `.gitea/workflows/release.yml` to remove the "Build migrate-mph (static)" job and the artifact upload step, and adjust the `linux-musl-cargo` job key to hash only `src/Cargo.lock`.
- Refactor `src/obikphylo/src/siblings/extensions/sibling_builder.rs` to update `build_family_annexes` documentation, noting that it builds the sibling annex from `siblings.psib` if missing and runs under the index's exclusive lock.
- Update `src/obikphylo/src/siblings/siblingannex.rs` documentation to clarify that `open` reports absent files differently when annexes were set aside by `migrate-mphf` or never built.
- Update `UserDocMD/usage/phylo.md` to clarify that `--sibling-annex` prepares the quartet annex on demand under an exclusive lock, and update descriptions for `--sibling-stats` and `--sibling-hist` to specify output file formats and contents.
- Update `DevDocMD/implementation/mphf_batch_queries.md` to reflect changes in batched query logic, `ptr_hash` versioning, and benchmark descriptions, noting that stale indexes with `ptr_hash` 1.x MPHFs fail on current binaries.
- Add `prompts/obi-migration.md` to document the context, decisions, and required actions for the `obikmer` project migration.
- Bump `obikmer` package version from 1.4.7 to 1.4.8 in `src/obikmer/Cargo.toml` and update `src/Cargo.lock` accordingly.
2026-12-01 10:31:25 +01:00
coissac d7ea6973e3 Merge pull request 'Push punmmmpkuymy' (#83) from push-punmmmpkuymy into main
Reviewed-on: OBIKmers/obikmer#83
2026-11-20 13:24:06 +00:00
Eric Coissac 1119af85ba feat: update indexing pipeline and bump obikmer version to 1.4.7
Release / create-release (push) Successful in 1m15s
Release / build-linux-x86_64 (push) Successful in 6m43s
Release / build-macos-arm64 (push) Successful in 1m57s
ci.yml / build (pull_request) Successful in 3m42s
Refactor the indexing process to support parallel phases, resumable builds, and three verification modes (Exact, Approximate, Hybrid). Update the on-disk layout to manage evidence-specific files and state in `index.meta`, and refine layer merging logic. Bump the obikmer package version from 1.4.6 to 1.4.7.

- Modify indexing routing to use low bits of hash and enable parallel, independent phases for resumable builds
- Update counting phase to build provisional MPHF and temporary counts, deleted unless `--keep-intermediate` is set
- Combine quorum filtering with local assembly by filtering kmers during de Bruijn graph construction before unitig assembly
- Expand verification modes to Exact, Approximate, and Hybrid, allowing post-build conversion between them
- Update on-disk layout to include specific files for each evidence type and manage build state in `index.meta`
- Refine layer merging to create new layers only for genuinely new kmer content and determine destination evidence mode from sources
- Add `--sparse` option to packing logic for sparse representation support
- Bump obikmer package version from 1.4.6 to 1.4.7 in Cargo.toml
2026-11-20 14:21:01 +01:00
Eric Coissac 36c7247acb feat: add k-mer sharing estimation and Poisson-binomial null model
Add a new `estimate --index` command to compare observed k-mer sharing against
a random-sequence model using a Poisson-binomial distribution. Introduce the
`row_presence_histogram` API to support this analysis across various matrix
types. Update documentation and dependencies accordingly.

- Add `src/obikstats/src/null_model.rs` implementing `SharingNullModel` and
  `SharingRow` for computing cumulative probabilities and false discovery rates
  based on a Poisson-binomial distribution.
- Add `src/obikstats/src/sharing.rs` defining `GenomeSharing` and `SharingSpectrum`
  to compute k-mer sharing spectra using parallel map-reduce.
- Add `src/obikmer/src/cmd/estimate/sharing.rs` with `run` and `write_csv` to
  execute sharing estimation and output CSV results containing observed, expected,
  and deviation metrics.
- Modify `src/obikmer/src/cmd/estimate/mod.rs` to support the new `--index`
  subcommand, adding `EstimateArgs` fields for index path, presence threshold,
  and output file.
- Add `src/obicompactvec/src/row_histogram.rs` implementing `row_presence_histogram`
  for `PersistentIntMatrix`, `PersistentBitMatrix`, and sparse matrices to count
  rows present in exactly $j$ columns.
- Update `src/obikindex/src/layer/content_layer.rs` and `src/obikindex/src/layer/typed_layer.rs`
  to expose the new `row_presence_histogram` method, dispatching based on layer type.
- Add tests in `src/obicompactvec/src/tests/bitmatrix.rs`, `intmatrix.rs`, and
  `sparse.rs` to verify `count_geq` and `row_presence_histogram` against naive
  implementations for various matrix structures.
- Update `UserDocMD/theory/kmer_indexing/kmers.md` to document the Poisson-binomial
  approach, $D_r$ bounds, and FDR calculations, replacing previous binomial approximations.
- Update `UserDocMD/usage/estimate.md` to describe the two uses of `estimate`:
  parameter estimation and index comparison via `--index`.
- Add `wiki` target to `Makefile` for regenerating documentation from user docs.
- Bump `obikmer` package version from 1.4.5 to 1.4.6 in `Cargo.toml` and `Cargo.lock`.
2026-11-19 17:50:29 +01:00
Eric Coissac 6d6d5e5e53 feat: add count_geq method to calculate column counts above a threshold
Introduce `count_geq` across the codebase to return the number of k-mers present in columns with counts greater than or equal to a specified threshold. This unifies the interface for counting distinct k-mers and updates `partial_kmer_counts` to rely on `count_geq(1)`.

- Add `count_geq` method to `PersistentBitMatrix` in `src/obicompactvec/src/bitmatrix/persistent.rs`, delegating to `count_ones`.
- Implement `ColumnWeights` trait for `PersistentBitMatrix` and add `count_geq` to `PersistentSparseBitMatrix` in `src/obicompactvec/src/bitmatrix/sparse.rs`.
- Add `count_geq` methods to `IntMatrix` variants (`Columnar`, `Packed`, `Sparse`) and `PersistentIntMatrix` in `src/obicompactvec/src/intmatrix.rs`, removing `partial_kmer_counts`.
- Implement `count_geq` for `SparseCompactIntMatrix` in `src/obicompactvec/src/sparse_intmatrix.rs`, handling threshold 0 explicitly, and remove `partial_kmer_counts`.
- Add `count_geq` method to `Reader` struct in `src/obicompactvec/src/reader.rs` with documentation.
- Update `ColumnWeights` trait in `src/obicompactvec/src/traits.rs` to include `count_geq` and redefine `partial_kmer_counts` as `count_geq(1)`.
- Add `count_geq` method to `Views` struct in `src/obicompactvec/src/views.rs` for distance calculations.
- Add `count_geq` tests in `src/obicompactvec/src/tests/sparse_intmatrix.rs` verifying behavior against naive implementations.
- Add `count_geq` to `ContentLayer` in `src/obikindex/src/layer/content_layer.rs`, delegating based on layer type.
- Add `count_geq` to `TypedLayer` in `src/obikindex/src/layer/typed_layer.rs`, delegating to `obicompactvec::ColumnWeights`.
- Add `count_geq` method to distance struct in `src/obikphylo/src/distance.rs` using `self.reduce`.
2026-11-19 17:49:19 +01:00
Eric Coissac 33d7a59dd9 docs: restructure documentation for kmer indexing and phylogeny theory
Reorganize the documentation structure to better separate kmer indexing logic from phylogenetic analysis methods. This involves moving several existing pages into new directories under `theory/kmer_indexing` and `theory/phylogeny`, updating navigation links across the site, and adding new content for VCF pseudo-alignment and specific phylogenetic models.

- Move `doc/index.html` to `doc/theory/kmer_indexing/minimizer_selection/index.html` to document minimizer selection logic.
- Move `doc/installation/index.html` to `doc/theory/phylogeny/kmer_based/kmer_set_distances/index.html` for whole k-mer set distance documentation.
- Move `doc/usage/dump/index.html` to `doc/theory/kmer_indexing/superkmers/index.html` to cover canonical super-kmers.
- Move `doc/usage/query/index.html` to `doc/theory/kmer_indexing/entropy_filter/index.html` for low-complexity kmer filtering details.
- Move `doc/theory/encoding/index.html` to `doc/theory/kmer_indexing/encoding/index.html` for DNA and kmer encoding specifics.
- Move `doc/theory/indexing_architecture/index.html` to `doc/theory/kmer_indexing/indexing_architecture/index.html` for partitioning and routing architecture.
- Move `doc/usage/query/index.html` (duplicate move noted in facts, likely referring to the query command usage or similar) to `doc/theory/phylogeny/snp_based/sankoff_model/index.html` for the 16-state Sankoff model.
- Move `doc/theory/minimizer_selection/index.html` to `doc/theory/phylogeny/snp_based/central_snp_model/index.html` for central-position SNP models and substitution corrections.
- Move `doc/theory/indexing_architecture/index.html` (duplicate move noted) to `doc/theory/phylogeny/snp_based/gamma_rate_heterogeneity/index.html` for gamma rate heterogeneity and automatic alpha estimation.
- Move `doc/theory/entropy_filter/index.html` to `doc/theory/phylogeny/snp_based/sampling_design/index.html` for entropy-biased sampling design.
- Move `doc/formats/index_layout/index.html` to `doc/formats/vcf/index.html` to document VCF pseudo-alignment output and structure.
- Add `doc/molecular-ecology-modified.csl` with a new XML style definition for Molecular Ecology Modified citations.
- Update `UserDocMD/formats/vcf.md` to clarify that `--vcf` implies `--pseudo-alignment`, requires `--n-sites`, and generates files alongside `--fasta`.
- Add three new BibTeX entries in `UserDocMD/references.bib` for Karlin (1997, 1995) and Bennett & Moran (2013).
- Update `UserDocMD/theory/kmer_indexing/kmers.md` to use binomial distribution for probability calculations and define k-mer sharing deviation.
- Clarify in `UserDocMD/theory/phylogeny/kmer_based/kmer_set_distances.md` that counts are used instead of presence/absence for $L^1$ distance.
- Update `UserDocMD/theory/phylogeny/snp_based/gamma_rate_heterogeneity.md` to attribute method-of-moments $\alpha$ estimation to obikmer, not Jin & Nei (1990).
- Update `UserDocMD/theory/phylogeny/snp_based/sampling_design.md` to redirect entropy sampling references to the correct phylo section.
- Add new options `--cpu-max`, `--output`, `--pair-balance`, `--sibling-stats`, `--family-overlap`, and `--shannon` to `UserDocMD/usage/phylo.md`.
- Mark SNP-based distance saving and session reuse as unavailable in `src/obikmer/src/cmd/phylo/args/distance.rs`.
2026-11-19 17:47:59 +01:00
coissac d78a6b4501 Merge pull request 'Push vpnykuuvnrnx' (#82) from push-vpnykuuvnrnx into main
Reviewed-on: OBIKmers/obikmer#82
2026-11-19 06:17:43 +00:00
Eric Coissac 5db7b440da refactor: treat absence as state unless --free-loss and update quartet annexes
ci.yml / build (pull_request) Successful in 4m33s
Release / create-release (push) Successful in 1m56s
Release / build-linux-x86_64 (push) Successful in 11m18s
Release / build-macos-arm64 (push) Successful in 2m27s
Refactor the handling of genome absence to be a distinct state unless `--free-loss` is specified. This change introduces `QuartetConvention` to pair ambiguity policies with the free-loss flag, updating file naming conventions and logic across sampling, masking, and stats modules.

- Update `--exclude-genome` description in `pair_coverage_sampling.md` to clarify absence as a state unless `--free-loss` is specified.
- Move multi-member genome handling convention from `pair_coverage_sampling.md` to file name conventions.
- Clarify persisted annex structure in `pair_coverage_sampling.md` as `PersistentBitVec` per non-monomorphic family with counting convention carried by file name.
- Fix initial version's absence handling in `has_bipartition`, the annex, and `--sample-stats` to correctly count index 0 when absence is a state.
- Replace entropy-only builder with `AnnexRequest` and `ensure_layer_family_annexes`.
- Consolidate sampling parameters into a single `SamplingSpec`.
- Update family constraint description in `sampling_design.md`.
- Modify uniform draws and `--quartet` removal text in `sampling_design.md`.
- Clarify state counting in tests for `--free-loss` option in `sampling_design.md`.
- State that absence forms a pair without `--free-loss` but never with it in `sampling_design.md`.
- Update `--quartet` option to require at least two distinct states, each carried by at least two genomes.
- Define absence as a state unless `--free-loss` is given for family carrier definition.
- Clarify `--pair-balance` favors families covering pairs with fewest shared families.
- Modify logic for families fitting every tree topology equally well in `phylo.md`.
- Change `--quartet` restriction logic to apply after pre-checks involving `--no-ambiguity` and `--exclude-genome`.
- Update `obikmer` dependency version from 1.4.4 to 1.4.5 in `Cargo.lock` and `Cargo.toml`.
- Modify `annex_selection` in `args/mod.rs` to derive `free_loss`, `entropy`, `quartet`, and `overlap` from `SamplingSpec`.
- Update `SamplingArgs::quartet` documentation in `sampling.rs` to describe state determination based on `--free-loss`.
- Add `free_loss` field to `AnnexSelection` struct in `family_annexes.rs`.
- Change `AnnexRequest` to use `Vec<QuartetConvention>` instead of `Vec<AmbiguityPolicy>`.
- Update `request` logic in `family_annexes.rs` to conditionally create `QuartetConvention` based on `self.quartet`.
- Modify `dedup` signature in `family_annexes.rs` to accept iterator of type `T: Ord`.
- Update `ensure_layer_family_annexes` in `family_annexes.rs` to use `missing_files` and `QuartetConvention`.
- Add `missing_files` definition to `family_annexes.rs`.
- Change `has_bipartition` in `masking.rs` to filter counts where count is `>= 2`.
- Update `is_quartet_informative` in `masking.rs` to accept `free_loss` boolean parameter.
- Modify `two_pairs_of_distinct_states_is_informative` and `singleton_variant_is_not_informative` in `masking.rs` to test both `free_loss` policies.
- Add `under_free_loss_absence_is_missing_and_forms_no_pair` and `without_free_loss_absence_is_a_state_that_can_form_a_pair` definitions to `masking.rs`.
- Update `no_ambiguity_drops_multi_member_genomes_from_the_count` in `masking.rs` to check `is_quartet_informative` under `free_loss=true`.
- Add `the_annex_rule_and_the_exact_check_agree_on_the_same_family` definition to `masking.rs`.
- Remove `absent_genomes_are_not_a_state` definition from `masking.rs`.
- Update `restrict_to_quartet` in `quartet.rs` to accept `QuartetConvention` instead of `AmbiquityPolicy`.
- Modify `add_site` in `sample_stats.rs` to handle state 0 as a state participating in bipartition.
- Add `absence_as_a_state_makes_a_site_informative` definition to `sample_stats.rs`.
- Add `quartet_convention` function to `SamplingSpec` in `subsample.rs`.
- Update `sample_index` in `subsample.rs` to use `spec.quartet_convention()` for `AnnexRequest`.
- Update `restrict_to_quartet` call in `subsample.rs` to use `spec.quartet_convention()`.
- Add comment regarding `--no-ambiguity` counting convention in `helpers.rs`.
- Import `QUARTET_ANNEX_FILE_NAMES` and `QuartetConvention` from `quartet_annex` in `mod.rs`.
- Add `QuartetConvention` struct with `policy` and `free_loss` fields to `quartet_annex.rs`.
- Modify `quartet_annex_file_name` in `quartet_annex.rs` to take `QuartetConvention`.
- Add `the_conventions_never_share_a_file` function to `quartet_annex.rs`.
- Remove `the_policies_never_share_a_file` definition from `quartet_annex.rs`.
2026-11-19 07:12:36 +01:00
Eric Coissac c93616b432 feat: add threshold-based Hamming distance and refine phylo documentation
Add `threshold_hamming_dist_matrix` to calculate k-mers present in exactly one genome using union minus intersection. Update `DistanceArgs` and `distance.rs` to support this metric on count indexes via `--presence-threshold`, removing the previous restriction that hamming was only for presence/absence indexes.

- Add `threshold_hamming_dist_matrix` method to `CountPartials` in `src/obikmer/src/traits.rs`
- Implement new test `threshold_hamming_counts_kmers_present_in_one_genome_only` in `src/obicompactvec/src/tests/intmatrix.rs`
- Update `DistanceArgs` in `src/obikmer/src/cmd/phylo/args/distance.rs` to clarify threshold effects on Jaccard/Mash/Hamming
- Modify `distance` function in `src/obikphylo/src/distance.rs` to support Hamming on count indexes and use pre-computed bit structures
- Update `obicompactvec.md` documentation with new function details and partial result explanations
- Refine `index.md` descriptions for `phylo`, `unitig`, and `select` options
2026-11-19 07:11:57 +01:00
Eric Coissac c4eacb3f72 feat(phylo): expand genome distance metrics and refactor CLI arguments
Refactor the `phylo` command to support explicit distance metrics (Jaccard, Hamming) and SNP-based pseudo-alignments. Replace implicit metric selection with explicit requirements, such as requiring `--n-sites` for SNP analysis. Add a new `shared-kmers` output option and update documentation for performance characteristics of sparse vs dense formats.

- Update `phylo` CLI to support genome-vs-genome distances using k-mer content or SNPs, including options for NJ/UPGMA tree building and data export
- Replace `reindex` command with `convert` for in-place index evidence conversion (exact/approx/hybrid) and add `--upgrade-index` to `utils` for missing layer metadata
- Refactor `distance_to_compute` logic to remove implicit Jaccard implications for `--nj`/`--upgma` unless `--distance` is specified, and enforce `--n-sites` for `--pseudo-alignment`/`--sankoff`
- Add `shared_kmers` method to `Metrics` trait in `src/obikphylo/src/distance.rs` and new `write_shared_kmers` function in `src/obikmer/src/cmd/phylo/shared.rs` for CSV export
- Update `PackArgs::dense` documentation to clarify that dense format is faster for column-oriented distance matrices while sparse is better for single-row access
- Remove `requires_counts` definition and update assertions in `values.rs` to reflect new distance computation signatures and metric requirements
2026-11-19 07:11:44 +01:00
Eric Coissac 14433e80a5 refactor: restructure phylo CLI arguments into submodules
Refactor the `phylo` command's argument handling by splitting the monolithic
`args.rs` file into specialized submodules (`distance`, `outputs`, `sampling`,
`select`) and a central `mod.rs`. This improves modularity and separates
concerns for distance metrics, sampling options, and output configurations.

- Move `alignment_output`, `ambiguity`, and `annex_selection` from `args.rs` to
  `args/mod.rs` in the `PhyloArgs` struct.
- Relocate distance parsing logic (`parse_gamma_shape`, `parse_n_sites`, `target`)
  and helper functions (`distance_to_compute`, `as_classic`, `as_snp`, etc.) from
  `args.rs` to `values.rs`.
- Add new submodule files: `args/distance.rs` for `DistanceArgs`, `args/outputs.rs`
  for `AlignArgs` and `CostsArgs`, `args/sampling.rs` for `SamplingArgs`, and
  `args/select.rs` for `SelectArgs` and `AnnexArgs`.
- Update `main.rs` to register the new `Phylo` command using `cmd::phylo::PhyloArgs`.
- Refactor `mod.rs` (`run`) to use nested argument structures (e.g., `args.dist`,
  `args.sample`) instead of flat fields.
- Update `alignment_out.rs` to reference the new nested paths (`args.align.fasta`,
  `args.sample.no_ambiguity`).
2026-11-19 07:11:26 +01:00
Eric Coissac 7f829ea557 docs: clarify merge re-merge behavior and input file handling
Update documentation to explain that merged indices can serve as sources if at least one source is unmerged, and that the resulting column order follows the base index first. Clarify that explicitly named files are always read regardless of extension, with format detection based on content.

- refactor: prevent I/O errors when re-merging packed outputs by restricting `choose_base` to valid destinations via new `can_be_destination` check
- fix: handle zero-layer partitions in `build_index_layer` and `remove_build_artifacts` to skip unnecessary operations
- feat: allow `PathIter` to treat unrecognized extensions as explicit files, ensuring they are not silently dropped during directory expansion
- test: add comprehensive tests for `PathIter` including extension recognition, explicit file handling, and stdin sentinel behavior
- test: update smoke tests to verify empty partitions, `.fna.gz` indexing, and refusal of merging only packed indexes
- chore: remove obsolete cargo build environment variables from `run.sh` script
2026-11-19 07:10:58 +01:00
Eric Coissac 07c0a54e04 feat: add compatibility testing scripts and update dependencies
Add `compat_ptrhash.sh` and `compat_ptrhash2.sh` to facilitate determinism control and incremental merge testing between obikmer binaries. Update `tikv-jemallocator` dependency version in `Cargo.toml` and refresh `Cargo.lock` with new crates and checksums.

- Add scripts/docker_debug/compat_ptrhash.sh for compatibility tests (T0-T4) comparing ptr_hash versions using Docker and md5sum
- Add scripts/docker_debug/compat_ptrhash2.sh for determinism control and incremental merge operations between binaries A and B
- Update src/obikmer/Cargo.toml to change tikv-jemallocator version from 0.7.0 to 0.5.4 under musl target cfg
- Update src/Cargo.lock by adding new crates (anes, block-pseudorand, criterion, plotters, etc.) and updating existing package versions/checksums
2026-11-19 07:10:37 +01:00
Eric Coissac af525cd268 feat: switch musl builds to jemalloc allocator for stability
Update Cargo.lock to remove unused dependencies and update tikv-jemallocator. Configure src/obikmer/Cargo.toml to use jemalloc for static musl builds, addressing fragmentation issues with the default multi-threaded allocator. Update main.rs to conditionally set Jemalloc as the global allocator when targeting musl.

- Remove unused dependencies from Cargo.lock: anes, block-pseudorand, chiapos-chacha8, criterion, criterion-plot, itertools (and its either dep), nanorand, hermit-abi, is-terminal, plotters ecosystem, tinytemplate deps, voracious_radix_sort rayon dep, and web-sys deps.
- Update tikv-jemallocator version from 0.5.4 to 0.7.0 in Cargo.lock.
- Add tikv-jemallocator = "0.7.0" to musl-specific dependencies in src/obikmer/Cargo.toml.
- Set Jemalloc as the global allocator in main.rs for static musl builds.
2026-11-19 07:10:20 +01:00
Eric Coissac d0668eb167 feat: add columnar sparse matrix support and windowed transposition
Introduce `sparse_columnar` and `sparse_intmatrix_columnar` modules to enable
building sparse matrices directly from columnar data without dense intermediates.
Add a `transpose` module with `RowBatch` and `transpose_windows` for efficient
windowed column-to-row transposition based on density checks.

- Add `src/obicompactvec/src/bitmatrix/sparse_columnar.rs` with `build_from_columnar`,
  `build_from_columnar_with`, and `read_bit_window` to build sparse bit matrices
  from columnar files using windowed reads.
- Add `src/obicompactvec/src/sparse_intmatrix_columnar.rs` with `build_from_columnar`,
  `build_from_columnar_with`, `invalid`, and `read_int_window` for integer matrix
  construction from PCIV columns, handling sentinel values and overflow.
- Add `src/obicompactvec/src/transpose.rs` containing `RowBatch<V>` struct and
  `transpose_windows` function for dynamic window sizing and memory-bounded
  column-to-row transposition.
- Update `src/obicompactvec/src/bitmatrix/sparse.rs` to use `packed_bit_matrix_n_cols`
  and `MatrixMeta` for validation, ensuring stale columnar data is transposed directly
  into a single `matrix.pbmx` file while removing old column files.
- Update `src/obicompactvec/src/sparse_intmatrix.rs` to use `packed_int_matrix_n_cols`
  for column count validation, making `pack_sparse_compact_int_matrix` idempotent and
  avoiding dense intermediates by transposing columnar data directly.
- Expose `packed_bit_matrix_n_cols` in `src/obicompactvec/src/bitmatrix/packed.rs` and
  make `packed_int_matrix_n_cols` public in `src/obicompactvec/src/intmatrix.rs`.
- Add `sparse_columnar` module to `src/obicompactvec/src/bitmatrix/mod.rs` and export
  `PersistentBitMatrixBuilder` and `batch_presence_counts`.
- Add `sparse_intmatrix_columnar` and `transpose` modules to `src/obicompactvec/src/lib.rs`.
- Add `transpose_columnar` test module in `src/obicompactvec/src/tests/mod.rs` with
  tests verifying columnar transpose matches dense route output.
2026-11-19 07:08:41 +01:00
Eric Coissac 4e98de4b77 feat: add BitSliceView::for_each_set_in and optimize build_from_dense
Introduce a new `views_scan` module containing `BitSliceView::for_each_set_in`, which iterates over set bits in a specified range using optimized word traversal. Update `build_from_dense` to use this method for batched, ordered column access, ensuring sorted row output. Add comprehensive tests for the new iteration logic and boundary handling.

- Add `src/obicompactvec/src/views_scan.rs` with `BitSliceView::for_each_set_in`, which iterates over a `Range<usize>` calling a closure for each set bit while optimizing sparse traversal via `word.trailing_zeros()`.
- Add `src/obicompactvec/src/tests/views_scan.rs` with tests `words`, `naive`, `scanned`, and helpers verifying that `for_each_set_in` matches naive iteration, handles empty/reversed ranges correctly, and rejects out-of-bounds ranges.
- Modify `build_from_dense` in `src/obicompactvec/src/bitmatrix/sparse.rs` to replace `nonzero_triples` with `dense.col_view(c).for_each_set_in`, ensuring column visits are batched and ordered for sorted row processing.
- Update module structure in `src/obicompactvec/src/lib.rs` and `src/obicompactvec/src/tests/mod.rs` to include the new `views_scan` module.
2026-11-19 07:08:07 +01:00
Eric Coissac 03eaa4544a feat: add pack optimization prompt, debug infrastructure, and monitoring scripts
Add a prompt template for optimizing the `pack` step and a suite of Docker-based
debug tools including build, run, and monitoring scripts. Enhance `pack_matrices`
with LFD partition sizing and detailed timing reports, and update `stop` with
additional system statistics.

- Add `prompts/pack_optimization.md` to guide optimization of the `pack` step,
  specifying context, performance measurements, and deliverable structures.
- Add `scripts/docker_debug/` infrastructure: Dockerfile for musl targets,
  `build.sh` for image creation, `run.sh` for parallel indexing and merging,
  `monitor.sh` for PID tracking, `gen_fasta.py` for synthetic genomes, and
  `gen_fasta_real.py` for real genome generation with `read_fna`.
- Add `scripts/monitor_pack.sh` as a 1 Hz sampler for I/O and memory metrics,
  writing samples to CSV and summary reports.
- Add `scripts/watch_merge.sh` to monitor process resource usage, enforcing
  memory limits via SIGTERM/SIGKILL guards based on VmRSS and VmSize.
- Modify `src/obikindex/src/index/kmer_index.rs`: add `pending_matrix_bytes` and
  `report_pack_timings`; update `pack_matrices` to use LFD strategy for partition
  sizing and clarify documentation regarding `stat()` proxy bytes.
- Modify `src/obisys/src/stage.rs`: update `stop` definition to include new
  variables (`user_secs`, `sys_secs`, faults, context switches, I/O blocks) and
  logic checking for swap usage.
2026-11-19 07:07:50 +01:00
Eric Coissac 24291a4484 refactor: remove unused dependencies and simplify logic
Remove obsolete dependencies across multiple crates to clean up the build graph and update `obikdump` to use `try_update`. Add dev-dependencies for tracing in `obiread` and clarify memoization logic in `obiksession`.

- Remove `obifastwrite`, `tracing`, `obidebruinj`, `obikentropy`, `obipipeline`, `obidex`, and `obiskbuilder` from `Cargo.lock`.
- Remove `obifastwrite` and `tracing` dependencies from `src/obidebruinj/Cargo.toml`.
- Update `dump` function in `src/obikdump/src/dump.rs` to use `try_update` instead of `fetch_update` for updating remaining counts.
- Remove `obitaxonomy`, `obidebruinj`, `obipipeline`, and `obikentropy` dependencies from `src/obikindex/Cargo.toml`.
- Remove `obiksession` dependency from `src/obikmer/Cargo.toml`.
- Remove `obiskbuilder` dependency from `src/obikphylo/Cargo.toml` and update `kodama` version to "0.3.0".
- Remove `bytes` dependency from `src/obikrope/Cargo.toml` and set `criterion2` version to "3" with `cargo_bench_support`.
- Add `tracing` and `tracing-subscriber` as dev-dependencies in `src/obiread/Cargo.toml`.
- Remove `lazy_static` dependency from `src/obiskbuilder/Cargo.toml` and add `obikseq` as a test-utils dev-dependency.
- Clarify `memo_key_from_debug` in `src/obiksession/src/memoize.rs` with comments explaining Debug-derived field usage.
2026-11-19 07:07:16 +01:00
coissac cbc344e4b4 Merge pull request 'Push txuyrtlmyoyl' (#81) from push-txuyrtlmyoyl into main
Reviewed-on: OBIKmers/obikmer#81
2026-11-17 14:38:33 +00:00
Eric Coissac 07bc5fc634 docs: update sparse packing strategy and benchmark scripts
ci.yml / build (pull_request) Successful in 4m53s
Release / create-release (push) Successful in 28s
Release / build-linux-x86_64 (push) Successful in 6m46s
Release / build-macos-arm64 (push) Successful in 4m8s
Update documentation to reflect that sparse packing now maps all columns of a layer at once and packs layers sequentially, reversing the previous choice to avoid materializing a packed copy. This change introduces an extra write/read cycle for the dense matrix, increasing pack benchmark time from 1.11s to 1.60s.

- Modify `pack_sparse_bit_matrix` in `src/obicompactvec/src/bitmatrix/sparse.rs` to always convert via the dense packed format, simplifying logic by removing conditional handling of existing files and ensuring a single mapping.
- Update `pack_sparse_compact_int_matrix` in `src/obicompactvec/src/sparse_intmatrix.rs` to exclusively handle conversion from the dense packed format (`matrix.pcmx`) to sparse, removing columnar format handling and simplifying file cleanup.
- Adjust `scripts/bench_merge_oracle.sh` to extract `PACK_WALL` metrics via `stage_field` for merge operations, updating grep patterns and output messages to report pack wall time.
- Revise `DevDocMD/implementation/merge_mmap_audit.md` and `merge_scaling.md` to document the new sequential packing strategy, noting that `N_part` scaling applies only to incremental merges and that `obisys::MemoryBudget` is no longer used by merge.
- Bump package version in `src/obikmer/Cargo.toml` from 1.4.3 to 1.4.4.
2026-11-17 15:35:41 +01:00
Eric Coissac 1f199c69db feat: implement in-memory column builders and refactor merge partitioning
Introduce `MemBitVecBuilder` and `MemCompactIntVecBuilder` to construct columns in RAM before writing, reducing the number of open file descriptors during merge operations. Refactor `partition_merge.rs` to use these new builders via `add_mem_col`, decoupling live memory mappings from source counts to prevent `SIGBUS` errors.

- Add `mem_builder` module with `MemBitVecBuilder` and `MemCompactIntVecBuilder` structs for in-memory column construction and PCIV file writing.
- Extend `MatrixBuilder` with `add_mem_col` and `n_cols` methods, updating `ColBuilder` enum to support `MemBit` and `MemInt` variants.
- Refactor `partition_merge.rs` to use `add_mem_col` instead of `add_col`, introducing `run_pass2` for batch processing and optimizing destination layer handling.
- Update `format.rs` with `pciv_index_layout`, `write_pciv_header`, and `write_pciv_tail` functions to manage PCIV index layout and header/tail sections.
- Modify `mmap_file.rs` to use `write_std_header` and introduce `write_built` for standardized file writing and flushing logic.
- Make `MAGIC` constant public in `bitvec.rs` and update documentation for memory mapping alignment and structure.
- Add test modules `tests/matrix_builder.rs` and `tests/mem_builder.rs` to verify column counts and byte-identical output of new builders against persistent versions.
- Update `mkdocs.yml` navigation to include "Merge mmap audit (2026-11)" documentation entry.
- Add implementation audit documentation in `DevDocMD/implementation/merge_mmap_audit.md` detailing memory mapping failures and refactoring plans.
- Add merge testing scripts `scripts/smoke_test_merge.sh` and `scripts/bench_merge_oracle.sh` for validation and benchmarking.
- Bump `obikmer` package version from 1.4.2 to 1.4.3 in `Cargo.toml`.
2026-11-17 15:16:41 +01:00
coissac b35127e4e3 Merge pull request 'Push smsmsoyssmnr' (#80) from push-smsmsoyssmnr into main
Reviewed-on: OBIKmers/obikmer#80
2026-11-09 10:01:21 +00:00
Eric Coissac 0134c69cf4 docs: clarify VCF pseudo-alignment format and update obikmer dependency
ci.yml / build (pull_request) Successful in 3m40s
Release / create-release (push) Successful in 1m7s
Release / build-macos-arm64 (push) Successful in 1m52s
Release / build-linux-x86_64 (push) Successful in 6m41s
Update the VCF export documentation to reflect that `-` represents an overlapping deletion (extra allele `*`) and introduce the `<ABS>` symbolic allele for absent families. Add a new dedicated documentation file for the VCF pseudo-alignment format, remove obsolete descriptions from phylo.md, and fix benchmark scripts to handle errors and directory creation correctly.

- Update `obikmer` dependency from 1.4.1 to 1.4.2 in Cargo.toml and Cargo.lock
- Add `UserDocMD/formats/vcf.md` describing VCF pseudo-alignment structure, alleles, and genotypes
- Remove obsolete VCF descriptions from `UserDocMD/usage/phylo.md` and update ploidy/free-loss notes
- Update `DevDocMD/theory/evolutionary_distances.md` to clarify `-` as overlapping deletion and `<ABS>` for others
- Fix `benchmark/index_one_count.sh` to create index directory and check read command errors
- Fix `benchmark/index_one_presence.sh` to create index directory and check simulation errors
- Update `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` to use `<ABS>` for absent families instead of `*`
2026-11-09 20:59:28 +11:00
Eric Coissac 5368c98875 refactor: replace no_ambiguity bool with AmbiguityPolicy enum
Replace the binary `no_ambiguity` flag with an `AmbiguityPolicy` enum (`Keep`, `Forbid`, `OnlyDiploid`) to support multiple ambiguity conventions. This change updates CLI arguments, internal logic, and persistent storage formats to distinguish between keeping all genomes, forbidding ambiguous ones, or restricting analysis to diploid sites only.

- Add `src/obikphylo/src/siblings/ambiguity.rs` defining the `AmbiguityPolicy` enum with variants `Keep`, `Forbid`, and `OnlyDiploid`, including methods for header flags and determining if a genome is dropped.
- Update `PhyloArgs` in `args.rs` to derive `AmbiquityPolicy` from CLI flags and construct `AnnexSelection` for sibling annexes.
- Modify `SamplingSpec` in `subsample.rs` to store `ambiguity: AmbiguityPolicy` instead of `no_ambiguity`, updating masking and scalar value logic accordingly.
- Update `SiblingExt` in `sibling_ext.rs` so `build_sibling_annex` accepts an `AnnexSelection` to build only requested derived annexes, and `family_overlap` uses the specific policy.
- Refactor `FamilyOverlap` in `family_overlap.rs` to store and use `AmbiguityPolicy`, replacing boolean checks with policy-based carrier determination.
- Update `FamilyScalarAnnex` in `family_scalar_annex.rs` to store `AmbiguityPolicy` in headers, enabling distinct file names for each policy variant.
- Modify `quartet_annex.rs` to generate distinct file names based on `AmbiguityPolicy`, ensuring no overlap between Keep, Forbid, and OnlyDiploid annexes.
- Update `family_annexes.rs` to use `AnnexSelection` for building entropy, quartet, and pair weight annexes under specific policies instead of a single boolean convention.
- Refactor algorithm modules (`entropy.rs`, `masking.rs`, `pair_weight.rs`, `quartet.rs`, `snp_distance.rs`) to accept `AmbiguityPolicy` arguments, replacing boolean checks with policy-specific logic (e.g., `OnlyDiploid` masking).
- Update documentation in `phylo.md` and `evolutionary_distances.md` to describe the new `--only-diploid` option, the behavior of `--sibling-annex` with specific policies, and the separate storage of entropies per convention.
2026-11-09 20:59:09 +11:00
Eric Coissac b55123a376 feat: add --only-diploid flag to filter for diploid genotypes only
Introduce a new `--only-diploid` option that restricts analysis to genomes with one or two family members (base or two-base IUPAC codes), treating others as missing data. This complements the existing `--no-ambiguity` behavior by providing a stricter filter for diploid-compatible sites, while ensuring conflict detection between the two flags.

- Add `only_diploid` boolean argument to `PhyloArgs` in `src/obikmer/src/cmd/phylo/args.rs`, documenting its effect on pseudo-alignment and its conflict with `--no-ambiguity`.
- Propagate `only_diploid` through `SamplingSpec` in `src/obikmer/src/cmd/phylo/mod.rs` and update the `run` function signature to accept the new argument.
- Implement masking logic in `src/obikphylo/src/siblings/algorithms/masking.rs`: modify `masked_state` to accept `only_diploid`, add `only_diploid_keeps_up_to_two_members` helper, and update `genome_mask` documentation.
- Update `sample_layer` in `src/obikphylo/src/siblings/algorithms/subsample.rs` to use `spec.only_diploid` for masking decisions and update `SamplingSpec` documentation.
- Adjust `tally_2genomes` in `src/obikphylo/src/siblings/algorithms/snp_distance.rs` to pass the new `only_diploid` parameter to `masked_state`.
- Update `DevDocMD/theory/evolutionary_distances.md` to describe the new `--only-diploid` option, the `masked_state` rule (`count_ones() > 2`), and clarify toy index behavior.
- Update `UserDocMD/usage/phylo.md` to document `--only-diploid`, `--quartet`, and `--pair-balance` behaviors, clarifying that diploid choice is a convention and explaining how three/four-allele genomes are treated as missing.
2026-11-09 20:58:21 +11:00
Eric Coissac b132f0847f feat: add VCF export and refine alignment output infrastructure
Introduce `--vcf` and `--fasta` options for phylo commands, allowing users to
export pseudo-alignment data as VCF or FASTA. Implement comprehensive VCF logic
including stable virtual coordinates, canonical ID generation, and flexible
genotype representation based on ambiguity settings. Refactor internal alignment
structures to track k-mer families and site loci, ensuring consistent data flow
from scanning through to output generation.

- Add `src/obikmer/src/cmd/phylo/alignment_out.rs` with `create` and
  `write_alignment_outputs` to handle file creation and dispatching of FASTA/VCF
  formats based on `PhyloArgs`.
- Add `src/obikphylo/src/siblings/algorithms/alignment_vcf.rs` implementing
  VCF-specific logic: `write_vcf`, `alignment`, `cell_alleles`, `majority_base`,
  and site construction via `site` using fixed $K=11$. Includes helpers for
  IUPAC state inversion, genotype ordering, and stable coordinate generation.
- Update `src/obikmer/src/cmd/phylo/args.rs` to add `fasta` and `vcf` flags
  and a new `alignment_output()` method that returns true if any output format
  is requested. Add `pseudo_alignment` field documentation.
- Modify `src/obikmer/src/cmd/phylo/mod.rs` to use `alignment_output()` for
  determining alignment needs, update error messages for `--n-sites`, and import
  `write_alignment_outputs` from the new module.
- Refactor `src/obikphylo/src/siblings/algorithms/alignment.rs` by adding
  `SiteLocus` struct (partition, layer, family_idx, family_id) and updating
  `SnpAlignment` and `AlignmentReducer` to track sites. Update `new`, `finish`,
  and `reduce` to populate site information from `SurvivingFamily`.
- Update `src/obikphylo/src/siblings/algorithms/iqtree.rs`: `alignment` now
  returns `SnpAlignment` with empty sites; update `drop_ascertainment_noninformative`
  and `recode_symbols_as_absent` to handle the new `sites` field.
- Update `src/obikphylo/src/siblings/algorithms/family_scan.rs`: `GeneratedBatch`
  now includes a `kmers` field; `scan_layer_families` accepts `CanonicalKmer`
  and passes it to closures instead of masks.
- Update `src/obikphylo/src/siblings/algorithms/subsample.rs`: `SurvivingFamily`
  gains a `kmer` field; `sample_layer` closure accepts and uses this k-mer.
- Update `src/obikphylo/src/siblings/algorithms/snp_distance.rs`: `tally_2genomes`
  initializes `SurvivingFamily` with explicit `CanonicalKmer` values.
- Update `src/obikphylo/src/siblings/algorithms/stats.rs`: `sibling_annex_stats`
  signature adds `_kmer` parameter.
- Update `src/obikphylo/src/siblings/algorithms/family_annexes.rs`: closures in
  `ensure_layer_family_annexes` and `ensure_layer_pair_weight_annexes` now accept
  `_kmer`.
- Update `src/obikphylo/src/siblings/algorithms/pairwise.rs`: `ambiguous_vs_single`
  initializes k-mer using `CanonicalKmer::from_raw_unchecked(0)`.
- Add `iupac_state` function to `src/obikphylo/src/siblings/algorithms/masking.rs`
  mapping DNA characters to binary codes.
- Update `src/obikphylo/src/siblings/algorithms/mod.rs` to export `SiteLocus`
  and include new `alignment_vcf` module.
- Add `family_id` and `write_family_id_ascii` methods to
  `src/obikseq/src/kmer.rs` for stable k-mer family identification.
- Add tests `family_id_partitions_kmers_into_families` and
  `family_id_ascii_masks_centre` to `src/obikseq/src/tests/kmer.rs`.
- Update `src/obikphylo/src/siblings/mod.rs` imports to include new algorithm
  exports.
2026-11-09 20:58:05 +11:00
coissac ee62b131f9 Merge pull request 'Push ltpzonnnkpqs' (#79) from push-ltpzonnnkpqs into main
Reviewed-on: OBIKmers/obikmer#79
2026-10-16 14:43:50 +00:00
Eric Coissac 85296a2ef8 Implement directory locking with shared and exclusive modes
Release / create-release (push) Successful in 2m41s
Release / build-linux-x86_64 (push) Successful in 9m17s
Release / build-macos-arm64 (push) Successful in 2m2s
ci.yml / build (pull_request) Successful in 3m48s
Introduces a robust, OS-level directory locking mechanism using LockSlot for managing shared and exclusive access, supporting lock transitions and non-blocking probes. Also sets up the index structure with new builder and index modules.
2026-10-16 16:02:00 +02:00
Eric Coissac 9ac3a37529 Implement explicit directory locking for index operations
Introduces explicit directory locking mechanisms (`DirLock`) to ensure exclusive access during index operations across command stages. This includes modifying index opening logic to acquire locks before proceeding, handling lock acquisition failures by exiting, and implementing safe conditional building of sibling annexes using locking to prevent concurrent corruption.
2026-10-16 16:00:49 +02:00
Eric Coissac 7c7d7615cb Implement sibling annex building and extension logic
This commit introduces the `SiblingBuilder` and `SiblingExt` traits to manage the creation, invalidation, and atomic building of sibling annexes. It also adds new functionality for sampling, statistics, and improved documentation for sibling-related operations.
2026-10-16 15:59:40 +02:00
coissac c6226dd40c Merge pull request 'Push wpvskkyozppn' (#78) from push-wpvskkyozppn into main
Reviewed-on: OBIKmers/obikmer#78
2026-10-15 10:38:58 +00:00
Eric Coissac 8296e3544c Simplify Hybrid layer implementation and update dependencies
Release / create-release (push) Successful in 2m31s
Release / build-linux-x86_64 (push) Successful in 9m24s
Release / build-macos-arm64 (push) Successful in 2m5s
ci.yml / build (pull_request) Successful in 3m51s
Dropped fields related to Hybrid layers for simplification and removed the unused `ahash` dependency. Updated dependency versions for `obidebruinj`, `obikmer`, and related crates, and cleaned up temporary artifacts.
2026-10-15 12:23:15 +02:00
Eric Coissac 12afbe819c Refactor MPHF layer logic and evidence handling
This commit implements core lookup functionality for MPHF layers, including `hash` and `find_strict` methods. It introduces support for different evidence types (Exact, Hybrid, Approximate) within layers, clarifying lookup behavior and improving partition calculation logic in the cache. Additionally, dead code is removed and dependencies are updated.
2026-10-15 12:22:45 +02:00
Eric Coissac f9edefd135 Refactor query system for performance and memory reduction
This change introduces dynamic chunk sizing based on input size estimates, ensuring memory constraints are respected while allowing for smaller chunks that yield significant speed improvements. Additionally, index structures were optimized, resulting in drastic memory footprint reduction and faster query execution times.
2026-10-15 12:21:38 +02:00
Eric Coissac 025c40c0db Refactor chunking logic to enforce 128 k-mer limit
This change reduces the maximum number of k-mers per chunk from 256 to 128. This modification requires updating the data model to handle sequences exceeding this limit by splitting them into overlapping chunks, ensuring no k-mers are lost. Extensive testing has been added to validate the new chunking logic and k-mer constraints.
2026-10-15 12:20:36 +02:00
Eric Coissac 8468319a63 Refactor unitig detection and graph traversal logic
Introduce new hashing mechanisms and support for directional unitig checks. Fix fragmentation issues and improve performance metrics through optimized graph construction and new benchmarking utilities.
2026-10-15 12:19:24 +02:00
Eric Coissac d32d86193f Refactor index metadata loading to use buffered I/O
This change replaces unbuffered file reads with buffered I/O operations to improve performance during index metadata loading. This includes implementing new methods for reading index metadata files and wrapping file handles in `BufReader` to optimize subsequent reads.
2026-10-15 12:17:51 +02:00
Eric Coissac 093d81c359 Introduce memory mapping for index files and sparse matrices
This change implements memory-mapped views for index readers and sparse matrices, enabling shared page-cache access. It also includes performance analysis confirming that the default chunk size cap negatively impacts parallelism for small inputs.
2026-10-15 12:17:09 +02:00
Eric Coissac 09c80468b2 Refactor k-mer storage to use flat arrays
This change replaces the HashMap-based k-mer storage mechanism with a compact, flat array structure for `PartitionKmers`. This significantly reduces memory usage per partition and improves query execution time.

It also updates the batch processing logic to handle the new data structure, introduces detailed memory footprint calculations, and updates relevant query layer APIs. Test coverage has been expanded to validate correct partitioning and k-mer ordering.
2026-10-15 12:16:21 +02:00
Eric Coissac fe38424682 Implement batch lookup and chunked data management
Introduces support for batched MPHF lookups, chunked data handling via `SlottedKmers`, and a comprehensive benchmarking suite to measure performance across the indexing and querying pipeline.

This includes new layer functionality for batch operations, chunking logic in the query layer, and scripts to measure wall time and resource usage for various commands. Documentation related to specific implementation details has also been cleaned up.
2026-10-15 12:14:51 +02:00
Eric Coissac 8b87078478 Implement MPHF migration tool and sparse matrix permutation logic
Refactors sparse matrix handling to implement row permutation logic and introduces a standalone tool for migrating indexes from MPHF 1.x to 2.x formats.
2026-10-15 12:12:51 +02:00
Eric Coissac d686d39506 Refactor indexing logic and update core dependencies
This commit introduces significant updates to the indexing system, including the introduction of zero-copy types, modifications to the `Mphf` type definition, and new hybrid search strategies. Core algorithms are updated to handle new hashing types and improved error handling during pointer hash construction. Dependency versions are also updated across the board, including new security features and system-level crates.
2026-10-15 12:07:08 +02:00
Eric Coissac 3bd7fd4f41 Implement memory mapping for file construction
Refactors the building process to utilize memory mapping (`memmap2`) for file creation and introduces the necessary infrastructure for publishing built files atomically. This includes expanding the public API surface and cleaning up deprecated architectural components.
2026-10-15 12:02:33 +02:00
Eric Coissac c226744405 Refactor sampling algorithms and coverage metrics
Optimize family scanning and sampling plan calculation logic. Introduce new per-genome richness metrics and redefine the sampling fraction $r$ for improved analysis.
2026-10-15 12:01:15 +02:00
Eric Coissac 0e40e83fd1 Refactor probability formula notation
Update the mathematical formula for $P(X \geq r)$ to explicitly use summation notation and clearly format the probability expression.
2026-10-15 12:00:51 +02:00
Eric Coissac cb5fc202b6 Refactor sampling logic and introduce diagnostic outputs
This commit introduces new features for sampling, including detailed `SamplePlan` generation, Shannon entropy summaries, and site statistics reporting. It formalizes conditional distance matrix computation and clarifies the logic for family weighting and site selection.
2026-10-15 12:00:44 +02:00
coissac 2232628e58 Merge pull request 'Push kkkmrtvotrsu' (#77) from push-kkkmrtvotrsu into main
Reviewed-on: OBIKmers/obikmer#77
2026-10-13 07:54:48 +00:00
Eric Coissac f29dcbcfb8 Implement advanced sampling and family annex logic
Release / create-release (push) Successful in 2m35s
Release / build-linux-x86_64 (push) Successful in 8m19s
Release / build-macos-arm64 (push) Successful in 2m3s
ci.yml / build (pull_request) Successful in 4m8s
Introduces complex sampling mechanisms including quartet filtering, pair balance weighting, and entropy bias. Enforces the `--no-ambiguity` convention for family counting and updates annex storage for scalar data.

This includes new logic for calculating family weights based on overlap, quota-based layer determination, and filtering families based on quartet informativeness. Updates also include argument parsing for `--n-sites` and improved handling of family overlap files.
2026-10-13 08:57:18 +02:00
Eric Coissac 0d12494f1a Refactor indexing, sampling, and entropy documentation
This commit introduces new theoretical frameworks for k-mer indexing, pair coverage sampling, and sibling partition unification. It also implements new algorithms for calculating family entropy and statistical tests for overlap analysis. Documentation is updated across the board to reflect these new features and theoretical concepts.
2026-10-13 08:54:21 +02:00
Eric Coissac 95bbc0b2ae Implement sparse matrix optimizations and update architecture documentation
This commit introduces significant functional improvements related to sparse matrix handling, including new storage layers, performance fixes for sparse operations, and bug corrections in matrix logic. Additionally, architectural documentation is cleaned up by removing obsolete entries and modifying structural text related to the Sibling Annex discussion.
2026-10-13 08:52:37 +02:00
Eric Coissac fdfc1eb3dd Refactor siblings module and enhance sampling logic
Introduces filtering for scan families, handles genome exclusion arguments, refactors the `siblings` module architecture, and clarifies invariants for statistical calculations.
2026-10-13 08:45:26 +02:00
Eric Coissac 996ebaf977 Refactor algorithms to use configuration flags
Introduce boolean flags for `AlignmentReducer` and `PairwiseReducer` to control behavior. Update masking logic and introduce the `SurvivingFamily` structure for explicit data handling.
2026-10-13 08:44:19 +02:00
Eric Coissac cd06fa2ce3 Implement masking logic for pairwise reduction
Introduces masking based on `free_loss` and `no_ambiguity` flags within pairwise algorithms. Updates reducer initialization and adds tests to verify cardinality calculation.
2026-10-13 08:43:29 +02:00
Eric Coissac 1702addbf9 Refactor algorithms for unified sampling and reduction
Introduces a unified sampling trunk, new reducer traits, and refined logic for SNP distance calculation and session handling. Enforces strict parameter sharing across all algorithms to ensure consistent sampling.
2026-10-13 08:43:06 +02:00
Eric Coissac 0d1ecac233 Refactor k-mer indexing, enhance session features, and update documentation
This commit introduces significant refinements across the codebase. Core indexing logic is updated with hard constraints on k-mer length, statistical modeling clarifications, and the implementation of the Karlin & Ost theory for chance-collision statistics. Session management features are enhanced with robust memoization capabilities, atomic file operations, per-key locking, and memory mapping support. Additionally, documentation is updated, including a new citation style, and new mathematical notebook support is added.
2026-10-13 08:41:42 +02:00
Eric Coissac e715528d34 Refactor documentation for kmer indexing and phylogenetic models
This commit updates documentation across the board, introducing definitions for kmer constraints, super-kmers, k-mer set distances, SNP models, and sampling design principles. It also clarifies the index construction pipeline and the underlying mathematical models used for genome pair calibration.
2026-10-13 08:38:49 +02:00
Eric Coissac 9da0876ee6 Refactor indexing logic using hash-based minimizer selection.
Updates indexing architecture to use hashing for minimizer distribution and introduces a new hash-based selection mechanism. Additionally, updates documentation references and implements a new script for converting MkDocs into a flat wiki structure.
2026-10-13 08:34:51 +02:00
coissac 755cf85334 Merge pull request 'Push twnyxtspltux' (#76) from push-twnyxtspltux into main
Reviewed-on: OBIKmers/obikmer#76
2026-09-12 05:57:25 +00:00
Eric Coissac 2693a6af09 Implement session persistence and checkpointing
Release / create-release (push) Successful in 2m32s
Release / build-linux-x86_64 (push) Successful in 8m21s
Release / build-macos-arm64 (push) Successful in 2m1s
ci.yml / build (pull_request) Successful in 3m45s
Introduces session persistence via the `--session` option, allowing sampled sets to be restored. Implements chunked dumps and shared checkpointing for alignment and tally artifacts, ensuring state restoration upon interruption. Refines sampling logic and introduces serialization mechanisms for state management.
2026-09-12 07:48:51 +02:00
Eric Coissac 7861e886e7 Introduce session persistence and artifact caching
This change implements a robust session management system allowing users to persist distance calculation samples and parameters across invocations. It includes concurrency-safe directory locking, deterministic parameter encoding, artifact integrity checks, and caching mechanisms to skip resampling when valid data is available.
2026-09-12 07:46:55 +02:00
Eric Coissac a8bcf5ffac Refactor distance matrix calculation logic for consistency
Ensures that combined distance matrix calculations use the exact same site selection by retaining sampled data within Sankoff bundles. This involves refactoring post-sampling logic into shared functions, implementing `SankoffBundle` to reuse internal tally data, and adding validation to guarantee consistent site selection across all distance calculation paths.
2026-09-12 07:45:32 +02:00
Eric Coissac be838da256 Refine theoretical justification for alpha estimation.
Document limitations of various $\alpha$-estimation methods, clarifying that tree-based methods require a tree for accurate heterogeneity estimation and that `PartitionDispersion` avoids violating identifiability requirements.
2026-09-12 07:44:51 +02:00
Eric Coissac 020b391636 Implement gamma shape correction for SNP distance calculation
Introduces support for rate heterogeneity via a Poisson-Gamma mixture model. This includes new command-line options (`--gamma-shape`, `--gamma-shape auto`) to enable automatic estimation of the shape parameter $\alpha$ based on substitution counts across partitions. The correction is applied to the distance metric, with logic to disable the correction if variance checks fail.
2026-09-12 07:44:39 +02:00
coissac e846d35adb Merge pull request 'Feat: Introduce resource profiling and monitoring APIs' (#75) from push-sktolxuyskpp into main
Reviewed-on: OBIKmers/obikmer#75
2026-09-11 07:51:03 +00:00
Eric Coissac c0e1968654 Feat: Introduce resource profiling and monitoring APIs
Release / create-release (push) Successful in 2m27s
ci.yml / build (pull_request) Successful in 3m52s
Release / build-linux-x86_64 (push) Successful in 7m50s
Release / build-macos-arm64 (push) Successful in 2m0s
This change introduces a comprehensive profiling system, allowing for periodic resource usage monitoring (CPU, I/O, memory) via a background thread. It also exposes new public APIs for budget management, locking, NUMA partitioning, and progress tracking.
2026-09-11 09:50:09 +02:00
coissac e280b6d0a3 Merge pull request 'Implement NUMA topology detection and CPU budget capping' (#74) from push-tnkxqmwztnmm into main
Reviewed-on: OBIKmers/obikmer#74
2026-09-11 05:23:42 +00:00
Eric Coissac 98dba1802d Implement NUMA topology detection and CPU budget capping
Release / create-release (push) Successful in 2m30s
ci.yml / build (pull_request) Successful in 3m50s
Release / build-linux-x86_64 (push) Successful in 8m23s
Release / build-macos-arm64 (push) Successful in 1m57s
This change introduces logic to detect NUMA topology, calculate per-node worker limits based on available CPU cores, and cap resource allocation to ensure worker counts respect the physical capacity of each node.
2026-09-11 07:22:35 +02:00
coissac dd4285b269 Merge pull request 'Introduce CPU budget and dynamic thread limiting' (#73) from push-lztkokoxqpuw into main
Reviewed-on: OBIKmers/obikmer#73
2026-09-10 15:10:19 +00:00
Eric Coissac b66a488277 Introduce CPU budget and dynamic thread limiting
Release / create-release (push) Successful in 3m4s
ci.yml / build (pull_request) Successful in 4m17s
Release / build-linux-x86_64 (push) Successful in 8m11s
Release / build-macos-arm64 (push) Successful in 2m2s
This change implements mechanisms to enforce resource limits based on the available CPU budget, including setting a hard CPU ceiling and calculating effective thread counts for CLI, query, and superkmer operations.
2026-09-10 17:08:32 +02:00
Eric Coissac b954032faa chore: remove obsolete configuration and memory files
Deletes unused tool configurations, planning plans, and local memory files across multiple directories.
2026-08-31 09:09:40 +02:00
coissac 43d89d8f02 Merge pull request 'disable default features for obisys dependency' (#72) from push-wvkttrwzkqoo into main
Reviewed-on: OBIKmers/obikmer#72
2026-08-29 06:18:11 +00:00
Eric Coissac 8bb1d52514 disable default features for obisys dependency
Release / create-release (push) Successful in 2m32s
Release / build-linux-x86_64 (push) Successful in 7m57s
Release / build-macos-arm64 (push) Successful in 1m53s
ci.yml / build (pull_request) Successful in 3m42s
Update obisys dependency configuration across multiple crates to explicitly set default-features = false. This restricts compilation to only explicitly enabled feature flags, affecting build resolution and potentially compile-time paths or binary size. Also updates the obikmer package version to 1.3.1.
2026-08-29 08:13:49 +02:00
coissac 77d4429645 Merge pull request 'chore: bump obikmer to 1.3.0 and disable obisys default features' (#71) from push-sllyqzuztwkr into main
Reviewed-on: OBIKmers/obikmer#71
2026-08-29 05:51:37 +00:00
Eric Coissac 4d55258ada chore: bump obikmer to 1.3.0 and disable obisys default features
Release / create-release (push) Successful in 2m32s
Release / build-linux-x86_64 (push) Successful in 8m22s
Release / build-macos-arm64 (push) Failing after 1m15s
ci.yml / build (pull_request) Successful in 3m33s
Updates package version and explicitly disables default features for the local obisys dependency.
2026-08-29 07:46:56 +02:00
coissac 7e28ca4853 Merge pull request 'Push zunrplorkwkt' (#70) from push-zunrplorkwkt into main
Reviewed-on: OBIKmers/obikmer#70
2026-08-28 23:15:37 +00:00
Eric Coissac 52f26809af refactor(benchmark): consolidate generated artifacts under run/ directory
ci.yml / build (pull_request) Successful in 3m49s
Restructure the benchmark pipeline to direct all simulated data, indices, statistics, and query outputs into a unified `run/` directory. Update Makefile targets, shell scripts, and Python utilities to resolve paths relative to this new base. Adjust documentation and dependency tracking to match the revised layout, and remove outdated temporary artifacts.
2026-08-29 00:19:31 +02:00
Eric Coissac 54e4600120 feat: add batched int group stats API and expand benchmark variants
Introduces a `batch_int_group_stats` API for computing presence counts, sums, minimums, and maximums across sparse and dense matrix representations. The selection layer now utilizes this batched approach to optimize aggregation semantics for boolean and numeric operations. Additionally, reorganizes the benchmarking infrastructure to support querying across presence and count index variants in both dense and sparse formats, including new packing scripts and updated statistics aggregation.
2026-08-28 23:37:16 +02:00
Eric Coissac 579cfd8752 docs: document partition runner deadlock fix and select CLI updates
Update documentation to reflect architectural fixes in the NUMA partition runner and implementation changes in the merge and select modules. The partition runner now wraps task execution in `catch_unwind`, emitting panic events that count toward completion thresholds to prevent controller deadlocks, while re-raising the first payload on return. CLI documentation for select has been updated to mandate output directories, introduce default hard-linking with automatic fallback, and document presence aggregation optimizations. Known issues such as self-merge crashes and sparse-packed index gaps are now documented as failing fast due to these improvements.
2026-08-28 23:25:46 +02:00
Eric Coissac 6b0c0867cc implement hybrid hard-link copy strategy for directory bootstrap
Introduces recursive directory replication functions that default to hard-linking for space efficiency, with automatic fallback to full file copying on cross-filesystem failures. Enforces mandatory real copies for presence and counts subdirectories to guarantee independent data matrices before merging, while preserving the existing separation between immutable index files and mutable matrix files.
2026-08-28 23:18:34 +02:00
Eric Coissac 93fe838f97 Remove in-place flag, optimize presence counting, and handle NUMA panics
The `obikmer select` CLI no longer supports in-place index rewriting; the `--output` flag is now required, with benchmarks updated to use temporary directories for atomic replacement. Added `--dense` and `--force-copy` flags. Introduced `batch_presence_counts` to compute presence counts across multiple column groups in a single pass, eliminating redundant I/O. Refactored the aggregation pipeline to branch on layer content, applying the optimized batched counting for `Presence` layers. Enhanced the NUMA runner to catch worker panics, track them, and re-raise after thread join to prevent indefinite blocking.
2026-08-28 23:16:37 +02:00
Eric Coissac 7363370065 feat: add --force-copy flag to copy files instead of hard-linking
Introduces the `--force-copy` CLI argument to bypass hard-linking during selection. When enabled, unchanged kmer-identity files are copied instead of hard-linked to ensure output independence from the source filesystem. The default behavior remains unchanged, continuing to use hard-links with automatic fallback to copying on failure.
2026-08-28 23:08:42 +02:00
Eric Coissac caf59b5658 Update documentation for CLI command renames and new commands
Renames the reindex command to convert across all usage guides and navigation menus. Adds documentation for the newly introduced name-tree command. Updates flag references, such as replacing --metric with --distance in pack and phylo modules, and adjusts MkDocs configuration to match the revised structure. All changes are strictly limited to documentation and configuration files.
2026-08-28 23:06:05 +02:00
Eric Coissac 95fa0c93b2 Rename CLI to obikmer2, add phylo commands, and unify index caching
Restructure the workspace and rename the CLI application to obikmer2. Replace direct KmerIndex usage across all commands with Arc-wrapped IndexCache to enable shared ownership. Introduce builder patterns for algorithmic operations and integrate explicit progress tracking. Add new Phylo, NameTree, and Convert subcommands with expanded CLI flags. Consolidate module structure, update dependency specifications, and remove legacy directories.
2026-08-28 22:34:46 +02:00
Eric Coissac e101f629e6 Add family overlap computation and CLI options for phylo analysis
Extends the entropy annex pipeline to optionally compute family overlap data in a single pass, introducing a memory-mapped binary format and an in-memory accumulator for efficient storage. Adds --min-shared-family to auto-exclude genomes below a threshold during SNP-family distance computation, and --family-overlap to export a shared family matrix as CSV. Centralizes upper-triangle indexing into a shared helper function to eliminate duplication.
2026-08-28 22:03:21 +02:00
Eric Coissac 4f34a646c5 Implement SNP distance models with gamma correction and PHYLIP output
Renames the CLI flag from --metric to --distance and introduces eight closed-form SNP distance models with optional Jin-Nei gamma correction. Integrates the ndarray crate for matrix operations and adds relaxed PHYLIP output formatting. Updates architecture and theory documentation to cover the new sparse matrix variants, algorithmic fixes, and distance metric implementations.
2026-08-28 21:54:19 +02:00
Eric Coissac 0b40d2d0da Add phylogenetic export support for TNT, PhyG, and IQ-TREE
Extends the phylogenetic pipeline with exporters for TNT, PhyG, and IQ-TREE that generate executable scripts, cost matrices, and recoded alignments. Adds internal helpers for state indexing, floating-point matrix scaling, and Floyd-Warshall metric closure to satisfy external tool constraints. Adjusts visibility modifiers for sibling iterators and entropy annex structs, and updates design documentation for evolutionary distance metrics.
2026-08-28 21:32:32 +02:00
Eric Coissac 1536217ac1 feat: add Sankoff cost-matrix calibration CLI and serialization
Introduce the --sankoff flag to generate subsampled calibration bundles and pairwise cost matrices. Expose internal sibling algorithm types as public to support external consumption. Implement YAML, CSV, and FASTA output serialization using serde, gated by a configurable substitution saturation ceiling and requiring the --subsample flag.
2026-08-28 21:19:20 +02:00
Eric Coissac 9043868228 Add single-pass pairwise reduction pipeline for SNP alignment
Replaces the previous two-pass design with a single-pass reduction that computes per-genome-pair substitution counts, cardinality and base-composition tallies, and transition cost matrices. Introduces internal APIs to derive downstream n×n matrices from reduced data and applies configurable filtering based on SNP ratios and exclusion masks. Adds a fused pipeline entry point aggregating alignment and distance outputs for downstream phylogenetic commands. Adjusts visibility of existing reduction functions to restrict external access while permitting sibling module invocation.
2026-08-28 21:10:16 +02:00
Eric Coissac e015362ce6 Refactor sampling and reduction to use batched SurvivingFamily data
Replace per-family callbacks with a per-layer batch callback that accumulates surviving families into an Arc<Vec<SurvivingFamily>>. Update the alignment reduction routine to iterate over this batched structure, enabling zero-copy sharing for parallel operations and structuring the code for future extensibility.
2026-08-28 21:02:35 +02:00
Eric Coissac 89629e118d Add sibling family size distribution statistics and CLI flags
Introduces `--sibling-stats` and `--sibling-hist` flags to compute and export family-size distributions from pre-built annexes. The new algorithms module implements parallel and sequential scanning routines, while the CLI layer handles CSV export with deduplication and standardized error handling.
2026-08-28 20:59:07 +02:00
Eric Coissac beb2951c20 feat: add phylogenetic sampling, masking, and plain FASTA writer
Introduces configurable phylogenetic sampling and masking controls via new CLI flags (`--subsample`, `--entropy`, `--exclude-genome`, etc.). Adds a complete SNP pseudo-alignment pipeline featuring entropy-biased Gaussian sampling, post-hoc state masking, and proportional per-layer filtering. Extends the FASTA writer with a `write_plain_record` API for bare-header output without JSON annotations.
2026-08-28 20:54:51 +02:00
Eric Coissac 5a0b71d105 Add per-family Shannon entropy calculation and reporting
Introduces an entropy.pent persisted format and algorithms to compute per-family Shannon entropy across genomic partitions. Refactors IndexCache to use Arc-based layer sharing for efficient iteration and restructures the siblings module with extension traits for annex generation. Adds a --shannon CLI flag to export partition-level entropy metrics to CSV.
2026-08-28 20:45:47 +02:00
Eric Coissac bbb58a698f Rename SiblingAnnexBuildExt to SiblingExt and add sibling iterators
Refactors the `SiblingAnnexBuildExt` trait to `SiblingExt` across all imports, implementations, and documentation. Introduces new modules for streaming and batched iteration over sibling layers, along with a two-phase pipeline for resolving minorant families.
2026-08-28 20:36:17 +02:00
Eric Coissac 920120d20e Implement --sibling-annex flag and k-mer family annex builder
Introduces a new `--sibling-annex` CLI flag that triggers the construction of a sibling-count/minorant annex for multi-genome indices. The implementation adds a `FamilyMask` data structure with memory-mapped I/O, enabling lock-free concurrent updates via atomic bitwise operations. Batched processing improves cache locality and parallelism, while helper functions derive family presence and minorant flags dynamically. The feature is exposed through an `IndexCache` extension trait, protected by an exclusive directory lock to prevent index corruption during construction.
2026-08-28 20:29:01 +02:00
Eric Coissac d084396aba Introduce concurrency-bounded parallel processing for index cache layers
Implement an `obipipeline::Throttle` with an RAII guard to acquire and release concurrency slots. Expose new bounded parallel methods on `IndexCache` to process cached layers with a configurable cap. Refactor downstream aggregation logic to use single-pass parallel map-reduce instead of manual collect-map-reduce sequences, enforcing a maximum of 8 concurrent layer scans to bound memory usage.
2026-08-28 20:20:12 +02:00
Eric Coissac 9dee6dcd08 refactor: decouple tree construction from Newick serialization
Refactor phylogenetic algorithms (`neighbor_joining`, `upgma`) to return an explicit `Tree` struct instead of a serialized Newick string. This change makes serialization an explicit step for downstream consumers via the new public `Tree::to_newick()` method, decoupling tree construction from output formatting. The `siblings` module has also been moved to `siblings_old`.
2026-08-28 20:15:23 +02:00
Eric Coissac 635fc830d1 feat: add phylogenetic analysis CLI command and lazy distance traits
Introduce the `obikphylo` crate to support genome-vs-genome distance matrix computation and phylogenetic tree inference via Neighbor-Joining and UPGMA algorithms. Extend the `obikmer2` CLI with a new `phylo` command that exposes configurable metrics, presence thresholds, and CSV/Newick output options. Refactor `obikindex` to expose trait-based partial aggregation for efficient distance metric finalization without full matrix materialization. Update dependency graphs and remove obsolete storage modules.
2026-08-28 20:11:13 +02:00
Eric Coissac 4b6005962e Rename PersistentCompactIntMatrix to PersistentIntMatrix
Update all matrix type references, imports, and instantiations across
the codebase to use the new PersistentIntMatrix name. The change also
includes standardizing code formatting, such as multi-line statements
and import ordering, without altering any behavioral logic or public
API contracts.
2026-08-28 19:59:59 +02:00
Eric Coissac 6bdc9354d3 refactor: restructure obikphylo module layout and adjust visibility
Relocate cardcomp into the siblings directory and update internal import paths to reflect the new hierarchy. Adjust the crate's public API surface by updating module declarations and re-exports. This is a purely structural change with no modifications to logic, data models, or runtime behavior.
2026-08-28 19:46:09 +02:00
Eric Coissac 4ea3cd32ba feat: add convert command for in-place index evidence modification
Introduce a new CLI command that modifies existing indices to support exact, approximate, or hybrid evidence modes. This change enables the reindex module in obikrebuild, exposing an IndexReindex trait for evidence persistence and layer processing. It also refactors obikindexer to publicly expose an IndexBuilder trait for post-build evidence construction, while adding a set_evidence API in obikindex to safely update configuration fields without altering core parameters.
2026-08-28 19:43:14 +02:00
Eric Coissac bd7729b095 refactor: Shift KmerIndex ownership to Arc for thread-safe sharing
Replaces lifetime-bound references with runtime reference counting across multiple crates. This enables safe concurrent access across parallel workers without explicit cloning or manual lifetime management. Introduces the `query` and `utils` CLI commands in obikmer2, along with supporting modules for batch processing, sparse indexing, sliding-window findere logic, and output formatting. Updates dependency manifests and aligns test suites with the new ownership model.
2026-08-28 19:32:45 +02:00
Eric Coissac 10a0909687 refactor: unify iterator construction in nonzero_iter
Change the return type of `nonzero_iter` from an opaque `impl Iterator` to a `Box<dyn Iterator>`. This enables direct return coercion in the `Count` layer branch, removing an explicit `Box::new()` wrapper and aligning it with the existing `Presence` implementation. The modification shifts iterator construction to runtime dynamic dispatch while preserving the public API contract and iteration semantics.
2026-08-28 19:08:55 +02:00
Eric Coissac b0890d1781 Add sparse storage variant to PersistentCompactIntMatrix
Introduce a new `Sparse` format alongside existing `Columnar` and `Packed` variants, enabling optimized row-major pairwise counting for distance and similarity metrics via the `CountPartials` trait. Update storage detection priorities, extend matrix dispatch logic to sparse backends, and correct diagonal/off-diagonal formulas in bit matrix partial computations. Expand layer APIs with format-agnostic `nonzero_iter`, update usage documentation for the `--sparse` flag, and add comprehensive tests verifying roundtrip integrity and metric equivalence against dense implementations.
2026-08-28 19:06:39 +02:00
Eric Coissac 904d85f33b Implement pack CLI command for matrix packing and layer compaction
Adds the `pack` subcommand to `obikmer2` for persisting presence and count matrices in sparse or dense formats. Introduces the `compact_layer` module in `obikrebuild` to merge multiple partition layers into a single layer in-place via atomic operations. Updates dependencies across `obikdump`, `obikmer2`, and `obikrebuild` to resolve new local crate references. Shifts the architecture from multi-layer accumulation to in-place compaction, removing legacy rebuild modules.
2026-08-26 14:48:44 +02:00
Eric Coissac 96dfb5300b Add unitig extraction command to obikdump and obikmer2
Introduces a new unitig extraction feature that reads k-mers from an index, filters them by group metadata, and partitions the computation using rayon. The implementation constructs per-partition de Bruijn graphs, merges them, computes node degrees, and writes the resulting sequences as FASTA. A corresponding CLI command is added to obikmer2 to expose this functionality with configurable filtering and progress reporting.
2026-08-26 14:40:02 +02:00
Eric Coissac 768fa0183d Add dump subcommand and introduce reusable group filtering arguments
Introduces a new `dump` CLI command to export index k-mers as a CSV table. Adds a reusable `GroupFilterArgs` struct for ingroup/outgroup metadata-predicate quorum filtering with configurable count and fraction thresholds. Refactors the filter command to use explicit flags and a `GenomeSelector`-based pipeline, improving error handling and predicate application order. Exposes `IndexDump` from the `obikdump` crate and updates local dependencies accordingly.
2026-08-26 14:33:45 +02:00
Eric Coissac 737966899f Add obikselect crate for k-mer selection and aggregation
Introduces a new `obikselect` module to handle k-mer selection and column aggregation. Adds a `select` CLI command in `obikmer2` that supports group predicates, aggregate operators, and output column filtering. Implements operator parsing with case-insensitive matching and default rules, along with a centralized module for resolving group specifications from metadata or genome filters. Updates dependencies to include the new crate and its prerequisites.
2026-08-26 14:27:19 +02:00
Eric Coissac 354e6f9bf1 Add unified matrix builder abstraction and k-mer filtering CLI
Introduces a unified MatrixBuilder abstraction for persistent bit and integer matrices, replacing custom dispatch enums and boolean flags across consumers. Refactors index, merge, and select layers to adopt explicit merge modes and centralized lifecycle management. Adds a complete k-mer filtering implementation with partition-level processing, progress tracking, and a new CLI subcommand supporting configurable predicates and thresholds.
2026-08-26 14:19:15 +02:00
Eric Coissac b7a8b5e6cf feat: add sparse compact integer matrix implementation and utilities
Introduces `PersistentSparseCompactIntMatrix`, a row-major sparse integer matrix combining a bitmatrix support layer with dual value streams for singleton and multi partitions. Adds builder and packing utilities to convert dense count matrices into the new on-disk format, featuring idempotency guards and crash-safe persistence workflows. Exposes core accessors, iterators, and column weight calculations while adjusting internal visibility for companion modules. Includes unit tests and diagnostic examples to validate equivalence with dense representations and measure compaction metrics.
2026-08-26 14:05:54 +02:00
Eric Coissac 294f132a0a refactor: relocate partition iterator and expose graph builder API
Move the partition iterator implementation from obikdump to obikfilter, updating imports and exposing the type publicly. Add obikidxcache as a local dependency for obikfilter. In obikindexer, expose the new build_layer_from_kmers function to enable shared graph-building logic across pipelines without code duplication.
2026-08-26 09:39:02 +02:00
Eric Coissac 16ade823d6 refactor: extract partition iteration and unify group selection
Move partition iteration logic to obikdump, introducing a FilteredPartitionIter trait over IndexCache for batch-oriented scanning with configurable data retrieval and early termination. Consolidate ingroup and outgroup index storage in GroupQuorumFilter into a unified Selection struct driven by predicate matching. Update dependency manifests to include obikidxcache, rayon, and obikentropy, and remove the deprecated dump_layer module while adjusting public API re-exports.
2026-08-26 09:33:37 +02:00
Eric Coissac 881b1532b5 refactor: consolidate mmap file operations into shared helper functions
Extracts file creation, opening, and memory mapping logic into a new `mmap_file` module. This replaces repetitive unsafe operations across persistent data structures with standardized helper functions, ensuring consistent header validation, error handling, and data layout while keeping public APIs unchanged.
2026-08-26 09:26:49 +02:00
Eric Coissac ad0b7173a3 Add select0 method and expand Elias-Fano query API
Update PersistentSparseBitMatrix documentation for clarity. Introduce select0 to the rank/select module, and add next_geq, contains, successor, and predecessor methods to the Elias-Fano implementation. Include naive reference implementations and unit tests to validate correctness and boundary conditions for all new APIs. All changes are strictly additive.
2026-08-26 09:21:52 +02:00
Eric Coissac 5dc16b0127 refactor(obikselect): implement Algorithm trait for selection
Shifts the selection logic from a direct method into a dedicated `Select` struct implementing the `Algorithm` trait. Introduces a two-phase initialization pattern with explicit builder methods and closure-based progress callbacks. Updates the crate's dependency graph to include `obikalgorithm`, refactors layer processing with unified matrix dispatch, and implements dual directory routing for partition execution.
2026-08-26 09:17:48 +02:00
Eric Coissac cbf6893f38 Add configurable sparsity flag to index finalization and merge CLI
Extends `KmerIndex::finalize_indexed` to accept a `sparse` boolean parameter, enabling control over whether output presence matrices are packed in a compact sparse format or stored densely. The merge command now exposes a `--dense` flag to invert this setting, defaulting to the existing sparse representation. Call sites in select and rebuild modules pass `false` to preserve current behavior. A benchmark lock file is also added for dependency tracking.
2026-08-22 17:36:50 +02:00
Eric Coissac bb380d0c7d Add sorted_slots parameter to nonzero_triples and batch build_from_dense
Extended `nonzero_triples` with a boolean flag to conditionally skip sorting when input slots are already ordered. Updated call sites to pass appropriate flags, enabling a single-pass columnar traversal in the sparse matrix builder. Refactored `build_from_dense` into a batched processing pipeline that reduces repeated file access and improves sequential read performance. Added a diagnostic example to validate the new builder against existing dense matrices.
2026-08-22 17:33:07 +02:00
Eric Coissac 23812d1af8 feat: add col_weights API and refactor obikstats to use Algorithm trait
Added a `col_weights` method to index layers for computing per-genome column sums or presence k-mer counts. Refactored `obikstats` to implement the `Algorithm` trait with a two-phase `new`/`run` model, replacing manual layer resolution with `IndexCache` for eager file I/O. Simplified per-genome counting logic and updated public exports and dependencies accordingly.
2026-08-22 17:28:51 +02:00
Eric Coissac fba9c65b1a feat: add annotate CLI command for applying genome metadata via CSV
Introduces the `annotate` subcommand to apply genome metadata from an external CSV file to a pre-built k-mer index. The command supports configurable field separators, ID columns, and null markers, while providing a `--dump` option to export current index metadata as sorted CSV. Supporting changes include minor internal refactoring in `obikindex` to use object-level directory accessors and updates to the `csv` dependency.
2026-08-22 17:23:39 +02:00
Eric Coissac fb31a35c76 Add unitig streaming iterators and estimate CLI subcommand
Introduce `iter_unitigs` methods across the index cache, content layer, MphfLayer, and typed layer to stream whole reconstructed sequences directly from underlying storage without decomposing into k-mers. Add a corresponding low-level streaming iterator in obiskio for thread-safe, lazy reads from memory-mapped files. Include a new CLI subcommand to compute and display approximate false-positive rates based on provided indexing parameters.
2026-08-22 17:14:07 +02:00
Eric Coissac 5048f43eea Start of a huge refactoring 2026-08-22 17:03:53 +02:00
Eric Coissac 1261aeba86 feat: Add superkmer CLI subcommand to obikmer2
Introduces a new `superkmer` command that implements a multi-stage pipeline for reading nucleotide pages and constructing superkmers with configurable parameters. The implementation uses partition-aware scatter writing via `obifastwrite` to distribute output batches across workers, and adds the necessary local dependencies to the project manifest.
2026-08-22 14:08:40 +02:00
Eric Coissac 7183e3adb4 Add directory-level locking and introduce layered index cache
Introduces directory-level locking to prevent concurrent index operations from corrupting shared directories, along with explicit APIs for acquiring, probing, and releasing locks. Restructures the index cache crate to use a layered store architecture that eagerly initializes metadata and provides fast hierarchical lookups. Updates dependent modules, test suites, and CLI commands to align with the refactored API surface, and adds an end-to-end smoke test for validation.
2026-08-22 14:04:46 +02:00
Eric Coissac 2419a6c21d refactor: shift indexing algorithms to layer-centric partition APIs
Replaces manual filesystem path handling and parallel iteration with dedicated internal utilities. Introduces `par_over_layer0` and `layer0()` to abstract partition layer access, enabling partition-driven initialization and centralized progress tracking. Removes disabled or internal methods (`rewrite_config`, `open_data`) no longer part of the active interface. Updates error propagation and metadata persistence to align with the new layer-centric workflow.
2026-08-22 13:51:42 +02:00
Eric Coissac fc4464a0ef Extract index modules into specialized workspace subcrates
This commit partitions the obikindex crate into multiple focused subcrates (obikfilter, obikmerge, obikquery, obikrebuild, obikselect, obikstats, obikdump, and obikidxcache) to reduce coupling and clarify module boundaries. It standardizes error handling across the workspace using OKIError and OKIResult, updates index APIs to support lazy, disk-backed partition access, and migrates NUMA system utilities to a new obisys crate. All modifications are structural, focusing on dependency graph expansion, import path updates, and API surface reorganization without altering core runtime behavior.
2026-08-22 06:25:28 +02:00
Eric Coissac c9d10d55c7 Simplify MphfLayer::open by removing explicit IndexMode parameter
The MphfLayer::open signature now accepts only a directory path. Mode configuration is resolved internally via disk-based auto-detection using LayerEvidence, eliminating the need for explicit arguments from callers. All internal query methods and external call sites have been updated accordingly, while TypedLayer::open temporarily retains the unused parameter for future cleanup.
2026-08-21 22:08:52 +02:00
Eric Coissac 00ba968628 Introduce obikalgorithm crate to unify pipeline algorithms
Define a shared Algorithm trait with an associated Output type and a parameterless run(&mut self) method. Refactor PartitionRouter, Dereplicator, Counter, and LayerBuilder to implement the trait, standardizing receivers to &mut self and moving configuration and progress callbacks to dedicated builder setters. Decouple error handling using a generic boxed error type and update workspace dependencies accordingly.
2026-08-21 22:03:08 +02:00
Eric Coissac 8d6ba6546b refactor: migrate index metadata to on-disk JSON with fallible access
Migrate index state tracking from filesystem sentinel files to an on-disk JSON schema within `index.meta`. The `IndexMeta` struct is now wrapped in an `Arc` with internal locking, exposing only fallible methods for genome and state access. In-memory mutation capabilities have been removed, requiring callers to handle I/O errors explicitly and pass immutable references to downstream components like `PartitionRouter`. Public sentinel constants have been removed from exports.
2026-08-21 21:51:42 +02:00
Eric Coissac 02dbdd11aa Split index lifecycle into IndexBuilder trait for maintenance operations
Extracts directory bookkeeping and construction methods into a new IndexBuilder trait, separating maintenance operations from scientific computation logic. Migrates relevant methods to the new trait, updates module imports across obikindex, and narrows the crate's public API surface. Adds an end-to-end CLI smoke test to verify multi-index merge workflows.
2026-08-21 10:46:57 +02:00
Eric Coissac da3aa5a2cb refactor: extract index construction state tracking into extension trait
Moves pipeline state bookkeeping, including sentinel file marking and spectrum persistence, into the algorithms' run and close methods. Introduces a crate-private extension trait to satisfy Rust's orphan rule while implementing construction-only operations on KmerIndex. Updates helper function visibility for cross-crate access and removes the now-empty index_layer module.
2026-08-21 10:38:51 +02:00
Eric Coissac 31bb324752 Rename Layer to KmerLayer across obikindex and obikphylo
This commit renames the `Layer` type to `KmerLayer` throughout the `obikindex` and `obikphylo` crates. All imports, struct fields, function signatures, pattern matches, and instantiation calls have been updated accordingly. The change is a purely structural refactor that tightens type constraints without altering runtime behavior or data models.
2026-08-21 10:27:29 +02:00
Eric Coissac 4b7b3c3c1a Extract indexing stage into LayerBuilder with NUMA-aware scheduling
Introduce a dedicated LayerBuilder struct to orchestrate parallel layer 0 construction across partitions. The fluent API supports configurable abundance thresholds and intermediate artifact retention. Parallel execution is delegated to a NUMA-aware PartitionRunner scheduler, while progress reporting and stage timing are shifted to the command layer. A new mark_indexed method cleanly separates state tracking from orchestration by generating a completion sentinel.
2026-08-21 10:20:03 +02:00
Eric Coissac 346095b9eb Rename index methods to hash and expose kmer iteration APIs
The layer API has been updated to rename `index` and `index_batch` to `hash` and `hash_batch`, aligning with raw MPHF slot hashing behavior. New public methods have been added to directly expose kmer hashing and iteration, enforcing strict state validation on empty layers. All other modifications are consistent code formatting adjustments without functional changes.
2026-08-21 10:14:22 +02:00
Eric Coissac 0299b608e2 chore: remove CLAUDE.md and update .gitignore
Removes the file from version control and adds an ignore rule to prevent tracking.
2026-08-21 06:03:58 +02:00
Eric Coissac 878b63566f Extract k-mer counting logic into a dedicated counter module
Decouple k-mer counting from the partitioner by introducing a new `Counter` struct. The module exposes a fluent builder API with optional partial file retention, executes partition processing in parallel via Rayon with memory-aware chunk sizing, and integrates thread-safe progress callbacks. Update all callers to use the new counter, simplify test pipelines by removing serialization overhead, and clarify algorithm separation in module documentation.
2026-08-21 05:48:02 +02:00
Eric Coissac 96b6517541 refactor: rename obikindex to obikindexer 2026-08-21 05:29:34 +02:00
Eric Coissac 5c1584967f feat: enable index resumption and enforce directory creation
The command now supports reopening existing indexes instead of failing when the output file exists. Control flow branches between opening an existing index and constructing a new one, moving configuration setup exclusively to the creation path. Directory existence is enforced upfront with proper I/O error propagation. The --force flag retains its original semantics by removing the target directory before proceeding with a fresh build.
2026-08-21 05:06:38 +02:00
Eric Coissac abc51c2add Extract dereplication logic into obikderep crate and centralize paths
Move partition dereplication logic into a dedicated `obikderep` crate that implements a two-phase hash-split/merge strategy with Rayon for parallel processing. Centralize superkmer file path construction in `obilayeredmap` and update dependent crates to use the new pipeline and shared path helpers. Adjust test suites to explicitly invoke the dereplication step.
2026-08-20 22:30:03 +02:00
Eric Coissac 616cb76af3 Refactor indexing pipeline and partition path resolution
Invert dependencies by moving partition path primitives to a dedicated module and updating the index crate accordingly. Reshape the partition router to accept a mutable index reference, enabling chainable configuration and resolving lifetime issues with explicit drops. Shift orchestration logic from the index crate to the CLI, replacing monolithic scatter calls with discrete dereplication and counting steps. Introduce a generic progress callback API to decouple rate calculation from UI rendering, and correct file I/O paths to route layer-0 artifacts under the partition index directory.
2026-08-20 22:15:13 +02:00
Eric Coissac 164e879585 feat: introduce obikpartition crate for kmer partition layer lookup
Introduces the `obikpartition` crate containing the `KmerPartition` struct to manage open layers in sequential order. The `open` constructor eagerly initializes layers under a specified directory, while the `find` method returns the index of the first layer containing a given k-mer. Dependencies are strictly scoped to `obilayeredmap` and `obikseq`, with unit tests validating layer ingestion and single-kmer lookup behavior. Batch lookups and further migration are deferred to a subsequent phase.
2026-08-20 20:47:20 +02:00
Eric Coissac c4b69e1af5 Introduce lifecycle-aware Layer::Empty variant and update callers
The `Layer` enum is transformed into a lifecycle-aware state machine with an `Empty` variant representing an unconstructed directory. Read and query operations now explicitly panic when invoked on this state, enforcing explicit progression through `create()` before use. Iterator methods are updated to handle the new variant exhaustively, and module visibility constants are adjusted to support the refactored structure.
2026-08-20 20:41:48 +02:00
Eric Coissac 1c54e60c9a Rename Layer<D> to TypedLayer and introduce heterogeneous Layer enum
Renames `Layer<D>` to `TypedLayer<D>` to establish a distinct typed abstraction. Introduces a new heterogeneous `Layer` enum that unifies count and presence storage with runtime dispatch, delegating operations to the underlying typed variants. Updates cache, index, and phylo consumers to align with the renamed type and new extension traits, preserving full test suite stability while preparing the foundation for multi-partition caching.
2026-08-20 20:35:29 +02:00
Eric Coissac 6c860f120f refactor: merge KmerPartitions into KmerIndex and rename obikpartition
Consolidates partition logic, metadata storage, and layer management directly into KmerIndex. Renames obikpartitionner to obikpartition, retaining only PartitionRouter for superkmer routing. Removes intermediate .partition() accessors in favor of direct methods on the index and updates PartitionCache::build to accept &KmerIndex directly. Derives n_partitions from config.n_bits and consolidates k-mer/minimizer sizes into IndexMeta.config. Fixes a regression where PartitionRouter::open incorrectly defaulted to closed.
2026-08-20 20:23:58 +02:00
Eric Coissac b5ec0122d0 Rename obikpartition crate to obikpartitionner
Update all dependent crates and internal imports to reference the renamed module. Expose configuration parameters and genome metadata through new public accessor methods in the index API, and update documentation comments to align with the new package name.
2026-08-20 19:43:00 +02:00
Eric Coissac f64ac14f0e chore: make COUNTS_DIR constant pub(crate)
Adjusts the visibility of the COUNTS_DIR constant to pub(crate), enabling internal crate-wide access without altering runtime behavior or data structures.
2026-08-20 16:42:43 +02:00
Eric Coissac 9379bbaad8 refactor: rename obikpartitionner crate to obikpartition
Update Cargo manifests, dependency paths, and Rust imports across the workspace to reflect the `obikpartitionner` to `obikpartition` rename. Synchronize architecture and implementation documentation with the new module structure. Fix minor syntax issues in test assertions to ensure compilation compatibility. No behavioral or API changes are introduced.
2026-08-20 16:41:22 +02:00
Eric Coissac f9ef6b8391 rename KmerPartition to KmerPartitions and update Mat enum
Rename the KmerPartition type to KmerPartitions across obikindex, obikpartitionner, and obikphylo/siblings to reflect an updated data model. Update the Mat enum in siblings/cache.rs to add a SparsePresence variant and simplify opening logic by delegating sparse versus dense detection to PersistentBitMatrix. Apply consistent code formatting, import reordering, and multi-line refactoring throughout the affected modules.
2026-08-20 15:57:33 +02:00
Eric Coissac 76cbd3a886 Centralize partition metadata access and add layer introspection APIs
Replaced scattered direct metadata loading with centralized instance methods on `KmerPartition` to guarantee consistent error mapping and legacy recovery. Introduced `StorageKind`, `LayerContent`, and `EvidenceKind` enums alongside lightweight disk-probe methods that inspect file presence without opening heavy data structures. Updated callers across the index, partitioner, and phylo modules to use the new partition API, and added unit tests validating the introspection behavior.
2026-08-20 15:29:53 +02:00
Eric Coissac f7ebc7a1ab Centralize partition directory resolution and add caching design spec
Introduce a design specification outlining performance bottlenecks in layer data access and an agreed-upon implementation direction for caching. Refactor the codebase to centralize index and layer directory path resolution within the partition object, replacing manual string joining and external helper functions with dedicated accessor methods.
2026-08-20 15:10:57 +02:00
Eric Coissac 7eaa8c2016 Replace manual layer path construction with obilayeredmap::layer_dir
Standardizes layer directory path resolution across obikindex, obikpartitionner, and obikphylo by replacing inline string formatting and join calls with the centralized obilayeredmap::layer_dir utility. This refactoring removes redundant path construction logic while preserving existing iteration bounds, control flow, and public APIs.
2026-08-20 14:54:13 +02:00
Eric Coissac 5a91817488 centralize layer path construction and data loading
Replace manual directory formatting and inline matrix opening with the newly introduced `layer_dir` and `open_data` helpers from the `obilayeredmap` crate. This standardizes filesystem access, encapsulates layer naming conventions, and simplifies error handling without altering computational behavior or test suites.
2026-08-20 14:43:10 +02:00
Eric Coissac 640f29725b Optimize sparse bit matrix packing to avoid intermediate copies
Refactor `pack_sparse_bit_matrix` to conditionally open either a packed or columnar dense representation based on file existence. This eliminates the previous unconditional pre-conversion step that forced a full packed copy. Update cleanup logic and add tests to verify direct transposition, proper file handling, and idempotency for both formats.
2026-08-20 14:38:20 +02:00
Eric Coissac c2e0533fa9 Refactor bit matrix operations and optimize distance computations
Consolidate row extraction and parallel column reduction into reusable generic utilities within the pairwise module. Replace manual iteration in builder and view methods with iterator-based zipped loops and deferred overflow processing to improve memory access patterns. Optimize distance functions by switching to bulk byte passes for branch-free SIMD vectorization, adding a merge-like helper to correct masked overflow values without secondary allocations. Add a comprehensive test validating the optimized distance paths against naive references across multiple thresholds and overflow scenarios.
2026-08-20 14:35:22 +02:00
Eric Coissac 9abee87af3 refactor: delegate distance computations and simplify matrix logic
Consolidate bit matrix operations by delegating pairwise metric calculations to IntSliceView and col_view implementations. Introduce chunked_presence_count in colgroup to handle threshold-based accumulation efficiently. Add a direct point lookup method to the sparse matrix representation to eliminate buffer allocations, and simplify match arms in persistent accessors accordingly. All public APIs and behavioral contracts remain unchanged.
2026-08-20 14:27:32 +02:00
Eric Coissac 19f9954050 refactor: centralize nonzero slot iteration logic across views
Extract duplicated traversal logic into a shared `NonzeroSlotsView` trait and `nonzero_triples` helper. Update slice view iterators to consistently yield `(position, value)` tuples and use a temporary buffer with explicit permutation mapping for sorted access. Delegate manual slot sorting and column iteration to the new shared helper, eliminating per-format duplication and eager collection while preserving existing public API signatures.
2026-08-20 14:20:24 +02:00
Eric Coissac 82374deca5 refactor: simplify sub_matrix with iterator-driven column population
Refactored `sub_matrix` to delegate column population to `fill_sub_matrix`, replacing manual buffer allocation and explicit permutation loops with direct value assignment via `enumerate_slots_values`. This eliminates intermediate allocations, reduces pipeline overhead, and simplifies control flow while preserving slot ordering and permutation semantics.
2026-08-20 14:17:05 +02:00
Eric Coissac ac38aa759b refactor: rename batch retrieval methods and update common_traits
Renames `get_batch`, `fill_batch`, and `fill_batch_sorted` to `collect_slots_values`, `fill_slots_values`, and `fill_slots_values_sorted` to align with updated `common_traits 0.13` APIs. Introduces optimized batch retrieval that sorts input indices for sequential mmap access before reordering outputs to match the original query order. Updates test suites to reflect the new method signatures without altering validation logic or coverage.
2026-08-20 14:15:28 +02:00
Eric Coissac 82ddeaddcd Introduce unified nonzero_iter API across matrix types
Replaces nested column-major point lookups with a batched iterator that delegates to format-native traversal strategies. The implementation enforces a single pass per matrix type, using row-major iteration for sparse formats and eager collection for packed/columnar layouts while preserving original slot ordering. Memory allocation is optimized by removing `n_cols`-wide buffers in favor of per-row buffering or lazy iteration. Correctness tests verify iterator output against dense baselines across all supported layouts, and architecture documentation is updated to reflect the new format-agnostic query pattern.
2026-08-20 14:07:09 +02:00
Eric Coissac a4eb20e67e add some doc about optimisation for query 2026-08-20 13:59:12 +02:00
Eric Coissac 89ea077456 Add benchmark pipeline for dense and sparse query testing
Introduces a complete query benchmark track to evaluate performance and verify consistency between dense and sparse index formats. Adds scripts to simulate fixed-size paired-end reads, pack a sparse presence index, execute queries in both modes, and capture wall time and RSS metrics. Includes a verification step that compares outputs by read ID to ensure content identity across parallel processing. Updates build configuration, documentation, and ignore patterns to support the new pipeline for two microbial specimens.
2026-08-20 13:59:12 +02:00
Eric Coissac 5a9d903e51 chore: update dependencies and adapt to updated crate APIs
Bumps core dependencies including ndarray, rand, hashbrown, niffler, ureq, sysinfo, indicatif, lru, and remove_dir_all. Adapts source code to accommodate breaking changes by migrating RNG initialization, adjusting HTTP response handling, and replacing the fs4 crate with standard library file locking. Adds a planning document for query benchmarking and sparse index regression tests.
2026-08-20 13:45:41 +02:00
Eric Coissac 32bcbd1465 chore(deps): update dependencies and clean up imports
Updated core libraries and ecosystem packages, including the full serde suite and regex dependencies. Restructured syn dependency resolution by pinning 2.0.117 while introducing a standalone 3.0.3 entry for derive macros. Downgraded windows-sys to 0.59.0 and replaced the anes dependency in criterion2 with bpaf and walkdir. Removed an unused IntSliceView import from test modules.
2026-08-20 13:25:35 +02:00
Eric Coissac 0da725ffe9 refine k-mer index architecture documentation and remove obsolete spec
Introduces raw mapping and iteration APIs that bypass membership checks, clarifies variant-specific storage layouts and auto-detection logic, and documents optimized batch access patterns with caller-provided buffers. Removes the outdated obicompactvector_reflexion.md specification to consolidate architectural details into current implementation docs.
2026-08-20 13:20:29 +02:00
Eric Coissac 3b65319529 Remove precomputed data assets, configurations, and documentation
This change removes precomputed model parameters, phylogenetic tree datasets, k-mer spectrum data, and compressed profile archives. It also deletes runtime logs and detailed pipeline documentation. The repository ignore list is updated to exclude the sandbox directory.
2026-08-20 13:15:56 +02:00
Eric Coissac 69747dcb53 chore: add editor and memory directory patterns to .gitignore 2026-08-20 12:50:54 +02:00
Eric Coissac 2dba217482 chore: remove src/profile.json.gz
Removes the compressed JSON archive containing profile configuration and data model definitions. Build processes and runtime loaders referencing this path will require updates to prevent missing file errors.
2026-08-20 12:49:48 +02:00
Eric Coissac dbd8af376c Consolidate compare_sparse as example and clean up project artifacts
Restructure the project by moving the standalone compare_sparse utility into an example directory, removing Sankoff parameter configurations and benchmark scripts, updating version control ignores, and expanding the test suite with diagnostic checks and performance benchmarks.
2026-08-20 12:48:42 +02:00
Eric Coissac dc3d82f8db Add resume API to persistent matrix builders for incremental appending
Introduce a `resume` method for persistent bit and int matrix builders to restore dimensions from persisted metadata. This enables incremental column appending across separate build sessions without requiring manual dimension tracking. Consolidate builder lifecycle management in the merge layer using a unified `MatrixBuilder` enum, simplify closure logic, and add instrumentation. Include tests verifying state preservation and data integrity across multiple resume cycles.
2026-08-20 12:36:47 +02:00
Eric Coissac 308d2b9f92 chore(deps): bump obikmer dependency to 1.2.2
Update Cargo.lock to track the patch release of obikmer. This modification only adjusts the version in the lockfile and introduces no behavioral or API changes.
2026-08-20 12:27:26 +02:00
coissac 0f389b37f2 Merge pull request 'chore: bump obikmer to 1.2.1 and disable obikindex default features' (#69) from push-vzoxtyuuuxqn into main
Reviewed-on: OBIKmers/obikmer#69
2026-08-17 11:33:56 +00:00
Eric Coissac 66ab1d0947 chore: bump obikmer to 1.2.1 and disable obikindex default features
Release / create-release (push) Successful in 2m25s
ci.yml / build (pull_request) Successful in 4m34s
Release / build-linux-x86_64 (push) Successful in 8m18s
Release / build-macos-arm64 (push) Successful in 1m55s
Updates the obikmer lockfile version to 1.2.1 and configures the obikindex dependency to explicitly disable default features. These are manifest and lockfile adjustments that do not modify source code or alter application behavior.
2026-08-17 13:32:30 +02:00
coissac 5e2bb393e0 Merge pull request 'Push luqxvxskktxv' (#68) from push-luqxvxskktxv into main
Reviewed-on: OBIKmers/obikmer#68
2026-08-17 10:35:12 +00:00
672 changed files with 80950 additions and 29471 deletions

No files matched your search

Vendored
BIN
View File
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
0.3.4+0.1.1
+240
View File
@@ -0,0 +1,240 @@
# crate-kit: common targets for the crates of a multi-crate Rust project.
#
# This directory (.crate-kit/) is a COPY of the kit/ folder of the crate-kit repository: do not
# modify it here, fix it in crate-kit then run `make kit-update`.
#
# Usage, in the crate's Makefile:
# RELEASE_PROJECT_DESC = acmexxx (short description) # optional
# include .crate-kit/crate.mk
#
# Adjustable variables (before the include or on the command line):
# CARGO, CARGO_TOML, FEATURES, API_DIR, RELEASE_NOTES_DIR, REGISTRY, KIT_SRC
# KIT_LANG language of LLM-generated documents (default en; any language name or ISO code)
# RELEASE=x.y.z forces the version of bump-version / jjrelease
# DRY_RUN=1 publish: checks the package without sending it
#
# Crate kind: CRATE_KIND (default "crate"). kinds/<kind>.mk sets, before the targets, the generic variables
# that the kit reads: BUILD_TARGET (--target of the builds), EXTRA_TARGETS (targets that check and clippy
# go through in addition to the host), PUBLISH, API_TRACKED, WIKI (yes|no: publication to the registry,
# API snapshot and version verdict, wiki), AFTER_RELEASE (command run after the tag). A kind
# can also add its own targets. Kinds specific to an organization come from its overlay (org.mk
# sets REGISTRY and REGISTRY_INDEX); see tools/kit-assemble.sh.
KIT_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
KIT_SRC ?= ../crate-kit
CARGO ?= cargo
CARGO_TOML ?= Cargo.toml
FEATURES ?=
API_DIR ?= api
RELEASE_NOTES_DIR ?= ReleaseNotes
CRATE_KIND ?= crate
BUILD_TARGET ?=
PUBLISH ?= yes
API_TRACKED ?= yes
WIKI ?= yes
AFTER_RELEASE ?=
# Additional targets that check and clippy go through (e.g. EXTRA_TARGETS = wasm32-unknown-unknown).
EXTRA_TARGETS ?=
RELEASE_PROJECT_DESC ?= $(shell sed -n 's/^name = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1)
GREEN = \033[0;32m
YELLOW = \033[1;33m
BLUE = \033[1;34m
NC = \033[0m
include $(KIT_DIR)/dev-patch.mk
include $(KIT_DIR)/jj.mk
# Language of the documents an LLM generates (release notes). Default English; an extension kit
# overrides it in its org.mk (KIT_LANG ?= fr), included above, or the user on the command line.
KIT_LANG ?= en
# Language of the commit messages written by `jj auto-doc` (pmojj reads PMOJJ_LANG).
export PMOJJ_LANG = $(KIT_LANG)
ifeq ($(wildcard $(KIT_DIR)/kinds/$(CRATE_KIND).mk),)
$(error unknown crate kind: CRATE_KIND = $(CRATE_KIND) (kinds: $(patsubst $(KIT_DIR)/kinds/%.mk,%,$(wildcard $(KIT_DIR)/kinds/*.mk))))
endif
include $(KIT_DIR)/kinds/$(CRATE_KIND).mk
export KIT_LANG CARGO CARGO_TOML API_DIR RELEASE_NOTES_DIR REGISTRY RELEASE_PROJECT_DESC KIT_SRC CRATE_KIND PUBLISH API_TRACKED WIKI
.DEFAULT_GOAL := build
.PHONY: help build release debug test test-doc doc doc-build clean check fmt fmt-check clippy \
watch ci deps update bench coverage bump-version api-level api-snapshot publish wiki \
jjnew jjpush jjfetch jjrelease bookmark-check kit-check needs-commit kit-update kit-version
help:
@echo "$(GREEN)Available commands:$(NC)"
@sed -n "s/^## *\([^:]*\): */\1$$(printf '\t')/p" $(MAKEFILE_LIST) | column -t -s "$$(printf '\t')" | sed -e 's/^/ /'
## build: Release build (alias of release)
build: release
## release: Release build (the kind's BUILD_TARGET, if it sets one)
release:
@echo "$(YELLOW)→ Building (release)...$(NC)"
$(CARGO) build --release $(if $(BUILD_TARGET),--target $(BUILD_TARGET)) $(FEATURES)
@echo "$(GREEN)✓ Build finished$(NC)"
## debug: Debug build (the kind's BUILD_TARGET, if it sets one)
debug:
@echo "$(YELLOW)→ Building (debug)...$(NC)"
$(CARGO) build $(if $(BUILD_TARGET),--target $(BUILD_TARGET)) $(FEATURES)
@echo "$(GREEN)✓ Build finished$(NC)"
## test: All tests
test:
@echo "$(YELLOW)→ Running the tests...$(NC)"
$(CARGO) test --all --all-features
@echo "$(GREEN)✓ Tests finished$(NC)"
## test-doc: Documentation example tests
test-doc:
@echo "$(YELLOW)→ Testing the documentation examples...$(NC)"
$(CARGO) test --doc --all-features
@echo "$(GREEN)✓ Documentation tests finished$(NC)"
## doc: Generates the documentation and opens it
doc:
@echo "$(YELLOW)→ Generating the documentation...$(NC)"
$(CARGO) doc --no-deps --document-private-items --all-features --open
## doc-build: Generates the documentation without opening it
doc-build:
@echo "$(YELLOW)→ Generating the documentation...$(NC)"
$(CARGO) doc --no-deps --document-private-items --all-features
## clean: Cleanup
clean:
@echo "$(YELLOW)→ Cleaning...$(NC)"
$(CARGO) clean
## check: Code check (host, then EXTRA_TARGETS)
check:
@$(KIT_DIR)/scripts/publish-guard.sh
@echo "$(YELLOW)→ Checking the code...$(NC)"
$(CARGO) check --all
@for t in $(EXTRA_TARGETS); do $(CARGO) check --all --target $$t || exit 1; done
@echo "$(GREEN)✓ Code valid$(NC)"
## fmt: Code formatting
fmt:
$(CARGO) fmt --all
## fmt-check: Formatting check
fmt-check:
$(CARGO) fmt --all -- --check
## clippy: Static analysis on the host then EXTRA_TARGETS (warnings = errors)
clippy:
@echo "$(YELLOW)→ Analysing with clippy...$(NC)"
$(CARGO) clippy --all-targets --all-features -- -D warnings
@for t in $(EXTRA_TARGETS); do $(CARGO) clippy --lib --all-features --target $$t -- -D warnings || exit 1; done
@echo "$(GREEN)✓ Clippy analysis finished$(NC)"
## watch: Continuous check
watch:
$(CARGO) watch -x check
## ci: Verification pipeline (deps-check fmt-check clippy test doc-build)
ci: deps-check fmt-check clippy test doc-build
@echo "$(GREEN)✓ All CI checks passed$(NC)"
## deps: Outdated dependencies
deps:
$(CARGO) outdated
## update: Updates the dependencies
update:
$(CARGO) update
## bench: Benchmarks
bench:
$(CARGO) bench
## coverage: Coverage report (cargo-llvm-cov)
coverage:
@echo "$(YELLOW)→ Generating the coverage report...$(NC)"
@mkdir -p target/coverage
$(CARGO) llvm-cov --json --output-path target/coverage/llvm-cov-report.json
$(CARGO) llvm-cov report
@echo "$(GREEN)✓ Report: target/coverage/llvm-cov-report.json$(NC)"
## api-level: Compares the public API to the last snapshot (initial, unchanged, additive or breaking)
api-level:
@$(KIT_DIR)/scripts/api-level.sh
## api-snapshot: Records the public API of the current version (api/<version>.txt and .json.gz)
api-snapshot:
@$(KIT_DIR)/scripts/api-snapshot.sh
## bump-version: Next version according to the API (breaking: x.y+1.0 in 0.x), or fixed RELEASE=x.y.z
bump-version:
@$(KIT_DIR)/scripts/bump-version.sh
## publish: Publishes to the $(REGISTRY) registry (done by the CI after the tag; manual troubleshooting, DRY_RUN=1: without sending)
publish:
@$(KIT_DIR)/scripts/publish.sh
## wiki: Publishes the API doc to the wiki (done by the CI after the tag; manual troubleshooting, DRY_RUN=1: without push)
wiki:
@$(KIT_DIR)/scripts/wiki.sh
## jjpush: Version bump, API snapshot, documentation, then main advances to the commit and is pushed
jjpush: bookmark-check deps-check bump-version api-snapshot
@echo "$(YELLOW)→ Pushing the commit to main...$(NC)"
@jj auto-doc
@$(KIT_DIR)/scripts/push-main.sh
@$(KIT_DIR)/scripts/new-commit.sh
@echo "$(GREEN)✓ main pushed; new working commit created on top of it$(NC)"
## jjrelease: Release (ci, version according to the API, snapshot, notes, push of main, tag; the CI then publishes)
jjrelease: bookmark-check kit-check ci bump-version api-snapshot
@echo "$(BLUE)→ Documenting the undocumented commits...$(NC)"
@jj auto-doc
@echo "$(BLUE)→ Synchronizing the tags with the remote repository...$(NC)"
@jj git fetch
@$(KIT_DIR)/scripts/release-notes.sh
@echo "$(BLUE)→ Documenting the current commit...$(NC)"
@jj auto-doc
@echo "$(BLUE)→ Pushing main...$(NC)"
@$(KIT_DIR)/scripts/push-main.sh
@$(KIT_DIR)/scripts/tag.sh
@$(KIT_DIR)/scripts/new-commit.sh
@echo "$(GREEN)✓ Tag pushed: the CI (Release workflow) publishes the crate, updates the wiki and creates the release$(NC)"
ifneq ($(strip $(AFTER_RELEASE)),)
@echo "$(BLUE)→ After the release: $(AFTER_RELEASE)$(NC)"
@$(AFTER_RELEASE)
endif
@name=$$(sed -n 's/^name = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1); \
v=$$(sed -n 's/^version = "\(.*\)"/\1/p' $(CARGO_TOML) | head -n 1); \
case "$$v" in 0.*) req=$$(echo "$$v" | cut -d. -f1,2);; *) req=$$(echo "$$v" | cut -d. -f1);; esac; \
echo "$(YELLOW)⚠ Dependent projects: the requirement must accept $$v. If it does not, the local [patch] is ignored: raise it in their Cargo.toml $$name = { version = \"$$req\", registry = \"$(REGISTRY)\" } then cargo update -p $$name$(NC)"
## bookmark-check: Does main track main@origin? Otherwise the push of main would fail at the end of the release (read-only)
bookmark-check:
@$(KIT_DIR)/scripts/bookmark-check.sh
## kit-check: Is this crate's kit and release workflow identical to crate-kit's? (read-only)
kit-check:
@$(KIT_DIR)/scripts/kit-check.sh
## needs-commit: Are there changes other than the kit's to commit? (read-only, code 1 if not)
needs-commit:
@$(KIT_DIR)/scripts/needs-commit.sh
## kit-update: Updates .crate-kit/ from the extension kit (KIT_SRC)
kit-update:
@test -x "$(KIT_SRC)/tools/kit-copy.sh" || { echo "crate-kit not found: $(KIT_SRC) (set KIT_SRC=...)"; exit 1; }
@"$(KIT_SRC)/tools/kit-copy.sh" $(KIT_DIR)
@echo "$(GREEN)✓ .crate-kit/ up to date: crate-kit $$(cat $(KIT_DIR)/VERSION)$(NC)"
## print-%: Value of a make variable (e.g. make print-PUBLISH); for the tools
print-%:
@echo '$($*)'
## kit-version: Kit version installed in this crate
kit-version:
@cat $(KIT_DIR)/VERSION
+42
View File
@@ -0,0 +1,42 @@
# Private registry and local Cargo configuration (joint development).
# Fragment included by crate.mk and by the Makefiles that are not crates (workspace):
# include .crate-kit/dev-patch.mk
DEVPATCH_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
CARGO_TOML ?= Cargo.toml
# Values specific to the organization (REGISTRY, REGISTRY_INDEX, FORGE_URL…): org.mk, provided by the
# extension that the crate declares (KIT_OVERLAY, tools/kit-assemble.sh). REGISTRY = crates-io: crates.io, without
# index or [patch]. Without org.mk, no registry: publish and deps-check fail saying so.
-include $(DEVPATCH_DIR)/org.mk
REGISTRY ?=
REGISTRY_INDEX ?=
export CARGO_TOML REGISTRY REGISTRY_INDEX FORGE_TOKEN_FILE
# Private registry: the index comes from the environment, never from a file tracked by the repository (CI,
# Docker and a repository cloned alone therefore work without configuration).
ifneq ($(filter-out crates-io,$(strip $(REGISTRY))),)
REGISTRY_UP := $(shell echo '$(REGISTRY)' | tr 'a-z-' 'A-Z_')
CARGO_REGISTRIES_$(REGISTRY_UP)_INDEX := $(REGISTRY_INDEX)
export CARGO_REGISTRIES_$(REGISTRY_UP)_INDEX
endif
# Joint development: .cargo/config.toml (local, ignored) is regenerated at EVERY invocation of
# make, whatever the target, from the project's actual dependencies. Nothing to remember.
DEV_PATCH_RUN := $(shell CARGO_TOML='$(CARGO_TOML)' REGISTRY='$(REGISTRY)' REGISTRY_INDEX='$(REGISTRY_INDEX)' $(DEVPATCH_DIR)/scripts/dev-patch.sh)
.PHONY: dev-patch
## dev-patch: Regenerates .cargo/config.toml (registry + local patches); already done at every make
dev-patch:
@$(DEVPATCH_DIR)/scripts/dev-patch.sh
@echo "ok: .cargo/config.toml up to date"
.PHONY: deps-check deps-bump
## deps-check: Dependencies up to date? from the private registry (requirement, lock, neighbour, duplicates) and external (requirement, minor, lock)
deps-check:
@rc=0; $(DEVPATCH_DIR)/scripts/deps-check.sh || rc=1; $(DEVPATCH_DIR)/scripts/deps-check-external.sh || rc=1; exit $$rc
## deps-bump: Raises the outdated requirements (private registry and external) to the latest version, then cargo update -p
deps-bump:
@$(DEVPATCH_DIR)/scripts/deps-check.sh bump
@$(DEVPATCH_DIR)/scripts/deps-check-external.sh bump
+22
View File
@@ -0,0 +1,22 @@
# Jujutsu targets common to all the crates and to crate-kit itself.
# Included by crate.mk; a repository that is not a crate includes it directly.
JJ_KIT_DIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
GREEN ?= \033[0;32m
YELLOW ?= \033[1;33m
BLUE ?= \033[1;34m
NC ?= \033[0m
## jjnew: Documents the current commit then creates a new one
jjnew:
@echo "$(YELLOW)→ Creating a new commit...$(NC)"
@jj auto-doc
@$(JJ_KIT_DIR)/scripts/new-commit.sh
@echo "$(GREEN)✓ Done$(NC)"
## jjfetch: Fetches the origin and rebases the local work on top of main@origin (nothing is lost)
jjfetch:
@$(JJ_KIT_DIR)/scripts/jjfetch.sh
@# Reruns make to resynchronize .crate-kit/: the Makefile does it at startup, before the rebase, and
@# the rebase may have left conflict markers there (kit copy newer than the origin's).
@$(MAKE) --no-print-directory -s help >/dev/null
+3
View File
@@ -0,0 +1,3 @@
# "crate" kind (default): ordinary Rust crate, published to the private registry, API tracked, wiki.
# The default values of BUILD_TARGET, EXTRA_TARGETS, PUBLISH, API_TRACKED, WIKI and AFTER_RELEASE
# (crate.mk) describe this kind: nothing to set here.
+9
View File
@@ -0,0 +1,9 @@
# Values specific to obi, read by dev-patch.mk (hence by every Makefile of the cluster) and by crate-kit.
# The cargo registry to publish to (a private name, or crates-io) and the forge hosting it.
REGISTRY ?= obi
FORGE_URL ?= https://forge.metabarcoding.org
REGISTRY_INDEX ?= sparse+$(FORGE_URL)/api/packages/$(REGISTRY)/cargo/
# No token here: the forge tokens of a workstation are files of the cluster, in secrets/ next to the
# repositories (secrets/forge.metabarcoding.org.token, ...), outside every repository. FORGETOKEN (CI) overrides them.
# Language of the documents an LLM generates (release notes, commit messages, Claude agents' notes).
KIT_LANG ?= en
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env bash
# Compares the current public API to the last snapshot and prints on standard output:
# initial no snapshot: first tracked version
# unchanged no change in the public API
# additive additions only (nothing removed or modified)
# breaking break: element removed/modified, or break seen by cargo-semver-checks
# All the detail goes to standard error.
#
# Two combined checks: cargo-semver-checks is the reference for breaks, but it does not
# report plain additions; the text diff of cargo public-api acts as a safety net (any removed
# or modified line = break) and provides the count of additions.
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${API_TRACKED:-yes}" = no ]; then
echo unchanged # no tracked Rust API: the version advances by patch (or RELEASE=x.y.z)
exit 0
fi
require_cargo_tool public-api cargo-public-api
require_cargo_tool semver-checks cargo-semver-checks
# A proc-macro crate has no library target: cargo-semver-checks cannot analyse it.
# Its API (the exported macros) is still tracked by the text diff of cargo public-api; this diff does
# not see a change in the macro's behaviour (rejected inputs, generated code): to be judged by hand.
is_proc_macro() {
"$CARGO" metadata --format-version 1 --no-deps | grep -q '"kind":\["proc-macro"\]'
}
last=$(latest_snapshot)
if [ -z "$last" ]; then
info " No snapshot in $API_DIR/: first tracked version"
echo initial
exit 0
fi
# A snapshot written with other tools (rustc, cargo-public-api) than today's is no longer
# comparable: cargo-semver-checks crashes on another rustdoc format, and the text diff sees
# breaks where only the rendering changed. It is regenerated from the tag of its version (no stamp =
# written before stamps existed, hence unknown).
if [ "$(cat "$API_DIR/$last.stamp" 2>/dev/null || true)" != "$(toolchain_stamp)" ]; then
info " Snapshot $last written with other tools: regenerating from tag version-$last"
regenerate_snapshot "$last" || {
err "✗ cannot regenerate snapshot $last: the comparison would be wrong"
exit 1
}
fi
tmp=$(mktemp -d)
trap 'rm -r "$tmp"' EXIT
info " Reference: API published in version $last"
"$CARGO" public-api -s >"$tmp/current.txt" 2>/dev/null || {
err "✗ cargo public-api failed"
exit 1
}
# `filter_unstable` (common.sh) removes from the cargo public-api text whatever is not the crate's API.
diff_out=$(diff <(filter_unstable "$API_DIR/$last.txt") <(filter_unstable "$tmp/current.txt") || true)
removed=$(printf '%s\n' "$diff_out" | grep -c '^<' || true)
added=$(printf '%s\n' "$diff_out" | grep -c '^>' || true)
# Code 100 = break; 0 = nothing to report; other = tool failure.
set +e
if is_proc_macro; then
info " proc-macro crate: cargo-semver-checks not applicable, text diff only"
rc=0
else
gzip -d -c "$API_DIR/$last.json.gz" >"$tmp/baseline.json"
"$CARGO" semver-checks --baseline-rustdoc "$tmp/baseline.json" --release-type minor >"$tmp/semver.log" 2>&1
rc=$?
fi
set -e
level=unchanged
if [ "$rc" -eq 100 ]; then
level=breaking
warn " Break detected by cargo-semver-checks:"
grep -E '^ +[A-Za-z0-9_]+::|^--- failure' "$tmp/semver.log" >&2 || true
elif [ "$rc" -ne 0 ]; then
err "✗ cargo-semver-checks failed (code $rc):"
tail -n 15 "$tmp/semver.log" >&2
exit 1
fi
if [ "$removed" -gt 0 ]; then
level=breaking
warn " $removed API line(s) removed or modified compared to $last:"
printf '%s\n' "$diff_out" | grep '^<' >&2
fi
if [ "$level" = unchanged ] && [ "$added" -gt 0 ]; then
level=additive
fi
info " API: +$added / -$removed lines; verdict: $level"
echo "$level"
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Records the public API of the current version:
# $API_DIR/<version>.txt readable, diffable list (cargo public-api)
# $API_DIR/<version>.json.gz compressed rustdoc JSON, reference of cargo-semver-checks
# $API_DIR/<version>.stamp rustc and cargo-public-api used (api-level regenerates if they change)
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${API_TRACKED:-yes}" = no ]; then
info " (kind ${CRATE_KIND:-crate}: no Rust API to record)"
exit 0
fi
require_cargo_tool public-api cargo-public-api
version=$(current_version)
name=$(crate_name)
warn "→ Public API snapshot of $name $version..."
emit_snapshot "$version" "$API_DIR"
ok "✓ $API_DIR/$version.txt and $API_DIR/$version.json.gz written"
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Checks that the local `main` bookmark tracks `main@origin` (read-only). Without this tracking, jj refuses
# to push main ("Non-tracking remote bookmark"), and jjrelease would fail at the very end,
# after the tests and the version bump: this check detects it beforehand.
# Without a jj repository, without a `main` bookmark or without `main@origin`, there is nothing to check: success.
set -euo pipefail
. "$(dirname "$0")/common.sh"
rows=$(jj bookmark list main --all-remotes -T 'remote ++ "|" ++ tracked ++ "\n"' 2>/dev/null) || exit 0
if printf '%s\n' "$rows" | grep -qx 'origin|false'; then
err "✗ main@origin exists but the local main bookmark does not track it: the push of main would be refused"
info " Fix once and for all: jj bookmark track main@origin"
exit 1
fi
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# Computes and applies the next version according to the public API (see api-level.sh):
# break -> x.y+1.0 while x = 0, otherwise x+1.0.0
# additions -> x.y+1.0 once x >= 1 (SemVer: new feature), x.y.z+1 while x = 0
# otherwise -> x.y.z+1
# RELEASE=x.y.z forces the version. Updates Cargo.toml, version.txt and the
# dependency line `<crate> = "x.y"` of README.md when they exist.
set -euo pipefail
. "$(dirname "$0")/common.sh"
warn "→ Computing the next version..."
current=$(current_version)
name=$(crate_name)
info " Current version: $current"
IFS=. read -r major minor patch <<<"$current"
if [ -n "${RELEASE:-}" ]; then
new_version="$RELEASE"
else
level=$("$(dirname "$0")/api-level.sh")
case "$level" in
breaking)
if [ "$major" = "0" ]; then
new_version="0.$((minor + 1)).0"
else
new_version="$((major + 1)).0.0"
fi
;;
additive)
if [ "$major" = "0" ]; then
new_version="0.$minor.$((patch + 1))"
else
new_version="$major.$((minor + 1)).0"
fi
;;
initial | unchanged)
new_version="$major.$minor.$((patch + 1))"
;;
*)
err "✗ unexpected API verdict: '$level'"
exit 1
;;
esac
fi
# No silent jump to another version: a break must never be downgraded.
rc=0
"$(dirname "$0")/tag-exists.sh" "$new_version" || rc=$?
case "$rc" in
0)
err "✗ The release version-$new_version already exists (locally or on the server)"
info " Use RELEASE=x.y.z to force another version"
exit 1
;;
1) ;;
*) warn " (remote tags not checked: no jj repository or origin unreachable)" ;;
esac
info " New version: $new_version"
sed -i.bak "s/^version = \"$current\"/version = \"$new_version\"/" "$CARGO_TOML"
rm "$CARGO_TOML.bak"
[ -f version.txt ] && echo "$new_version" >version.txt
if [ -f README.md ]; then
sed -i.bak "s/^$name = \"[0-9][0-9.]*\"/$name = \"$(echo "$new_version" | cut -d. -f1,2)\"/" README.md
rm README.md.bak
fi
ok "✓ Version $new_version written to $CARGO_TOML (and version.txt, README.md if they exist)"
+266
View File
@@ -0,0 +1,266 @@
#!/usr/bin/env bash
# Functions shared by the kit scripts. To be sourced: `. "$(dirname "$0")/common.sh"`.
#
# Parameters read from the environment (default values below); crate.mk exports
# them, the scripts also remain usable on their own from the root of a crate.
CARGO="${CARGO:-cargo}"
CARGO_TOML="${CARGO_TOML:-Cargo.toml}"
API_DIR="${API_DIR:-api}"
RELEASE_NOTES_DIR="${RELEASE_NOTES_DIR:-ReleaseNotes}"
# Private cargo registry and its sparse index: provided by the organisation overlay (org.mk), empty otherwise.
REGISTRY="${REGISTRY:-}"
REGISTRY_INDEX="${REGISTRY_INDEX:-}"
info() { printf '\033[1;34m%s\033[0m\n' "$*" >&2; }
warn() { printf '\033[1;33m%s\033[0m\n' "$*" >&2; }
ok() { printf '\033[0;32m%s\033[0m\n' "$*" >&2; }
err() { printf '\033[0;31m%s\033[0m\n' "$*" >&2; }
# API call: `forge_call <operation> <curl args…>`. Returns the response body on standard output;
# on an HTTP response ≥ 400 (or a transport failure), states the operation, the code and the body on standard
# error and returns 1. Replaces `curl -sf`, which fails silently (code 22).
forge_call() {
local operation="$1" body code
shift
body=$(mktemp)
code=$(curl -s -o "$body" -w '%{http_code}' "$@") || code="000"
if [ "$code" -ge 400 ] || [ "$code" = "000" ]; then
err "✗ $operation : HTTP $code : $(head -c 500 "$body")"
rm -f "$body"
return 1
fi
cat "$body"
rm -f "$body"
}
# Directory of the forge tokens of a workstation: `secrets/` of the cluster, i.e. next to the repositories
# (the parent of the current repository), outside every repository. FORGE_SECRETS_DIR overrides it.
forge_secrets_dir() {
if [ -n "${FORGE_SECRETS_DIR:-}" ]; then
printf '%s' "$FORGE_SECRETS_DIR"
return 0
fi
local root
root=$(jj root 2>/dev/null) || root=$(pwd)
printf '%s/secrets' "$(dirname "$root")"
}
# "host owner repo" of a git or registry URL: ssh://git@host[:port]/owner/repo.git, git@host:owner/repo.git,
# https://host/owner/repo, sparse+https://host/api/packages/owner/cargo/ (owner of the registry, no repo).
# Fails if the URL has no known form. Fields are empty when absent.
forge_parse_url() {
local u="${1#sparse+}" host path owner repo
case "$u" in
*://*) u="${u#*://}"; u="${u#*@}"; host="${u%%/*}"; path="${u#*/}" ;;
*@*:*) u="${u#*@}"; host="${u%%:*}"; path="${u#*:}" ;;
*) return 1 ;;
esac
[ "$path" = "$u" ] && path=""
host="${host%%:*}"
path="${path%/}"; path="${path%.git}"
case "$path" in
api/packages/*) owner="${path#api/packages/}"; owner="${owner%%/*}"; repo="" ;;
*) owner="${path%%/*}"; repo="${path#*/}"; [ "$repo" = "$path" ] && repo="" ;;
esac
[ -n "$host" ] || return 1
printf '%s %s %s\n' "$host" "$owner" "$repo"
}
# Forge token. `forge_token [url]`: the forge is that of the URL (registry index, repository), by default that of
# the `origin` remote. Order, the first that exists wins:
# 1. $FORGETOKEN: the CI, where each forge provides its own secret to its own jobs;
# 2. the token files of the cluster, most specific first (one line, mode 0600; see forge_secrets_dir):
# <secrets>/<host>/<owner>/<repo>.token, <secrets>/<host>/<owner>.token, <secrets>/<host>.token;
# 3. the file $FORGE_TOKEN_FILE (former single-token layout).
# Nothing on standard output if there is none; the caller then says where to put it. Never displayed.
forge_token() {
if [ -n "${FORGETOKEN:-}" ]; then
printf '%s' "$FORGETOKEN"
return 0
fi
local url="${1:-}" host owner repo dir f
[ -n "$url" ] || url=$(jj git remote list 2>/dev/null | awk '$1=="origin"{print $2; exit}')
if [ -n "$url" ] && read -r host owner repo < <(forge_parse_url "$url"); then
dir=$(forge_secrets_dir)
for f in ${repo:+"$dir/$host/$owner/$repo.token"} ${owner:+"$dir/$host/$owner.token"} "$dir/$host.token"; do
if [ -f "$f" ]; then
head -n 1 "$f" | tr -d '[:space:]'
return 0
fi
done
fi
if [ -n "${FORGE_TOKEN_FILE:-}" ] && [ -f "$FORGE_TOKEN_FILE" ]; then
head -n 1 "$FORGE_TOKEN_FILE" | tr -d '[:space:]'
fi
return 0
}
# cargo authentication against the private registry: CARGO_REGISTRIES_<REGISTRY>_TOKEN ("Bearer <token>"),
# built from the forge token if not already defined. Needed by any cargo call that
# resolves registry dependencies (publish, wiki doc). For crates.io (REGISTRY = crates-io) nothing
# is built: the crates.io token is CARGO_REGISTRY_TOKEN, supplied by the user.
if [ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ]; then
reg_var="CARGO_REGISTRIES_$(printf '%s' "$REGISTRY" | tr 'a-z-' 'A-Z_')_TOKEN"
if [ -z "${!reg_var:-}" ] && [ -n "$(forge_token "$REGISTRY_INDEX")" ]; then
export "$reg_var=Bearer $(forge_token "$REGISTRY_INDEX")"
fi
fi
# Version: content of $VERSION_FILE if set (repositories that are not crates, like
# crate-kit itself), otherwise first occurrence in the crate's Cargo.toml.
current_version() {
# Source of the version: VERSION_FILE (exported by the Makefiles of the kits), else the Cargo.toml of a crate.
# Without either (script run by hand at the root of a kit, not through make): kit/VERSION (crate-kit) or
# overlay/kit/VERSION (extension kit), if present.
local file="${VERSION_FILE:-}" candidate
if [ -z "$file" ] && [ ! -f "$CARGO_TOML" ]; then
for candidate in kit/VERSION overlay/kit/VERSION; do
[ -f "$candidate" ] && { file="$candidate"; break; }
done
fi
if [ -n "$file" ]; then
head -n 1 "$file"
elif [ -f "$CARGO_TOML" ]; then
sed -n 's/^version = "\(.*\)"/\1/p' "$CARGO_TOML" | head -n 1
else
err "✗ no source for the version: no VERSION_FILE, no $CARGO_TOML, no kit/VERSION nor overlay/kit/VERSION here"
return 1
fi
}
# Package name: first occurrence in the crate's Cargo.toml.
# Abandons the empty commits without a description between trunk() and @ (excluding @ itself): jj refuses to
# push a commit without a description, and these carry nothing (leftovers of `jj new`). Descendants
# are rebased automatically; neither work nor an already pushed (immutable) commit is touched.
abandon_blank_commits() {
jj abandon 'trunk()..@ & mutable() & empty() & description(exact:"") ~ @' >/dev/null 2>&1 || true
}
# The commit to publish: @, unless it is empty and without a description (the working commit that `jj new`
# leaves after a release or a push); we then go up to the first ancestor that carries work.
# Such a commit is not pushed (jj refuses a commit without a description) and deserves neither tag nor main.
release_rev() {
local rev='@' blank
while :; do
blank=$(jj log -r "$rev" --no-graph -T 'if(empty && description == "", "1", "0")')
[ "$blank" = 1 ] || break
rev="$rev-"
done
echo "$rev"
}
crate_name() { sed -n 's/^name = "\(.*\)"/\1/p' "$CARGO_TOML" | head -n 1; }
# Last version having an API snapshot (sorted by version number), empty if there is none.
latest_snapshot() {
ls "$API_DIR"/*.json.gz 2>/dev/null | sed 's|.*/||; s|\.json\.gz$||' | sort -V | tail -n 1 || true
}
# Fingerprint of the tools that produce a snapshot. The rustdoc JSON (format number) and the text
# rendering of cargo public-api change with rustc and cargo-public-api: a snapshot written with other
# tools than today's is no longer comparable (cargo-semver-checks crashes, or the text diff
# announces a break where only the rendering changed).
toolchain_stamp() {
printf '%s | %s\n' "$(rustc -V)" "$("$CARGO" public-api --version)"
}
# Writes the snapshot of version <version> of the code in the current directory (root of a
# crate), into <api_dir>: <version>.txt, <version>.json.gz and <version>.stamp (toolchain_stamp).
# Parameters: version, snapshot directory (absolute if the current directory is not the crate).
emit_snapshot() {
local version="$1" api_dir="$2" name target_dir
name=$(crate_name)
mkdir -p "$api_dir"
# -s: without the blanket implementations (`impl<T> Into<U> for Type`…), added by rustc to
# every public type and unrelated to its API (they made up half of the file).
"$CARGO" public-api -s >"$api_dir/$version.txt"
# The rustdoc JSON is unstable; RUSTC_BOOTSTRAP makes it possible to produce it with the stable toolchain,
# the same one cargo-semver-checks uses to build the current state.
# --document-private-items: cargo-semver-checks builds the current state with private items
# (private fields included); a reference without them makes a struct with a private field look like
# it "gains a private field" and gives a break wrongly.
RUSTC_BOOTSTRAP=1 "$CARGO" rustdoc --lib -q -- -Zunstable-options --output-format json --document-private-items
target_dir=$("$CARGO" metadata --format-version 1 --no-deps |
sed -n 's/.*"target_directory":"\([^"]*\)".*/\1/p')
# Compressed (gzip -n: reproducible output): the JSON exceeds 1 MB, jj's limit for a new file.
gzip -9 -n -c "$target_dir/doc/${name//-/_}.json" >"$api_dir/$version.json.gz"
toolchain_stamp >"$api_dir/$version.stamp"
}
# Regenerates the snapshot of the published version <version> with the current tools, from the code of
# its tag `version-<version>` (read-only: `jj file list/show`, no modification of the repository).
# The tag is exported into a sibling folder of the crate (`<crate>.baseline.tmp`): the relative paths
# of `.cargo/config.toml` (`[patch.<registry>]` towards the neighbours) remain valid there. Only `.cargo/` (ignored
# by the repository, generated by `make`) is copied in addition.
regenerate_snapshot() {
local version="$1" api_dir root tmp rev="version-$1" f
api_dir="$(pwd)/$API_DIR"
root="$(pwd)"
tmp="$root.baseline.tmp"
if ! jj file list -r "$rev" >/dev/null 2>&1; then
err "✗ tag $rev not found: cannot regenerate the snapshot of $version"
return 1
fi
rm -rf "$tmp"
mkdir -p "$tmp"
while IFS= read -r f; do
mkdir -p "$tmp/$(dirname "$f")"
jj file show -r "$rev" "$f" >"$tmp/$f"
done < <(jj file list -r "$rev")
[ -d "$root/.cargo" ] && cp -R "$root/.cargo" "$tmp/.cargo"
(
cd "$tmp"
CARGO_TARGET_DIR="$tmp/target" emit_snapshot "$version" "$api_dir"
) || { rm -rf "$tmp"; return 1; }
rm -rf "$tmp"
}
# Fails with an installation message if a cargo tool is missing.
require_cargo_tool() {
local sub="$1" crate="$2"
if ! command -v "cargo-$sub" >/dev/null 2>&1; then
err "✗ cargo-$sub is required: cargo install $crate --locked"
exit 1
fi
}
# Lines that are not the crate's API and that the text diff must not see:
# - `impl core::marker::Freeze`: unstable auto trait, invisible on stable; it appears or
# disappears as soon as a field goes under `Mutex`/`Atomic*`, with no effect for a caller;
# - the blanket implementations (`impl<T> other_crate::Trait for Type`) of traits of OTHER crates
# and their associated items: rustdoc lists them for every trait of the dependency graph, so
# they appear or disappear when a dependency changes (e.g. `crossbeam_epoch::Pointable`,
# `either::IntoEither`), without the crate's API having moved. Those of `core`,
# `alloc`, `std` and of the crate itself are kept.
filter_unstable() {
grep -v '^impl core::marker::Freeze for ' "$1" | awk -v crate="$(crate_name)" '
/^impl</ {
skip = 0
rest = $0
sub(/^impl<[^>]*> /, "", rest)
split(rest, parts, " ")
trait = parts[1]
if (trait !~ /^(core|alloc|std)::/ && index(trait, crate "::") != 1 && match($0, / for [^ ]+/)) {
self = substr($0, RSTART + 5, RLENGTH - 5)
skip = 1
next
}
print
next
}
skip && (index($0, "pub fn " self "::") == 1 || index($0, "pub unsafe fn " self "::") == 1 ||
index($0, "pub type " self "::") == 1 || index($0, "pub const " self "::") == 1) { next }
{ skip = 0; print }
' || true
}
# API text for the release notes: `filter_unstable`, then without the auto traits
# (`Send`, `Sync`, `Unpin`, `UnwindSafe`, `RefUnwindSafe`, `Freeze`, `Forget`, `Move`, `UnsafeUnpin`,
# `StructuralPartialEq`) that cargo public-api lists for every type: a new type adds nine
# lines that drown the API. They remain in the snapshot, hence in the verdict of `make api-level`
# (losing `Send` is a break); only the readable notes omit them.
filter_notes() {
filter_unstable "$1" | grep -v -E '^impl core::(marker::(Forget|Freeze|Move|Send|Sync|Unpin|UnsafeUnpin|StructuralPartialEq)|panic::unwind_safe::(RefUnwindSafe|UnwindSafe)) for ' || true
}
+193
View File
@@ -0,0 +1,193 @@
#!/usr/bin/env bash
# Freshness of the EXTERNAL dependencies (crates.io) declared by the project. `cargo outdated` compares the
# Cargo.lock version to the latest published one, but not the requirement written in Cargo.toml: a
# requirement `os_info = "3.8"` with a lock up to date at 3.15 goes unnoticed, and a consumer of the
# crate may end up with a version seven minor versions old.
#
# For each direct dependency `name = "x.y"` or `name = { version = "x.y", … }` (excluding `path`, `git`,
# `registry`, `workspace`), in [dependencies], [dev-dependencies], [build-dependencies], their
# `target.*` variants and [workspace.dependencies], it checks:
# 1. the requirement accepts the latest published version (for a 0.x, `0.5` does not accept 0.6);
# 2. for a version ≥ 1, the required minor version is not behind the latest
# (`tokio = "1.35"` while 1.52 exists). A 0.x is not checked at this level: its
# patch number does not count;
# 3. Cargo.lock is on the latest version that the requirement accepts.
# Requirements that are not written `x`, `x.y` or `x.y.z` (`=1.2.3`, `~1.2`, `>=1`, ranges) are
# explicit choices: ignored.
#
# deps-check-external.sh check (read-only, except for the network)
# deps-check-external.sh bump raises the outdated requirements then `cargo update -p`
#
# Variables: DEPS_CHECK_EXTERNAL=0 disables the check (workspace too large to be kept up
# to date all at once); DEPS_CHECK_EXTERNAL_IGNORE="crate1 crate2" sets crates aside (to be justified in
# the Makefile: for example a public dependency that must move up with the neighbouring crates); CRATES_IO_INDEX (default https://index.crates.io); DEPS_CHECK_OFFLINE=1 ignores
# the absence of network (warning).
# shellcheck disable=SC2154 # manifests comes from deps-lib.sh
set -euo pipefail
. "$(dirname "$0")/common.sh"
. "$(dirname "$0")/deps-lib.sh"
mode="${1:-check}"
case "$mode" in check | bump) ;; *)
err "usage: deps-check-external.sh [check|bump]"
exit 2
;;
esac
if [ "${DEPS_CHECK_EXTERNAL:-1}" = 0 ]; then
info " (external dependencies: check disabled by DEPS_CHECK_EXTERNAL=0)"
exit 0
fi
[ -f "$CARGO_TOML" ] || exit 0
crates_index="${CRATES_IO_INDEX:-https://index.crates.io}"
crates_index="${crates_index%/}"
fail=0
bad() {
err " ✗ $*"
fail=1
}
# External declarations of a manifest: "key<TAB>crate<TAB>requirement" (the crate differs from the key
# when the dependency is renamed by `package = "…"`).
declarations() {
awk '
/^\[/ { dep = ($0 ~ /^\[(workspace\.|target\..*\.)?(dev-|build-)?dependencies\]$/); next }
!dep { next }
/^[ \t]*#/ { next }
{
if (match($0, /^[A-Za-z0-9_-]+[ \t]*=/) == 0) next
key = $0; sub(/[ \t]*=.*/, "", key)
rest = $0; sub(/^[A-Za-z0-9_-]+[ \t]*=[ \t]*/, "", rest)
crate = key
if (rest ~ /^"/) {
req = rest; sub(/^"/, "", req); sub(/".*/, "", req)
} else if (rest ~ /^\{/) {
if (rest ~ /(path|git|registry|workspace)[ \t]*=/) next
if (match(rest, /version[ \t]*=[ \t]*"[^"]*"/) == 0) next
req = substr(rest, RSTART, RLENGTH)
sub(/^version[ \t]*=[ \t]*"/, "", req); sub(/"$/, "", req)
if (match(rest, /package[ \t]*=[ \t]*"[^"]*"/)) {
crate = substr(rest, RSTART, RLENGTH)
sub(/^package[ \t]*=[ \t]*"/, "", crate); sub(/"$/, "", crate)
}
} else next
print key "\t" crate "\t" req
}
' "$1"
}
# Replaces the requirement of the dependency `key` (in a dependencies section) of manifest $1 with $3.
rewrite_req() {
awk -v n="$2" -v r="$3" '
/^\[/ { dep = ($0 ~ /dependencies\]$/) }
dep && $0 ~ "^" n "[ \t]*=" {
if ($0 ~ /\{/) sub(/version[ \t]*=[ \t]*"[^"]*"/, "version = \"" r "\"")
else sub(/"[^"]*"/, "\"" r "\"")
}
{ print }
' "$1" >"$1.tmp" && mv "$1.tmp" "$1"
}
# Requirement to write for version $1: x.y (≥ 1) or 0.y.
floor_for() { echo "$1" | cut -d. -f1,2; }
tmp=$(mktemp -d)
trap 'rm -r "$tmp"' EXIT
info "→ Freshness of the external dependencies (crates.io)..."
count=0
offline=0
updates=""
for manifest in "${manifests[@]}"; do
while IFS=$'\t' read -r key crate req; do
[ -n "$crate" ] || continue
# Dependency deliberately set aside (DEPS_CHECK_EXTERNAL_IGNORE, with its reason in the Makefile).
case " ${DEPS_CHECK_EXTERNAL_IGNORE:-} " in *" $crate "*) continue ;; esac
# Explicit requirement (=, ~, >=, range): a choice, not checked (and no network request).
case "${req#^}" in '' | *[!0-9.]*) continue ;; esac
count=$((count + 1))
if [ ! -f "$tmp/$crate" ]; then
rc=0
found=$(latest_published "$crate" "$crates_index") || rc=$?
printf '%s %s\n' "$rc" "$found" >"$tmp/$crate"
fi
read -r rc latest <"$tmp/$crate"
if [ "$rc" -eq 2 ]; then
offline=1
continue
fi
if [ "$rc" -eq 1 ] || [ -z "$latest" ]; then
warn " ⚠ $crate ($manifest): not found on crates.io, not checked"
continue
fi
acc=0
req_accepts "$req" "$latest" || acc=$?
if [ "$acc" -eq 1 ]; then
# Newer than the latest published (pre-release, yank): nothing to raise.
[ "$(printf '%s\n%s\n' "$req" "$latest" | sort -V | tail -n 1)" = "$latest" ] || continue
if [ "$mode" = bump ]; then
new=$(floor_for "$latest")
rewrite_req "$manifest" "$key" "$new"
info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)"
updates+="$crate "
else
bad "$crate ($manifest): the requirement \"$req\" does not accept the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)"
fi
continue
fi
# The requirement accepts the latest version: is the required minor (≥ 1.0) behind?
IFS=. read -r rmaj rmin _ <<<"${req#^}"
IFS=. read -r _ lmin _ <<<"$latest"
if [ "$rmaj" != 0 ] && [ -n "$rmin" ] && [ "$rmin" -lt "$lmin" ]; then
if [ "$mode" = bump ]; then
new=$(floor_for "$latest")
rewrite_req "$manifest" "$key" "$new"
info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)"
updates+="$crate "
else
bad "$crate ($manifest): the requirement \"$req\" is behind the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)"
fi
fi
# Cargo.lock: on the latest version that the requirement accepts.
if [ -f Cargo.lock ]; then
locked=$(lock_entries | awk -v n="$crate" '$1 == n && index($3, "crates.io-index") { print $2 }' | sort -V | tail -n 1)
if [ -n "$locked" ] && [ "$locked" != "$latest" ] &&
[ "$(printf '%s\n%s\n' "$locked" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
if [ "$mode" = bump ]; then
updates+="$crate "
else
bad "$crate: Cargo.lock is on $locked, the latest version is $latest → cargo update -p $crate (make deps-bump)"
fi
fi
fi
done < <(declarations "$manifest")
done
if [ "$offline" -eq 1 ]; then
if [ "${DEPS_CHECK_OFFLINE:-}" = 1 ]; then
warn " ⚠ crates.io unreachable: freshness of the external dependencies not verified (DEPS_CHECK_OFFLINE=1)"
else
bad "crates.io unreachable ($crates_index): freshness cannot be verified (DEPS_CHECK_OFFLINE=1 to ignore)"
fi
fi
if [ "$mode" = bump ] && [ -n "$updates" ]; then
for n in $(printf '%s\n' $updates | sort -u); do
info " cargo update -p $n"
"$CARGO" update -p "$n" >/dev/null
done
fi
if [ "$fail" -ne 0 ]; then
err "✗ External dependencies out of date (see above)"
exit 1
fi
ok "✓ External dependencies up to date ($count checked)"
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env bash
# Freshness of the dependencies between crates of the private registry: we must never keep running with an
# old version of a registry crate when a new one is published. Fails (code 1) at the slightest discrepancy.
#
# For each dependency `name = { version = "x.y", registry = "<registry>" }` declared by the project
# (same reading as dev-patch.sh), it checks:
# 1. the requirement accepts the latest version published on the registry (for a 0.x, `0.1` never
# accepts 0.2: Cargo says nothing);
# 2. Cargo.lock is on that latest version (if it points to the registry);
# 3. the neighbouring folder ../<name>, which replaces the dependency in joint development, is not
# behind the registry (otherwise we build against stale code);
# 4. Cargo.lock contains no [[patch.unused]] (ignored local patch: requirement too low);
# 5. no registry crate appears in several versions in Cargo.lock (two copies in the build).
# A neighbour newer than the registry (pending publication) is reported without failing.
#
# deps-check.sh check (read-only, except for the network)
# deps-check.sh bump fixes the outdated requirements (rewrites the Cargo.toml) then `cargo update -p`
#
# Network: the sparse index of the registry ($REGISTRY_INDEX), public. Without network, the check
# fails; DEPS_CHECK_OFFLINE=1 explicitly ignores it (warning).
# shellcheck disable=SC2154 # index_url and manifests come from deps-lib.sh
set -euo pipefail
. "$(dirname "$0")/common.sh"
[ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; }
[ "$REGISTRY" != crates-io ] || { info " (crates.io registry: dependencies checked by deps-check-external)"; exit 0; }
mode="${1:-check}"
case "$mode" in check | bump) ;; *)
err "usage: deps-check.sh [check|bump]"
exit 2
;;
esac
[ -f "$CARGO_TOML" ] || exit 0
fail=0
bad() {
err " ✗ $*"
fail=1
}
. "$(dirname "$0")/deps-lib.sh"
decl=""
for m in "${manifests[@]}"; do
lines=$(grep -E "^[A-Za-z0-9_-]+[[:space:]]*=[[:space:]]*\{[^}]*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\"" "$m" || true)
[ -n "$lines" ] && decl+="$(printf '%s\n' "$lines" | sed "s|^|$m |")"$'\n'
done
if [ -z "$decl" ]; then
ok "✓ No dependency on registry $REGISTRY to check"
exit 0
fi
info "→ Freshness of the registry dependencies (registry $REGISTRY)..."
count=0
updates=""
offline=0
while IFS=$'\t' read -r manifest line; do
[ -n "$manifest" ] || continue
name=${line%%[[:space:]=]*}
req=$(printf '%s' "$line" | sed -nE 's/.*version[[:space:]]*=[[:space:]]*"([^"]*)".*/\1/p')
count=$((count + 1))
if [ -z "$req" ]; then
bad "$name ($manifest): no \"version\" in the declaration"
continue
fi
rc=0
latest=$(latest_published "$name") || rc=$?
if [ "$rc" -eq 2 ]; then
offline=1
continue
fi
if [ "$rc" -eq 1 ] || [ -z "$latest" ]; then
bad "$name ($manifest): no version published on registry $REGISTRY"
continue
fi
acc=0
req_accepts "$req" "$latest" || acc=$?
case "$acc" in
2) bad "$name ($manifest): requirement \"$req\" cannot be parsed (write x.y, or x for a version ≥ 1)" ;;
1)
if [ "$(printf '%s\n%s\n' "$req" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
if [ "$mode" = bump ]; then
new=$(req_for "$latest")
sed -E "/^${name}[[:space:]]*=.*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\"/ s/(version[[:space:]]*=[[:space:]]*\")[^\"]*/\1$new/" "$manifest" >"$manifest.tmp" &&
mv "$manifest.tmp" "$manifest"
info " $name ($manifest): \"$req\" → \"$new\" (latest published version: $latest)"
updates+="$name "
else
bad "$name ($manifest): the requirement \"$req\" does not accept the latest published version $latest → $name = { version = \"$(req_for "$latest")\", registry = \"$REGISTRY\" } (make deps-bump)"
fi
else
bad "$name ($manifest): the requirement \"$req\" is newer than the latest published version $latest (publication pending?)"
fi
;;
esac
# Cargo.lock: on the latest version if the dependency comes from the registry.
if [ -f Cargo.lock ]; then
locked=$(lock_entries | awk -v n="$name" -v r="/api/packages/$REGISTRY/" '$1 == n && index($3, r) { print $2 }' | sort -V | tail -n 1)
if [ -n "$locked" ] && [ "$locked" != "$latest" ] && [ "$acc" -eq 0 ]; then
if [ "$mode" = bump ]; then
updates+="$name "
else
bad "$name: Cargo.lock is on $locked, the latest published version is $latest → cargo update -p $name (make deps-bump)"
fi
fi
fi
# Neighbouring folder: replaces the dependency in joint development.
if [ -f "../$name/Cargo.toml" ]; then
neighbor=$(sed -n 's/^version = "\(.*\)"/\1/p' "../$name/Cargo.toml" | head -n 1)
if [ -n "$neighbor" ] && [ "$neighbor" != "$latest" ]; then
if [ "$(printf '%s\n%s\n' "$neighbor" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then
bad "$name: the neighbouring folder ../$name is at $neighbor, the registry at $latest → update the neighbour (jj git fetch)"
else
warn " ⚠ $name: the neighbouring folder ../$name ($neighbor) is newer than the published version ($latest): publication pending"
fi
fi
fi
done <<<"$decl"
if [ "$offline" -eq 1 ]; then
if [ "${DEPS_CHECK_OFFLINE:-}" = 1 ]; then
warn " ⚠ registry unreachable: freshness of the dependencies not verified (DEPS_CHECK_OFFLINE=1)"
else
bad "registry $REGISTRY unreachable ($index_url): freshness cannot be verified (DEPS_CHECK_OFFLINE=1 to ignore)"
fi
fi
# Cargo.lock: ignored patch and duplicates.
if [ -f Cargo.lock ]; then
unused=$(awk '
/^\[\[patch.unused\]\]/ { u = 1; next }
/^\[/ { u = 0 }
u && /^name = / { gsub(/"/, "", $3); print $3 }
' Cargo.lock | sort -u | paste -sd' ' -)
if [ -n "$unused" ] && [ "$mode" = check ]; then
bad "Cargo.lock: local patch ignored for $unused — the project's requirement does not accept the version of the neighbouring folder"
fi
dups=$(lock_entries | awk -v r="/api/packages/$REGISTRY/" '
{ c[$1]++; vs[$1] = vs[$1] " " $2; if ($3 == "-" || index($3, r)) p[$1] = 1 }
END { for (n in c) if (c[n] > 1 && p[n]) print n ":" vs[n] }
')
if [ -n "$dups" ]; then
while IFS= read -r d; do
bad "Cargo.lock: several versions of ${d%%:*} in the build (${d#*: }) — align the requirements of the crates that depend on it"
done <<<"$dups"
fi
fi
if [ "$mode" = bump ] && [ -n "$updates" ]; then
for n in $(printf '%s\n' $updates | sort -u); do
info " cargo update -p $n"
"$CARGO" update -p "$n" >/dev/null
done
fi
if [ "$fail" -ne 0 ]; then
err "✗ Registry dependencies stale or inconsistent (see above)"
exit 1
fi
ok "✓ Registry dependencies up to date ($count checked)"
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Functions shared by the dependency checks (deps-check.sh, deps-check-external.sh).
# To be sourced after common.sh. Nothing here writes a file.
index_url="${REGISTRY_INDEX#sparse+}"
index_url="${index_url%/}"
# Path of a crate in a sparse index (1, 2, 3 characters, then two pairs).
index_path() {
local n
n=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
case ${#n} in
1) echo "1/$n" ;;
2) echo "2/$n" ;;
3) echo "3/${n:0:1}/$n" ;;
*) echo "${n:0:2}/${n:2:2}/$n" ;;
esac
}
# Latest published version (not yanked, excluding pre-releases) of $1 in the sparse index $2 (default:
# the private registry); empty if not found.
# Code: 0 found, 1 absent from the index, 2 index unreachable.
latest_published() {
local body rc=0 base="${2:-$index_url}"
body=$(curl -sS -f -m 20 "$base/$(index_path "$1")" 2>/dev/null) || rc=$?
if [ "$rc" -ne 0 ]; then
case "$rc" in 22 | 37) return 1 ;; *) return 2 ;; esac
fi
printf '%s\n' "$body" |
sed -n 's/.*"vers":"\([^"]*\)".*"yanked":false.*/\1/p' |
grep -v -- '-' | sort -V | tail -n 1
}
# Does the requirement $1 (x, x.y or x.y.z, with optional ^) accept version $2?
# Code: 0 yes, 1 no, 2 unsupported form.
req_accepts() {
local r="${1#^}" v="$2" rmaj rmin rest vmaj vmin
case "$r" in '' | *[!0-9.]*) return 2 ;; esac
IFS=. read -r rmaj rmin rest <<<"$r"
IFS=. read -r vmaj vmin rest <<<"$v"
[ "$rmaj" = "$vmaj" ] || return 1
if [ "$rmaj" = 0 ] && [ -n "$rmin" ]; then
[ "$rmin" = "$vmin" ] || return 1
fi
return 0
}
# Minimal requirement that accepts version $1: x.y for a 0.x, x otherwise.
req_for() {
case "$1" in
0.*) echo "$1" | cut -d. -f1,2 ;;
*) echo "$1" | cut -d. -f1 ;;
esac
}
# Packages of Cargo.lock, one per line: "name version source" ("-" without source). The
# [[patch.unused]] blocks are excluded.
lock_entries() {
awk '
function flush() { if (n != "") print n, v, (s == "" ? "-" : s); n = v = s = "" }
/^\[\[package\]\]/ { flush(); inpkg = 1; next }
/^\[/ { flush(); inpkg = 0; next }
inpkg && /^name = / { gsub(/"/, "", $3); n = $3 }
inpkg && /^version = / { gsub(/"/, "", $3); v = $3 }
inpkg && /^source = / { gsub(/"/, "", $3); s = $3 }
END { flush() }
' Cargo.lock
}
manifests=("$CARGO_TOML")
# Root of a workspace whose member CARGO_TOML designates (workspace): shared dependencies.
[ "$CARGO_TOML" != Cargo.toml ] && [ -f Cargo.toml ] && manifests+=(Cargo.toml)
for m in */Cargo.toml; do
if [ -f "$m" ]; then manifests+=("$m"); fi
done
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# Generates .cargo/config.toml (local, ignored by jj) for joint development:
# - the definition of the private registry;
# - a [patch.<registry>] for each registry dependency that has a neighbouring folder
# (../<name>/Cargo.toml), so that the project builds against the neighbouring code without publishing.
# Only the dependencies actually declared by this project are patched: no unused patch
# (Cargo complains about it), whatever the number of crates coming out of a workspace.
#
# Run by crate.mk on every make invocation. The file is rewritten only if it changes.
# Reads the root Cargo.toml and those of the direct subfolders (workspace members);
# only the dependencies on one line `name = { …, registry = "<registry>" }` are seen.
# A .cargo/config.toml that was not generated by this script is never overwritten (warning).
set -euo pipefail
. "$(dirname "$0")/common.sh"
[ -f "$CARGO_TOML" ] || exit 0
# Nothing to generate without a registry (no extension) nor for crates.io (cargo's default index and token).
[ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ] || exit 0
marker="# Generated by .crate-kit/scripts/dev-patch.sh"
config=".cargo/config.toml"
if [ -f "$config" ] && ! grep -q "^$marker" "$config"; then
warn "⚠ $config was not generated by the kit: left as is. If it is tracked by the repository,"
warn " delete it and add /.cargo/config.toml to .gitignore (the CI uses an environment variable)."
exit 0
fi
self=$(crate_name)
manifests=("$CARGO_TOML")
# Root of a workspace whose member CARGO_TOML designates (workspace): this is where the shared
# dependencies ([workspace.dependencies]) are declared.
[ "$CARGO_TOML" != Cargo.toml ] && [ -f Cargo.toml ] && manifests+=(Cargo.toml)
for m in */Cargo.toml; do [ -f "$m" ] && manifests+=("$m"); done
registry_deps() {
sed -nE "s/^([A-Za-z0-9_-]+)[[:space:]]*=[[:space:]]*\{[^}]*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\".*/\1/p" "$@"
}
names=$(registry_deps "${manifests[@]}" | sort -u)
# Transitive closure through the neighbours: a dependency of a patched neighbour (a -> a-macros)
# must be patched too, otherwise the project builds the neighbour against the published version of its own
# dependency and not against the neighbouring code.
while :; do
more=$(for n in $names; do [ -f "../$n/Cargo.toml" ] && registry_deps "../$n/Cargo.toml"; done | sort -u)
merged=$(printf '%s\n%s\n' "$names" "$more" | sed '/^$/d' | sort -u)
[ "$merged" = "$names" ] && break
names=$merged
done
patches=""
for n in $names; do
[ "$n" = "$self" ] && continue
[ -f "../$n/Cargo.toml" ] && patches+="$n = { path = \"../$n\" }"$'\n'
done
new="$marker on every \`make\`: do not edit, do not commit (ignored by the repository).
# Private registry and, for joint development, dependencies resolved to the neighbouring folders.
[registries.$REGISTRY]
index = \"$REGISTRY_INDEX\"
"
[ -n "$patches" ] && new+="
[patch.$REGISTRY]
$patches"
if [ ! -f "$config" ] || [ "$(cat "$config")" != "${new%$'\n'}" ]; then
mkdir -p .cargo
printf '%s' "$new" >"$config"
list=$(printf '%s' "$patches" | sed 's/ = .*//' | paste -sd' ' -)
info " $config updated (local patches: ${list:-none})"
fi
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Creates the Forgejo release associated with the tag version-x.y.z. Description: the message of the tag if it is
# annotated, otherwise (lightweight tag created by tag.sh) the file $RELEASE_NOTES_DIR/version-x.y.z.md of the
# working directory, which must be the checkout of the tag. Meant for the CI; idempotent: an already existing release is
# reused, and an attached file that is already present is not sent again.
#
# Variables (provided by the workflow):
# FORGETOKEN Forgejo API token (write access to releases)
# TAG tag to publish (e.g. version-0.1.4)
# SERVER Forgejo server URL (e.g. https://forge.example.org)
# REPO owner/repository (e.g. org/crate)
# ASSET optional: file to attach to the release (e.g. dist/crate-kit-0.1.4.tar.gz)
set -euo pipefail
. "$(dirname "$0")/common.sh"
: "${FORGETOKEN:?FORGETOKEN required}" "${TAG:?TAG required}" "${SERVER:?SERVER required}" "${REPO:?REPO required}"
command -v jq >/dev/null || { err "✗ jq is required"; exit 1; }
api="$SERVER/api/v1/repos/$REPO"
auth="Authorization: token $FORGETOKEN"
if release_json=$(curl -sf -H "$auth" "$api/releases/tags/$TAG"); then
warn " The release $TAG already exists: reused"
else
# Message of the annotated tag (object of type "tag"); empty for a lightweight tag.
ref_json=$(forge_call "reading tag $TAG" -H "$auth" "$api/git/refs/tags/$TAG") || exit 1
obj_sha=$(echo "$ref_json" | jq -r '.[0]?.object.sha // empty')
obj_type=$(echo "$ref_json" | jq -r '.[0]?.object.type // empty')
body=""
if [ "$obj_type" = "tag" ]; then
tag_json=$(forge_call "reading the message of tag $TAG" -H "$auth" "$api/git/tags/$obj_sha") || exit 1
body=$(echo "$tag_json" | jq -r '.message // empty')
fi
# Lightweight tag (tag.sh, jj only): the notes are the file committed in the tagged revision, read in the
# working directory (the workflow runs in the checkout of the tag).
if [ -z "$body" ] && [ -f "$RELEASE_NOTES_DIR/$TAG.md" ]; then
body=$(cat "$RELEASE_NOTES_DIR/$TAG.md")
fi
release_json=$(forge_call "creating release $TAG" -X POST "$api/releases" -H "$auth" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg tag "$TAG" --arg body "$body" '{tag_name: $tag, name: $tag, body: $body}')") || exit 1
ok "✓ Release $TAG created"
fi
if [ -n "${ASSET:-}" ]; then
[ -f "$ASSET" ] || { err "✗ file to attach not found: $ASSET"; exit 1; }
release_id=$(echo "$release_json" | jq -r '.id')
name=$(basename "$ASSET")
if echo "$release_json" | jq -e --arg n "$name" '.assets[]? | select(.name == $n)' >/dev/null; then
warn " $name is already attached to the release: nothing to do"
else
forge_call "uploading $name to release $TAG" -X POST "$api/releases/$release_id/assets?name=$name" \
-H "$auth" -F "attachment=@$ASSET" >/dev/null || exit 1
ok "✓ $name attached to release $TAG"
fi
fi
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Fetches the latest commits from origin WITHOUT losing local work: the mutable revisions
# sitting on the old main are rebased on top of the fetched main@origin.
#
# - local work (mutable revisions between main@origin and @, including an empty working
# copy): rebased onto main@origin;
# - work sitting on a pushed revision not yet merged into main@origin (pending
# PR): left in place, with a warning (rebasing it would cut it off from that revision);
# - working copy already contained in main@origin: we start again from a new revision on top of it.
#
# JJ_BASE (default main@origin): the base to join.
set -euo pipefail
. "$(dirname "$0")/common.sh"
base="${JJ_BASE:-main@origin}"
info "→ Fetching the latest commits..."
jj git fetch
jj log -r "$base" --no-graph -T 'change_id' >/dev/null 2>&1 || {
err "✗ $base not found after the fetch"
exit 1
}
# Local work = mutable revisions between the base and @ that are NOT already published (reachable
# from a remote bookmark): we do not rewrite what origin knows. We only keep the roots
# whose parent is already in the base's history.
work="(mutable() & ($base..@)) ~ ::remote_bookmarks()"
# A local revision rewritten AFTER its push (describe, rebase…) then merged on the server side in its
# pushed version has a twin in $base: same change id, other commit, hence a divergent
# change. We never designate a revision by its change id (jj refuses a divergent
# identifier), and we do not rebase what is already merged:
# - same content as the merged twin: the local revision is abandoned (nothing is lost);
# - different content: we stop before rewriting anything, with the course of action to follow.
for c in $(jj log --no-graph -r "($work) & divergent()" -T 'commit_id ++ "\n"'); do
cid=$(jj log --no-graph -r "$c" -T 'change_id')
twin=$(jj log --no-graph -r "change_id($cid) & ::$base" -T 'commit_id ++ "\n"' | head -n 1)
[ -n "$twin" ] || continue
short=$(jj log --no-graph -r "$c" -T 'commit_id.short(12)')
if [ -z "$(jj interdiff --from "$twin" --to "$c" --summary)" ]; then
jj abandon "$c"
ok "✓ Revision $short already merged into $base (same content): abandoned"
else
err "✗ The local revision $short has already been merged into $base in another version"
err " (same change id, different content): nothing was rewritten."
err " See the difference: jj interdiff --from $twin --to $c"
err " Keep the merged version: jj abandon $c"
err " Keep the local version: jj metaedit --update-change-id $c, then rerun"
exit 1
fi
done
roots=$(jj log --no-graph -r "roots($work) & children(::$base)" -T 'commit_id ++ "\n"')
if [ -n "$roots" ]; then
args=()
for r in $roots; do args+=(-s "$r"); done
jj rebase "${args[@]}" -d "$base"
ok "✓ Local work rebased onto $base"
elif [ -n "$(jj log --no-graph -r "@ & ::$base" -T 'change_id')" ]; then
# The working copy is already part of the base: nothing to keep.
jj new "$base"
ok "✓ New revision on $base"
elif [ -n "$(jj log --no-graph -r "($base..@) & (::remote_bookmarks() | immutable())" -T 'change_id')" ]; then
warn "⚠ The work rests on pushed revisions not merged into $base (pending PR):"
warn " left in place. Merge the PR then rerun, if needed."
else
ok "✓ Already up to date on $base"
fi
if [ -n "$(jj log --no-graph -r 'conflicts() & ::@ & mutable()' -T 'change_id' 2>/dev/null)" ]; then
warn "⚠ Conflicts after the rebase: jj st, then jj resolve."
fi
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Checks that the crate is adopted: the CI release workflow is installed and up to date with the template of
# its kind (comments and step names ignored; opt out with a `# kit-workflow: custom` line), and the kit copy
# (.crate-kit/) is identical to the reference kit (crate-kit + overlay, assembled by $KIT_SRC/tools/kit-assemble.sh; default ../crate-kit). Read-only.
#
# Compares the CONTENT, not VERSION: a fix to the kit does not always change its number.
# `--fix`: instead of failing on an out-of-date workflow, replace it with the template of its kind.
# Without a crate-kit repository alongside (clone of the crate alone, CI), there is nothing to compare: success.
set -euo pipefail
. "$(dirname "$0")/common.sh"
fix=0
[ "${1:-}" = "--fix" ] && fix=1
kit_dir="$(cd "$(dirname "$0")/.." && pwd)"
crate_dir="$(dirname "$kit_dir")"
# Without this workflow, a version-* tag publishes nothing: the crate was not adopted all the way.
workflow=".gitea/workflows/release.yaml"
if [ ! -f "$crate_dir/$workflow" ]; then
err "✗ $workflow is missing in $crate_dir: the release CI will not trigger"
info " Complete the adoption: crate-kit/adopt.sh [--kind <kind>] $crate_dir"
exit 1
fi
kit_src="${KIT_SRC:-../crate-kit}"
# Workflow up to date with the template of the crate's kind (the same one adopt.sh lays down). Only the
# logic counts: comment lines and `- name:` labels are ignored, so a rewording is not a difference.
if [ -x "$kit_src/tools/kit-assemble.sh" ] && ! grep -q '^# kit-workflow: custom' "$crate_dir/$workflow"; then
kind="${CRATE_KIND:-}"
if [ -z "$kind" ] && [ -f "$crate_dir/Makefile" ]; then
kind=$(sed -n 's/^CRATE_KIND *[:?]*= *\([a-z]*\).*/\1/p' "$crate_dir/Makefile" | head -n 1)
fi
template="$("$kit_src/tools/kit-assemble.sh" --root)/template"
overlay=$("$kit_src/tools/kit-assemble.sh" --overlay 2>/dev/null || true)
[ -n "$kind" ] && [ -n "$overlay" ] && [ -d "$overlay/templates/$kind" ] && template="$overlay/templates/$kind"
norm() { grep -v '^ *#' "$1" | grep -v '^ *- name:' | sed 's/[[:space:]]*$//'; }
if [ -f "$template/$workflow" ] && ! diff <(norm "$crate_dir/$workflow") <(norm "$template/$workflow") >/dev/null; then
if [ "$fix" = 1 ]; then
cp "$template/$workflow" "$crate_dir/$workflow"
ok "→ $workflow replaced with the template of its kind"
else
err "✗ $workflow differs from the template of its kind: the release CI is out of date"
diff <(norm "$crate_dir/$workflow") <(norm "$template/$workflow") >&2 || true
info " Replace it: cp $template/$workflow $crate_dir/$workflow"
info " (keep a deliberate customization by adding the line \"# kit-workflow: custom\" to the workflow)"
exit 1
fi
fi
fi
if [ ! -x "$kit_src/tools/kit-assemble.sh" ]; then
info " (reference kit not found: $kit_src, check skipped)"
exit 0
fi
ref="$(mktemp -d "${TMPDIR:-/tmp}/kit-check.XXXXXX")"
trap 'rm -r "$ref"' EXIT
"$kit_src/tools/kit-assemble.sh" "$ref"
if diff -rq "$ref" "$kit_dir" >/dev/null 2>&1; then
ok "✓ Kit up to date (crate-kit $(cat "$ref/VERSION"))"
exit 0
fi
err "✗ This crate's kit is not the one from $kit_src:"
diff -rq "$ref" "$kit_dir" >&2 || true
info " Update: make kit-update"
exit 1
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
# Is there, in the crate's jj working copy (current directory), a change that justifies a
# commit, that is, something other than what the kit itself produces or modifies? Read-only.
#
# Do not count:
# - .crate-kit/ (kit copy) and .cargo/ (generated local configuration);
# - a template file (.gitea/workflows/release.yaml, LICENSE, .gitignore, Makefile…) identical to
# that of the kind's template (<extension>/templates/<kind>, otherwise crate-kit/template): adopt.sh laid it down as is;
# - Cargo.lock when only the `version` line of the crate itself changed (version bump);
# - the Makefile when only its kit bootstrap lines changed (KIT_SRC, copy or sync of
# .crate-kit/, comments that talk about the kit): the rest (description, PLUGIN_ID…) belongs to the crate.
# Without a crate-kit repository alongside ($KIT_SRC), the second filter cannot apply: these files
# then count as changes.
#
# Output: one file per line on standard output. Code 0 if there are any, 1 otherwise (nothing to commit).
set -euo pipefail
. "$(dirname "$0")/common.sh"
kit_src="${KIT_SRC:-../crate-kit}"
kind="${CRATE_KIND:-}"
if [ -z "$kind" ] && [ -f Makefile ]; then
kind=$(sed -n 's/^CRATE_KIND *[:?]*= *\([a-z]*\).*/\1/p' Makefile | head -n 1)
fi
template="$("$kit_src/tools/kit-assemble.sh" --root)/template"
overlay=$("$kit_src/tools/kit-assemble.sh" --overlay 2>/dev/null || true)
[ -n "$kind" ] && [ -n "$overlay" ] && [ -d "$overlay/templates/$kind" ] && template="$overlay/templates/$kind"
# Cargo.lock: did only the `version` line of the crate's package change?
lock_is_version_bump() {
local name
name=$(crate_name)
jj diff --git --context 1 Cargo.lock 2>/dev/null | awk -v name="$name" '
/^(\+\+\+|---)/ { next }
/^@@/ { prev = ""; next }
/^[-+]/ {
changed++
if ($0 !~ /^[-+]version = / || prev != " name = \"" name "\"") bad = 1
next
}
/^ / { prev = $0 }
END { exit (changed > 0 && !bad) ? 0 : 1 }'
}
# Makefile: did only the kit bootstrap lines change? Those that name KIT_SRC or
# `crate-kit` (variable, sync, copy of .crate-kit/) and the comments that talk about the kit; a
# modification of any other line (description, PLUGIN_ID, targets) is a real change of the crate.
makefile_is_kit_bootstrap() {
jj diff --git --context 1 Makefile 2>/dev/null | awk '
/^(\+\+\+|---)/ { next }
/^[-+]/ {
changed++
if ($0 !~ /KIT_SRC|crate-kit|kit-copy|^[-+]# .*[Kk]it/) bad = 1
}
END { exit (changed > 0 && !bad) ? 0 : 1 }'
}
found=0
while IFS= read -r line; do
# Format of `jj diff --summary`: "M path"; a rename "R {a => b}" remains a change.
path="${line#? }"
case "$path" in
.crate-kit/* | .cargo/*) continue ;;
Cargo.lock)
if lock_is_version_bump; then continue; fi
;;
Makefile)
if makefile_is_kit_bootstrap; then continue; fi
;;
esac
if [ "${line%% *}" = M ] && [ -f "$template/$path" ] && cmp -s "$template/$path" "$path"; then
continue
fi
echo "$path"
found=1
done < <(jj diff --summary)
[ "$found" -eq 1 ] || { info " nothing to commit outside the kit" ; exit 1; }
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Starts a new working commit (`jj new`), unless @ already is a blank one (empty, without a description).
# After a push of main, @ is usually already blank: when the pushed commit was @, it became immutable and jj
# itself created an empty working commit on top of it (operation "push bookmark main"). An unconditional
# `jj new` would then stack a second, useless empty commit.
set -euo pipefail
. "$(dirname "$0")/common.sh"
blank=$(jj log -r @ --no-graph -T 'if(empty && description == "", "1", "0")')
if [ "$blank" = 1 ]; then
info " (@ is already an empty working commit: no new commit)"
exit 0
fi
jj new
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# Safeguard: a crate published on a private registry declares `publish = ["<registry>"]` in its
# Cargo.toml, so that cargo itself refuses any publication elsewhere (crates.io for example).
# Not applicable: kind without publication (PUBLISH=no), registry absent or crates-io.
set -euo pipefail
. "$(dirname "$0")/common.sh"
[ "${PUBLISH:-yes}" = no ] && exit 0
{ [ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ]; } || exit 0
[ -f "$CARGO_TOML" ] || exit 0
grep -qE "^publish[[:space:]]*=[[:space:]]*\[[[:space:]]*\"$REGISTRY\"[[:space:]]*\]" "$CARGO_TOML" && exit 0
err "✗ $CARGO_TOML : publish = [\"$REGISTRY\"] missing in [package] (without it, cargo publish would accept crates.io)"
exit 1
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Publishes the current version on the $REGISTRY registry (private, or crates-io with CARGO_REGISTRY_TOKEN).
# DRY_RUN non-empty: assembles and builds the package without sending it.
#
# Idempotent: if the version is already published, it is a success (allows replaying the release
# workflow after a later failure). Authentication: variable CARGO_REGISTRIES_<REGISTRY>_TOKEN
# ("Bearer <token>"), otherwise built from the forge token (forge_token: FORGETOKEN in CI).
#
# --allow-dirty: in a colocated jj repository, git always sees the working copy as
# modified relative to its HEAD, even when the jj commit is already pushed.
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${PUBLISH:-yes}" = no ]; then
info " (kind ${CRATE_KIND:-crate}: nothing to publish on the registry)"
exit 0
fi
[ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; }
version=$(current_version)
name=$(crate_name)
if [ -n "${DRY_RUN:-}" ]; then
warn "→ Checking the publication of $name $version (without sending)..."
"$CARGO" publish --registry "$REGISTRY" --allow-dirty --dry-run
exit 0
fi
warn "→ Publishing $name $version on registry $REGISTRY..."
log=$(mktemp)
trap 'rm -f -- "$log"' EXIT
if "$CARGO" publish --registry "$REGISTRY" --allow-dirty 2>&1 | tee "$log" >&2; then
ok "✓ $name $version published"
elif grep -qiE 'already (exists|uploaded)|crate version .* is already' "$log"; then
warn " $name $version is already published on $REGISTRY: nothing to do"
else
err "✗ Publication of $name $version failed"
exit 1
fi
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Advances the main bookmark to the current commit (@, or its first non-empty ancestor if @ is an
# empty working commit without a description: release_rev) and pushes it: no PR branch, main receives
# the commit directly. Moving main must be a fast-forward (jj refuses otherwise): if
# main@origin has advanced, `make jjfetch` first rebases the local work onto it.
set -euo pipefail
. "$(dirname "$0")/common.sh"
abandon_blank_commits
rev=$(release_rev)
if ! jj bookmark set main -r "$rev" 2>/dev/null; then
err "✗ main cannot advance to $rev (main has diverged or $rev does not descend from it)"
info " Run make jjfetch to rebase the work onto main@origin, then start again."
exit 1
fi
jj git push --bookmark main
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Generates $RELEASE_NOTES_DIR/version-<version>.md: notes produced by `jj release-notes`
# (fallback to one line if they fail, e.g. before the first tag), then adds a
# "Public API" section with the snapshot diff since the previous version.
set -euo pipefail
. "$(dirname "$0")/common.sh"
version=$(current_version)
notes="$RELEASE_NOTES_DIR/version-$version.md"
info "→ Generating the release notes ($notes)..."
mkdir -p "$RELEASE_NOTES_DIR"
PMOJJ_RELEASE_LANG="${KIT_LANG:-en}" PMOJJ_RELEASE_PROJECT="${RELEASE_PROJECT_DESC:-$(crate_name)}" jj release-notes --release "$version" >"$notes" ||
echo "Release version-$version" >"$notes"
prev=$(ls "$API_DIR"/*.txt 2>/dev/null | sed 's|.*/||; s|\.txt$||' | sort -V |
grep -v -x "$version" | tail -n 1 || true)
if [ -n "$prev" ] && [ -f "$API_DIR/$version.txt" ]; then
api_diff=$(diff <(filter_notes "$API_DIR/$prev.txt") <(filter_notes "$API_DIR/$version.txt") | grep '^[<>]' || true)
if [ -n "$api_diff" ]; then
printf '\n## Public API (changes since %s)\n\n```diff\n%s\n```\n' \
"$prev" "$api_diff" >>"$notes"
fi
fi
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Does the release tag `version-<version>` already exist (locally or on origin)? jj only, no git command.
# Usage: tag-exists.sh <version>
# Exit: 0 = the tag exists, 1 = it does not, 2 = not checked (no jj repository, origin unreachable).
# jj has no equivalent of `ls-remote`: the tag alone is fetched (`jj git fetch --tag`), which imports it as a
# tracked remote tag if it exists on origin and changes nothing else, then `jj tag list` tells.
set -uo pipefail
version="${1:?usage: tag-exists.sh <version>}"
tag="version-$version"
jj root >/dev/null 2>&1 || exit 2
jj git fetch --tag "exact:$tag" >/dev/null 2>&1 || exit 2
if [ -n "$(jj tag list "exact:$tag" -T 'name ++ "\n"' 2>/dev/null)" ]; then
exit 0
fi
exit 1
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Creates and pushes the tag version-<version> on the published commit (release_rev: @, or its first
# non-empty ancestor), with jj only. The tag is lightweight (jj creates no annotated tag): the release notes
# are not its message but the file $RELEASE_NOTES_DIR/version-<version>.md committed in the tagged revision,
# which forgejo-release.sh reads in the CI as the body of the release.
set -euo pipefail
. "$(dirname "$0")/common.sh"
version=$(current_version)
tag="version-$version"
notes="$RELEASE_NOTES_DIR/$tag.md"
[ -f "$notes" ] || { err "✗ release notes missing: $notes (make release-notes)"; exit 1; }
if [ -n "$(jj tag list "exact:$tag" 2>/dev/null)" ]; then
err "✗ tag $tag already exists"
exit 1
fi
rev=$(release_rev)
jj tag set "$tag" -r "$rev"
jj git push --tag "exact:$tag"
ok "✓ Release $tag published"
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env bash
# Publishes the API documentation (rustdoc -> JSON -> Markdown) to the crate's Forgejo wiki.
#
# The Forgejo wiki is a second repository (<repository>.wiki.git). It is never kept: the script
# clones it into a temporary directory (git), replaces the generated pages, commits and pushes, then
# removes the clone. Works identically locally and in the CI (release workflow).
#
# Pages produced: Home.md (module index), _Sidebar.md, one page per module.
# The wiki content is ENTIRELY replaced: any page written by hand on the Forgejo side
# disappears at the next run.
#
# Variables:
# WIKI_URL wiki repository URL (default: `origin` URL with .git replaced by .wiki.git)
# WIKI_TOKEN access token (CI, https URL): sent in the header "Authorization: token …"
# GIT_USER_NAME / GIT_USER_EMAIL commit identity if git has none configured
# DRY_RUN non-empty: generates and commits in the temporary clone, shows the diff, does not push
#
# Prerequisites: cargo-doc-md (cargo install cargo-doc-md --locked); the wiki must exist on the
# Forgejo side (create a first page by hand once per crate, otherwise the repository is not found).
set -euo pipefail
. "$(dirname "$0")/common.sh"
if [ "${WIKI:-yes}" = no ]; then
info " (kind ${CRATE_KIND:-crate}: no API documentation for the wiki)"
exit 0
fi
require_cargo_tool doc-md cargo-doc-md
name=$(crate_name)
version=$(current_version)
# Wiki URL: that of origin, with .git replaced by .wiki.git.
if [ -z "${WIKI_URL:-}" ]; then
origin=$(git remote get-url origin 2>/dev/null || true)
[ -n "$origin" ] || { err "✗ remote origin not found: set WIKI_URL=..."; exit 1; }
WIKI_URL="${origin%.git}.wiki.git"
fi
# Common git options: token in a header (CI) and fallback identity.
git_opts=()
if [ -n "${WIKI_TOKEN:-}" ]; then
git_opts+=(-c "http.extraHeader=Authorization: token $WIKI_TOKEN")
fi
if [ -z "$(git config user.name 2>/dev/null || true)" ]; then
git_opts+=(-c "user.name=${GIT_USER_NAME:-crate-kit}")
fi
if [ -z "$(git config user.email 2>/dev/null || true)" ]; then
git_opts+=(-c "user.email=${GIT_USER_EMAIL:-crate-kit@localhost}")
fi
wgit() { git "${git_opts[@]}" "$@"; }
work=$(mktemp -d "${TMPDIR:-/tmp}/crate-kit-wiki.XXXXXX")
[ -n "$work" ] && [ -d "$work" ] || { err "✗ temporary directory not created"; exit 1; }
trap 'rm -rf -- "$work"' EXIT
# 1. Rustdoc -> Markdown (one file per module, in $work/md/<crate>/).
info "→ Generating the Markdown ($name $version)..."
"$CARGO" doc-md --no-deps -o "$work/md" >&2
src="$work/md/$name"
[ -f "$src/index.md" ] || {
# The folder name follows the library name (hyphens -> underscores).
src="$work/md/${name//-/_}"
[ -f "$src/index.md" ] || { err "✗ index.md not found in $work/md"; exit 1; }
}
# 2. Wiki pages: flat, links between pages without the .md extension (Forgejo wiki convention).
pages="$work/pages"
mkdir -p "$pages"
for f in "$src"/*.md; do
base=$(basename "$f")
[ "$base" = index.md ] && continue
cp "$f" "$pages/$base"
done
# Home = crate index as produced by cargo-doc-md (title, crate doc, modules);
# the version appears in the sidebar.
sed -E 's/\]\(([^)#]+)\.md\)/](\1)/g' "$src/index.md" >"$pages/Home.md"
{
printf '**[%s](Home)** %s\n\n' "$name" "$version"
sed -nE 's/^### \[`([^`]+)`\]\(([^)]+)\.md\).*/- [\1](\2)/p' "$src/index.md"
} >"$pages/_Sidebar.md"
# Rustdoc intra-doc links (``[`item`]``, ``[`module::item`]``): cargo-doc-md does not resolve them
# and leaves them in literal brackets. We resolve them here to the wiki page that defines
# the item (table built from the "Contents" of each module page); a module
# points to its own page. Names not found (std, other crates) lose their
# brackets and remain as code.
map="$work/map"
: >"$map"
for f in "$pages"/*.md; do
p=$(basename "$f" .md)
case "$p" in Home | _Sidebar) continue ;; esac
echo "$p $p" >>"$map"
done
for f in "$pages"/*.md; do
p=$(basename "$f" .md)
case "$p" in Home | _Sidebar) continue ;; esac
sed -nE 's/^- \[`([A-Za-z0-9_]+)`\]\(#.*/\1 '"$p"'/p' "$f" >>"$map"
done
resolve="$work/resolve.sed"
: >"$resolve"
while read -r item page; do
# First wins: the module pages (lines at the start) take precedence; an item already
# turned into a link is no longer a candidate (it is followed by "(").
printf 's/\\[`((([A-Za-z0-9_]+::)*)%s)`\\]([^(:[]|$)/[`\\1`](%s)\\4/g\n' "$item" "$page" >>"$resolve"
done <"$map"
for f in "$pages"/*.md; do
sed -E -f "$resolve" "$f" | sed -E 's/\[(`[^`]+`)\]([^(:[]|$)/\1\2/g' >"$f.tmp"
mv "$f.tmp" "$f"
done
# 3. Clone the wiki, replace the pages, commit, push.
info "→ Cloning the wiki ${WIKI_URL}..."
clone="$work/clone"
wgit clone --quiet "$WIKI_URL" "$clone" >&2 || {
err "✗ cannot clone: does the wiki exist? (create a first page on Forgejo)"
exit 1
}
cd "$clone"
# Default branch of the wiki (master or main depending on the instance): the one the clone checked out.
branch=$(git symbolic-ref --short HEAD)
# The generated files replace all the .md; the rest (images…) is kept.
find . -maxdepth 1 -name '*.md' -type f -delete
cp "$pages"/*.md .
git add -A
if [ -z "$(git status --porcelain)" ]; then
ok "✓ Wiki already up to date"
exit 0
fi
git diff --cached --stat >&2
wgit commit --quiet -m "API documentation: $name $version"
if [ -n "${DRY_RUN:-}" ]; then
warn "→ DRY_RUN: local commit in the temporary clone, nothing is pushed"
exit 0
fi
wgit push --quiet origin "$branch" >&2
ok "✓ Wiki of $name updated ($version)"
+5 -5
View File
@@ -76,12 +76,12 @@ jobs:
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
run: |
mkdir -p /tmp/dist
cp target/x86_64-unknown-linux-musl/release/obikmer /tmp/dist/obikmer-linux-x86_64
strip /tmp/dist/obikmer-linux-x86_64
cp target/x86_64-unknown-linux-musl/release/obiskim /tmp/dist/obiskim-linux-x86_64
strip /tmp/dist/obiskim-linux-x86_64
curl -s -X POST \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets" \
-H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@/tmp/dist/obikmer-linux-x86_64"
-F "attachment=@/tmp/dist/obiskim-linux-x86_64"
build-macos-arm64:
needs: create-release
@@ -112,7 +112,7 @@ jobs:
docker start -a "$CID"
STATUS=$(docker wait "$CID")
mkdir -p /tmp/dist
docker cp "$CID:/src/src/target/aarch64-apple-darwin/release/obikmer" /tmp/dist/obikmer-macos-arm64
docker cp "$CID:/src/src/target/aarch64-apple-darwin/release/obiskim" /tmp/dist/obiskim-macos-arm64
docker rm "$CID" > /dev/null
[ "$STATUS" -eq 0 ]
@@ -124,4 +124,4 @@ jobs:
curl -s -X POST \
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/$RELEASE_ID/assets" \
-H "Authorization: token $GITEA_TOKEN" \
-F "attachment=@/tmp/dist/obikmer-macos-arm64"
-F "attachment=@/tmp/dist/obiskim-macos-arm64"
+25 -17
View File
@@ -1,32 +1,36 @@
.venv/
.DS_Store
.claude/
.kilo/
.serena/
.zed/
.ast-cache/
CLAUDE.md
memory/
sandbox/
src/target
data-stress
*.fasta
*.fasta.gz
*.fastq
*.fastq.gz
*.vcf
*.zst
*.zst.meta
*.pb
./**/*.json
**/*.json
*.bin
*.log
*.csv
*.meta
*.pfiv
*.done
*.efh
*.efl
*.bin.idx
*.prsb
Betula_exilis--IGA-24-33
benchmark/genomes
benchmark/genomes_orig
benchmark/simulated_data
benchmark/specimen_index_presence
benchmark/specimen_index_count
benchmark/global_index_presence
benchmark/global_index_presence_orig
benchmark/global_index_presence_sav
benchmark/all_specific
benchmark/global_index_count
benchmark/stats
benchmark/reference_index
benchmark/reference_dist
benchmark/obikmer_dist
benchmark/specific_index_count
benchmark/specific_index_presence
benchmark/run/
TNT
phyg
biblio
@@ -40,3 +44,7 @@ biblio
*.parstree
*.ckp.gz
*.model
scripts/__pycache__/mk_wiki.cpython-314.pyc
# Generated by .crate-kit/dev-patch.mk at every make
/.cargo/config.toml
-87
View File
@@ -1,87 +0,0 @@
# Plan d'amélioration technique - obiskio
## 1. Contexte et objectifs
- **Objectif** : Renforcer la robustesse, la maintenabilité et les performances de la crate `obiskio`.
- **Priorités** :
1. Gestion des erreurs
2. Optimisation de la mémoire du pool
3. Robustesse concurrente
4. Couverture de tests
5. Documentation
---
## 2. Axes d'amélioration détaillés
### 2.1 Gestion des erreurs
- **Problème** : `SKError` ne couvre pas tous les cas (format invalide, taille maximale, CRC)
- **Actions** :
- Ajouter variante `ParseError(String)` dans `src/error.rs`
- Valider les tailles de SuperKmer avant parsing
- Remplacer `expect()` par `unwrap_or_else` avec messages explicites
- Documenter chaque variante d’erreur dans le README
### 2.2 Optimisation du pool de fichiers
- **Problème** : `SKFilePool` utilise un `Vec<WriteEntry>` non contraint et n’effectue pas de nettoyage en cas d’erreur
- **Actions** :
- Implémenter un `LimitedVec` avec limite stricte à `MAX_POOL_SIZE`
- Créer `clear_memory()` qui supprime les entrées orphelines
- Ajouter `evict_lru_threshold()` pour éviction proactive
- Introduire un `RwLock` pour les opérations de lecture massives
### 2.3 Robustesse concurrente
- **Problème** : Risque de deadlocks dans `SKFileWriter::write_batch()` et `SKFileReader::reopen_and_seek()`
- **Actions** :
- Remplacer `Mutex` par `RwLock` pour les accès en lecture
- Ajouter un compteur de blocage et logs de timeout
- Utiliser `std::thread::park_timeout` pour débloquer
- Insérer `debug_assert!` sur les états invariants
### 2.4 Couverture de tests
- **Problème** : Absence de benchmarks, de tests de migration, de résilience de fichiers corrompus
- **Actions** :
- Benchmarks I/O sur 10k+ SuperKmer avec `criterion`
- Tests de migration de version de fichier `.meta` → `.v2.meta`
- Tests de corruption volontaire (truncature, inversion de bits)
- Tests de stress sur pool saturation (100 threads)
### 2.5 Documentation & exemples
- **Actions** :
- Ajouter des examples dans chaque module (`# Examples`)
- Documenter la logique LRU avec diagrammes Mermaid
- Créer un guide « How to recover from eviction »
- Mettre à jour le `README.md` avec tableau des variantes d’erreur
---
## 3. Plan d'exécution (Roadmap)
| Sprint | Durée | Livrables clés |
|--------|-------|----------------|
| **S1** | 2 jours | Refactorisation `SKError`, ajout de tests unitaires |
| **S2** | 3 jours | Implémentation `clear_memory()` + `LimitedVec` |
| **S3** | 2 jours | Passage à `RwLock`, ajout de compteurs de blocage |
| **S4** | 2 jours | Benchmarks + tests de migration |
| **S5** | 1 jour | Documentation finale & mise à jour du README |
---
## 4. Dépendances externes
- Mettre à jour `niffler` vers la version 2.0 (performance compression)
- Évaluer `bincode` vs `serde_json` pour les métas (I/O)
- Ajouter dépendance `criterion` (dev‑dependencies)
---
## 5. KPI de suivi
- **Couverture de tests** : ≥85 % des chemins critiques
- **Latence moyenne d’écriture** : ↓15 % après optimisation du pool
- **Taux d’erreurs résolues** : 100 % des nouvelles variantes couvertes
- **Temps de build CI** : ≤5 min pour l’ensemble des benchmarks
---
## 6. Validation finale
- Revue de code avec `cargo clippy -- -D warnings`
- Analyse de toxicité avec `cargo deny open-source-licenses`
- Vérification de la conformité aux standards de naming du projet
-2
View File
@@ -1,2 +0,0 @@
/cache
/project.local.yml
-133
View File
@@ -1,133 +0,0 @@
# the name by which the project can be referenced within Serena
project_name: "obikmer"
# list of languages for which language servers are started; choose from:
# al angular ansible bash clojure
# cpp cpp_ccls crystal csharp csharp_omnisharp
# dart elixir elm erlang fortran
# fsharp go groovy haskell haxe
# hlsl html java json julia
# kotlin lean4 lua luau markdown
# matlab msl nix ocaml pascal
# perl php php_phpactor powershell python
# python_jedi python_ty r rego ruby
# ruby_solargraph rust scala scss solidity
# svelte swift systemverilog terraform toml
# typescript typescript_vts vue yaml zig
# (This list may be outdated. For the current list, see values of Language enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Angular projects, use angular (subsumes typescript+html; requires `npm install` in the project root)
# - For Svelte projects, use svelte (subsumes typescript/javascript for .svelte projects; requires npm)
# - For SCSS / Sass / plain CSS, use scss (some-sass-language-server handles all three)
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# Some languages require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple languages, the first language server that supports a given file will be used for that file.
# The first language is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
languages:
- rust
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# line ending convention to use when writing source files.
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
line_ending:
# The language backend to use for this project.
# If not set, the global setting from serena_config.yml is used.
# Valid values: LSP, JetBrains
# Note: the backend is fixed at startup. If a project with a different backend
# is activated post-init, an error will be returned.
language_backend:
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the options.
# Have a look at the docstring of the constructors of the LS implementations within solidlsp (e.g., for C# or PHP) to see which options are available.
# No documentation on options means no options are available.
ls_specific_settings: {}
# list of additional workspace folder paths for cross-package reference support (e.g. in monorepos).
# Paths can be absolute or relative to the project root.
# Each folder is registered as an LSP workspace folder, enabling language servers to discover
# symbols and references across package boundaries.
# Currently supported for: TypeScript.
# Example:
# additional_workspace_folders:
# - ../sibling-package
# - ../shared-lib
additional_workspace_folders: []
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude.
# This extends the existing exclusions (e.g. from the global configuration)
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
excluded_tools: []
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
fixed_tools: []
# list of mode names that are to be activated by default, overriding the setting in the global configuration.
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# If the setting is undefined/empty, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# Therefore, you can set this to [] if you do not want the default modes defined in the global config to apply
# for this project.
# This setting can, in turn, be overridden by CLI parameters (--mode).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
default_modes:
# list of mode names to be activated additionally for this project, e.g. ["query-projects"]
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
added_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
# time budget (seconds) per tool call for the retrieval of additional symbol information
# such as docstrings or parameter information.
# This overrides the corresponding setting in the global configuration; see the documentation there.
# If null or missing, use the setting from the global configuration.
symbol_info_budget:
# list of regex patterns which, when matched, mark a memory entry as read‑only.
# Extends the list from the global configuration, merging the two lists.
read_only_memory_patterns: []
# list of regex patterns for memories to completely ignore.
# Matching memories will not appear in list_memories or activate_project output
# and cannot be accessed via read_memory or write_memory.
# To access ignored memory files, use the read_file tool on the raw file path.
# Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: []
-59
View File
@@ -1,59 +0,0 @@
// Project tasks configuration. See https://zed.dev/docs/tasks for documentation.
//
// Example:
[
{
"label": "Example task",
"command": "for i in {1..5}; do echo \"Hello $i/5\"; sleep 1; done",
//"args": [],
// Env overrides for the command, will be appended to the terminal's environment from the settings.
"env": { "foo": "bar" },
// Current working directory to spawn the command into, defaults to current project root.
//"cwd": "/path/to/working/directory",
// Whether to use a new terminal tab or reuse the existing one to spawn the process, defaults to `false`.
"use_new_terminal": false,
// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish, defaults to `false`.
"allow_concurrent_runs": false,
// What to do with the terminal pane and tab, after the command was started:
// * `always` — always show the task's pane, and focus the corresponding tab in it (default)
// * `no_focus` — always show the task's pane, add the task's tab in it, but don't focus it
// * `never` — do not alter focus, but still add/reuse the task's tab in its pane
"reveal": "always",
// Where to place the task's terminal item after starting the task:
// * `dock` — in the terminal dock, "regular" terminal items' place (default)
// * `center` — in the central pane group, "main" editor area
"reveal_target": "dock",
// What to do with the terminal pane and tab, after the command had finished:
// * `never` — Do nothing when the command finishes (default)
// * `always` — always hide the terminal tab, hide the pane also if it was the last tab in it
// * `on_success` — hide the terminal tab on task success only, otherwise behaves similar to `always`
"hide": "never",
// Which shell to use when running a task inside the terminal.
// May take 3 values:
// 1. (default) Use the system's default terminal configuration in /etc/passwd
// "shell": "system"
// 2. A program:
// "shell": {
// "program": "sh"
// }
// 3. A program with arguments:
// "shell": {
// "with_arguments": {
// "program": "/bin/bash",
// "args": ["--login"]
// }
// }
"shell": "system",
// Whether to show the task line in the output of the spawned task, defaults to `true`.
"show_summary": true,
// Whether to show the command line in the output of the spawned task, defaults to `true`.
"show_command": true,
// Which edited buffers to save before running the task:
// * `all` — save all edited buffers
// * `current` — save currently active buffer only
// * `none` — don't save any buffers
"save": "none",
// Represents the tags for inline runnable indicators, or spawning multiple tasks at once.
// "tags": []
},
]
-103
View File
@@ -1,103 +0,0 @@
**PROMPT**
Tu es ma base de connaissance et mon bloc-notes intelligent sur le projet **obikmer**. Tu ne proposes pas, tu ne codes pas spontanément — tu réponds à mes questions et tu structures mes idées au fur et à mesure que je les exprime.
**Règle absolue : une question appelle une réponse, pas une action.**
Ne modifier aucun fichier à moins d'une demande explicite de modification. En particulier : observer un bug ou une incohérence dans le code montré ne constitue pas un mandat pour le corriger. Le code montré peut refléter une intention en cours — modifier sans mandat risque d'introduire un vrai bug là où tu croyais corriger.
**Règle absolue : ne jamais substituer une dépendance ou une bibliothèque sans validation explicite.**
Si une dépendance demandée pose problème (erreur de compilation, bug, API manquante), exposer le problème et proposer des alternatives — ne jamais switcher silencieusement vers une autre bibliothèque. Le choix des dépendances est une décision d'architecture qui appartient au développeur.
**Règle absolue : le code existant est une hypothèse, pas une vérité.**
Quand une nouvelle construction (type, itérateur, abstraction) rend du code historique injustifié, le signaler immédiatement et proposer de le supprimer — ne pas conserver les deux en parallèle par inertie. Le développeur demande explicitement de remettre en cause le code base : ne pas attendre qu'il insiste.
Tu maintiens en **anglais**, dense et sans remplissage, les documents suivants :
- `DevDocMD/index.md` — document de discussion de base, enrichi progressivement au fil de nos échanges ; il reflète l'état courant de la réflexion sur le projet
- les autres fichiers Markdown dans `DevDocMD/` selon leur thème respectif
Les snippets de code y sont courts et illustrent uniquement des principes architecturaux. Nos échanges se font en **français**.
---
## Contexte du projet
`obikmer` est un outil Rust de manipulation, comptage, indexation et opérations ensemblistes sur des séquences ADN représentées comme des ensembles de kmers.
**Contraintes fondamentales**
- Efficacité maximale en calcul, mémoire et disque
- Données métagénomiques : plusieurs dizaines de Gbases, milliards de kmers
- k impair, k ∈ [11, 31], fixé à l'exécution
- Formats d'entrée : FASTA, FASTQ, gzip, streaming stdin
**Opérations prioritaires**
- Comptage de kmers (fréquences)
- Recherche / requête rapide
- Opérations ensemblistes (union, intersection, diff)
**Ce qui a déjà été discuté**
- Encodage 2 bits/base → kmer tient dans un `u64`
- Forme canonique : `min(kmer, revcomp)` pour réduire l'espace de moitié
---
## Infrastructure de documentation
La documentation est gérée via **MkDocs + thème Material**, avec publication sur **GitHub Pages**. Deux arbres de documentation indépendants, deux configurations à la racine du dépôt (voir aussi `UserDocMD/` ci-dessous pour la doc utilisateur) :
**Structure des répertoires**
```
DevDocMD/ ← sources Markdown, doc développeur (discussion, historique, rationale)
UserDocMD/ ← sources Markdown, doc utilisateur (état factuel courant, sans code Rust)
mkdocs.yml ← config doc développeur : docs_dir DevDocMD, site_dir DevDoc
mkdocs-user.yml ← config doc utilisateur : docs_dir UserDocMD, site_dir doc
DevDoc/ ← site HTML généré (doc développeur)
doc/ ← site HTML généré (doc utilisateur — publié par GitHub Pages, répertoire par défaut)
.venv/ ← environnement Python (ignoré par git)
```
**Commandes Makefile**
| Commande | Effet |
|---|---|
| `make doc` | Construit la doc développeur dans `DevDoc/` |
| `make doc-serve` | Serveur local (doc développeur), rechargement automatique |
| `make clean-doc` | Supprime `DevDoc/` |
| `make doc-user` | Construit la doc utilisateur dans `doc/` |
| `make doc-user-serve` | Serveur local (doc utilisateur), rechargement automatique |
| `make clean-doc-user` | Supprime `doc/` |
| `make clean` | Supprime `DevDoc/`, `doc/` et `.venv/` |
Le `.venv/` est dans `.gitignore`. `DevDoc/` et `doc/` (sorties HTML) sont versionnés — `doc/` spécifiquement parce que c'est le répertoire par défaut que GitHub Pages sert.
Lors de l'ajout de nouveaux fichiers Markdown dans `DevDocMD/`, mettre à jour la section `nav:` de `mkdocs.yml` ; dans `UserDocMD/`, mettre à jour `mkdocs-user.yml`.
---
Je continue à poser mes questions et à guider la discussion.
---
## MCP Tools
**Règle absolue : avant tout travail de code, appeler `mcp__serena__initial_instructions` pour charger les instructions Serena.**
### Hiérarchie des outils pour ce projet Rust
**Navigation et édition de code → serena en priorité**
- Trouver un symbole, une déclaration, les implémentations d'un trait : `mcp__serena__find_symbol`, `mcp__serena__find_declaration`, `mcp__serena__find_implementations`
- Trouver les usages d'un symbole : `mcp__serena__find_referencing_symbols`
- Diagnostics LSP (erreurs de compilation) : `mcp__serena__get_diagnostics_for_file`
- Vue d'ensemble d'un fichier : `mcp__serena__get_symbols_overview`
- Modifier le corps d'une fonction/impl : `mcp__serena__replace_symbol_body`
- Ne pas utiliser `cclsp` quand serena couvre le besoin
**Analyse architecturale → jcodemunch**
- Hotspots, couplage, dead code, dépendances entre modules
- Utiliser avant de refactorer une zone critique
**Raisonnement complexe → sequential-thinking**
- Décisions d'architecture, choix d'algorithme, trade-offs non triviaux
**Documentation de crates → context7**
- Toujours consulter avant d'utiliser une API de bibliothèque externe
+59 -3
View File
@@ -722,14 +722,14 @@
<li class="md-nav__item">
<a href="/implementation/obilayeredmap/" class="md-nav__link">
<a href="/implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -939,6 +939,62 @@
<li class="md-nav__item">
<a href="/implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="/implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1063,7 +1119,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1214,10 +1270,10 @@
<h1 id="coverage-architectureindex_architecturemd">Coverage: architecture/index_architecture.md</h1>
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obilayeredmap/src/layer.rs</code> — Layer<D>, trait LayerData, modes () / PersistentCompactIntMatrix / PersistentBitMatrix</li>
<li><code>obilayeredmap/src/mphf_layer.rs</code> — MphfLayer, EvidenceKind (Exact / Approx), LayerEvidence enum</li>
<li><code>obilayeredmap/src/map.rs</code> — LayeredMap<D></li>
<li><code>obilayeredmap/src/meta.rs</code> — LayerMeta, PartitionMeta</li>
<li><code>obikindex/src/layer/typed_layer.rs</code> — Layer<D>, trait LayerData, modes () / PersistentCompactIntMatrix / PersistentBitMatrix</li>
<li><code>obikindex/src/layer/mphf_layer.rs</code> — MphfLayer, EvidenceKind (Exact / Approx), LayerEvidence enum</li>
<li><code>obikindex/src/layer/map.rs</code> — LayeredMap<D></li>
<li><code>obikindex/src/layer/meta.rs</code> — LayerMeta, PartitionMeta</li>
<li><code>obikindex/src/meta.rs</code> — IndexConfig (kmer_size, n_bits, with_counts, evidence, block_bits), IndexMeta</li>
<li><code>obikindex/src/index.rs</code> — KmerIndex, build_layers</li>
<li><code>obicompactvec/src/</code> — PersistentCompactIntMatrix, PersistentBitMatrix (DataStore implementations)</li>
@@ -731,14 +731,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -948,6 +948,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1314,7 +1370,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -729,14 +729,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -946,6 +946,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1072,7 +1128,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1311,6 +1367,17 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#panic-propagation-fixed-2026-08-28" class="md-nav__link">
<span class="md-ellipsis">
Panic propagation (fixed, 2026-08-28)
</span>
</a>
</li>
<li class="md-nav__item">
@@ -1497,6 +1564,17 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#panic-propagation-fixed-2026-08-28" class="md-nav__link">
<span class="md-ellipsis">
Panic propagation (fixed, 2026-08-28)
</span>
</a>
</li>
<li class="md-nav__item">
@@ -1780,11 +1858,27 @@ dormant workers have been woken and grows every node by the same amount per
step, capped by that node's remaining dormant workers and by the run's total
budget (<code>n_total</code>) — balance across nodes is now guaranteed by construction,
not incidental to channel implementation details.</p>
<h2 id="panic-propagation-fixed-2026-08-28">Panic propagation (fixed, 2026-08-28)</h2>
<p>A worker whose <code>f(i)</code> panicked used to never send its <code>WorkerEvent::Completed</code>
— the controller's <code>while completed &lt; n_total</code> loop then waited forever for
an event that partition could no longer produce, since other live
workers/timer threads kept <code>event_rx</code> open. Discovered via <code>obikselect</code>
panicking on an unimplemented <code>Sparse</code> matrix case (see <code>implementation/select.md</code>):
the process hung indefinitely instead of erroring out.</p>
<p>Fixed: each worker wraps <code>f(i)</code> in <code>std::panic::catch_unwind</code> and sends a new
<code>WorkerEvent::Panicked(i, payload)</code> instead of silently dropping the
partition. The controller counts it toward <code>completed</code> (unblocking the loop)
and keeps the first payload seen; once <code>run</code> returns, <code>panic::resume_unwind</code>
re-raises it on the caller's thread — the original message/backtrace still
surfaces, from the right place, instead of a silent deadlock. Takes priority
over a plain <code>Err</code> (a panic means a bug, not a normal typed failure).</p>
<h2 id="open-questions">Open questions</h2>
<ul>
<li>
<p><strong>Error handling</strong>: <code>run</code> currently returns the first error; remaining errors
are dropped. A <code>Vec&lt;E&gt;</code> return would give complete diagnostics.</p>
are dropped. A <code>Vec&lt;E&gt;</code> return would give complete diagnostics. (Panics are
now caught and re-raised individually — see above — this only concerns
plain <code>Err</code> results.)</p>
</li>
<li>
<p><strong><code>INITIAL_DIVISOR</code> / <code>GROWTH_DIVISOR</code> tuning</strong>: currently <code>4</code> and <code>8</code>
@@ -731,14 +731,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -948,6 +948,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1074,7 +1130,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1504,7 +1560,7 @@
<td>Replace <code>available_parallelism()</code> with per-NUMA core count for spawn criterion</td>
</tr>
<tr>
<td><code>obikpartitionner/src/merge_layer.rs</code></td>
<td><code>obikindex/src/partition/merge_layer.rs</code></td>
<td>No change — <code>merge_partition</code> already works inside any Rayon context</td>
</tr>
<tr>
@@ -1512,7 +1568,7 @@
<td>No change — <code>par_iter</code> and <code>current_num_threads</code> are pool-context-aware</td>
</tr>
<tr>
<td><code>obikpartitionner/src/partition.rs</code></td>
<td><code>obikindex/src/partition/partition.rs</code></td>
<td>No change — same reason</td>
</tr>
</tbody>
+60 -4
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1215,7 +1271,7 @@
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obikmer/src/cmd/query.rs</code> — commande query, format de sortie</li>
<li><code>obikpartitionner/src/query_layer.rs</code> — routage de la requête à travers les partitions</li>
<li><code>obikindex/src/partition/query_layer.rs</code> — routage de la requête à travers les partitions</li>
<li><code>obiread/src/lib.rs</code> — lecture des séquences d'entrée pour la requête</li>
</ul>
<h2 id="notes">Notes</h2>
+69 -13
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1499,7 +1555,7 @@
</ul>
<hr />
<h2 id="algorithm">Algorithm</h2>
<p>The query follows the same superkmer-based partitioning strategy used at indexing time. Everything below happens inside <code>process_chunk</code> (<code>query.rs</code>); there is no separate per-stage function, but the internal data flow is staged: k-mer-level dereplication, a two-part MPHF/column-major matrix lookup (<code>obikpartitionner::query_partition_with</code>), and a sparse Findere pass, each producing sparse intermediate structures rather than one dense allocation for the whole chunk.</p>
<p>The query follows the same superkmer-based partitioning strategy used at indexing time. Everything below happens inside <code>process_chunk</code> (<code>query.rs</code>); there is no separate per-stage function, but the internal data flow is staged: k-mer-level dereplication, a two-part MPHF/column-major matrix lookup (<code>obikindex::partition::query_partition_with</code>), and a sparse Findere pass, each producing sparse intermediate structures rather than one dense allocation for the whole chunk.</p>
<div class="highlight"><pre><span></span><code>for each chunk of sequences (parallel workers via obipipeline, one call to process_chunk):
build QueryBatch (QueryBatch::from_records):
decompose all sequences into superkmers (SuperKmerIter) — construction only,
@@ -1574,9 +1630,9 @@
<p>The <code>-z</code> CLI option overrides the index metadata value. A higher z increases stringency (lower FP, some true positives may be discarded at sequence ends); a lower z increases sensitivity.</p>
<hr />
<h2 id="layer-lookup-mphflayerfind">Layer lookup: <code>MphfLayer::find</code></h2>
<p><code>MphfLayer::open(dir, mode: &amp;IndexMode)</code> receives the mode from <code>PartitionMeta</code> — no per-layer file is read. The caller (<code>QueryLayer</code>) never chooses the dispatch path: it is fixed at open time by <code>LayerEvidence</code>. See <a href="../../implementation/obilayeredmap/">obilayeredmap</a> for the full <code>find</code> / <code>find_strict</code> API.</p>
<p><code>MphfLayer::open(dir, mode: &amp;IndexMode)</code> receives the mode from <code>PartitionMeta</code> — no per-layer file is read. The caller (<code>QueryLayer</code>) never chooses the dispatch path: it is fixed at open time by <code>LayerEvidence</code>. See <a href="../../implementation/layer_tier/">obikindex::layer</a> for the full <code>find</code> / <code>find_strict</code> API.</p>
<h3 id="querylayer-variant-selection"><code>QueryLayer</code> variant selection</h3>
<p><code>QueryLayer::open</code> (<code>obikpartitionner/src/query_layer.rs:28-45</code>) only ever returns two variants — <code>Presence</code> or <code>Count</code>, checked in this order:</p>
<p><code>QueryLayer::open</code> (<code>obikindex/src/partition/query_layer.rs:28-45</code>) only ever returns two variants — <code>Presence</code> or <code>Count</code>, checked in this order:</p>
<table>
<thead>
<tr>
@@ -1746,7 +1802,7 @@ Fix direction: restructure <code>query</code>'s pipe with an initial <code>Flat<
<p><strong>3. Chunk-size memory formula ignores <code>n_genomes</code>.</strong>
<code>chunk_bytes = available_memory_bytes() / (n_workers * 16)</code> (<code>query.rs:407-414</code>) assumes a fixed ~8–16× overhead per raw input byte. But <code>KmerResults::new</code> (<code>query.rs:165-179</code>) allocates <code>data: Vec&lt;u32&gt;</code> sized <code>total_kmers_in_chunk × n_genomes</code> — dense, <strong>for every k-mer position in the chunk, hit or not</strong> — plus <code>win_min</code> and (with <code>--detail</code>) <code>cov</code>, same scaling. Real per-chunk memory is <code>O(n_genomes)</code>, not constant; the formula doesn't know <code>n_genomes</code> at all. This is the direct cause of the OOM kill on indexes with many reference genomes.</p>
<p><strong>4. MPHF lookup and matrix-row fetch are fused, not staged.</strong>
<code>QueryLayer::find_into</code> (<code>obikpartitionner/src/query_layer.rs:48-67</code>) does the MPHF <code>find</code> <em>and</em> the <code>fill_row</code> matrix read in one call per k-mer, inside a single-threaded loop (<code>query_partition_with</code>). There is no separation between "is this k-mer indexed" (cheap, <code>O(1)</code>, independent of <code>n_genomes</code>) and "what are its per-genome values" (the expensive, <code>n_genomes</code>-scaling part).</p>
<code>QueryLayer::find_into</code> (<code>obikindex/src/partition/query_layer.rs:48-67</code>) does the MPHF <code>find</code> <em>and</em> the <code>fill_row</code> matrix read in one call per k-mer, inside a single-threaded loop (<code>query_partition_with</code>). There is no separation between "is this k-mer indexed" (cheap, <code>O(1)</code>, independent of <code>n_genomes</code>) and "what are its per-genome values" (the expensive, <code>n_genomes</code>-scaling part).</p>
<p><strong>5. Dereplication should happen at k-mer granularity, directly — not via an intermediate superkmer-level dedup.</strong>
<code>QueryBatch::from_records</code> currently dereplicates at the <em>superkmer</em> level (<code>HashMap&lt;RoutableSuperKmer, Vec&lt;SKDesc&gt;&gt;</code>, <code>query.rs:112</code>). This misses redundancy between k-mers shared by <em>different</em> superkmers (read overlaps, repeats, a SNP splitting an otherwise-identical run). Superkmer <em>construction</em> (<code>SuperKmerIter</code>) stays mandatory — it is the mechanism that computes minimizers/partition routing, not an optional dedup layer — but the dedup structure built on top of it should key directly on <code>CanonicalKmer</code>, in the same pass: <code>HashMap&lt;CanonicalKmer, Vec&lt;(seq_idx, pos)&gt;&gt;</code>. This also means the MPHF <code>find</code> itself runs once per <strong>distinct</strong> k-mer instead of once per occurrence — a win independent of the matrix-fetch cost below.</p>
<p><strong>6. Stage 1 output: bucket confirmed hits by layer, keyed by MPHF slot.</strong>
@@ -1778,12 +1834,12 @@ Stage 2's output should be <code>HashMap&lt;genome_idx, Vec&lt;(seq_idx, positio
<p>None of this is implemented yet — parked here as a coherent roadmap while the design is discussed further. Suggested dependency order: (1) I/O parallelism → (3) genome-aware chunk sizing → (4)–(9) staged/k-mer-deduped/NUMA-aware-partition-and-column-major/sparse query engine (larger refactor, biggest structural payoff — reuses <code>PartitionRunner</code> rather than inventing a new parallelism mechanism) → (2) parallel gzip (separate, orthogonal, tracked in chunkreader.md) → secondary diagnostics patterns.</p>
<hr />
<h2 id="implementation-plan">Implementation plan</h2>
<p>Concrete, phased translation of the roadmap above. Phases 0–2 are small, independent, low-risk, and each individually testable against current <code>query</code> 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 <code>obikmer</code>, <code>obikpartitionner</code>, and <code>obicompactvec</code> — they should not be split across releases mid-way, because the intermediate state (e.g. k-mer-level dedup feeding the old dense <code>KmerResults</code>) has no correctness or performance benefit on its own. Phase 6 is unrelated to phases 0–5 and can happen any time, independently, if <code>rapidgzip-rs</code> is validated (see <a href="../../implementation/chunkreader/#future-work--parallel-gzip-decompression-in-xopen">chunkreader.md</a>).</p>
<p>Concrete, phased translation of the roadmap above. Phases 0–2 are small, independent, low-risk, and each individually testable against current <code>query</code> 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 <code>obikmer</code>, <code>obikindex::partition</code>, and <code>obicompactvec</code> — they should not be split across releases mid-way, because the intermediate state (e.g. k-mer-level dedup feeding the old dense <code>KmerResults</code>) has no correctness or performance benefit on its own. Phase 6 is unrelated to phases 0–5 and can happen any time, independently, if <code>rapidgzip-rs</code> is validated (see <a href="../../implementation/chunkreader/#future-work--parallel-gzip-decompression-in-xopen">chunkreader.md</a>).</p>
<p>Instrumentation is deliberately sequenced <em>before</em> 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.</p>
<p>Performance measurement on the reference 192-core/8-NUMA machine is done by the project owner, not from this development environment (macOS, 16 cores — <code>PartitionRunner</code>'s NUMA pinning is Linux-only, so even phase 4's mechanism can't be functionally exercised for its actual purpose here). Each phase below is therefore written to be <em>self-measuring</em>: the debug-level logging it adds must be enough, on its own, to judge whether that phase's algorithmic choice paid off from a cluster run's logs, without needing to attach a profiler.</p>
<h3 id="conventions-applied-to-every-phase-below">Conventions applied to every phase below</h3>
<p><strong>Debug logging.</strong> Every phase that changes an algorithmic choice (not phase 0, which <em>is</em> the logging) adds <code>tracing::debug!</code>/<code>trace!</code> 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 <code>find</code> 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 <code>debug!</code> 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.</p>
<p><strong>Unit tests.</strong> This project's convention (<code>obiread</code>, <code>obikseq</code>, <code>obidebruinj</code>, <code>obicompactvec</code>, <code>obilayeredmap</code>, <code>obiskio</code>, <code>obifastwrite</code>) is <code>#[cfg(test)] #[path = "tests/&lt;name&gt;.rs"] mod tests;</code> at the bottom of the source file, with the actual test code in a sibling <code>src/tests/&lt;name&gt;.rs</code>. Neither <code>obikmer</code> nor <code>obikpartitionner</code> (the two crates phases 3 and 5 touch most) currently have a <code>src/tests/</code> directory at all — this needs creating, following the existing pattern exactly, not inventing a new one.</p>
<p><strong>Unit tests.</strong> This project's convention (<code>obiread</code>, <code>obikseq</code>, <code>obidebruinj</code>, <code>obicompactvec</code>, <code>obikindex::layer</code>, <code>obiskio</code>, <code>obifastwrite</code>) is <code>#[cfg(test)] #[path = "tests/&lt;name&gt;.rs"] mod tests;</code> at the bottom of the source file, with the actual test code in a sibling <code>src/tests/&lt;name&gt;.rs</code>. Neither <code>obikmer</code> nor <code>obikindex::partition</code> (the two crates phases 3 and 5 touch most) currently have a <code>src/tests/</code> directory at all — this needs creating, following the existing pattern exactly, not inventing a new one.</p>
<p><strong>Workflow (<code>jj</code>).</strong> Work happens in a fresh <code>jj</code> commit, easy to abandon. <code>jj new</code> 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 <code>query_layer.rs</code> 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.</p>
<h3 id="phase-0-instrumentation-prerequisite-for-measuring-every-later-phase">Phase 0 — Instrumentation (prerequisite for measuring every later phase)</h3>
<p><strong>Goal</strong>: 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.</p>
@@ -1826,26 +1882,26 @@ Stage 2's output should be <code>HashMap&lt;genome_idx, Vec&lt;(seq_idx, positio
<li><code>obikmer/src/cmd/query.rs</code>:</li>
<li>Replace <code>QueryBatch::from_records</code>'s dedup map (<code>HashMap&lt;RoutableSuperKmer, Vec&lt;SKDesc&gt;&gt;</code>, current <code>query.rs:112</code>) with a per-partition <code>HashMap&lt;CanonicalKmer, Vec&lt;(seq_idx: u32, pos: u32)&gt;&gt;</code>, built in the same <code>SuperKmerIter</code> pass: superkmer construction and partition routing (<code>part_idx</code> from the superkmer's minimizer hash) are unchanged, only the granularity of what gets deduplicated changes — each <code>CanonicalKmer</code> within a superkmer is inserted individually instead of the whole superkmer being the dedup key.</li>
<li><strong>Verified</strong>: <code>CanonicalKmer</code> (<code>obikseq/src/kmer.rs:390</code>, <code>pub type CanonicalKmer = CanonicalKmerOf&lt;KLen&gt;</code>) — the underlying <code>CanonicalKmerOf&lt;L&gt;</code> derives <code>Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash</code> (<code>kmer.rs:269</code>). Usable as a <code>HashMap</code>/<code>HashSet</code> key as-is, no change needed.</li>
<li><code>obikpartitionner/src/query_layer.rs</code>:</li>
<li><code>obikindex/src/partition/query_layer.rs</code>:</li>
<li>Split <code>QueryLayer::find_into</code> (<code>query_layer.rs:48-67</code>) into two methods: <code>find_slot(&amp;self, kmer: CanonicalKmer) -&gt; Option&lt;usize&gt;</code> (MPHF only, no matrix touch) and keep <code>fill_row</code> as-is for phase 4 to call later.</li>
<li>Replace <code>query_partition_with</code>'s inner loop (<code>query_layer.rs:103-113</code>) with a version that, for each unique <code>CanonicalKmer</code>, calls <code>find_slot</code> across the partition's layers (stopping at first hit, same as today), and instead of immediately filling a row, records <code>(layer_idx, slot)</code>.</li>
<li>New return shape for the partition-level query, replacing today's <code>on_hit(sk_idx, kmer_idx, row)</code> callback: <code>HashMap&lt;layer_idx, HashMap&lt;slot, Vec&lt;(seq_idx, pos)&gt;&gt;&gt;</code> (roadmap point 6) — built directly from the k-mer dedup map's <code>Vec&lt;(seq_idx,pos)&gt;</code> values, keyed by the resolved slot instead of the k-mer.</li>
<li><strong>This phase alone has no throughput benefit yet</strong> (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.</li>
<li>Log, per chunk: total k-mer occurrences vs. unique <code>CanonicalKmer</code> count (the dedup ratio — the entire justification for this phase) and the resulting MPHF <code>find</code> call count. If the dedup ratio is close to <code>1.0</code> 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.</li>
<li><strong>Unit tests</strong>: create <code>obikmer/src/cmd/tests/query.rs</code> (new <code>src/tests/</code> dir for this crate, following the project's <code>#[cfg(test)] #[path = "tests/query.rs"] mod tests;</code> convention) and <code>obikpartitionner/src/tests/query_layer.rs</code> (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 <code>find_slot</code>/bucket-by-layer-and-slot construction against a small hand-built <code>QueryLayer</code> fixture, asserting the <code>(layer_idx, slot, seq_idx, pos)</code> tuples match what the old per-occurrence loop would have produced.</li>
<li><strong>Unit tests</strong>: create <code>obikmer/src/cmd/tests/query.rs</code> (new <code>src/tests/</code> dir for this crate, following the project's <code>#[cfg(test)] #[path = "tests/query.rs"] mod tests;</code> convention) and <code>obikindex/src/partition/tests/query_layer.rs</code> (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 <code>find_slot</code>/bucket-by-layer-and-slot construction against a small hand-built <code>QueryLayer</code> fixture, asserting the <code>(layer_idx, slot, seq_idx, pos)</code> tuples match what the old per-occurrence loop would have produced.</li>
</ul>
<h3 id="phase-4-column-major-matrix-fetch-roadmap-points-78-implemented-numa-parallelism-deferred">Phase 4 — Column-major matrix fetch (roadmap points 7–8) — implemented, NUMA parallelism deferred</h3>
<p><strong>Goal (revised during implementation)</strong>: replace <code>fill_row</code>-per-hit (row-major, worst-case mmap locality) with a column-major scan. <code>PartitionRunner</code> turned out to be the wrong mechanism for this at this call granularity — see below; the column-major fetch itself is implemented and validated, without it.</p>
<p><strong>What shipped:</strong>
- <code>obicompactvec</code>: the per-column accessors this phase needed <strong>already existed</strong> — <code>PersistentCompactIntMatrix::col_view(c)</code> and <code>PersistentBitMatrix::col_view(c)</code> are public, and <code>IntSliceView::get(slot)</code>/<code>BitSliceView::get(slot)</code> are public — the original plan underestimated how much of this plumbing the pairwise-distance code (<code>dump</code>/<code>select</code>/<code>stats</code>) had already required. The one real gap: <code>PersistentBitMatrix::col_view()</code> panics on the <code>Implicit</code> variant (the documented mono-genome fast path, <code>bitmatrix.rs</code>). Added <code>PersistentBitMatrix::get(c, slot) -&gt; u32</code> (<code>bitmatrix.rs</code>), a non-panicking column-major point lookup that returns <code>1</code> for <code>Implicit</code> regardless of <code>c</code> — the smallest surface needed, not a new <code>col_get</code> API from scratch.
- <code>obikpartitionner/src/query_layer.rs</code>: <code>query_partition_with</code> is now two explicit stages, matching roadmap points 6–8: <strong>stage 1</strong> (MPHF-only, per unique k-mer, bucket hits by <code>(layer_idx, slot)</code>, emits <code>QueryHit::Found</code>) then <strong>stage 2</strong> (per layer with ≥1 hit, column-major: for each genome column <code>g</code> in <code>0..layer.n_cols().min(n_genomes)</code>, scan that layer's bucketed slots and call <code>col_value(g, slot)</code>, emitting <code>QueryHit::Value(descs, g, value)</code> on nonzero). <code>QueryHit</code> is a single enum delivered through one <code>FnMut(QueryHit)</code> callback — an earlier two-closure design (<code>on_found</code> + <code>on_value</code>) didn't borrow-check, since the caller's single mutable accumulator (<code>KmerResults</code>) can't be captured by two separate <code>FnMut</code> closures passed to the same call.
- <code>obikindex/src/partition/query_layer.rs</code>: <code>query_partition_with</code> is now two explicit stages, matching roadmap points 6–8: <strong>stage 1</strong> (MPHF-only, per unique k-mer, bucket hits by <code>(layer_idx, slot)</code>, emits <code>QueryHit::Found</code>) then <strong>stage 2</strong> (per layer with ≥1 hit, column-major: for each genome column <code>g</code> in <code>0..layer.n_cols().min(n_genomes)</code>, scan that layer's bucketed slots and call <code>col_value(g, slot)</code>, emitting <code>QueryHit::Value(descs, g, value)</code> on nonzero). <code>QueryHit</code> is a single enum delivered through one <code>FnMut(QueryHit)</code> callback — an earlier two-closure design (<code>on_found</code> + <code>on_value</code>) didn't borrow-check, since the caller's single mutable accumulator (<code>KmerResults</code>) can't be captured by two separate <code>FnMut</code> closures passed to the same call.
- <code>obikmer/src/cmd/query.rs</code>: <code>KmerResults::set</code> (row-major, whole-row-at-once) replaced by <code>mark_found</code> (stage 1: flag a position as indexed, independent of any genome's value) and <code>set_one</code> (stage 2: write one genome's value at one position). <code>QueryStats</code> extended with <code>n_columns_scanned</code>/<code>n_col_get_calls</code>, logged per chunk.
- Total <code>get()</code>-equivalent calls are unchanged from the row-major version (<code>n_hits × n_cols</code> in the worst case, confirmed by <code>n_col_get_calls</code> in the debug log) — the win is locality (sequential access within one layer's column at a time, across <code>mmap</code>'d regions, instead of jumping across all columns per hit), exactly as predicted.</p>
<p><strong>What did not ship, and why — <code>PartitionRunner</code> is architecturally the wrong tool here:</strong>
Reading <code>obikindex/src/numa.rs</code>'s actual <code>run()</code> body (not just its doc comments) shows every call spawns a timer thread <strong>plus one OS thread per worker slot on every NUMA node</strong> (<code>std::thread::scope</code> + one <code>s.spawn()</code> per node per <code>max_workers</code>) — on the 192-core/8-NUMA reference machine, that's on the order of 190+ fresh OS threads spawned <strong>per call</strong>. This is fine for its actual, established usage in this codebase (<code>merge.rs</code>, <code>index.rs</code>'s <code>build_layers</code>): one <code>PartitionRunner::new()</code> + one <code>run()</code> call per command invocation, amortised over a batch of ~256 long-running partitions. It is not fine for <code>query</code>'s call pattern: <code>query_partition_with</code> runs once per <code>(chunk, partition)</code>, potentially thousands of times per second — spawning ~190 OS threads that often to scan a handful of genome columns would very likely cost far more than the row-major approach it's meant to replace. This is exactly the "resolve empirically, don't assume" composition risk the roadmap flagged, just resolved by reading the mechanism's actual cost before wiring it in, rather than by measuring a regression on the cluster after the fact.
The column-major loop in stage 2 is therefore a <strong>plain sequential loop</strong> for now — it captures the whole, provable locality win (roadmap point 8's actual claim) without adding any parallelism mechanism. Genome-column-level parallelism (point 8's "bonus" axis) and partition-level parallelism (point 7) are both deferred — not abandoned. Candidates for a follow-up, once there's a concrete profiling need: (a) <code>rayon</code>'s already-warm global pool (<code>into_par_iter()</code>) for the column axis specifically — cheap to invoke repeatedly since it doesn't spawn threads per call, though it's the same "naive rayon" pattern <code>numa_worker_pools.md</code> warns about for a <em>different</em> workload (random pointer-chasing over large hash maps); a column scan's access pattern (sequential reads within one <code>mmap</code>'d region) has a different contention profile and hasn't been shown to have the same problem — needs its own measurement, not an assumption either way; (b) restructuring so <code>PartitionRunner</code> is invoked once per whole <code>query</code> run (or per large batch of chunks) rather than per <code>(chunk, partition)</code>, amortising its spawn cost the way <code>merge</code>/<code>build_layers</code> do — a bigger structural change than this phase's scope.
- Log (implemented): <code>QueryStats::n_columns_scanned</code>/<code>n_col_get_calls</code>, folded into the existing per-chunk <code>debug!("k-mer dedup + column-major fetch", ...)</code> line (<code>query.rs</code>) alongside phase 3's dedup counters.
- <strong>Unit tests</strong>: extended <code>obikpartitionner/src/tests/query_layer.rs</code> (phase 3's file) — <code>query_partition_with</code>'s empty/missing-index paths updated for the new <code>QueryStats</code> fields and single-callback signature.
- <strong>Unit tests</strong>: extended <code>obikindex/src/partition/tests/query_layer.rs</code> (phase 3's file) — <code>query_partition_with</code>'s empty/missing-index paths updated for the new <code>QueryStats</code> fields and single-callback signature.
- <strong>Validation performed</strong>: full workspace build + <code>cargo test --workspace</code>, zero failures. Functional validation against real indexes: (1) a single-genome index — output byte-identical to pre-phase-4 (same <code>kmer_count</code>/<code>kmer_strict_matches</code> on every record); (2) the existing 20-genome <code>benchmark/global_index_presence</code> index — runs correctly, <code>n_hits=0</code> for an unrelated query (expected: no shared k-mers between a plant read and a bacterial reference set), no panics, confirming the <code>Implicit</code>/multi-column bounds logic doesn't crash on a real multi-genome, mixed-format index; (3) <strong>the critical correctness case</strong>: built two single-sequence-pair test genomes, merged into one 2-genome index, queried with reads from both — reads from <code>genomeA</code> matched <strong>only</strong> <code>genomeA</code> (<code>kmer_count</code> identical to the pre-dedup occurrence count, zero leakage into <code>genomeB</code>'s column) and vice versa. This is the test that would have caught a column-index mixup, an off-by-one in <code>n_cols</code>, or cross-genome bleed from the stage-1/stage-2 split — it passed cleanly.
- <strong>Not yet done</strong>: the microbenchmark comparing column-major vs. the old row-major access pattern's wall time / page-fault counters on a large-<code>n_genomes</code> layer — needs a realistically large multi-genome index and, for the page-fault counters specifically, Linux (not available from this development environment). Left for cluster validation alongside phases 1–3's own pending measurements.</p>
<h3 id="phase-5-sparse-findere-rework-roadmap-point-9">Phase 5 — Sparse Findere rework (roadmap point 9)</h3>
+61 -5
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1389,9 +1445,9 @@ IO pattern: sequential read of each source column → random write into new colu
</table>
<h2 id="files-to-modify">Files to modify</h2>
<ul>
<li><code>src/obikpartitionner/src/rebuild_layer.rs</code> — <code>rebuild_partition</code> and <code>iter_src_layers</code></li>
<li><code>src/obikindex/src/partition/rebuild_layer.rs</code> — <code>rebuild_partition</code> and <code>iter_src_layers</code></li>
<li>Possibly <code>src/obicompactvec/</code> — add column iterator API if not already present</li>
<li><code>src/obilayeredmap/</code> — check if per-column sequential access is exposed on <code>SrcLayerData</code></li>
<li><code>src/obikindex/src/layer/</code> — check if per-column sequential access is exposed on <code>SrcLayerData</code></li>
</ul>
<h2 id="open-questions">Open questions</h2>
<ul>
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -9,7 +9,7 @@
<link rel="prev" href="../../../implementation/obitaxonomy/">
<link rel="prev" href="../../../implementation/partition_layer_cache/">
<link rel="next" href="../../index_architecture/">
@@ -731,14 +731,14 @@
<li class="md-nav__item">
<a href="../../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -948,6 +948,62 @@
<li class="md-nav__item">
<a href="../../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1084,7 +1140,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
File diff suppressed because it is too large. Load diff
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+27 -3
View File
@@ -405,11 +405,11 @@
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="../obilayeredmap/">
<a class="md-nav__link" href="../layer_tier/">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -497,6 +497,30 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="../benchmark_query_testing/">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="../partition_layer_cache/">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
@@ -555,7 +579,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1214,9 +1270,9 @@
<h1 id="coverage-implementationevidence_eliminationmd">Coverage: implementation/evidence_elimination.md</h1>
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obilayeredmap/src/fingerprint.rs</code> — FingerprintVec, FingerprintVecWriter, stockage b bits/slot, matches()</li>
<li><code>obilayeredmap/src/mphf_layer.rs</code> — build_approx_evidence(dir, b, z), find_approx()</li>
<li><code>obilayeredmap/src/meta.rs</code> — EvidenceKind::Approx { b, z }, LayerMeta</li>
<li><code>obikindex/src/layer/fingerprint.rs</code> — FingerprintVec, FingerprintVecWriter, stockage b bits/slot, matches()</li>
<li><code>obikindex/src/layer/mphf_layer.rs</code> — build_approx_evidence(dir, b, z), find_approx()</li>
<li><code>obikindex/src/layer/meta.rs</code> — EvidenceKind::Approx { b, z }, LayerMeta</li>
<li><code>obikindex/src/reindex.rs</code> — KmerIndex::reindex(), conversion exact↔approx en place</li>
<li><code>obikmer/src/cmd/reindex.rs</code> — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size</li>
<li><code>obikmer/src/cmd/index.rs</code> — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp</li>
@@ -12,7 +12,7 @@
<link rel="prev" href="../unitig_evidence/">
<link rel="next" href="../obilayeredmap/">
<link rel="next" href="../layer_tier/">
@@ -868,14 +868,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1085,6 +1085,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1209,7 +1265,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+61 -5
View File
@@ -733,14 +733,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1208,6 +1208,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1332,7 +1388,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -2130,7 +2186,7 @@ obikmer<span class="w"> </span>phylo<span class="w"> </span>myindex<span class="
<h2 id="implementation">Implementation</h2>
<ul>
<li>
<p><strong><code>obikpartitionner::filter::GroupQuorumFilter</code></strong> — implements <code>KmerFilter</code>
<p><strong><code>obikindex::partition::filter::GroupQuorumFilter</code></strong> — implements <code>KmerFilter</code>
using pre-computed ingroup and outgroup index vectors. The heavy logic
(predicate parsing, three-value evaluation, genome classification) happens
once before any iteration; each k-mer row evaluation is a simple index
@@ -2143,7 +2199,7 @@ obikmer<span class="w"> </span>phylo<span class="w"> </span>myindex<span class="
list.</p>
</li>
<li>
<p><strong><code>obikpartitionner::KmerPartition::iter_partition_kmers</code></strong> — accepts
<p><strong><code>obikindex::partition::KmerPartition::iter_partition_kmers</code></strong> — accepts
<code>filters: &amp;[Box&lt;dyn KmerFilter&gt;]</code> and applies them per-kmer before invoking
the callback. <code>filter</code>, <code>dump</code>, and <code>unitig</code> all go through this single
entry point.</p>
+59 -3
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -868,14 +868,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1085,6 +1085,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1209,7 +1265,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -19,7 +19,7 @@
<title>Obilayeredmap.refs - obikmer</title>
<title>Layer tier.refs - obikmer</title>
@@ -60,7 +60,7 @@
<div data-md-component="skip">
<a href="#coverage-implementationobilayeredmapmd" class="md-skip">
<a href="#coverage-implementationlayer_tiermd" class="md-skip">
Skip to content
</a>
@@ -96,7 +96,7 @@
<div class="md-header__topic" data-md-component="header-topic">
<span class="md-ellipsis">
Obilayeredmap.refs
Layer tier.refs
</span>
</div>
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1211,15 +1267,15 @@
<!-- coverage sidecar — ne pas ajouter au nav mkdocs -->
<h1 id="coverage-implementationobilayeredmapmd">Coverage: implementation/obilayeredmap.md</h1>
<h1 id="coverage-implementationlayer_tiermd">Coverage: implementation/layer_tier.md</h1>
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obilayeredmap/src/mphf_layer.rs</code> — MphfLayer, LayerEvidence enum (Exact/Approx), find(), find_exact(), find_approx()</li>
<li><code>obilayeredmap/src/layer.rs</code> — Layer<D>, trait LayerData, modes () / PersistentCompactIntMatrix / PersistentBitMatrix, build(), build_evidence(), append_genome_column()</li>
<li><code>obilayeredmap/src/map.rs</code> — LayeredMap<D>, push_layer(), query()</li>
<li><code>obilayeredmap/src/evidence.rs</code> — Evidence, EvidenceWriter, encodage chunk_id:rank</li>
<li><code>obilayeredmap/src/fingerprint.rs</code> — FingerprintVec, FingerprintVecWriter, matches()</li>
<li><code>obilayeredmap/src/meta.rs</code> — LayerMeta, EvidenceKind (Exact / Approx { b, z })</li>
<li><code>obikindex/src/layer/mphf_layer.rs</code> — MphfLayer, LayerEvidence enum (Exact/Approx), find(), find_exact(), find_approx()</li>
<li><code>obikindex/src/layer/typed_layer.rs</code> — Layer<D>, trait LayerData, modes () / PersistentCompactIntMatrix / PersistentBitMatrix, build(), build_evidence(), append_genome_column()</li>
<li><code>obikindex/src/layer/map.rs</code> — LayeredMap<D>, push_layer(), query()</li>
<li><code>obikindex/src/layer/evidence.rs</code> — Evidence, EvidenceWriter, encodage chunk_id:rank</li>
<li><code>obikindex/src/layer/fingerprint.rs</code> — FingerprintVec, FingerprintVecWriter, matches()</li>
<li><code>obikindex/src/layer/meta.rs</code> — LayerMeta, EvidenceKind (Exact / Approx { b, z })</li>
</ul>
<h2 id="notes">Notes</h2>
<p>FORT RISQUE DE DÉRIVE. C'est le fichier le plus affecté par les changements récents :
@@ -23,7 +23,7 @@
<title>obilayeredmap crate - obikmer</title>
<title>obikindex layer tier - obikmer</title>
@@ -64,7 +64,7 @@
<div data-md-component="skip">
<a href="#obilayeredmap-layered-kmer-index-crate" class="md-skip">
<a href="#obikindexlayer-the-layer-tier" class="md-skip">
Skip to content
</a>
@@ -100,7 +100,7 @@
<div class="md-header__topic" data-md-component="header-topic">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
</span>
</div>
@@ -749,7 +749,7 @@
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -767,7 +767,7 @@
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -940,6 +940,67 @@
</ul>
</nav>
</li>
<li class="md-nav__item">
<a href="#layerd-raw-mapping-iteration-and-batch-access" class="md-nav__link">
<span class="md-ellipsis">
Layer\&lt;D> — raw mapping, iteration, and batch access
</span>
</a>
<nav class="md-nav" aria-label="Layer\&lt;D&gt; — raw mapping, iteration, and batch access">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#raw-kmer-slot-mapping" class="md-nav__link">
<span class="md-ellipsis">
Raw kmer → slot mapping
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#kmer-iteration" class="md-nav__link">
<span class="md-ellipsis">
Kmer iteration
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#batch-lookup-on-payload-vectorsviews" class="md-nav__link">
<span class="md-ellipsis">
Batch lookup on payload vectors/views
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#sub_matrix-fill_sub_matrix" class="md-nav__link">
<span class="md-ellipsis">
sub_matrix / fill_sub_matrix
</span>
</a>
</li>
</ul>
</nav>
</li>
<li class="md-nav__item">
@@ -1263,6 +1324,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1387,7 +1504,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1638,6 +1755,67 @@
</ul>
</nav>
</li>
<li class="md-nav__item">
<a href="#layerd-raw-mapping-iteration-and-batch-access" class="md-nav__link">
<span class="md-ellipsis">
Layer\&lt;D> — raw mapping, iteration, and batch access
</span>
</a>
<nav class="md-nav" aria-label="Layer\&lt;D&gt; — raw mapping, iteration, and batch access">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#raw-kmer-slot-mapping" class="md-nav__link">
<span class="md-ellipsis">
Raw kmer → slot mapping
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#kmer-iteration" class="md-nav__link">
<span class="md-ellipsis">
Kmer iteration
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#batch-lookup-on-payload-vectorsviews" class="md-nav__link">
<span class="md-ellipsis">
Batch lookup on payload vectors/views
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#sub_matrix-fill_sub_matrix" class="md-nav__link">
<span class="md-ellipsis">
sub_matrix / fill_sub_matrix
</span>
</a>
</li>
</ul>
</nav>
</li>
<li class="md-nav__item">
@@ -1773,9 +1951,9 @@
<h1 id="obilayeredmap-layered-kmer-index-crate">obilayeredmap — layered kmer index crate</h1>
<h1 id="obikindexlayer-the-layer-tier">obikindex::layer — the Layer tier</h1>
<h2 id="purpose">Purpose</h2>
<p><code>obilayeredmap</code> implements a persistent, incrementally extensible kmer index. Each layer covers a disjoint kmer set and wraps a <code>ptr_hash</code> MPHF with associated per-slot data. Adding a new dataset never rebuilds existing layers.</p>
<p><code>obikindex::layer</code> (the <code>layer/</code> submodule of the <code>obikindex</code> crate — a standalone <code>obilayeredmap</code> crate until 2026-08-21, folded back in alongside <code>obikpartition</code> as part of a broader <code>Index { Partition { Layer } }</code> submodule regrouping) implements a persistent, incrementally extensible kmer index. Each layer covers a disjoint kmer set and wraps a <code>ptr_hash</code> MPHF with associated per-slot data. Adding a new dataset never rebuilds existing layers.</p>
<hr />
<h2 id="three-usage-modes">Three usage modes</h2>
<p>The MPHF + evidence infrastructure is the same for all modes. The <strong>payload</strong> varies.</p>
@@ -2000,6 +2178,38 @@
</code></pre></div>
<p>Mode 3 (<code>PersistentBitMatrix</code>) has no <code>push_layer</code> on <code>LayeredMap</code>; callers build directly via <code>Layer&lt;PersistentBitMatrix&gt;::build_presence</code>.</p>
<hr />
<h2 id="layerd-raw-mapping-iteration-and-batch-access">Layer\&lt;D&gt; — raw mapping, iteration, and batch access</h2>
<p>Beyond <code>query</code>/<code>find</code> (membership-checked), <code>Layer&lt;D&gt;</code> exposes lower-level access used by consumers that already know a kmer is in the layer (e.g. cross-partition sibling resolution) or that need to sweep every kmer/slot without paying for a membership check each time.</p>
<h3 id="raw-kmer-slot-mapping">Raw kmer → slot mapping</h3>
<div class="highlight"><pre><span></span><code><span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">index</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">kmer</span><span class="p">:</span><span class="w"> </span><span class="nc">CanonicalKmer</span><span class="p">)</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="kt">usize</span>
<span class="nc">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">index_batch</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">kmers</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="p">[</span><span class="n">CanonicalKmer</span><span class="p">])</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">usize</span><span class="o">&gt;</span>
</code></pre></div>
<p>Pure MPHF mapping, no evidence/fingerprint check — equivalent to <code>MphfOnly::index</code>. Only meaningful when the caller already knows <code>kmer</code> belongs to the layer; on an absent kmer the MPHF still returns <em>some</em> slot (undefined, not <code>None</code>).</p>
<h3 id="kmer-iteration">Kmer iteration</h3>
<p>Four iterators, all built from <code>unitigs.bin</code> (physical layout order, <strong>not</strong> correlated with MPHF slot numbers):</p>
<div class="highlight"><pre><span></span><code><span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">iter_kmers</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">)</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nc">KmerIter</span><span class="o">&lt;&#39;</span><span class="nb">_</span><span class="o">&gt;</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">enumerate_kmers</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">)</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nc">Enumerate</span><span class="o">&lt;</span><span class="n">KmerIter</span><span class="o">&lt;&#39;</span><span class="nb">_</span><span class="o">&gt;&gt;</span><span class="w"> </span><span class="c1">// (order_index, kmer)</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">iter_kmers_batch</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">n</span><span class="p">:</span><span class="w"> </span><span class="kt">usize</span><span class="p">)</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nc">KmerBatchIter</span><span class="o">&lt;&#39;</span><span class="nb">_</span><span class="o">&gt;</span><span class="w"> </span><span class="c1">// Vec&lt;CanonicalKmer&gt; of size ≤ n</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">enumerate_kmers_batch</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">n</span><span class="p">:</span><span class="w"> </span><span class="kt">usize</span><span class="p">)</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nc">impl</span><span class="w"> </span><span class="nb">Iterator</span><span class="o">&lt;</span><span class="n">Item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="kt">usize</span><span class="p">,</span><span class="w"> </span><span class="nb">Vec</span><span class="o">&lt;</span><span class="n">CanonicalKmer</span><span class="o">&gt;</span><span class="p">)</span><span class="o">&gt;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nb">Send</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="o">&#39;</span><span class="nb">static</span>
</code></pre></div>
<p><code>KmerIter</code>/<code>KmerBatchIter</code> own a clone of the underlying <code>Arc&lt;UnitigFileReader&gt;</code> rather than borrowing <code>self</code> — <code>Send + 'static</code>, streamed from disk one kmer at a time, never materialised as a whole. Multiple instances can coexist concurrently, each with its own cursor. <code>enumerate_kmers_batch</code>'s index is the batch's starting offset in iteration order (a multiple of <code>n</code> except for the final, possibly shorter, batch).</p>
<h3 id="batch-lookup-on-payload-vectorsviews">Batch lookup on payload vectors/views</h3>
<p><code>PersistentCompactIntVec</code>, <code>PersistentBitVec</code>, <code>IntSliceView</code>, <code>BitSliceView</code> all expose:</p>
<div class="highlight"><pre><span></span><code><span class="k">fn</span><span class="w"> </span><span class="nf">get_batch</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">slots</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="p">[</span><span class="kt">usize</span><span class="p">])</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nb">Vec</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span>
<span class="k">fn</span><span class="w"> </span><span class="nf">fill_batch</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">slots</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="p">[</span><span class="kt">usize</span><span class="p">],</span><span class="w"> </span><span class="n">out</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="nc">mut</span><span class="w"> </span><span class="p">[</span><span class="n">T</span><span class="p">])</span>
</code></pre></div>
<p>Both sort <code>slots</code> internally for sequential mmap access, then reorder results back to the caller's original order. <code>fill_batch</code> fills a caller-provided buffer, avoiding the <code>Vec</code> allocation.</p>
<h3 id="sub_matrix-fill_sub_matrix">sub_matrix / fill_sub_matrix</h3>
<div class="highlight"><pre><span></span><code><span class="c1">// Layer&lt;PersistentCompactIntMatrix&gt;</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">sub_matrix</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">slots</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="p">[</span><span class="kt">usize</span><span class="p">])</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nb">Vec</span><span class="o">&lt;</span><span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">u32</span><span class="o">&gt;&gt;</span><span class="w"> </span><span class="c1">// column-first</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">fill_sub_matrix</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">slots</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="p">[</span><span class="kt">usize</span><span class="p">],</span><span class="w"> </span><span class="n">out</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="nc">mut</span><span class="w"> </span><span class="p">[</span><span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">u32</span><span class="o">&gt;</span><span class="p">])</span>
<span class="c1">// Layer&lt;PersistentBitMatrix&gt; (and any D: BinaryMatrix, e.g. PersistentSparseBitMatrix)</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">sub_matrix</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">slots</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="p">[</span><span class="kt">usize</span><span class="p">])</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nb">Vec</span><span class="o">&lt;</span><span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">bool</span><span class="o">&gt;&gt;</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">fill_sub_matrix</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">slots</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="p">[</span><span class="kt">usize</span><span class="p">],</span><span class="w"> </span><span class="n">out</span><span class="p">:</span><span class="w"> </span><span class="kp">&amp;</span><span class="nc">mut</span><span class="w"> </span><span class="p">[</span><span class="nb">Vec</span><span class="o">&lt;</span><span class="kt">bool</span><span class="o">&gt;</span><span class="p">])</span>
</code></pre></div>
<p>Column-first to match the on-disk column-major layout. <code>fill_sub_matrix</code> sorts <code>slots</code> once, then calls each column's <code>fill_batch</code> in turn — no redundant per-column sort. On <code>PersistentSparseBitMatrix</code> (k-mer-major, no column method) this goes through <code>nonzero_iter</code> instead, decoding one row at a time; see <a href="../obicompactvec/">obicompactvec.md</a>, "Sparse matrix formats".</p>
<hr />
<h2 id="layeredstores-and-aggregation-traits">LayeredStore\&lt;S&gt; and aggregation traits</h2>
<p><code>LayeredStore&lt;S&gt;</code> is a generic aggregation wrapper over <code>Vec&lt;S&gt;</code>. It propagates three traits from <code>obicompactvec::traits</code> up the hierarchy via blanket impls:</p>
<div class="highlight"><pre><span></span><code><span class="k">pub</span><span class="w"> </span><span class="k">struct</span><span class="w"> </span><span class="nc">LayeredStore</span><span class="o">&lt;</span><span class="n">S</span><span class="o">&gt;</span><span class="p">(</span><span class="k">pub</span><span class="w"> </span><span class="nb">Vec</span><span class="o">&lt;</span><span class="n">S</span><span class="o">&gt;</span><span class="p">);</span>
+62 -6
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1215,9 +1271,9 @@
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obikindex/src/merge.rs</code> — <code>KmerIndex::merge()</code>, validation de compatibilité d'évidence, <code>validate_evidence_compat()</code></li>
<li><code>obikpartitionner/src/merge_layer.rs</code> — <code>merge_partition()</code>, construction de la nouvelle layer, paramètre <code>block_bits</code></li>
<li><code>obikpartitionner/src/rebuild_layer.rs</code> — <code>rebuild_partition()</code>, paramètre <code>block_bits</code></li>
<li><code>obilayeredmap/src/layer.rs</code> — <code>Layer::append_genome_column()</code> (PersistentCompactIntMatrix et PersistentBitMatrix)</li>
<li><code>obikindex/src/partition/merge_layer.rs</code> — <code>merge_partition()</code>, construction de la nouvelle layer, paramètre <code>block_bits</code></li>
<li><code>obikindex/src/partition/rebuild_layer.rs</code> — <code>rebuild_partition()</code>, paramètre <code>block_bits</code></li>
<li><code>obikindex/src/layer/typed_layer.rs</code> — <code>Layer::append_genome_column()</code> (PersistentCompactIntMatrix et PersistentBitMatrix)</li>
<li><code>obicompactvec/src/intmatrix.rs</code> — <code>append_column</code> pour PersistentCompactIntMatrix</li>
<li><code>obicompactvec/src/bitmatrix.rs</code> — <code>append_column</code> pour PersistentBitMatrix</li>
</ul>
+89 -3
View File
@@ -733,14 +733,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1034,6 +1034,17 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#known-issue-not-yet-fixed-2026-08-28" class="md-nav__link">
<span class="md-ellipsis">
Known issue (not yet fixed, 2026-08-28)
</span>
</a>
</li>
</ul>
@@ -1157,6 +1168,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1281,7 +1348,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1542,6 +1609,17 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#known-issue-not-yet-fixed-2026-08-28" class="md-nav__link">
<span class="md-ellipsis">
Known issue (not yet fixed, 2026-08-28)
</span>
</a>
</li>
</ul>
@@ -1739,6 +1817,14 @@ spectrums/
&lt;label&gt;.json ← one file per genome, rebuilt from all sources
index.meta ← complete genome list + evidence kind written at bootstrap
</code></pre></div>
<p><code>mphf.bin</code>/<code>unitigs.bin</code>/<code>evidence.bin</code>/<code>unitigs.bin.idx</code>/<code>fingerprint.bin</code>/<code>layer_meta.json</code> marked "unchanged" above are hard-linked from the base source's own files during the bootstrap copy (2026-08-28), not copied — <code>merge_partition</code> never rewrites them for pre-existing layers, only the <code>presence</code>/<code>counts</code> subdirectory gets widened in place, so only that subdirectory is a real, independent copy. Falls back to a real copy per file if linking itself fails (different filesystems). Verified: source files are byte-identical (checksummed) before/after a normal merge.</p>
<h2 id="known-issue-not-yet-fixed-2026-08-28">Known issue (not yet fixed, 2026-08-28)</h2>
<p>Merging an index against itself — literally the same directory passed twice as separate source arguments (e.g. <code>obikmer merge -o out IDX IDX --rename-duplicates</code>) — panics deep in the MPHF's rank-select structure (<code>common_traits::select_in_word</code>, <code>assertion failed: rank &lt; self.count_ones()</code>), inside <code>MphfLayer::find</code> called from <code>merge_partition</code>'s "is this source kmer already in dst" check against the bootstrap-copied <code>dst_layers</code>. Root cause not identified; ruled out so far:</p>
<ul>
<li><strong>Not an empty-new-layer issue</strong>: 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.</li>
<li><strong>Not caused by the hard-link change above</strong>: verified via checksum that a normal (two distinct sources) merge leaves every source file byte-identical.</li>
</ul>
<p>Only reproduces when <code>sources[0]</code> and <code>sources[1]</code> are the exact same on-disk path opened as two independent <code>KmerIndex</code> handles — an artificial scenario (nobody merges an index with itself intentionally), deprioritized rather than investigated further for now. Does terminate cleanly rather than hang, since <code>PartitionRunner</code>'s panic propagation fix (see <code>architecture/numa_partition_runner.md</code>) now surfaces it as a normal process panic/exit 101 instead of a silent deadlock.</p>
@@ -733,14 +733,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1152,6 +1152,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1276,7 +1332,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+61 -5
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1214,8 +1270,8 @@
<h1 id="coverage-implementationmphfmd">Coverage: implementation/mphf.md</h1>
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obilayeredmap/src/mphf_layer.rs</code> — type Mphf (PtrHash + CubicEps + CachelineEfVec + Xx64), construction en 2 passes, <code>build()</code>, <code>build_exact_evidence()</code>, <code>build_approx_evidence()</code>, <code>build_evidence()</code></li>
<li><code>obikpartitionner/src/index_layer.rs</code> — <code>build_index_layer()</code> avec passage de <code>block_bits</code></li>
<li><code>obikindex/src/layer/mphf_layer.rs</code> — type Mphf (PtrHash + CubicEps + CachelineEfVec + Xx64), construction en 2 passes, <code>build()</code>, <code>build_exact_evidence()</code>, <code>build_approx_evidence()</code>, <code>build_evidence()</code></li>
<li><code>obikindex/src/partition/index_layer.rs</code> — <code>build_index_layer()</code> avec passage de <code>block_bits</code></li>
</ul>
<h2 id="notes">Notes</h2>
<p>FORT RISQUE DE DÉRIVE. Changements récents :
+62 -6
View File
@@ -946,14 +946,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1163,6 +1163,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1287,7 +1343,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1577,7 +1633,7 @@
<h2 id="why-two-phases-are-needed">Why two phases are needed</h2>
<p>Kmer indexing per partition proceeds in two phases. The separation is necessary because the exact number of surviving unique kmers is not known until after counting and filtering low-abundance kmers.</p>
<h3 id="phase-1-provisional-mphf-kmer-spectrum">Phase 1 — provisional MPHF + kmer spectrum</h3>
<p>Implemented in <code>obikpartitionner::KmerPartition::count_kmer()</code> → <code>count_partition()</code>.</p>
<p>Implemented in <code>obikindex::partition::KmerPartition::count_kmer()</code> → <code>count_partition()</code>.</p>
<ol>
<li><strong>External sort</strong>: read the dereplicated superkmer file; extract the raw <code>u64</code> canonical kmer value for every kmer of every superkmer. Sort in RAM-bounded chunks (adaptive budget: 40% of available RAM ÷ n_threads, minimum 1 M kmers per chunk), then k-way merge with inline dedup. Result: <code>sorted_unique.bin</code> — a flat array of f0 distinct sorted <code>u64</code> values. Exact kmer count f0 is known at this point.</li>
<li><strong>Build provisional MPHF</strong> (ptr_hash, same configuration as phase 2) over <code>sorted_unique.bin</code> using <code>new_from_par_iter</code>. Delete <code>sorted_unique.bin</code> immediately after. Persist to <code>mphf1.bin</code>.</li>
@@ -1667,7 +1723,7 @@
<hr />
<h2 id="multilayer-index-architecture">Multilayer index architecture</h2>
<h3 id="layer-structure">Layer structure</h3>
<p>Each layer is a self-contained unit. See <a href="../obilayeredmap/">obilayeredmap</a> for the full on-disk layout. The MPHF-relevant files are:</p>
<p>Each layer is a self-contained unit. See <a href="../layer_tier/">obikindex::layer</a> for the full on-disk layout. The MPHF-relevant files are:</p>
<div class="highlight"><pre><span></span><code>layer_i/
unitigs.bin — packed 2-bit nucleotide sequences (kmer evidence source)
unitigs.bin.idx — random-access block index (block_bits controls granularity)
@@ -1702,7 +1758,7 @@ MphfLayer::build_approx_evidence(dir, b, z)
Uses open_sequential(); never writes .idx
</code></pre></div>
<p>There is no <code>build_evidence</code> dispatch wrapper. Callers choose the appropriate post-hoc build directly.</p>
<p>In <code>obikpartitionner</code>, <code>build_index_layer</code> receives <code>block_bits: u8</code> from <code>IndexConfig::block_bits</code> and forwards it directly to <code>Layer::build</code> and <code>Layer::build_approx_evidence</code>.</p>
<p>In <code>obikindex::partition</code>, <code>build_index_layer</code> receives <code>block_bits: u8</code> from <code>IndexConfig::block_bits</code> and forwards it directly to <code>Layer::build</code> and <code>Layer::build_approx_evidence</code>.</p>
<h3 id="membership-verification">Membership verification</h3>
<p>ptr_hash maps any input to a valid slot — it does not natively detect absent keys. Membership is verified using the evidence entry:</p>
<ul>
+266 -14
View File
@@ -320,11 +320,11 @@
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="../obilayeredmap/">
<a class="md-nav__link" href="../layer_tier/">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -412,6 +412,30 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="../benchmark_query_testing/">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="../partition_layer_cache/">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
@@ -470,7 +494,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -608,6 +632,46 @@
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="#sparse-matrix-formats">
<span class="md-ellipsis">
Sparse matrix formats
</span>
</a>
<nav aria-label="Sparse matrix formats" class="md-nav">
<ul class="md-nav__list">
<li class="md-nav__item">
<a class="md-nav__link" href="#persistentsparsebitmatrix">
<span class="md-ellipsis">
PersistentSparseBitMatrix
</span>
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="#nonzero_iter-the-one-traversal-per-format">
<span class="md-ellipsis">
nonzero_iter — the one traversal per format
</span>
</a>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="#persistentsparsecompactintmatrix">
<span class="md-ellipsis">
PersistentSparseCompactIntMatrix
</span>
</a>
</li>
</ul>
</nav>
</li>
<li class="md-nav__item">
<a class="md-nav__link" href="#aggregation-traits-matrix-level">
<span class="md-ellipsis">
@@ -1144,29 +1208,40 @@ Pass 1 — byte max, SIMD-vectorizable, O(n)
</code></pre></div>
<hr/>
<h2 id="matrix-types">Matrix types</h2>
<p>Four matrix types, two encodings × two formats:</p>
<p>Both matrix types are enums behind a transparent API — the caller never matches on the variant. <code>PersistentCompactIntMatrix</code> has three variants (<code>Columnar</code>, <code>Packed</code>, <code>Sparse</code>). <code>PersistentBitMatrix</code> has four:</p>
<table>
<thead>
<tr>
<th></th>
<th>Columnar format</th>
<th>Packed format</th>
<th>Variant</th>
<th>Storage</th>
<th>When</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Bit</strong></td>
<td><code>PersistentBitMatrix</code> (Columnar variant)</td>
<td><code>PersistentBitMatrix</code> (Packed variant)</td>
<td><code>Columnar</code></td>
<td>one <code>.pbiv</code>/<code>.pciv</code> file per column + <code>meta.json</code></td>
<td>build-time default (<code>*Builder::new</code>)</td>
</tr>
<tr>
<td><strong>Int</strong></td>
<td><code>PersistentCompactIntMatrix</code> (Columnar variant)</td>
<td><code>PersistentCompactIntMatrix</code> (Packed variant)</td>
<td><code>Packed</code></td>
<td>single <code>matrix.pbmx</code>/<code>matrix.pcmx</code> mmap file</td>
<td>query-optimised, produced by <code>pack_bit_matrix</code>/<code>pack_compact_int_matrix</code></td>
</tr>
<tr>
<td><code>Sparse</code></td>
<td>bit: <code>sparse_meta.json</code> + PFIV/Elias-Fano component files, row-major. Int: same support files (built on <code>PersistentSparseBitMatrix</code> internally) plus <code>singleton_values.pciv</code>/<code>multi_values.pciv</code>/<code>multi_offsets</code> for the per-row, non-deduplicated values</td>
<td><code>pack --sparse</code>; see "Sparse matrix formats" below for the sparse-vs-dense access-pattern trade-off</td>
</tr>
<tr>
<td><code>Implicit</code> (bit only)</td>
<td>no file at all</td>
<td>mono-genome presence layers — <code>n_cols</code> is always reported as <code>1</code>, every value is <code>true</code></td>
</tr>
</tbody>
</table>
<p>Both matrix types are enums (<code>Columnar</code> / <code>Packed</code> / <code>Implicit</code> for bit) behind a transparent API. <code>col_view(c)</code> returns the appropriate view directly:</p>
<p><code>PersistentBitMatrix::open(layer_dir)</code> auto-detects the variant, in order: <code>matrix.pbmx</code> → Packed, <code>presence/meta.json</code> → Columnar, <code>presence/sparse_meta.json</code> → Sparse, <code>layer_meta.json</code> (no presence dir at all) → Implicit. <code>PersistentCompactIntMatrix::open(layer_dir)</code> mirrors the same priority order minus <code>Implicit</code> (there's no implicit count matrix — counts always have at least one on-disk column): <code>matrix.pcmx</code> → Packed, <code>counts/meta.json</code> → Columnar, <code>counts/singleton_values.pciv</code> → Sparse. <code>col_view</code>/<code>col</code>/<code>sub_matrix</code> panic on <code>Sparse</code>/<code>Implicit</code> where the operation has no direct-slice equivalent (Sparse is k-mer-major, not column-major; Implicit has no backing storage) — callers needing per-column data on those variants go through <code>row</code>/<code>fill_row</code>.</p>
<p><code>col_view(c)</code> returns the appropriate view directly:</p>
<div class="highlight"><pre><span></span><code><span class="c1">// PersistentBitMatrix</span>
<span class="k">pub</span><span class="w"> </span><span class="k">fn</span><span class="w"> </span><span class="nf">col_view</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">c</span><span class="p">:</span><span class="w"> </span><span class="kt">usize</span><span class="p">)</span><span class="w"> </span><span class="p">-&gt;</span><span class="w"> </span><span class="nc">BitSliceView</span><span class="o">&lt;'</span><span class="nb">_</span><span class="o">&gt;</span>
@@ -1176,6 +1251,183 @@ Pass 1 — byte max, SIMD-vectorizable, O(n)
<p>No wrapper enums (<code>BitColView</code>, <code>IntColView</code>): the caller receives a <code>Copy</code> view struct immediately usable with any view method or bulk builder method.</p>
<p><code>pack_compact_int_matrix</code> and <code>pack_bit_matrix</code> convert columnar → packed format.</p>
<hr/>
<h2 id="sparse-matrix-formats">Sparse matrix formats</h2>
<p>Motivated by real k-mer-family data being extremely row-sparse (most rows —
k-mers — present in only a handful of genome columns out of dozens to
thousands): a row-major, deduplicated alternative to the dense column-major
formats above, built once per layer like the rest of the pipeline (never the
whole multi-billion-row index at once). Implements the exact-duplicate
special case of Alanko, Bille, Gørtz, Navarro, Puglisi, "Compact Data
Structures for Collections of Sets" (2025,
<code>biblio/Alanko et al. - Compact Data Structures for Collections of
Sets.pdf</code>) — a plain dedup dictionary, not their full subset-containment
hierarchy.</p>
<h3 id="persistentsparsebitmatrix"><code>PersistentSparseBitMatrix</code></h3>
<p>Four mmap-backed on-disk components: an <code>is_multi</code> rank-capable flag per row
(singleton vs. multi-genome), a fixed-bit-width array for singleton rows
(genome index directly, <code>ceil(log2(n_cols))</code> bits), a separate fixed-width
array for multi-genome rows (<code>dict_id</code>, <code>ceil(log2(n_distinct_multi_sets))</code>
bits — kept apart from the singleton array because <code>n_distinct_multi_sets</code>
can be large in absolute terms even when multi-genome rows are a small
<em>fraction</em> of all rows, and a shared array would force every row, singletons
included, to pay the wider width), and a deduplicated dictionary of distinct
multi-genome sets (Elias-Fano-encoded byte offsets + a varint-encoded values
blob). Supporting primitives: <code>PersistentFixedIntVec</code> (arbitrary,
runtime-parameterised bit width, width <code>0</code> included — needed once an
<code>EliasFano</code> reopen bug surfaced, see below), <code>PersistentRankSelectBitVec</code>
(rank1/rank0/select1 on top of the crate's existing <code>count_ones</code>, via
<code>common_traits::SelectInWord</code>), <code>EliasFano</code> (composes the two). <code>BinaryMatrix</code>
(<code>n</code>, <code>n_cols</code>, <code>row</code>/<code>fill_row</code>, <code>fill_sub_matrix</code>, <code>count_ones</code>) is the
trait unifying dense and sparse at the call sites that need both
interchangeably; column-oriented methods (<code>col</code>, <code>col_view</code>, the
<code>partial_*_dist_matrix</code> family) stay dense-only — <code>Sparse</code>/<code>Implicit</code> panic
there (see the <code>PersistentBitMatrix::open</code> note above).</p>
<p>Measured on real data (one layer, 30.2M rows, 91 genomes):</p>
<table>
<thead>
<tr>
<th></th>
<th>dense</th>
<th>sparse</th>
<th>ratio</th>
</tr>
</thead>
<tbody>
<tr>
<td>on-disk size</td>
<td>328.1MB</td>
<td>43.7MB</td>
<td><strong>7.5x</strong> smaller</td>
</tr>
<tr>
<td>build time / peak RSS</td>
<td>—</td>
<td>4.26s / 628MB</td>
<td>per-layer, in-memory construction</td>
</tr>
<tr>
<td>row access, sequential (2M reads)</td>
<td>43ns/row</td>
<td>32ns/row</td>
<td>sparse faster (smaller structure, better cache fit)</td>
</tr>
<tr>
<td>row access, random (2M reads)</td>
<td>409ns/row</td>
<td>85ns/row</td>
<td>sparse <strong>~4.8x faster</strong> — the <code>--shannon</code>/family-lookup access shape</td>
</tr>
<tr>
<td>column access, one full column (30.2M rows)</td>
<td>11.5ms</td>
<td>993ms</td>
<td>sparse <strong>86x slower</strong> — no native column method, every read decodes a full row to keep one bit</td>
</tr>
</tbody>
</table>
<p>The row-access wins (compactness was the stated design goal, not speed) come
from dense's genome-major layout scattering a single row read across a much
bigger file — costlier than sparse's rank/select/varint decode once the file
is this much smaller. Column access is the flip side of the same layout
choice; <code>nonzero_iter</code> (below) is what removes it from the hot path that
actually matters (<code>query</code>).</p>
<p>Two reopen-correctness bugs, now fixed at the source: (1) <code>EliasFano::open</code>
re-derived its low-bits width from the persisted low-vector's own width
byte; the width-<code>0</code> case was built with a dummy 1-bit placeholder (the
builder used to reject true width <code>0</code>), silently doubling every reopened
value. Fixed by making <code>PersistentFixedIntVec</code> genuinely support width <code>0</code>
(no storage, <code>get</code> always <code>0</code>). (2) An empty row (cardinality 0) used to be
recorded as a singleton at genome <code>0</code>, indistinguishable on read-back from a
<em>real</em> singleton at genome <code>0</code>. Fixed by routing cardinality-0 rows through
the dictionary path (a genuine empty entry).</p>
<p>Still deferred: full Alanko et al. subset-hierarchy compression (only the
exact-duplicate case is built), a sparse <code>PersistentCompactIntMatrix</code>
variant beyond what's described below, BRWT-style column-correlation
exploitation, and a row-major rewrite of
<code>partial_jaccard_dist_matrix</code>/<code>partial_hamming_dist_matrix</code>/etc. as a
per-row co-occurrence accumulation (<code>O(Σ_rows k̄²)</code>) so <code>obikindex</code>'s
<code>--metric</code> distance-matrix path stops paying the column-access penalty on
<code>Sparse</code> — needs its own design pass (how it plugs into
<code>BitPartials</code>/<code>ColumnWeights</code> so both matrix types keep serving <code>--metric</code>),
not just "port the loop".</p>
<h3 id="nonzero_iter-the-one-traversal-per-format"><code>nonzero_iter</code> — the one traversal per format</h3>
<p><code>fn nonzero_iter&lt;'a&gt;(&amp;'a self, slots: &amp;'a [usize]) -&gt; Box&lt;dyn Iterator&lt;Item = (usize, usize, u32)&gt; + 'a&gt;</code>
(item: index into <code>slots</code>, column, value) is the single foundational
per-format traversal primitive every consumer builds on — <code>fill_sub_matrix</code>
and a <code>for_each</code>-style callback are both trivial, free consumers of it
(<code>.for_each(f)</code> is <code>Iterator::for_each</code>; <code>fill_sub_matrix</code> drains the
iterator and scatters into <code>out[][]</code>), instead of two independently
hand-maintained traversals that can silently diverge. <code>Box&lt;dyn Iterator&gt;</code>,
not a bare <code>impl Iterator</code>: <code>Columnar</code>/<code>Packed</code>/<code>Sparse</code>/<code>Implicit</code> are
genuinely different concrete types and the method isn't on a
dyn-compatible trait (<code>BinaryMatrix</code> is used as <code>dyn BinaryMatrix</code>
elsewhere, and RPITIT methods aren't dyn-compatible) — one <code>Box</code> per
<code>nonzero_iter</code> call, not per cell.</p>
<p>Per-format implementation: <code>PersistentSparseBitMatrix</code> decodes natively,
buffered one row at a time (<code>std::iter::from_fn</code> over the existing
<code>for_each_genome_in_row</code>, no <code>n_cols</code>-wide allocation ever). <code>Columnar</code>/
<code>Packed</code> loop columns, collecting each column's hits via
<code>BitSliceView::nonzero_among_sorted</code>/<code>IntSliceView::nonzero_among_sorted</code>
(a <code>filter</code>/<code>filter_map</code> over the vector-level <code>get()</code>, no new state
machine — <code>std</code>'s own <code>Filter</code> iterator already is one) into one <code>Vec</code> via
<code>.extend()</code> (not <code>flat_map</code>: a <code>flat_map</code> closure can't lazily return
something borrowing its own captured sort permutation across separate calls
without either boxing per-column or fighting the borrow checker — eager
collection sidesteps it at zero extra cost, since <code>fill_sub_matrix</code> already
fully materialises anyway). <code>Implicit</code> is trivial (<code>slots.iter().map(|&amp;i| (i, 0, 1))</code>).</p>
<p>This closed a real dispatch bug by construction, not by patching it:
<code>PersistentBitMatrix::fill_sub_matrix</code>/<code>sub_matrix</code> used to reimplement a
naive per-<code>(column, slot)</code> loop instead of delegating to
<code>PersistentSparseBitMatrix</code>'s own efficient native method for <code>Self::Sparse</code>
— two hand-written traversals for the same format, free to drift apart, and
they had (<code>obikphylo</code>'s own cache layer had independently built a parallel
enum wrapper that <em>did</em> dispatch correctly, evidence the bug was worked
around rather than fixed at the source). With <code>fill_sub_matrix</code>/<code>sub_matrix</code>
rewritten to drain <code>nonzero_iter</code>, there is only one traversal per format
left to get right. <code>KmerPartition::query_partition_with</code>
(<code>obikindex/src/partition/query_layer.rs</code>) — previously column-major
(<code>for g { for slot { col_value } }</code>, which for <code>Sparse</code> rebuilt a full row
per single cell touched, O(hits × n_cols) instead of O(hits) — the original
motivation for this primitive) — now issues one <code>layer.nonzero_iter(&amp;slot_list)</code>
call per layer, format-agnostic. Dense/sparse query performance parity
confirmed on real data (previously sparse 30-50% slower than dense,
reproducibly; now within ~1-3% either way — noise level).</p>
<h3 id="persistentsparsecompactintmatrix"><code>PersistentSparseCompactIntMatrix</code></h3>
<p>The count-matrix analogue, built on <code>PersistentSparseBitMatrix</code> as its
"which columns are non-zero" support, values <strong>not</strong> deduplicated (unlike
the bit side, two rows can share the same non-zero column set — same
<code>dict_id</code> — while carrying different counts, so the dict-multiplicity
shortcut <code>BitPartials for PersistentSparseBitMatrix</code> uses doesn't carry
over). <code>CountPartials</code> here: a single row-major pass (<code>row_major_pairwise</code>
in <code>sparse_intmatrix.rs</code>, decodes each row once via
<code>for_each_cell_in_row</code>, nests over that row's own co-present columns) —
<code>O(Σ k̄²)</code> over populated rows, avoiding the naive <code>O(n_cols² × n)</code>
column-pair rescan. <code>min(a,b)</code>-based kernels (<code>bray</code>, <code>relfreq_bray</code>) need
no correction — they vanish when either side is absent. <code>a·b</code> and <code>√(a·b)</code>
kernels (<code>euclidean</code>/<code>relfreq_euclidean</code>/<code>hellinger</code>) do need one, since
<code>(a-0)² = a² ≠ 0</code> unlike the <code>min</code>-based formulas — reconstructed from
per-column marginals via <code>Σ(a-b)² = Σa²+Σb²-2Σab</code>.
<code>threshold_jaccard(1)</code> shortcuts to <code>BitPartials::partial_jaccard</code>
(threshold 1 is exactly presence); <code>threshold_jaccard(0)</code> is closed-form
(every <code>u32</code> is <code>≥ 0</code>).</p>
<p>Wiring the <code>threshold==1</code> shortcut surfaced two pre-existing formula bugs in
<code>BitPartials for PersistentSparseBitMatrix</code> (present since that type's own
introduction, never caught because no test had compared <code>Sparse</code>'s raw
<code>partial_*</code> output against dense on real data — only the diagonal-blind
<code>jaccard_dist_matrix</code>/<code>hamming_dist_matrix</code> finalisations were tested),
fixed at the source:</p>
<ol>
<li><code>partial_jaccard</code>'s diagonal used to be <code>(0, 2×col_weights[i])</code> instead
of a genuine self-comparison <code>(col_weights[i], col_weights[i])</code> —
<code>col_weights_and_pair_counts</code>'s <code>inter</code> never pairs a column with itself
by construction, so the diagonal needs its own case.</li>
<li><code>partial_hamming</code>'s off-diagonal formula itself was wrong: it computed
<code>total - union</code> (rows where <em>neither</em> column is present) instead of the
actual Hamming distance <code>col_weights[i] + col_weights[j] - 2×inter[i,j]</code>
(symmetric-difference size) — the two only coincide when
<code>col_weights[i] + col_weights[j] == total</code>, which small/synthetic test
data can easily satisfy by accident.</li>
</ol>
<h2 id="aggregation-traits-matrix-level">Aggregation traits (matrix level)</h2>
<h3 id="columnweights">ColumnWeights</h3>
<div class="highlight"><pre><span></span><code><span class="k">trait</span><span class="w"> </span><span class="n">ColumnWeights</span><span class="p">:</span><span class="w"> </span><span class="nb">Send</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nb">Sync</span><span class="w"> </span><span class="p">{</span>
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1219,7 +1275,7 @@
</ul>
<h2 id="notes">Notes</h2>
<p>Document stable (librairie générique, peu de risque de dérive).
Vérifier si <code>obipipeline</code> est toujours utilisé dans la phase scatter de <code>obikpartitionner</code>
Vérifier si <code>obipipeline</code> est toujours utilisé dans la phase scatter de <code>obikindex::partition</code>
ou s'il a été remplacé par Rayon dans certains chemins.</p>
+59 -3
View File
@@ -896,14 +896,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1113,6 +1113,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1237,7 +1293,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+60 -4
View File
@@ -12,7 +12,7 @@
<link rel="prev" href="../select/">
<link rel="next" href="../../architecture/sequences/invariant/">
<link rel="next" href="../benchmark_query_testing/">
@@ -733,14 +733,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1125,6 +1125,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1249,7 +1305,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
File diff suppressed because it is too large. Load diff
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -733,14 +733,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1225,6 +1225,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1349,7 +1405,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -9,7 +9,7 @@
<link rel="prev" href="../obilayeredmap/">
<link rel="prev" href="../layer_tier/">
<link rel="next" href="../persistent_bit_vec/">
@@ -733,14 +733,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1208,6 +1208,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1332,7 +1388,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+63 -7
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1214,12 +1270,12 @@
<h1 id="coverage-implementationpipelinemd">Coverage: implementation/pipeline.md</h1>
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obikpartitionner/src/partition.rs</code> — estimation des paramètres (phase 0)</li>
<li><code>obikindex/src/partition/partition.rs</code> — estimation des paramètres (phase 0)</li>
<li><code>obiskbuilder/src/iter.rs</code> — scatter : filtre entropie, extraction superkmers, routage partition (phase 1)</li>
<li><code>obikpartitionner/src/filter.rs</code> — déduplication bucket-sort (phase 2)</li>
<li><code>obikpartitionner/src/kmer_sort.rs</code> — tri externe + agrégation de comptages (phase 3)</li>
<li><code>obikindex/src/partition/filter.rs</code> — déduplication bucket-sort (phase 2)</li>
<li><code>obikindex/src/partition/kmer_sort.rs</code> — tri externe + agrégation de comptages (phase 3)</li>
<li><code>obidebruinj/src/debruijn.rs</code> — graphe De Bruijn, extraction des unitigs (phase 5)</li>
<li><code>obikpartitionner/src/index_layer.rs</code> — construction MPHF + évidence (phase 6), paramètre <code>block_bits</code></li>
<li><code>obikindex/src/partition/index_layer.rs</code> — construction MPHF + évidence (phase 6), paramètre <code>block_bits</code></li>
<li><code>obikindex/src/index.rs</code> — <code>build_layers()</code>, <code>dereplicate_and_count()</code></li>
</ul>
<h2 id="notes">Notes</h2>
+60 -4
View File
@@ -857,14 +857,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1074,6 +1074,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1198,7 +1254,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1546,7 +1602,7 @@ branching / dead-end → unitig start or end
counts/ ← PersistentCompactIntMatrix (with_counts only)
</code></pre></div>
<p><strong>Cleanup:</strong> unless <code>--keep-intermediate</code> is set, <code>remove_build_artifacts</code> deletes <code>dereplicated.skmer.zst</code>, <code>mphf1.bin</code>, and <code>counts1.bin</code> after all partitions are indexed.</p>
<p>See <a href="../obilayeredmap/">obilayeredmap</a> and <a href="../mphf/">MPHF selection</a> for data structure details.</p>
<p>See <a href="../layer_tier/">obikindex::layer</a> and <a href="../mphf/">MPHF selection</a> for data structure details.</p>
<p><strong>Query path (exact evidence):</strong></p>
<div class="highlight"><pre><span></span><code>query kmer q
→ canonical_minimizer(q) → hash → PART → part_XXXXX/
+147 -59
View File
@@ -733,14 +733,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1119,17 +1119,6 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#in-place-keep-only-group-a" class="md-nav__link">
<span class="md-ellipsis">
In-place: keep only group A
</span>
</a>
</li>
<li class="md-nav__item">
@@ -1157,6 +1146,23 @@
</span>
</a>
<nav class="md-nav" aria-label="Implementation notes">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#known-gap-not-yet-fixed-2026-08-28" class="md-nav__link">
<span class="md-ellipsis">
Known gap (not yet fixed, 2026-08-28)
</span>
</a>
</li>
</ul>
</nav>
</li>
</ul>
@@ -1196,6 +1202,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1320,7 +1382,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1582,17 +1644,6 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#in-place-keep-only-group-a" class="md-nav__link">
<span class="md-ellipsis">
In-place: keep only group A
</span>
</a>
</li>
<li class="md-nav__item">
@@ -1620,6 +1671,23 @@
</span>
</a>
<nav class="md-nav" aria-label="Implementation notes">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#known-gap-not-yet-fixed-2026-08-28" class="md-nav__link">
<span class="md-ellipsis">
Known gap (not yet fixed, 2026-08-28)
</span>
</a>
</li>
</ul>
</nav>
</li>
</ul>
@@ -1672,23 +1740,32 @@ are preserved unchanged; only the data matrices are rewritten.</p>
<hr />
<h2 id="synopsis">Synopsis</h2>
<div class="highlight"><pre><span></span><code>obikmer<span class="w"> </span><span class="k">select</span><span class="w"> </span>&lt;input-index&gt;
<span class="w"> </span><span class="o">{</span><span class="w"> </span>--output<span class="w"> </span>&lt;dir&gt;<span class="w"> </span><span class="p">|</span><span class="w"> </span>--in-place<span class="w"> </span><span class="o">}</span>
<span class="w"> </span>--output<span class="w"> </span>&lt;dir&gt;
<span class="w"> </span><span class="o">[</span>--group<span class="w"> </span>&lt;name&gt;:&lt;pred&gt;<span class="w"> </span>...<span class="o">]</span>
<span class="w"> </span><span class="o">[</span>--group-op<span class="w"> </span>&lt;name&gt;:&lt;op&gt;<span class="w"> </span>...<span class="o">]</span>
<span class="w"> </span><span class="o">[</span>--aggregate-by<span class="w"> </span>&lt;key&gt;<span class="w"> </span><span class="o">]</span>
<span class="w"> </span><span class="o">[</span>--aggregate-op<span class="w"> </span>&lt;op&gt;<span class="w"> </span><span class="o">]</span>
<span class="w"> </span><span class="o">[</span>--select<span class="w"> </span>&lt;col1,col2,...&gt;<span class="w"> </span><span class="o">]</span>
<span class="w"> </span><span class="o">[</span>--presence-threshold<span class="w"> </span>&lt;N&gt;<span class="w"> </span><span class="o">]</span>
<span class="w"> </span><span class="o">[</span>--force-copy<span class="w"> </span><span class="o">]</span>
</code></pre></div>
<hr />
<h2 id="output-destination">Output destination</h2>
<p>Exactly one of <code>--output</code> or <code>--in-place</code> must be specified.</p>
<p><strong><code>--output &lt;dir&gt;</code></strong> — writes a new index to <code>&lt;dir&gt;</code>. The source index is
unchanged. The MPHF and unitig files are copied; only the data matrices are
rewritten with the new column layout.</p>
<p><strong><code>--in-place</code></strong> — rewrites the data matrices of the source index directly.
Removed or replaced columns are lost. The operation writes to temporary files
first, then renames atomically, so an interrupted run leaves the index intact.</p>
<p><code>--output &lt;dir&gt;</code> is required — <code>select</code> always writes a new index; there is no
<code>--in-place</code> mode (2026-08-28: never implemented, removed from the design). The
source index is unchanged.</p>
<p>Each layer's kmer-identity files (<code>mphf.bin</code>/<code>unitigs.bin</code>/<code>evidence.bin</code>/
<code>unitigs.bin.idx</code>/<code>fingerprint.bin</code>/<code>layer_meta.json</code>) are never rewritten by a
column projection/aggregation, so they are hard-linked into the output rather
than copied — no extra disk for them even on a large index. Falls back to a
real copy automatically if linking fails (different filesystems); <code>--force-copy</code>
forces a real copy always, for an output that must survive independently of the
source on disk (a hard link shares the same inode — rewriting one path outside
<code>select</code> itself would affect the other). Only the <code>presence</code>/<code>counts</code>
subdirectory is ever a genuinely new, independent file.</p>
<p>To replace an index with a selected version of itself, select to a temporary
directory and swap it in (<code>rm -rf INDEX &amp;&amp; mv INDEX.tmp INDEX</code>) — the case
<code>--in-place</code> used to cover.</p>
<hr />
<h2 id="defining-output-columns">Defining output columns</h2>
<h3 id="named-groups-group">Named groups — <code>--group</code></h3>
@@ -1852,9 +1929,6 @@ is &gt; N.</p>
<div class="highlight"><pre><span></span><code>obikmer<span class="w"> </span><span class="k">select</span><span class="w"> </span>myindex<span class="w"> </span>--output<span class="w"> </span>out<span class="w"> </span><span class="se">\</span>
<span class="w"> </span>--select<span class="w"> </span><span class="s2">&quot;Betula_nana--TROM-V-149986,Betula_nana--AG-P04-25-01&quot;</span>
</code></pre></div>
<h3 id="in-place-keep-only-group-a">In-place: keep only group A</h3>
<div class="highlight"><pre><span></span><code>obikmer<span class="w"> </span><span class="k">select</span><span class="w"> </span>myindex<span class="w"> </span>--in-place<span class="w"> </span>--group<span class="w"> </span><span class="s2">&quot;A:group=A&quot;</span><span class="w"> </span>--select<span class="w"> </span><span class="s2">&quot;A&quot;</span>
</code></pre></div>
<h3 id="compose-with-filter">Compose with filter</h3>
<div class="highlight"><pre><span></span><code><span class="c1"># Step 1: keep only B. nana-specific k-mers</span>
obikmer<span class="w"> </span>filter<span class="w"> </span>myindex<span class="w"> </span>--output<span class="w"> </span>filtered<span class="w"> </span><span class="se">\</span>
@@ -1865,32 +1939,46 @@ obikmer<span class="w"> </span><span class="k">select</span><span class="w"> </s
</code></pre></div>
<hr />
<h2 id="implementation-notes">Implementation notes</h2>
<p><code>select</code> does not rebuild the MPHF. The 256 partitions are processed in parallel
(rayon), each writing its output independently; results require no synchronisation
because every partition owns a distinct set of files.</p>
<p>For each layer in each partition:</p>
<p><code>select</code> does not rebuild the MPHF. Every partition is processed independently
(<code>PartitionRunner</code>), each writing its own output layers; no cross-partition
synchronisation is needed.</p>
<p>For each layer in each partition (<code>obikselect::select_layer::select_partition</code>):</p>
<ol>
<li>The slot count <code>n</code> is read by opening the source data matrix.</li>
<li>A new data matrix is built with M columns (M = number of output columns).</li>
<li>For each slot <code>s</code> in <code>0..n</code>:</li>
<li><code>old_row = matrix.fill_row(s)</code> — reads the original <code>N</code>-column row without allocating.</li>
<li>For each output column <code>j</code>:<ul>
<li><code>new_row[j] = aggregate(op, old_row[group_indices])</code>.</li>
<li>Pass-through columns are represented as single-element groups with the
default operator (<code>any</code> for presence, <code>sum</code> for count) — same code path.</li>
</ul>
</li>
<li>The new row is written slot by slot into each column builder.</li>
<li>All plain files in the source layer directory (<code>mphf.bin</code>, <code>unitigs.bin</code>,
evidence files, <code>layer_meta.json</code>) are copied verbatim; only the <code>presence/</code>
or <code>counts/</code> subdirectory is rewritten.</li>
<li><code>copy_layer_files</code> hard-links the source layer's kmer-identity files
(<code>mphf.bin</code>/<code>unitigs.bin</code>/<code>evidence.bin</code>/<code>unitigs.bin.idx</code>/
<code>fingerprint.bin</code>/<code>layer_meta.json</code>) into the destination — never a real
copy unless linking fails or <code>--force-copy</code> is given.</li>
<li>A new data matrix is built with M columns (M = number of output columns),
under a fresh <code>presence/</code>/<code>counts/</code> subdirectory (never touching the
source's own).</li>
<li><strong>Presence source (2026-08-28: <code>batch_presence_counts</code>)</strong>: one shared pass
over the source bit matrix computes every output group's presence count at
once — row-major native for a <code>Sparse</code> source (<code>for_each_genome_in_row</code>,
which has no column representation to read a <code>col_view</code> from at all — the
reason this replaced the old per-group loop, not just an optimisation of
it), deduplicated column-major (one <code>col_view</code> per <em>distinct referenced
column</em>, not per group) for <code>Columnar</code>/<code>Packed</code>. Every <code>AggOp</code> for a bit
matrix is then a cheap derivation of that one count vector (<code>sum</code> = the
count itself, <code>any</code>/<code>max</code> = <code>count ≥ 1</code>, <code>all</code>/<code>min</code> = <code>count == group
size</code>, <code>none</code> = <code>count == 0</code>) — see
<code>obikselect::select_layer::agg_result_from_count</code>.</li>
<li><strong>Count source</strong>: unchanged, one <code>col_view</code>-driven pass per output column
via <code>MatrixGroupOps</code> — <code>sum</code>/<code>min</code>/<code>max</code> are genuine per-value reductions
for a count matrix, not derivable from a single presence count the way
they are for a bit matrix.</li>
<li><code>index.meta</code> is rewritten with the new genome list and updated <code>with_counts</code>.</li>
</ol>
<p><strong><code>--in-place</code> write strategy:</strong> new data is written to a temporary sibling
directory (<code>presence_new/</code> or <code>counts_new/</code>); on success the old directory is
removed and the temporary one is renamed into place. An interrupted run leaves
at most one stale <code>*_new/</code> directory; the original data is intact until the
rename step.</p>
<h3 id="known-gap-not-yet-fixed-2026-08-28">Known gap (not yet fixed, 2026-08-28)</h3>
<p>Step 4 above still panics (<code>col_view() not available on Sparse
PersistentCompactIntMatrix</code>) if the source is a <strong>count</strong> index packed
sparse — <code>batch_presence_counts</code>' row-major treatment was only ported to the
bit-matrix (<code>Presence</code>) case, since that was the one actually blocking a real
benchmark run. <code>select</code>/<code>filter</code> on a sparse-packed count index still hits
this; the fix would follow the same shape (a <code>PersistentSparseCompactIntMatrix</code>
row-major decode, analogous to <code>for_each_genome_in_row</code>), just not done. Since
<code>obisys::numa::runner::PartitionRunner</code>'s panic-propagation fix (see
<code>architecture/numa_partition_runner.md</code>), this at least fails fast (process
panic, exit 101) instead of hanging.</p>
+60 -4
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1216,7 +1272,7 @@
<ul>
<li><code>obikindex/src/meta.rs</code> — IndexMeta, IndexConfig (version, config, genomes)</li>
<li><code>obikindex/src/index.rs</code> — layout sur disque : partitions/, index.meta</li>
<li><code>obilayeredmap/src/meta.rs</code> — LayerMeta (evidence kind), PartitionMeta (n_layers)</li>
<li><code>obikindex/src/layer/meta.rs</code> — LayerMeta (evidence kind), PartitionMeta (n_layers)</li>
<li><code>obiskio/src/unitig_index.rs</code> — fichiers unitigs.bin + unitigs.bin.idx</li>
</ul>
<h2 id="notes">Notes</h2>
+59 -3
View File
@@ -929,14 +929,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1146,6 +1146,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1270,7 +1326,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -835,14 +835,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1052,6 +1052,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1176,7 +1232,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1215,7 +1271,7 @@
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obiskio/src/unitig_index.rs</code> — format unitigs.bin + unitigs.bin.idx, UnitigFileWriter, UnitigFileReader, build_unitig_idx(), DEFAULT_BLOCK_BITS=0, chemin chaud block_bits=0 dans chunk_start()</li>
<li><code>obilayeredmap/src/evidence.rs</code> — encodage Evidence (chunk_id 25 bits | rank 7 bits), EvidenceWriter</li>
<li><code>obikindex/src/layer/evidence.rs</code> — encodage Evidence (chunk_id 25 bits | rank 7 bits), EvidenceWriter</li>
<li><code>obidebruinj/src/debruijn.rs</code> — extraction unitigs, chunking à MAX_KMERS_PER_CHUNK</li>
</ul>
<h2 id="notes">Notes</h2>
@@ -957,14 +957,14 @@
<li class="md-nav__item">
<a href="../obilayeredmap/" class="md-nav__link">
<a href="../layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1174,6 +1174,62 @@
<li class="md-nav__item">
<a href="../benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1298,7 +1354,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -831,14 +831,14 @@
<li class="md-nav__item">
<a href="implementation/obilayeredmap/" class="md-nav__link">
<a href="implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1048,6 +1048,62 @@
<li class="md-nav__item">
<a href="implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1172,7 +1228,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../implementation/obilayeredmap/" class="md-nav__link">
<a href="../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -917,14 +917,14 @@
<li class="md-nav__item">
<a href="../implementation/obilayeredmap/" class="md-nav__link">
<a href="../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1134,6 +1134,62 @@
<li class="md-nav__item">
<a href="../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1258,7 +1314,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../implementation/obilayeredmap/" class="md-nav__link">
<a href="../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -830,14 +830,14 @@
<li class="md-nav__item">
<a href="../implementation/obilayeredmap/" class="md-nav__link">
<a href="../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1047,6 +1047,62 @@
<li class="md-nav__item">
<a href="../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1171,7 +1227,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
Binary file not shown.
+59 -3
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -802,14 +802,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1019,6 +1019,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1143,7 +1199,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -868,14 +868,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1085,6 +1085,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1209,7 +1265,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
File diff suppressed because it is too large. Load diff
+61 -5
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -1214,8 +1270,8 @@
<h1 id="coverage-theoryindexingmd">Coverage: theory/indexing.md</h1>
<h2 id="code-couvert">Code couvert</h2>
<ul>
<li><code>obikpartitionner/src/partition.rs</code> — routage par hash de minimiseur, choix des paramètres</li>
<li><code>obikpartitionner/src/lib.rs</code> — structure KmerPartition, nombre de partitions</li>
<li><code>obikindex/src/partition/partition.rs</code> — routage par hash de minimiseur, choix des paramètres</li>
<li><code>obikindex/src/partition/mod.rs</code> — structure KmerPartition, nombre de partitions</li>
</ul>
<h2 id="notes">Notes</h2>
<p>Vérifier que la doc mentionne bien que le nombre de partitions est une puissance de 2
+59 -3
View File
@@ -802,14 +802,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1019,6 +1019,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1143,7 +1199,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -727,14 +727,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -944,6 +944,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1068,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
+59 -3
View File
@@ -846,14 +846,14 @@
<li class="md-nav__item">
<a href="../../implementation/obilayeredmap/" class="md-nav__link">
<a href="../../implementation/layer_tier/" class="md-nav__link">
<span class="md-ellipsis">
obilayeredmap crate
obikindex layer tier
@@ -1063,6 +1063,62 @@
<li class="md-nav__item">
<a href="../../implementation/benchmark_query_testing/" class="md-nav__link">
<span class="md-ellipsis">
Benchmark: query-path testing
</span>
</a>
</li>
<li class="md-nav__item">
<a href="../../implementation/partition_layer_cache/" class="md-nav__link">
<span class="md-ellipsis">
Partition and layer caching (discussion)
</span>
</a>
</li>
</ul>
</nav>
@@ -1187,7 +1243,7 @@
<span class="md-ellipsis">
Sibling annex (discussion)
Sibling annex
@@ -0,0 +1,61 @@
# Hot resume and memoization of long computations (discussion, 2026-10-14)
## Goal (user)
1. **Hot resume**: a run killed midway (crash, `Ctrl-C`, scheduler walltime) restarts from the last finished unit of work, not from zero.
2. **No recomputation**: a long function called again with the same parameters (same command rerun, or another command needing the same intermediate) reuses its stored result.
Not a goal: bit-identical resumed samples. Sampling uses an OS-seeded RNG on purpose, repeated runs must stay independent draws to measure variance; a resumed run being a *different* valid draw is not a defect.
## Why it matters: one real run
`phylo --entropy 1 --pseudo-alignment --n-sites 5000000 --free-loss --no-ambiguity --quartet --pair-balance --family-overlap --sibling-stats` on the 180-genome Primulaceae index, from the stderr of the OAR job (2026-10-13), 256 partitions:
| Stage | Wall |
|---|---|
| `sibling_stats` (full scan, `Selection::All`) | 8 235 s |
| `family_overlap` (sweep 1: overlap annex) | 5 582 s |
| `sampled_scan`: sweep 1 again (entropy + quartet annexes) | ≈ 5 347 s |
| `sampled_scan`: sweep 2 (pair-weight annex) | ≈ 5 296 s |
| `sampled_scan`: the draw itself | ≈ 9 573 s |
| `distance` (Jaccard, not asked for; older binary) | 53 s |
| Total | 34 085 s (9 h 28) |
The three annex sweeps cost about the same although their per-family work differs, so the cost is the layer traversal. Part of it was addressed by restricting the matrix pass to selected families (`family_scan.rs`, same session); the sweeps were not fused. Nothing in this run could be resumed or reused: every stage restarts from its beginning.
## What exists today (verified in the code, 2026-10-14)
**Persisted per-layer annexes.** Entropy (`entropy*.pent`), quartet (`quartet*.pbiv`), pair weight, sibling annex: one file per layer, built by `ensure_layer_*` and skipped when `path.exists()` (`family_annexes.rs`). A rerun with the same conventions skips every sweep. This is already memoization, keyed by *file name only* (convention in the name, no fingerprint of the inputs; a rebuilt sibling annex deletes everything derived from it, see `pair_coverage_sampling.md`).
**Not persisted.** The family-overlap accumulator (`FamilyOverlapAccumulator`) is written once at the end of sweep 1 (`sibling_builder.rs`). The draw (`sample_index`) and the `sibling_stats` scan keep their state in memory only.
**Defect found, then fixed (2026-10-14): a killed annex build left a file that looked finished.** `create_mmap_file` (`obicompactvec/src/mmap_file.rs`) created the file at its *final path* with magic, header and the full length (`set_len`) before any data was written. A kill during a layer left a valid-looking file with unwritten data; the next run saw `path.exists()` and treated the annex as built, silently.
Reproduced on the 1x testbed (20 genomes, 512 layers): derived annexes deleted, `phylo --family-overlap --quartet --pair-balance --entropy 1 …` killed by `timeout 6`, then rerun. Old binary: 141 finals after the kill, 2 differing from a reference build; the rerun exited 0 and kept both. Fixed binary: kill at 6 s left 499 finals, all identical to the reference, plus 2 `.building` files; the rerun completed 1 537 files identical to the reference, no `.building` left. (Kill at 3 s: nothing published, nothing broken.)
**Fix.** `obicompactvec::building_path` / `publish_built`: a file is built under `<name>.building` and moved to its final name (same-directory `rename`, atomic) by the builder's `close()`, after the flush. Applied to the builders that go through `create_mmap_file` or write their own mmap on the annex path: `PersistentBitVecBuilder` (all constructors; quartet annex), `PersistentFixedIntVecBuilder`, `PersistentRankSelectBitVecBuilder`, `FamilyScalarAnnexBuilder` (entropy, pair weight), `SiblingAnnexBuilder` (`siblings.psib`) and `FamilyOverlapAccumulator::write` (overlap matrix). A leftover `.building` is truncated by the next build of that file. A build that is dropped without `close()` no longer produces the final file (no caller did; workspace tests pass). Also reordered in `--sibling-annex`: derived annexes are now removed *before* the new sibling annex is built and published, so a kill between the two leaves the old annex with no derived files, never a new annex next to files computed against the old numbering.
**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**: `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.
## Proposed direction (not implemented; to be validated)
Start from the goal, not from the existing crate.
1. **Unit of work = one `(partition, layer)` step that already produces files.** The annex builds, the draw per layer and the scans all iterate that way (`for part … for layer …`). Resume means "skip the units whose output is complete", exactly what `exists()` approximates today.
2. **Complete-or-absent outputs.** Done for the annex path (see the fix above); the remaining builders are to be covered as their stages become resumable. Prerequisite for everything below. The mechanism lives in `obicompactvec` (shared lower-level API), not in each consumer.
3. **Key = function identity + parameters + fingerprint of the inputs.** A result is reusable iff the function, every parameter that influences it and the identity of its inputs (index content, upstream artifacts) match. Today the key is a file name plus an invalidation convention. The fingerprint requirement is the cost: what identifies an index version cheaply is to be decided (meta file, rebuild counter, hash of annex headers).
4. **The cache holds results of long functions, not domain objects.** The crate must not know `PairwiseTally`. Callers serialize their own values (`rkyv` was already chosen for that). Whether `Memoize`'s API fits is unproven: it has no caller, no documentation and was written against the earlier design.
5. **Granularity matters more than the API.** A cached 9 h result helps only the exact rerun; a per-layer cache also helps a changed parameter that leaves earlier layers untouched. The overlap accumulator (end-of-sweep write) would need a per-layer partial (a sum of per-layer matrices, mergeable) to be resumable.
6. **Fuse before caching.** Three sweeps over the same layers where two suffice (overlap first, then entropy + quartet + pair weight together, since the pair weight needs only the finished overlap matrix) is a cost no cache removes on a first run; to do independently.
## Open questions
- Fingerprint of an index version: which cheap, stable identity?
- Overlap accumulator resume: per-layer partial matrices on disk (size n² × layers) or a checkpoint every N layers?
- `Memoize`/`Session`: keep (adapt to the points above), rewrite, or delete the crate until a caller exists (the "existing code is a hypothesis" rule applies; today it has no user).
- Scope of the next step: atomic writes are done for the annex path; extend to the other builders, or go to the cache.
- Draw resume: a layer's draw is independent of the others except through the quotas, which depend on every layer's mass; quotas can be recomputed from annexes on resume (cheap), so only the per-layer survivors need storing.
@@ -3,10 +3,10 @@
## Code couvert
- `obilayeredmap/src/layer.rs` — Layer<D>, trait LayerData, modes () / PersistentCompactIntMatrix / PersistentBitMatrix
- `obilayeredmap/src/mphf_layer.rs` — MphfLayer, EvidenceKind (Exact / Approx), LayerEvidence enum
- `obilayeredmap/src/map.rs` — LayeredMap<D>
- `obilayeredmap/src/meta.rs` — LayerMeta, PartitionMeta
- `obikindex/src/layer/typed_layer.rs` — Layer<D>, trait LayerData, modes () / PersistentCompactIntMatrix / PersistentBitMatrix
- `obikindex/src/layer/mphf_layer.rs` — MphfLayer, EvidenceKind (Exact / Approx), LayerEvidence enum
- `obikindex/src/layer/map.rs` — LayeredMap<D>
- `obikindex/src/layer/meta.rs` — LayerMeta, PartitionMeta
- `obikindex/src/meta.rs` — IndexConfig (kmer_size, n_bits, with_counts, evidence, block_bits), IndexMeta
- `obikindex/src/index.rs` — KmerIndex, build_layers
- `obicompactvec/src/` — PersistentCompactIntMatrix, PersistentBitMatrix (DataStore implementations)
+20 -1
View File
@@ -304,10 +304,29 @@ step, capped by that node's remaining dormant workers and by the run's total
budget (`n_total`) — balance across nodes is now guaranteed by construction,
not incidental to channel implementation details.
## Panic propagation (fixed, 2026-08-28)
A worker whose `f(i)` panicked used to never send its `WorkerEvent::Completed`
— the controller's `while completed < n_total` loop then waited forever for
an event that partition could no longer produce, since other live
workers/timer threads kept `event_rx` open. Discovered via `obikselect`
panicking on an unimplemented `Sparse` matrix case (see `implementation/select.md`):
the process hung indefinitely instead of erroring out.
Fixed: each worker wraps `f(i)` in `std::panic::catch_unwind` and sends a new
`WorkerEvent::Panicked(i, payload)` instead of silently dropping the
partition. The controller counts it toward `completed` (unblocking the loop)
and keeps the first payload seen; once `run` returns, `panic::resume_unwind`
re-raises it on the caller's thread — the original message/backtrace still
surfaces, from the right place, instead of a silent deadlock. Takes priority
over a plain `Err` (a panic means a bug, not a normal typed failure).
## Open questions
- **Error handling**: `run` currently returns the first error; remaining errors
are dropped. A `Vec<E>` return would give complete diagnostics.
are dropped. A `Vec<E>` return would give complete diagnostics. (Panics are
now caught and re-raised individually — see above — this only concerns
plain `Err` results.)
- **`INITIAL_DIVISOR` / `GROWTH_DIVISOR` tuning**: currently `4` and `8`
(start at 1/4 of a node's cores, grow by 1/8 per step), chosen to fix an
+2 -2
View File
@@ -72,9 +72,9 @@ Each NUMA group runs its own independent adaptive pool. Workers are distributed
|------|--------|
| `obikindex/src/merge.rs` | Detect NUMA topology; build N `ThreadPool`s with pinned threads; assign each pre-spawned worker to a pool; wrap `merge_partition` in `pool.install()` |
| `obikindex/src/merge.rs` | Replace `available_parallelism()` with per-NUMA core count for spawn criterion |
| `obikpartitionner/src/merge_layer.rs` | No change — `merge_partition` already works inside any Rayon context |
| `obikindex/src/partition/merge_layer.rs` | No change — `merge_partition` already works inside any Rayon context |
| `obidebruinj/src/debruijn.rs` | No change — `par_iter` and `current_num_threads` are pool-context-aware |
| `obikpartitionner/src/partition.rs` | No change — same reason |
| `obikindex/src/partition/partition.rs` | No change — same reason |
## Platform guard
+64 -22
View File
@@ -16,7 +16,7 @@ Given a set of query sequences, determine for each sequence how many of its k-me
## Algorithm
The query follows the same superkmer-based partitioning strategy used at indexing time. Everything below happens inside `process_chunk` (`query.rs`); there is no separate per-stage function, but the internal data flow is staged: k-mer-level dereplication, a two-part MPHF/column-major matrix lookup (`obikpartitionner::query_partition_with`), and a sparse Findere pass, each producing sparse intermediate structures rather than one dense allocation for the whole chunk.
The query follows the same superkmer-based partitioning strategy used at indexing time. Everything below happens inside `process_chunk` (`query.rs`); there is no separate per-stage function, but the internal data flow is staged: k-mer-level dereplication, a two-part MPHF/column-major matrix lookup (`obikindex::partition::query_partition_with`), and a sparse Findere pass, each producing sparse intermediate structures rather than one dense allocation for the whole chunk.
```
for each chunk of sequences (parallel workers via obipipeline, one call to process_chunk):
@@ -24,7 +24,7 @@ for each chunk of sequences (parallel workers via obipipeline, one call to proce
decompose all sequences into superkmers (SuperKmerIter) — construction only,
not the dedup key
deduplicate at k-mer granularity, split by partition in the same pass:
by_partition: Vec<HashMap<CanonicalKmer, Vec<KmerDesc>>> ← KmerDesc = (seq_idx, pos)
by_partition: Vec<PartitionKmers> ← sorted unique k-mers + flat KmerDesc = (seq_idx, pos) slices (2026-10-15, was a HashMap — see "Query memory" below)
allocate SmerIndex (SmerIndex::new): in_index: Vec<bool>, sized total_smers —
NOT multiplied by n_genomes
allocate by_genome: Vec<Vec<(seq_idx, pos, value)>>, one empty Vec per genome —
@@ -118,11 +118,11 @@ The `-z` CLI option overrides the index metadata value. A higher z increases str
## Layer lookup: `MphfLayer::find`
`MphfLayer::open(dir, mode: &IndexMode)` receives the mode from `PartitionMeta` — no per-layer file is read. The caller (`QueryLayer`) never chooses the dispatch path: it is fixed at open time by `LayerEvidence`. See [obilayeredmap](../implementation/obilayeredmap.md) for the full `find` / `find_strict` API.
`MphfLayer::open(dir, mode: &IndexMode)` receives the mode from `PartitionMeta` — no per-layer file is read. The caller (`QueryLayer`) never chooses the dispatch path: it is fixed at open time by `LayerEvidence`. See [obikindex::layer](../implementation/layer_tier.md) for the full `find` / `find_strict` API.
### `QueryLayer` variant selection
`QueryLayer::open` (`obikpartitionner/src/query_layer.rs:28-45`) only ever returns two variants — `Presence` or `Count`, checked in this order:
`QueryLayer::open` (`obikindex/src/partition/query_layer.rs:28-45`) only ever returns two variants — `Presence` or `Count`, checked in this order:
| Order | Condition | Variant | Data returned per k-mer |
|---|---|---|---|
@@ -203,7 +203,7 @@ Genome keys follow the iteration order of `meta.genomes`.
## CLI
```
obikmer query <index> [--detail] [--mismatch] [--count-missing]
obiskim query <index> [--detail] [--mismatch] [--count-missing]
[--force-presence] [--presence-threshold <n>]
[-z <z>] [-T <threads>] [--chunk-size <MiB>]
<query.fa> [<query2.fa> ...]
@@ -244,7 +244,7 @@ Fix direction: restructure `query`'s pipe with an initial `Flat` stage analogous
`chunk_bytes = available_memory_bytes() / (n_workers * 16)` (`query.rs:407-414`) assumes a fixed ~8–16× overhead per raw input byte. But `KmerResults::new` (`query.rs:165-179`) allocates `data: Vec<u32>` sized `total_kmers_in_chunk × n_genomes` — dense, **for every k-mer position in the chunk, hit or not** — plus `win_min` and (with `--detail`) `cov`, same scaling. Real per-chunk memory is `O(n_genomes)`, not constant; the formula doesn't know `n_genomes` at all. This is the direct cause of the OOM kill on indexes with many reference genomes.
**4. MPHF lookup and matrix-row fetch are fused, not staged.**
`QueryLayer::find_into` (`obikpartitionner/src/query_layer.rs:48-67`) does the MPHF `find` *and* the `fill_row` matrix read in one call per k-mer, inside a single-threaded loop (`query_partition_with`). There is no separation between "is this k-mer indexed" (cheap, `O(1)`, independent of `n_genomes`) and "what are its per-genome values" (the expensive, `n_genomes`-scaling part).
`QueryLayer::find_into` (`obikindex/src/partition/query_layer.rs:48-67`) does the MPHF `find` *and* the `fill_row` matrix read in one call per k-mer, inside a single-threaded loop (`query_partition_with`). There is no separation between "is this k-mer indexed" (cheap, `O(1)`, independent of `n_genomes`) and "what are its per-genome values" (the expensive, `n_genomes`-scaling part).
**5. Dereplication should happen at k-mer granularity, directly — not via an intermediate superkmer-level dedup.**
`QueryBatch::from_records` currently dereplicates at the *superkmer* level (`HashMap<RoutableSuperKmer, Vec<SKDesc>>`, `query.rs:112`). This misses redundancy between k-mers shared by *different* superkmers (read overlaps, repeats, a SNP splitting an otherwise-identical run). Superkmer *construction* (`SuperKmerIter`) stays mandatory — it is the mechanism that computes minimizers/partition routing, not an optional dedup layer — but the dedup structure built on top of it should key directly on `CanonicalKmer`, in the same pass: `HashMap<CanonicalKmer, Vec<(seq_idx, pos)>>`. This also means the MPHF `find` itself runs once per **distinct** k-mer instead of once per occurrence — a win independent of the matrix-fetch cost below.
@@ -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`, `obikpartitionner`, 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`, `obilayeredmap`, `obiskio`, `obifastwrite`) is `#[cfg(test)] #[path = "tests/<name>.rs"] mod tests;` at the bottom of the source file, with the actual test code in a sibling `src/tests/<name>.rs`. Neither `obikmer` nor `obikpartitionner` (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/<name>.rs"] mod tests;` at the bottom of the source file, with the actual test code in a sibling `src/tests/<name>.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<usize>` 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<usize>` 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<PathBuf>`, 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,16 +342,16 @@ 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<RoutableSuperKmer, Vec<SKDesc>>`, current `query.rs:112`) with a per-partition `HashMap<CanonicalKmer, Vec<(seq_idx: u32, pos: u32)>>`, 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<KLen>`) — the underlying `CanonicalKmerOf<L>` derives `Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash` (`kmer.rs:269`). Usable as a `HashMap`/`HashSet` key as-is, no change needed.
- `obikpartitionner/src/query_layer.rs`:
- `obikindex/src/partition/query_layer.rs`:
- Split `QueryLayer::find_into` (`query_layer.rs:48-67`) into two methods: `find_slot(&self, kmer: CanonicalKmer) -> Option<usize>` (MPHF only, no matrix touch) and keep `fill_row` as-is for phase 4 to call later.
- Replace `query_partition_with`'s inner loop (`query_layer.rs:103-113`) with a version that, for each unique `CanonicalKmer`, calls `find_slot` across the partition's layers (stopping at first hit, same as today), and instead of immediately filling a row, records `(layer_idx, slot)`.
- New return shape for the partition-level query, replacing today's `on_hit(sk_idx, kmer_idx, row)` callback: `HashMap<layer_idx, HashMap<slot, Vec<(seq_idx, pos)>>>` (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 `obikpartitionner/src/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
@@ -359,15 +359,15 @@ 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.
- `obikpartitionner/src/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.
- `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.
- `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:**
Reading `obikindex/src/numa.rs`'s actual `run()` body (not just its doc comments) shows every call spawns a timer thread **plus one OS thread per worker slot on every NUMA node** (`std::thread::scope` + one `s.spawn()` per node per `max_workers`) — on the 192-core/8-NUMA reference machine, that's on the order of 190+ fresh OS threads spawned **per call**. This is fine for its actual, established usage in this codebase (`merge.rs`, `index.rs`'s `build_layers`): one `PartitionRunner::new()` + one `run()` call per command invocation, amortised over a batch of ~256 long-running partitions. It is not fine for `query`'s call pattern: `query_partition_with` runs once per `(chunk, partition)`, potentially thousands of times per second — spawning ~190 OS threads that often to scan a handful of genome columns would very likely cost far more than the row-major approach it's meant to replace. This is exactly the "resolve empirically, don't assume" composition risk the roadmap flagged, just resolved by reading the mechanism's actual cost before wiring it in, rather than by measuring a regression on the cluster after the fact.
The column-major loop in stage 2 is therefore a **plain sequential loop** for now — it captures the whole, provable locality win (roadmap point 8's actual claim) without adding any parallelism mechanism. Genome-column-level parallelism (point 8's "bonus" axis) and partition-level parallelism (point 7) are both deferred — not abandoned. Candidates for a follow-up, once there's a concrete profiling need: (a) `rayon`'s already-warm global pool (`into_par_iter()`) for the column axis specifically — cheap to invoke repeatedly since it doesn't spawn threads per call, though it's the same "naive rayon" pattern `numa_worker_pools.md` warns about for a *different* workload (random pointer-chasing over large hash maps); a column scan's access pattern (sequential reads within one `mmap`'d region) has a different contention profile and hasn't been shown to have the same problem — needs its own measurement, not an assumption either way; (b) restructuring so `PartitionRunner` is invoked once per whole `query` run (or per large batch of chunks) rather than per `(chunk, partition)`, amortising its spawn cost the way `merge`/`build_layers` do — a bigger structural change than this phase's scope.
- Log (implemented): `QueryStats::n_columns_scanned`/`n_col_get_calls`, folded into the existing per-chunk `debug!("k-mer dedup + column-major fetch", ...)` line (`query.rs`) alongside phase 3's dedup counters.
- **Unit tests**: extended `obikpartitionner/src/tests/query_layer.rs` (phase 3's file) — `query_partition_with`'s empty/missing-index paths updated for the new `QueryStats` fields and single-callback signature.
- **Unit tests**: extended `obikindex/src/partition/tests/query_layer.rs` (phase 3's file) — `query_partition_with`'s empty/missing-index paths updated for the new `QueryStats` fields and single-callback signature.
- **Validation performed**: full workspace build + `cargo test --workspace`, zero failures. Functional validation against real indexes: (1) a single-genome index — output byte-identical to pre-phase-4 (same `kmer_count`/`kmer_strict_matches` on every record); (2) the existing 20-genome `benchmark/global_index_presence` index — runs correctly, `n_hits=0` for an unrelated query (expected: no shared k-mers between a plant read and a bacterial reference set), no panics, confirming the `Implicit`/multi-column bounds logic doesn't crash on a real multi-genome, mixed-format index; (3) **the critical correctness case**: built two single-sequence-pair test genomes, merged into one 2-genome index, queried with reads from both — reads from `genomeA` matched **only** `genomeA` (`kmer_count` identical to the pre-dedup occurrence count, zero leakage into `genomeB`'s column) and vice versa. This is the test that would have caught a column-index mixup, an off-by-one in `n_cols`, or cross-genome bleed from the stage-1/stage-2 split — it passed cleanly.
- **Not yet done**: the microbenchmark comparing column-major vs. the old row-major access pattern's wall time / page-fault counters on a large-`n_genomes` layer — needs a realistically large multi-genome index and, for the page-fault counters specifically, Linux (not available from this development environment). Left for cluster validation alongside phases 1–3's own pending measurements.
@@ -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<bool>` 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<ConfirmedHit>, 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<bool>` (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.
@@ -404,3 +404,45 @@ Tracked separately in [chunkreader.md](../implementation/chunkreader.md#future-w
- **Thread-budget oversubscription** (phase 4): the single biggest unresolved design question in this whole plan — see phase 4's composition note. Should be settled with real measurements early in phase 4, not assumed from the design alone.
- **`obicompactvec` API surface growth** (phase 4): new public per-column accessors are additive (existing `fill_row`/`row` stay for other callers — `dump`, `select`, distance computations) — no breaking change expected, but worth checking `obicompactvec`'s other callers aren't already relying on `fill_row` being the only/cheapest access path in a way that would make maintaining two access patterns (row-major and column-major) a real maintenance cost rather than a one-off addition.
- **`PersistentBitMatrix::Implicit`'s hardcoded `n_cols: 1` — resolved, not a bug.** `LayerMeta`'s own doc comment (`obicompactvec/src/layer_meta.rs:1-9`) states it is written "alongside `mphf.bin`" and read by `PersistentBitMatrix::open` "to determine `n_rows` for **the implicit (mono-genome presence/absence) case**" — i.e. `Implicit` is a documented single-genome fast path (no presence matrix needed when there is trivially one genome), not a generic "no matrix built yet" fallback. `n_cols: 1` is correct by design for the case it's meant to handle. Phase 4's column loop is safe as planned — this was worth checking once, doesn't need further action.
## Query memory: `PartitionKmers` replaces the per-partition `HashMap` (2026-10-15)
**Problem.** A full-size query (two ~450 MB fastq.gz of a skim against a 354 M-kmer index) reached **74–81 GB RSS** with the default 256 MiB chunk. Cause, read in `batch.rs`/`chunk.rs` and measured with the `by_partition memory retained` debug log: `QueryBatch::by_partition` was a `HashMap<CanonicalKmer, Vec<KmerDesc>>` per partition. On genomic reads almost every k-mer is unique (12.5 M unique for 13.5 M occurrences in a 48 MB chunk, a dedup of 8 %), so each k-mer paid a table slot, growth slack and its own heap `Vec`: **889 MB per 48 MB chunk, ~71 bytes per unique k-mer, 18× the chunk size** — the dominant term of the per-chunk memory, several chunks being in flight at once.
**Change.** `obikquery::PartitionKmers`: occurrences collected as `(kmer, KmerDesc)` per partition, sorted by `(kmer, seq_idx, pos)` and stored as three flat arrays (unique k-mers, u32 offsets, descs). `query_partition_with` takes `&PartitionKmers`; `QueryHit` already carried slices. Occurrence order per k-mer is unchanged (query order); no per-k-mer allocation.
**Measured** (same inputs, release build, identical sorted output digests before and after):
| | `by_partition` (48 MB chunk) | RSS, 2×48 MB chunks | RSS, full run (≈ 1 GB reads) | wall, full run |
|---|---|---|---|---|
| before | 889 MB | 5.6 GB | 73.7–80.7 GB | 135–172 s (one 312 s outlier) |
| after | 259 MB | 4.1 GB | **28.2 GB** | **103 s** |
With `--chunk-size 4` the same small query peaks at 3.6 GB: that floor is the touched pages of the index itself, so after the change the remaining per-chunk anonymous memory is ≈ 6× the chunk size, below the formula's factor 12 (`BASE_OVERHEAD + 8·n_genomes`, still a conservative bound — left unchanged). The sort replaces hashing in `from_records` and was not slower (17.3 s vs 21.2 s on the small test).
**Side finding.** The 256 MiB cap makes small inputs poorly parallel: the two 48 MB files above are two chunks, so two workers; with `--chunk-size 4` the same query takes 3.7 s instead of 17 s. Not changed here.
**Not verified.** Prod-scale (192 workers × 256 MiB chunks in flight): the factor is now ≈ 6 instead of ≈ 21, but how many chunks are in flight at once on that machine was not observed.
### Chunk size sweep on a small input (2026-10-15)
Input: 2 × 48 MB decompressed fastq (200 000 reads each) against a 354 M-kmer single-genome index (4 partitions), 16 cores on AC power, 3 runs per size, sorted outputs identical (same md5) for every size:
| `--chunk-size` (MiB) | chunks | wall (s) | user CPU (s) | RSS (GB) |
|---|---|---|---|---|
| 2 | ~50 | 2.5–2.6 | 25.0–25.3 | 3.2 |
| 4 | ~25 | 2.5–2.7 | 24.3–25.5 | 3.5 |
| 8 | ~12 | 2.5–2.7 | 23.6–26.1 | 4.1 |
| 16 | ~6 | 4.4 | 23.1–23.7 | 4.1 |
| 32 | 4 | 8.3 | 22.9–23.0 | 4.0 |
| 64 and 256 (default) | 2 | 11.6–11.8 | 22.4–22.9 | 4.1 |
Wall time follows the number of chunks (one worker per chunk) until it reaches the core count, then plateaus at ≈ total CPU / cores; total CPU is almost constant (≈ +10 % at 2 MiB, per-chunk fixed cost, here with 1 genome and 4 partitions). With the 256 MiB cap, **any input below ≈ 16 × 256 MiB = 4 GiB decompressed leaves cores idle**. A rule such as `chunk ≈ input_bytes / (workers × 2)` with a floor of 4–8 MiB would use all cores on small inputs — **implemented, see below**. Unmeasured: the per-chunk cost on an index with many genomes and 256 partitions, which could move the floor up.
### Automatic chunk size now follows the input size (2026-10-15)
`cmd/query/mod.rs`: when `--chunk-size` is not given, the memory-derived size (unchanged: `available RAM / (workers × overhead × 2)`, clamped to 4–256 MiB) is further capped by `estimated input bytes / (workers × 2)`, never below 4 MiB. The estimate is `obiread::estimated_decompressed_len`: the file length, ×3 when the magic bytes say gzip (≈ 2.8 measured on FASTQ), ×4 for bzip2/xz/zstd — a deliberately rough figure, detected from the magic bytes, not the extension. For stdin, URLs or unreadable files the size is unknown and the memory-derived size stands. An explicit `--chunk-size` still wins.
Measured (2 × 48 MB reads, 16 cores, AC power, outputs identical): single-genome index, 354 M kmers — default chunk 256 MiB → 4 MiB: **11.4 s → 2.4 s** (−79 %), CPU 22.3 → 26 s (+17 %), peak footprint 1.44 → 0.75 GB. On the 91-genome index the memory-derived size was already 4 MiB (overhead factor 4 + 8 × 91), so nothing changes there (5.1–5.7 s either way). Not measured: a large input (≈ 1 GB gz, whose estimate gives ≈ 95 MiB chunks instead of 256 MiB: more, smaller chunks, expected lower memory).
+2 -2
View File
@@ -3,8 +3,8 @@
## Code couvert
- `obikmer/src/cmd/query.rs` — commande query, format de sortie
- `obikpartitionner/src/query_layer.rs` — routage de la requête à travers les partitions
- `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
## Notes
Loaded 100 of 672 files, more files were not shown because too many files have changed in this diff. Show more