Compare commits

..
1 Commits
Author SHA1 Message Date
Eric Coissac 26026288de refactor(benchmark): consolidate generated artifacts under run/ directory
Release / create-release (push) Successful in 2m34s
Release / build-linux-x86_64 (push) Successful in 8m10s
Release / build-macos-arm64 (push) Failing after 1m19s
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:20:31 +02:00
557 changed files with 15802 additions and 52920 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
0.3.4+0.1.1
-240
View File
@@ -1,240 +0,0 @@
# 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
@@ -1,42 +0,0 @@
# 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
@@ -1,22 +0,0 @@
# 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
@@ -1,3 +0,0 @@
# "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
@@ -1,9 +0,0 @@
# 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
@@ -1,96 +0,0 @@
#!/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
@@ -1,20 +0,0 @@
#!/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
@@ -1,14 +0,0 @@
#!/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
@@ -1,67 +0,0 @@
#!/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
@@ -1,266 +0,0 @@
#!/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
@@ -1,193 +0,0 @@
#!/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
@@ -1,166 +0,0 @@
#!/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
@@ -1,75 +0,0 @@
#!/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
@@ -1,70 +0,0 @@
#!/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
@@ -1,56 +0,0 @@
#!/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
@@ -1,74 +0,0 @@
#!/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
@@ -1,68 +0,0 @@
#!/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
@@ -1,77 +0,0 @@
#!/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
@@ -1,14 +0,0 @@
#!/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
@@ -1,12 +0,0 @@
#!/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
@@ -1,38 +0,0 @@
#!/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
@@ -1,16 +0,0 @@
#!/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
@@ -1,24 +0,0 @@
#!/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
@@ -1,17 +0,0 @@
#!/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
@@ -1,20 +0,0 @@
#!/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
@@ -1,141 +0,0 @@
#!/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/obiskim /tmp/dist/obiskim-linux-x86_64
strip /tmp/dist/obiskim-linux-x86_64
cp target/x86_64-unknown-linux-musl/release/obikmer /tmp/dist/obikmer-linux-x86_64
strip /tmp/dist/obikmer-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/obiskim-linux-x86_64"
-F "attachment=@/tmp/dist/obikmer-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/obiskim" /tmp/dist/obiskim-macos-arm64
docker cp "$CID:/src/src/target/aarch64-apple-darwin/release/obikmer" /tmp/dist/obikmer-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/obiskim-macos-arm64"
-F "attachment=@/tmp/dist/obikmer-macos-arm64"
-4
View File
@@ -44,7 +44,3 @@ 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
@@ -0,0 +1,87 @@
# 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
@@ -0,0 +1,2 @@
/cache
/project.local.yml
+169
View File
@@ -0,0 +1,169 @@
# the name by which the project can be referenced within Serena/when chatting with the LLM.
project_name: "obikmer"
# 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.
# The settings are considered only if the project is trusted (see global configuration to define trusted projects).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#language-server-specific-settings
ls_specific_settings: {}
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Important: quote patterns that start with `*`, otherwise YAML treats them as aliases.
# Example:
# ignored_paths:
# - "examples/**"
# - ".worktrees/**"
# - "**/bin/**"
# - "**/obj/**"
# 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: []
# list of additional workspace folder paths for cross-package reference support.
# 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, but these folders are not indexed by Serena,
# i.e. the respective symbols will not be found using Serena's symbol search tools.
# Example:
# additional_workspace_folders:
# - ../sibling-package
# - ../shared-lib
ls_additional_workspace_folders: []
# list of language servers to start when using the LSP backend; choose from:
# ada al angular ansible bash
# bsl clojure cpp cpp_ccls crystal
# csharp csharp_omnisharp cue dart deno
# elixir elm erlang fortran fsharp
# gdscript gleam go groovy haskell
# haxe hlsl html java json
# julia kotlin latex lean4 lua
# luau markdown matlab msl nextflow
# nix ocaml pascal perl php
# php_phpactor php_phpantom powershell python python_basedpyright
# python_jedi python_pyrefly python_ty qml r
# rego ruby ruby_solargraph rust scala
# scss solidity svelte swift systemverilog
# terraform toml typescript typescript_vts vue
# wolfram yaml zig
# (This list may be outdated; generated with scripts/print_language_list.py;
# For the current list, see values of the LanguageServerId enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py)
# For some languages, there are several 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 Deno projects, use deno (serves the same .ts/.js files as typescript; requires the deno CLI on PATH)
# - For SCSS / Sass / plain CSS, use scss (some-sass-language-server handles all three)
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# Some language servers require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple language servers, the first language server that supports a given file will be used for that file.
# The first language server 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.
language_servers:
- rust
# list of workspace folder paths (LSP backend only).
# These folders will be used to build up Serena's symbol index.
# Paths must be within the project root and should thus be relative to the project root.
# Furthermore, the paths should not be filtered by ignore settings.
# Default setting: The entire project root folder (".") is considered.
# In (large) monorepos, this can be used to index only subfolders of the project root, e.g.
# ls_workspace_folders:
# - "./subproject1"
# - "./subproject2"
ls_workspace_folders:
- .
# optional shell command to run before the language backend (LSP or JetBrains) is initialised.
# the command runs in the project root directory and is only executed if the project is trusted
# (see trusted_project_path_patterns in the global configuration).
# serena waits for the command to exit: a non-zero exit code is logged as an error but does not
# abort activation. a per-project timeout (activation_command_timeout, default 180s) is the safety
# backstop for non-terminating commands; on expiry the process is killed and activation continues.
# example: activation_command: "npx nx run-many -t build"
activation_command:
# maximum time in seconds to wait for activation_command to complete before killing it (default 180s).
# must be a positive number.
activation_command_timeout: 180.0
+59
View File
@@ -0,0 +1,59 @@
// 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": []
},
]
+1 -1
View File
@@ -1119,7 +1119,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1370,7 +1370,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1128,7 +1128,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1130,7 +1130,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1140,7 +1140,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
File diff suppressed because it is too large. Load diff
@@ -1265,7 +1265,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1485,9 +1485,8 @@ this pipeline.</p>
by <code>verify_presence</code>/<code>verify_merge_presence</code>, which only check index
<em>content</em> against the <code>.npz</code> truth, never the query API.</li>
<li><code>pack --sparse</code> produces a presence-matrix format documented (see
<a href="../obicompactvec/">obicompactvec.md</a>, "Sparse matrix formats") as faster
for single-row access (query) and slower for column-oriented access
(phylo <code>--metric</code>).
<a href="../../architecture/siblings/">siblings.md</a>) as faster for single-row
access (query) and slower for column-oriented access (phylo <code>--metric</code>).
<code>global_index_presence/</code> built by <code>merge_presence.sh</code> is always packed
dense (packing is a stage inside <code>merge</code>, not a separate <code>pack</code>
invocation) — there was no dense/sparse regression check.</li>
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -579,7 +579,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1265,7 +1265,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1388,7 +1388,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1265,7 +1265,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+2 -2
View File
@@ -1504,7 +1504,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -2208,7 +2208,7 @@
<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>
<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 degrades to a row-by-row decode; see <a href="../../architecture/siblings/">siblings.md</a>.</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>
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1348,7 +1348,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1332,7 +1332,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1343,7 +1343,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+3 -219
View File
@@ -494,7 +494,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -632,46 +632,6 @@
</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">
@@ -1231,7 +1191,7 @@ Pass 1 — byte max, SIMD-vectorizable, O(n)
<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>
<td><code>pack --sparse</code>; see <a href="../../architecture/siblings/">siblings.md</a> for the sparse-vs-dense access-pattern trade-off</td>
</tr>
<tr>
<td><code>Implicit</code> (bit only)</td>
@@ -1241,6 +1201,7 @@ Pass 1 — byte max, SIMD-vectorizable, O(n)
</tbody>
</table>
<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>Unlike the bit side, <code>PersistentSparseCompactIntMatrix</code>'s values are <em>not</em> deduplicated across rows — two rows can share the same non-zero column set (same <code>dict_id</code> in the shared support) while carrying different counts — so its <code>CountPartials</code> impl can't reuse the support's dict-multiplicity shortcut the way <code>BitPartials for PersistentSparseBitMatrix</code> does. It still avoids the naive <code>O(n_cols² × n)</code> column-pair scan via a single row-major pass (<code>row_major_pairwise</code> in <code>sparse_intmatrix.rs</code>), reconstructing the squared-difference formulas (<code>euclidean</code>/<code>relfreq_euclidean</code>/<code>hellinger</code>) from per-column marginals via <code>Σ(a-b)² = Σa²+Σb²-2Σab</code> — see <a href="../../architecture/siblings/">siblings.md</a>'s "<code>PersistentCompactIntMatrix::Sparse</code> — implemented" entry for the full derivation.</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>
@@ -1251,183 +1212,6 @@ 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>
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1293,7 +1293,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1305,7 +1305,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1563,7 +1563,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1405,7 +1405,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1388,7 +1388,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1254,7 +1254,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1382,7 +1382,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1326,7 +1326,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1232,7 +1232,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1354,7 +1354,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1228,7 +1228,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1314,7 +1314,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1227,7 +1227,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
Binary file not shown.
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1199,7 +1199,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1265,7 +1265,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+4 -594
View File
@@ -932,17 +932,6 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#automatic-estimation-gamma-shape-auto" class="md-nav__link">
<span class="md-ellipsis">
Automatic α estimation (--gamma-shape auto)
</span>
</a>
</li>
<li class="md-nav__item">
@@ -954,45 +943,6 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#-estimation-literature-survey-and-design-discussion-2026-09-11" class="md-nav__link">
<span class="md-ellipsis">
α-estimation literature survey and design discussion (2026-09-11)
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#sharing-one-sample-across-algorithms-sankoff-tnt-phyg-iqtree-snp-distance-implemented-2026-09-11" class="md-nav__link">
<span class="md-ellipsis">
Sharing one sample across algorithms (--sankoff/--tnt/--phyg/--iqtree + snp-* --distance) — implemented 2026-09-11
</span>
</a>
<nav class="md-nav" aria-label="Sharing one sample across algorithms (--sankoff/--tnt/--phyg/--iqtree + snp-* --distance) — implemented 2026-09-11">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#explicit-session-implemented-2026-09-12" class="md-nav__link">
<span class="md-ellipsis">
Explicit --session (implemented 2026-09-12)
</span>
</a>
</li>
</ul>
</nav>
</li>
<li class="md-nav__item">
@@ -1741,7 +1691,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -2318,17 +2268,6 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#automatic-estimation-gamma-shape-auto" class="md-nav__link">
<span class="md-ellipsis">
Automatic α estimation (--gamma-shape auto)
</span>
</a>
</li>
<li class="md-nav__item">
@@ -2340,45 +2279,6 @@
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#-estimation-literature-survey-and-design-discussion-2026-09-11" class="md-nav__link">
<span class="md-ellipsis">
α-estimation literature survey and design discussion (2026-09-11)
</span>
</a>
</li>
<li class="md-nav__item">
<a href="#sharing-one-sample-across-algorithms-sankoff-tnt-phyg-iqtree-snp-distance-implemented-2026-09-11" class="md-nav__link">
<span class="md-ellipsis">
Sharing one sample across algorithms (--sankoff/--tnt/--phyg/--iqtree + snp-* --distance) — implemented 2026-09-11
</span>
</a>
<nav class="md-nav" aria-label="Sharing one sample across algorithms (--sankoff/--tnt/--phyg/--iqtree + snp-* --distance) — implemented 2026-09-11">
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="#explicit-session-implemented-2026-09-12" class="md-nav__link">
<span class="md-ellipsis">
Explicit --session (implemented 2026-09-12)
</span>
</a>
</li>
</ul>
</nav>
</li>
<li class="md-nav__item">
@@ -4576,75 +4476,9 @@ F84/TN93 and is included below. <code>snp-</code> prefix on every CLI value.</p>
<p><strong><code>+Γ</code> rate-heterogeneity modifier, applicable to <code>snp-jc</code>, <code>snp-k2p</code>,
<code>snp-k81</code>, <code>snp-t92</code>, <code>snp-f84</code>, <code>snp-hky85</code>, <code>snp-tn93</code></strong> (not <code>snp-raw</code>,
nothing to correct; not <code>snp-logdet</code>, no standard gamma formulation) — same
formula as the base correction, weighted by a shape parameter <code>α</code> either
supplied by the user (<code>--gamma-shape &lt;alpha&gt;</code>) or estimated from the data
(<code>--gamma-shape auto</code>/<code>estimate</code>, method-of-moments — not ML; see
"Automatic α estimation" below). A modifier on existing values, not a
separate enum arm per distance.</p>
<h3 id="automatic-estimation-gamma-shape-auto">Automatic α estimation (<code>--gamma-shape auto</code>)</h3>
<p><strong>Correction (verified against the primary source, 2026-09-11):</strong> Jin &amp;
Nei (1990) itself (<em>"Limitations of the Evolutionary Parsimony Method of
Phylogenetic Analysis"</em>, Mol. Biol. Evol. 7(2):82–102 — the paper this
whole <code>+Γ</code> correction is cited from, confirmed algebraically to match this
codebase's <code>corrected_log</code>/<code>k2p</code> exactly against their eq. A4, general, and
A8, the <code>a = 1</code> case) contains <strong>no</strong> data-driven α-estimation procedure.
Their own recommendation (p. 98) is a fixed default: <em>"we suggest that the
gamma distance with a = 1 [eq. A8] be used. However, one may choose a
different gamma distance, estimating a from data. Wilson et al. (1989)
recently used a distance with a = 1/2 for restriction-site data of
mitochondrial DNA in hominoids."</em> — i.e. Jin &amp; Nei explicitly punt
data-driven estimation to a <em>different</em> paper (Wilson et al. 1989), not
read/verified here. The estimator below is therefore <strong>not</strong> "Jin &amp; Nei's
method" under any framing — that attribution (present in an earlier
revision of this section) was wrong, not just under-cited.</p>
<p><strong>Implemented</strong> (<code>PartitionDispersion</code>, <code>obikphylo/src/siblings/algorithms/pairwise.rs</code>)
as an independent method-of-moments estimator, unrelated to any specific
published procedure: pools substitution counts by <strong>partition</strong> rather
than by genome pair, during the same <code>reduce_pairwise</code> pass that builds
<code>PairwiseTally</code> (no second scan).</p>
<p>For partition <code>i</code>: <code>n_i</code> = substitutions pooled over every genome pair,
<code>L_i</code> = eligible loci pooled over every genome pair, <code>R_i = n_i / L_i</code>.
Modeling among-site rate heterogeneity the same way as the <code>+Γ</code> correction
itself (a <code>Gamma(α, α)</code>-distributed, mean-1, multiplicative rate shared by
every locus in a partition — the classical Poisson-Gamma/negative-binomial
mixture, the general identity behind gamma-rate-heterogeneity corrections,
also behind Uzzell &amp; Corbin's (1971) original observation that substitution
counts across sites/regions are over-dispersed relative to Poisson):</p>
<div class="arithmatex">\[
\mathbb{E}[R_i] = \mu \qquad \mathrm{Var}[R_i] = \frac{\mu}{L_i} + \frac{\mu^2}{\alpha}
\]</div>
<p>Weighting each partition's squared deviation by its own <code>L_i</code> cancels the
Poisson term before attributing what's left to <code>α</code>:</p>
<div class="arithmatex">\[
\hat\mu = \frac{\sum_i n_i}{\sum_i L_i} \qquad
V = \frac{\sum_i L_i (R_i-\hat\mu)^2}{\sum_i L_i} \qquad
\hat\alpha = \frac{\hat\mu^2}{V - \hat\mu/\bar L}
\]</div>
<p>where <code>\bar L</code> is the mean partition size. Returns "no estimate" (falls
back to the uncorrected formula, warns) when fewer than 2 partitions have
data, <code>\hat\mu \le 0</code>, or <code>V</code> doesn't exceed the Poisson floor
<code>\hat\mu/\bar L</code> — no detectable over-dispersion, <code>α</code> would be unbounded.</p>
<p><strong>Caveat, stated explicitly rather than left implicit</strong>: unlike every
closed-form correction in <code>snp_distance.rs</code> (each verified line-by-line
against <code>ape</code>'s <code>dist_dna.c</code>, and now also against Jin &amp; Nei 1990 directly
for the base <code>+Γ</code> formula), this estimator is derived from first
principles (the general Poisson-Gamma/negative-binomial identity) with no
primary-source procedure behind it at all — not Jin &amp; Nei's (confirmed
above), and Wilson et al. (1989), the paper they point to instead, hasn't
been read/verified either. Mathematically self-consistent (re-derived and
checked, not guessed), but a from-scratch method, not a literature
implementation. If <code>--gamma-shape</code> needs a value with a literature
pedigree rather than an estimated one, Jin &amp; Nei's own stated default,
<code>α = 1</code> (<code>--gamma-shape 1</code>), is the better-supported choice today.</p>
<p>Deliberately <strong>not</strong> gated by <code>--sankoff-ratio-ceiling</code> the way
<code>base_pair_tally</code> is (same precedent as <code>cardinality_tally</code> — see its own
doc comment): that filter excludes individual saturated <em>pairs</em> from a
composition estimate computed once at the very end, from the complete
<code>PairwiseTally</code>; the partition axis needed here only exists transiently,
one partition at a time, while <code>PairwiseTally</code> is still being built — long
before any pair's final SNP ratio (and thus its ratio_ceiling eligibility)
is known. <code>--exclude-genome</code> isn't applied either, matching
<code>reduce_pairwise</code>'s own raw per-pair fold.</p>
formula as the base correction, weighted by a shape parameter <code>α</code> supplied
by the user (<code>--gamma-shape &lt;alpha&gt;</code>), not estimated by ML. A modifier on
existing values, not a separate enum arm per distance.</p>
<p><strong>Implemented now: <code>snp-raw</code>, <code>snp-jc</code>, <code>snp-k2p</code>, <code>snp-k81</code>, <code>snp-f81</code>,
<code>snp-t92</code>, <code>snp-tn93</code>, <code>snp-tv</code>, all with <code>+Γ</code> except <code>raw</code>/<code>tv</code></strong> — see
"Exact formulas" below. <code>snp-tajima-nei</code>, <code>snp-f84</code>, <code>snp-hky85</code>,
@@ -4757,430 +4591,6 @@ special-casing K80). K81/T92/TN93's gamma branches follow the same
mechanical substitution but weren't independently checked against an
<code>ape</code>-equivalent reference for those three specifically — flagged here, not
silently assumed correct.</p>
<h3 id="-estimation-literature-survey-and-design-discussion-2026-09-11">α-estimation literature survey and design discussion (2026-09-11)</h3>
<p>Follow-up discussion after implementing <code>PartitionDispersion::estimate_alpha</code>
(previous section), triggered by the user pointing out that the literature
conflates two distinct problems: <em>estimating α from an alignment</em> versus
<em>using a given α in a Jin-Nei-style corrected distance</em>. Jin &amp; Nei (1990)
itself is squarely in the second camp — α is a user-supplied parameter
there, not something their paper estimates (confirmed by reading the paper
directly, see previous section). This section catalogs the actual
α-estimation literature and records which approaches were considered and
why each was or wasn't adopted.</p>
<p><strong>Bibliography</strong> (methodological papers, not exhaustive users of <code>+Γ</code>):</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Reference</th>
<th>Needs a tree?</th>
<th>Estimates "true" α or a task-specific one?</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td>ML, continuous Γ (foundational)</td>
<td><strong>Gu, Fu &amp; Li (1995)</strong>, MBE 12:546–557 — read in full</td>
<td>yes, topology fixed a priori</td>
<td>true α (+ θ jointly, invariant+Γ)</td>
<td>very high, ≤5–6 taxa in practice</td>
</tr>
<tr>
<td>ML, discrete Γ</td>
<td>Yang (1993/94), MBE 10:1396; JME 39:306</td>
<td>yes</td>
<td>true α</td>
<td>high</td>
</tr>
<tr>
<td>Parsimony-based ML on inferred changes</td>
<td>Yang &amp; Kumar (1996), MBE 13:650</td>
<td>yes, equal branch lengths assumed</td>
<td>true α, biased when branches unequal</td>
<td>low</td>
</tr>
<tr>
<td>Corrected substitutions/site → NB fit</td>
<td><strong>Gu &amp; Zhang (1997)</strong>, MBE 14:1106 — read in full</td>
<td>yes, + ancestral reconstruction</td>
<td>true α, close to ML accuracy</td>
<td>low (given a tree)</td>
</tr>
<tr>
<td>Topology-optimizing grid search</td>
<td><strong>Guindon &amp; Gascuel (2002)</strong>, MBE 19:534 — read in full</td>
<td>yes, but built <em>from</em> the candidate distances themselves (BIONJ)</td>
<td><strong>not</strong> true α — deliberately biased <em>upward</em> for topological accuracy</td>
<td>low–moderate (grid × tree build)</td>
</tr>
<tr>
<td>Free (non-parametric) rate distribution</td>
<td>Susko et al. (2003), Syst. Biol. 52:594</td>
<td>yes</td>
<td>tests the Γ assumption itself</td>
<td>high</td>
</tr>
<tr>
<td>Parsimony counts/site → NB fit</td>
<td><strong>Wakeley (1993)</strong>, JME 37:613 — read in full</td>
<td>yes, NJ tree + Fitch parsimony ancestral reconstruction</td>
<td>true α, biased <em>upward</em> by parsimony (conservative)</td>
<td>low (given a tree)</td>
</tr>
<tr>
<td>Poisson-Gamma/negative-binomial, foundational</td>
<td>Uzzell &amp; Corbin (1971), Science 172:1089 — <strong>not read</strong>, only seen via citations</td>
<td>unknown — likely also count-per-site/tree-based, unverified</td>
<td>true α (indirect, via NB overdispersion)</td>
<td>unknown</td>
</tr>
<tr>
<td>Bayesian posterior over α</td>
<td>BPP/MrBayes/BEAST2/RevBayes</td>
<td>yes</td>
<td>posterior, not point estimate</td>
<td>very high</td>
</tr>
</tbody>
</table>
<p><strong>Correction (2026-09-11, after reading Wakeley in full):</strong> an earlier
revision of this table filed Wakeley (1993) under "no tree needed" —
wrong. Wakeley's method: build a tree (neighbor-joining, Saitou &amp; Nei
1987, on the real mtDNA data; coalescent-simulated for the simulation
study), reconstruct ancestral states at internal nodes by Fitch (1971)
parsimony, count the <em>minimum</em> number of changes per site this implies,
then fit either a two-rate Poisson mixture or a gamma-distributed-rates
model (⟹ negative binomial, parameters by the methods of Cohen 1965 and
Johnson &amp; Kotz 1969) to the resulting per-site count distribution — the
same general "tree + ancestral reconstruction + per-site counts + NB fit"
shape as Gu &amp; Zhang (1997), just using raw parsimony counts directly
rather than Gu &amp; Zhang's multiple-hit-corrected <code>k̂</code>. Confirmed by
simulation (Wakeley's own Fig. 1) that parsimony underestimates both the
mean <em>and</em> (more severely) the variance of per-site change counts, which
biases <code>α</code> <strong>upward</strong> (toward apparent uniformity) — consistent with Gu &amp;
Zhang's own citation of Wakeley for exactly this bias, and with the
general "parsimony overestimates α" pattern noted throughout this
literature. Real hypervariable-region-1 mtDNA data gave <code>α̂ ≈ 0.44–0.60</code>
per data set, <code>0.47</code> combined — despite the conservative bias, still
solidly in the "strong heterogeneity" range, which is the paper's own
point: the method is biased but usefully conservative, not useless.</p>
<p><strong>Where <code>PartitionDispersion::estimate_alpha</code> actually sits</strong>: nowhere in
this table's tree-dependent rows. It shares only the <em>abstract
mathematical identity</em> (Poisson-Gamma mixture ⟹ negative binomial
over-dispersion) with Wakeley/Uzzell-Corbin/Gu&amp;Zhang, applied via a
genuinely different, tree-free and ancestral-reconstruction-free route:
pairwise genome-to-genome substitution counts pooled by <em>partition</em>
instead of per-site counts pooled across an alignment's columns after
ancestral state reconstruction. As far as this survey has established
(Uzzell &amp; Corbin not read, so not fully ruled out), <strong>no tree and no
ancestral reconstruction of any kind</strong> appears to be a genuinely
distinguishing property of <code>PartitionDispersion</code>, not something it
inherits from prior art — consistent with it being an independent
derivation rather than a literature implementation (see previous
section's caveat, now on firmer footing).</p>
<p><strong>Why a tree-free estimate is even valid — the identifiability question.</strong>
Raised directly by the user after reading Gu, Fu &amp; Li (1995), which states
explicitly: <em>"one cannot estimate the rate heterogeneity when the number
of sequences is &lt;3."</em> This is a real non-identifiability result, not a
practical inconvenience: with only 2 sequences, a site's history is
summarized by one binary observation (differ / don't differ), collapsed
across all sites into two aggregate numbers (transition and transversion
proportions) — divergence time and among-site rate variance are
confounded in that pair of numbers, with no way to separate them. Every
method surveyed above (Gu,Fu&amp;Li, Yang, Wakeley, Gu&amp;Zhang) needs ≥3
sequences <em>sharing one evolutionary history</em> (a tree) specifically to get
multiple independent looks at the <em>same</em> site's rate across different
lineages, which is what identifies its variance.</p>
<p><code>PartitionDispersion</code> doesn't violate this, because it isn't estimating
the same quantity. The literature above estimates rate variation <strong>across
sites, within one shared tree</strong>. <code>PartitionDispersion</code> estimates rate
variation <strong>across partitions, pooled over every genome pair in the
index</strong> — each genome pair stands in for one independent draw of a
partition's relative rate, the same identifying role multiple lineages
play in the tree-based methods, just substituting "genome pair" for
"lineage" and "partition" for "site." With <code>P</code> genome pairs (potentially
in the hundreds here) all contributing to every partition's pooled count,
the ≥3-samples identifiability requirement is met by the pair count, not
by tree depth — closer in spirit to Jin &amp; Nei's own original motivating
scenario (comparing several genomic <em>regions</em> across one fixed panel of
taxa) than to single-tree site-rate estimation.</p>
<p>This substitution carries its own assumption, which must be named rather
than left implicit: that a partition's <em>relative</em> rate (fast/slow) is
reasonably stable <strong>across genome pairs</strong>, not just across sites within
one pair — the direct analogue of the "no lineage-specific rate variation,
only site-specific" assumption every tree-based <code>+Γ</code> method already makes,
just moved from lineage→pair and site→partition. If this breaks — e.g. an
index mixing very closely related and very divergent genome pairs, where a
partition's saturation behavior differs qualitatively between the two —
the estimate could be misled in a way a tree-based method would at least
have the topology to detect and a tree-free, pool-everything method
cannot. Not yet tested against real data with strongly heterogeneous
pairwise divergence; worth keeping in mind as the main open validity
question for <code>--gamma-shape auto</code>, not the citation question (now settled)
this whole discussion started from.</p>
<p><strong>Gu, Fu &amp; Li (1995), read in full — the foundational ML method, not a
candidate to implement.</strong> Models rate variation as invariant+Γ (<code>θ</code> =
proportion of invariant sites, <code>α</code> = gamma shape among the variable sites),
and derives the exact joint likelihood over nucleotide <em>configurations</em>
across all <code>n</code> sequences on a <strong>fixed, a-priori-known tree topology</strong> —
for 3 sequences this is closed-form (Jukes-Cantor), for <code>n</code> sequences it's
a sum over <code>4^n</code> configurations weighted by coefficients tied to the
specific topology's branching structure (their eq. 32–34), with branch
lengths, <code>α</code>, and <code>θ</code> jointly optimized by Newton-Raphson (Hessian over all
free parameters). The site-rate integral has the same closed form
<code>E = θ + (1-θ)(1+D/α)^{-α}</code> that underlies <code>+Γ</code> distance corrections
generally (the same mechanism as <code>corrected_log</code>, not a coincidence — Jin &amp;
Nei's own formula is the <code>θ=0</code> special case applied to a pairwise <code>D</code>
rather than a whole-tree one). Explicitly stated by the authors as
infeasible beyond about 5–6 taxa (their own simulations stop at 5); not a
candidate for obikmer's typical genome counts. Notable contribution worth
keeping in mind regardless: <code>ρ = (1+θα)/(1+α)</code> is shown to be a more robust
summary of rate heterogeneity than <code>α</code> alone whenever <code>θ</code> isn't negligible
— <code>α</code> and <code>θ</code> are confounded (nearly-invariant sites can come from either a
small <code>α</code>'s left tail or from a nonzero <code>θ</code>), so <code>α</code> alone can be very
unstable while <code>ρ</code> stays well-behaved. <code>PartitionDispersion</code> has no <code>θ</code>
term at all (no invariant-site component), so this confound doesn't arise
for it the same way, but it's worth remembering if an invariant+Γ variant
is ever considered.</p>
<p><strong>Gu &amp; Zhang (1997), read in full — rejected for now.</strong> Their procedure:
(1) a tree with least-squares branch lengths must already exist; (2)
ancestral states are reconstructed at every internal node (they use Zhang &amp;
Nei 1997's likelihood method, but note plain parsimony would work, just
less accurately); (3) per site, branches are split into "changed"/"unchanged"
given the ancestral reconstruction, and the <em>expected</em> substitution count
<code>k̂</code> (corrected for multiple hits) is obtained by solving their eq. (7)
(or eq. 12 for the generalized model) numerically — a root-find per site,
not a closed form; (4) the site-level <code>k̂</code> values (real-valued, not
integers) are fit to a negative binomial (Uzzell &amp; Corbin 1971) by ML to
get α — again no closed form, numerical optimization. This is a real
per-site pipeline requiring a tree <em>before</em> distances/α can be computed —
the reverse of obikmer's current dependency order (<code>snp_distance</code> computes
distances, which <code>--nj</code>/<code>--upgma</code> only turn into a tree <em>afterward</em>). Their
own answer to this chicken-and-egg problem is an iterative
distance→tree→α→distance loop, which they themselves flag as expensive.
Adopting this would mean a new ancestral-reconstruction subsystem (even a
parsimony/Fitch-only version) plus a per-family nonlinear solve plus an NB
ML fit — a much bigger addition than <code>PartitionDispersion</code>, not something
to build without a concrete need beyond "closer to Gu&amp;Zhang's own
simulated accuracy than our moment estimator."</p>
<p><strong>Guindon &amp; Gascuel (2002), read in full — plausible future addition, not implemented.</strong>
Their <strong>Q criterion</strong>: for a candidate α, build a tree (they use BIONJ) from
the α-corrected distance matrix; for every internal branch, group taxa into
the 4 subtrees it separates (A, B, C, D), compute mean inter-subtree
distances <span class="arithmatex">\(\bar\delta_{AB}\)</span>, <span class="arithmatex">\(\bar\delta_{CD}\)</span>, etc., and let <code>S ≤ M ≤ L</code>
be the three pairings' sums (<code>{AB,CD}</code>, <code>{AC,BD}</code>, <code>{AD,BC}</code>); the branch's
reliability score is <code>Q_branch = L − M</code> (zero when the four points are
perfectly tree-additive). The whole-tree <code>Q</code> is the mean over internal
branches (negative/zero branches excluded). <code>α* = argmin_α Q(α)</code> over a
grid (their run: ~60–100 points, 0.1 to 5000, finer spacing where
sensitivity is highest). Complexity: <code>O(n²l)</code> once for the base
frequencies, then <code>O(n²r)</code> for the <code>r</code> candidate distance matrices, then
<code>O(n³r)</code> worst case for building <code>r</code> trees and evaluating <code>Q</code> on each
(same order as the tree-building step itself, so "free" relative to it).</p>
<p>Central finding, <strong>the opposite direction from an initial misreading in
this discussion</strong>: <code>α_opt</code> (Guindon-Gascuel's topology-optimal value) is
<strong>always ≥ the true α</strong>, not the reverse — underestimating rate
heterogeneity (i.e., picking a larger α than reality) reduces the variance
of distance estimates and thereby improves NJ/BIONJ topological accuracy,
especially when the molecular clock roughly holds (where <code>α_opt → ∞</code>, i.e.
no correction at all is topologically best). This is an <em>empirical
regularity</em> observed across their tested conditions (η ∈ {0.5, 2.0}, true
α ∈ {0.1, 0.7}, 20-taxon trees) — not a theorem — so treating it as a hard
guarantee would be another unverified-claim mistake of the kind this whole
discussion has been correcting.</p>
<p><strong>Proposed integration (not yet implemented)</strong>: since <code>α_true ≤ α_opt</code>
empirically, <code>PartitionDispersion::estimate_alpha()</code>'s output could seed
the <em>lower bound</em> of Guindon-Gascuel's grid (search <code>[α̂, ∞)</code> instead of
<code>[0.1, 5000]</code>), narrowing the grid substantially and reusing the existing
estimator rather than needing an independent "true α" source — this also
sidesteps Gu &amp; Zhang's tree-first dependency problem entirely, since
Guindon-Gascuel's own grid already builds a tree per candidate. Still
requires: (a) a <strong>BIONJ</strong> implementation (see below), (b) the Q-criterion
subtree-grouping logic, (c) a grid-search driver. Not started.</p>
<p><strong>BIONJ availability in the Rust ecosystem — checked 2026-09-11, none found.</strong>
Searched crates.io directly (API query for "bionj": 0 results) and read the
docs.rs pages of the most plausible candidates: <code>phylotree</code> (builds/reads/
manipulates trees but has no distance-matrix reconstruction — no NJ, no
BIONJ, no UPGMA despite web-search summaries claiming otherwise, corrected
after checking the actual docs), <code>speedytree</code> (NJ only — Canonical/RapidNJ/
Hybrid variants, explicitly no BIONJ), <code>nj</code> (plain NJ only), <code>phylo</code> (no
distance-based reconstruction at all). <code>obikphylo::neighbor_joining</code>
(<code>tree.rs</code>) is plain NJ, not BIONJ — BIONJ (Gascuel 1997) differs only in
how branch lengths are weighted during agglomeration (accounts for
distance-estimate variance, not just the sum), a modest delta over an
existing NJ implementation rather than a rewrite, but would need to be
written in-house if the Guindon-Gascuel integration above is ever pursued
(their own paper notes other tree-building methods gave similar results in
their simulations, so plain NJ may be an acceptable substitute if BIONJ
proper is judged not worth the effort).</p>
<h3 id="sharing-one-sample-across-algorithms-sankoff-tnt-phyg-iqtree-snp-distance-implemented-2026-09-11">Sharing one sample across algorithms (<code>--sankoff</code>/<code>--tnt</code>/<code>--phyg</code>/<code>--iqtree</code> + <code>snp-*</code> <code>--distance</code>) — implemented 2026-09-11</h3>
<p><strong>Correctness bug, not just a performance one.</strong> <code>--sankoff</code>/<code>--tnt</code>/<code>--phyg</code>/
<code>--iqtree</code> (via <code>SiblingExt::sankoff_bundle</code>) and a <code>snp-*</code> <code>--distance</code>
(via <code>SiblingExt::snp_distance</code>) always consume the <em>exact same</em> selection
parameters when requested together in one <code>obikmer phylo</code> invocation
(<code>n</code>/<code>free_loss</code>/<code>no_ambiguity</code>/excluded-set/<code>entropy_bias</code> — the CLI has
no way to give them different values in one run, see <code>cmd/phylo/args.rs</code>).
Before this fix, each independently called <code>sample_index</code>, and
<code>sample_layer</code>'s <code>rand::rng()</code> (<code>subsample.rs:235</code>) is a <strong>thread-local
generator that advances across calls, not reseeded each time</strong> — so the
second call silently drew a <em>different</em> random sample of sites than the
first, even with identical parameters. Verified empirically (throwaway
8-genome index): running <code>snp-jc</code> alone vs. combined with <code>--sankoff</code>
produced visibly different distance matrices from the same index/params.
This defeated the actual point of combining these flags — running several
algorithms (Sankoff/TNT/PhyG/IQ-TREE calibration, a <code>snp-*</code> distance) on
one <em>identical</em> site selection for direct comparison.</p>
<p><strong>Fix</strong>: <code>SankoffBundle</code> (<code>sankoff.rs</code>) now retains its <code>PairwiseTally</code>/
<code>PartitionDispersion</code> internally (previously consumed into <code>raw</code>/
<code>base_pair_tally</code>/<code>cardinality_tally</code> and dropped) and exposes
<code>SankoffBundle::snp_distance(kind, gamma_shape)</code>, which computes the
matrix from that <em>same</em> already-sampled tally — no second <code>sample_index</code>
call. The shared post-sampling logic (the <code>--gamma-shape</code> support check,
<code>alpha</code> resolution, final matrix build — previously all inline in the
<code>snp_distance()</code> free function) was factored into
<code>pub(crate) fn distance_matrix(tally, dispersion, kind, gamma_shape)</code> in
<code>snp_distance.rs</code>, called by both the standalone <code>snp_distance()</code> (after
its own fresh sampling) and <code>SankoffBundle::snp_distance</code> (reusing the
bundle's). <code>cmd/phylo/mod.rs</code> keeps the <code>Option&lt;SankoffBundle&gt;</code> alive past
the Sankoff-family <code>if</code> block and, when a <code>snp-*</code> <code>--distance</code> is also
requested, calls <code>bundle.snp_distance(...)</code> instead of
<code>cache.snp_distance(...)</code> whenever a bundle was built — since both branches
are driven by the same <code>args.*</code> fields, the parameters trivially always
match when both fire; no runtime "do the params match" check needed.
Verified end-to-end: the reused path logs <code>(reusing the Sankoff bundle's
sample)</code> and the <code>snp_distance</code> stage timer reads <code>0ms</code> (<code>formula(kind)</code>
is <code>O(n²)</code> post-processing, no I/O), vs. ~150-230ms for a fresh sample on
the same tiny test index.</p>
<h4 id="explicit-session-implemented-2026-09-12">Explicit <code>--session</code> (implemented 2026-09-12)</h4>
<p>The in-process fix above only covered reuse <em>within one command</em>.
<code>--session DIR</code> (<code>cmd/phylo/args.rs</code>) names a directory (outside the
index) that persists the <code>snp-*</code> <code>--distance</code> sample — the
<code>PairwiseTally</code>/<code>PartitionDispersion</code> pair <code>sample_index</code> would otherwise
rebuild from scratch — across <em>separate</em> <code>obikmer phylo</code> invocations.</p>
<p><strong>Crate placement, as planned</strong>: a new <strong><code>obiksession</code></strong> crate
(<code>src/obiksession/</code>), domain-agnostic — no <code>PairwiseTally</code>/"site" concept
anywhere in it. <code>Session::open(dir, params: &amp;[u8], force: bool)</code> handles
directory lifecycle and the params-conflict check against an opaque byte
blob; <code>Session::store(name, bytes)</code>/<code>Session::restore(name) -&gt; Option&lt;Mmap&gt;</code>
handle a checksummed artifact cache. <code>obikphylo</code>
(<code>siblings/algorithms/session_cache.rs</code>, shared by <code>snp_distance.rs</code> and
<code>sankoff.rs</code> — see below) is the consumer: it serializes its own
<code>PairwiseTally</code>/<code>PartitionDispersion</code>/<code>SnpAlignment</code> to bytes (via <code>rkyv</code>)
and hands them to <code>obiksession</code>, which never sees their type.</p>
<p><strong>Serialization</strong>: <code>rkyv</code> 0.8.18, added as planned. One deviation from the
original zero-copy pitch, scoped down deliberately: artifacts are restored
via <code>rkyv::from_bytes</code> (full owned deserialize) rather than <code>rkyv::access</code>
(zero-copy over the <code>mmap</code>). True zero-copy would require every
<code>PairwiseTally</code> query method (<code>categories</code>, <code>base_freq</code>, <code>pair</code>, ...) to
work generically over <code>Archived&lt;PairwiseTally&gt;</code> as well as the owned type
— a separate, larger change not needed to get the actual win (skipping
<code>sample_index</code>'s expensive re-scan of the sibling annex; deserializing an
already-in-memory-sized count array is comparatively cheap CPU, not I/O).
<code>#[derive(Archive, Serialize, Deserialize)]</code> was added to <code>PairStats</code>,
<code>PairwiseTally</code>, and <code>PartitionDispersion</code> (<code>pairwise.rs</code>) for this.</p>
<p><strong>Startup behavior, as designed</strong>: <code>Session::open</code> creates <code>DIR</code> if
missing (fresh, params recorded); if <code>DIR</code> already holds different saved
params, <code>cmd/phylo</code> reports a hard error and exits rather than silently
preferring one side, unless <code>--session-force</code> is given (which discards the
directory's cached artifacts and starts over under the new params) —
implements exactly the "explicit escape hatch, not silent override"
decision from the design discussion. <code>obiksession</code> itself doesn't decode
either side's bytes to produce a field-by-field diff (true to "opaque
blob," left to whoever needs it); <code>cmd/phylo</code>'s conflict message is
currently a single generic sentence listing which flags could be the
cause, not a computed diff — an honest v1 simplification, not a limitation
of <code>obiksession</code> itself.</p>
<p><strong>Per-artifact caching, as designed</strong>: only <code>PairwiseTally</code>/
<code>PartitionDispersion</code> are cached (<code>snp_distance.rs</code>'s <code>restore_tally</code>/
<code>store_tally</code>) — <code>ratio_ceiling</code>/<code>gamma_shape</code> remain pure post-processing
over whatever tally is in hand, cached or fresh, exactly as planned.</p>
<p><strong>Locking, reconsidered and kept as the whole-session <code>DirLock</code>.</strong> First
written up as a corner cut ("per-entry locking was sketched, not
implemented"). On actually working through the concrete race, whole-session
locking turned out to be the <em>correct</em> choice, not a simplification:
<code>--session-force</code> resets a session by deleting its whole <code>artifacts/</code>
directory. If the directory lock were only held briefly (during
<code>Session::open</code>, then released so a long-running <code>Session</code> doesn't block
other processes from touching <em>different</em> artifacts), a second process
calling <code>open(..., force: true)</code> could acquire the lock, see mismatched
params, and wipe <code>artifacts/</code> <strong>while a first process's already-open
<code>Session</code> is mid-checkpoint</strong> — genuine corruption risk, not just wasted
work. Holding the lock for the <code>Session</code>'s entire lifetime makes that
sequence impossible: a <code>force</code> reset must wait for every currently-open
<code>Session</code> on that directory to be dropped first. The concurrency this
gives up (two <em>different</em> processes reading/writing <em>different</em> artifacts
of the same session at once) isn't exercised by anything today — only one
code path (<code>snp_distance</code>/<code>sankoff_bundle</code>, sequentially per invocation)
uses sessions at all.</p>
<p><strong>Per-layer chunked/resumable dumps — implemented.</strong> <code>subsample::sample_index</code>
gained a <code>skip_layers: usize</code> parameter (skip the first N (partition,
layer) pairs, in its own deterministic iteration order, entirely — no
I/O, no <code>on_layer</code> call) and its <code>on_layer</code> callback gained a <code>raw_index</code>
argument (that pair's 0-based position in the same order), so a caller can
tell exactly how far a run has gotten. <code>snp_distance</code>/<code>sankoff_bundle</code>
checkpoint their tally/dispersion (and, for <code>sankoff_bundle</code>, the
in-progress <code>SnpAlignment</code>) to the session every
<code>session_cache::CHECKPOINT_INTERVAL_LAYERS</code> (8) layers or
<code>CHECKPOINT_INTERVAL</code> (30s) of wall time, whichever comes first — bounding
how much completed scanning a crash can lose, without paying a full
tally-rewrite on every one of what can be thousands of layers. A <code>progress</code>
artifact records how many layers are reflected in the checkpoint, with a
<code>PROGRESS_COMPLETE</code> (<code>u64::MAX</code>) sentinel once every layer has been
processed (distinct from any real layer count, so "finished" is never
confused with "stopped after N layers where N happens to equal the total").</p>
<p>Verified with a real kill: built a 10-genome/64-partition index, ran
<code>--distance snp-jc --session DIR</code> under <code>timeout 0.4</code>, confirmed a
checkpoint at <code>progress=8</code> (exactly <code>CHECKPOINT_INTERVAL_LAYERS</code>) was on
disk, then re-ran the same command and confirmed it resumed from layer 8
and completed successfully — 0-effort verification that the mechanism
itself is real, not just plausible-sounding.</p>
<p><strong>Important correction from that same test — resume is <em>not</em> bit-reproducible,
and shouldn't be.</strong> The output matrix from the resumed run differed from
an uninterrupted control run against the same index/params. Root cause:
<code>sample_layer</code>'s random draws come from <code>rand::rng()</code>, a per-process,
OS-seeded generator with no continuity across a process boundary — the
layers processed before a kill and the layers processed after a resume
come from two independent random streams. An earlier revision of this doc
(and of the code comments) claimed resume "reproduces the exact same
sample an uninterrupted run would have" — that's wrong, and was corrected
after the user pointed out the actual reasoning error: true randomness has
no notion of continuity in the first place, so there was never a
correctness requirement for a resumed run to match an uninterrupted one
bit-for-bit. The sample produced after a resume is exactly as legitimate a
random draw as one from an uninterrupted run — just a <em>different</em> one,
same as running the command twice without <code>--session</code> already gives two
different samples today. That variance is explicitly wanted (see below),
not a defect to fix. Comments in <code>subsample.rs</code>/<code>session_cache.rs</code> were
corrected to state this plainly instead of the false reproducibility claim.</p>
<p><strong>Explicitly declined: deterministic/seeded sampling.</strong> Raised as a
possible fix for the above (seed <code>sample_layer</code>'s RNG from a per-session
value plus <code>(partition, layer)</code>, making a resume reproduce bit-identical
results, and, if applied everywhere, making <em>any</em> two runs with identical
parameters produce identical samples). The user explicitly declined this
for now: repeated runs are relied on to measure sampling variance, and a
<code>--seed</code> flag would need its own explicit design if wanted later — this is
not an accidental gap, it's a stated preference to revisit only if asked.</p>
<p><strong><code>SankoffBundle</code> integration — implemented.</strong> <code>sankoff_bundle</code> accepts
the same <code>session: Option&lt;&amp;Session&gt;</code> and uses the <em>same</em> artifact names
(<code>session_cache::{TALLY_ARTIFACT, DISPERSION_ARTIFACT, PROGRESS_ARTIFACT}</code>)
as <code>snp_distance</code>, plus its own <code>ALIGNMENT_ARTIFACT</code> (<code>sankoff.rs</code>) folded
in lockstep with the tally at every checkpoint (same <code>on_layer</code> call
produces both, so they can never drift out of sync). Consequence verified
directly: a tally checkpointed by <code>--sankoff --session DIR</code> is restored by
a <em>later, separate</em> <code>--distance snp-k2p --session DIR</code> invocation with no
<code>--sankoff</code> at all, and vice versa — cross-consumer reuse, not just
same-command reuse, exactly the synergy this design aimed for.</p>
<p><strong>Per-artifact caching, as designed</strong>: only the tally/dispersion (plus,
for <code>sankoff_bundle</code>, the alignment) are cached — <code>ratio_ceiling</code>/
<code>gamma_shape</code> remain pure post-processing over whatever tally is in hand,
cached or fresh, exactly as planned.</p>
<p><strong>Still not done — genuine follow-up, not a justified tradeoff:</strong>
<strong>exhaustive-sample caching for <code>--subsample</code>-varying exploration.</strong> The
design discussion's suggestion — cache the exhaustive (<code>n = None</code>) sample
once and subsample <em>from</em> it on each run instead of one session per exact
<code>n</code> — wasn't implemented; a session today is still scoped to one exact
parameter tuple, <code>--subsample</code> included.</p>
<h3 id="output-format-phylip-relaxed-by-default-for-the-distance-matrix">Output format: PHYLIP-relaxed by default for the distance matrix</h3>
<p><strong>Implemented.</strong> The primary distance-matrix output
(<code>_dist.csv</code> today) gains multiple formats: <strong>PHYLIP-relaxed becomes the
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1199,7 +1199,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1124,7 +1124,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
+1 -1
View File
@@ -1243,7 +1243,7 @@
<span class="md-ellipsis">
Sibling annex
Sibling annex (discussion)
@@ -1,61 +0,0 @@
# 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.
+15 -57
View File
@@ -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<PartitionKmers> ← sorted unique k-mers + flat KmerDesc = (seq_idx, pos) slices (2026-10-15, was a HashMap — see "Query memory" below)
by_partition: Vec<HashMap<CanonicalKmer, Vec<KmerDesc>>> ← KmerDesc = (seq_idx, pos)
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 —
@@ -203,7 +203,7 @@ Genome keys follow the iteration order of `meta.genomes`.
## CLI
```
obiskim query <index> [--detail] [--mismatch] [--count-missing]
obikmer query <index> [--detail] [--mismatch] [--count-missing]
[--force-presence] [--presence-threshold <n>]
[-z <z>] [-T <threads>] [--chunk-size <MiB>]
<query.fa> [<query2.fa> ...]
@@ -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.
`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.
`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.
>
> **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 `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)).
Concrete, phased translation of the roadmap above. Phases 0–2 are small, independent, low-risk, and each individually testable against current `query` output — land them first, in order, and measure on the reference 192-core/8-NUMA machine before deciding whether phases 3–5 (the staged/sparse engine, the larger structural payoff) are still worth their cost. Phases 3–5 are one coordinated change spanning `obikmer`, `obikindex::partition`, and `obicompactvec` — they should not be split across releases mid-way, because the intermediate state (e.g. k-mer-level dedup feeding the old dense `KmerResults`) has no correctness or performance benefit on its own. Phase 6 is unrelated to phases 0–5 and can happen any time, independently, if `rapidgzip-rs` is validated (see [chunkreader.md](../implementation/chunkreader.md#future-work--parallel-gzip-decompression-in-xopen)).
Instrumentation is deliberately sequenced *before* the I/O fix (reordering the roadmap's own listed order), because every later phase's justification rests on a measurement ("to be measured, not assumed" appears throughout the roadmap above) — without it, phases 3–5 would be undertaken on faith.
@@ -295,7 +295,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**Debug logging.** Every phase that changes an algorithmic choice (not phase 0, which *is* the logging) adds `tracing::debug!`/`trace!` at points that let a cluster run's logs answer "did this help": counts, ratios, and timings that quantify the specific claim that phase makes — e.g. phase 3 must log how many MPHF `find` calls were saved by k-mer-level dedup (the whole justification for that phase), phase 4 must log per-column scan timings, phase 5 must log actual retained-memory / sparsity ratios achieved. Prefer one structured `debug!` per chunk (fields, not prose) over free-text — the cluster logs will be the only evidence available for judging these choices, so they need to be grep/awk-able, not just readable.
**Unit tests.** This project's convention (`obiread`, `obikseq`, `obidebruinj`, `obicompactvec`, `obikindex::layer`, `obiskio`, `obifastwrite`) is `#[cfg(test)] #[path = "tests/<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.
**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 `obikmer` nor `obikindex::partition` (the two crates phases 3 and 5 touch most) currently have a `src/tests/` directory at all — this needs creating, following the existing pattern exactly, not inventing a new one.
**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.
- `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`.
- `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`.
- 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()` (`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 `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 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.
- `obiskim/src/cmd/query.rs`:
- `obikmer/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.
- `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:
- `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:
```rust
let computed = avail / (n_workers as u64 * 16);
```
@@ -342,7 +342,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**Goal**: replace superkmer-level dedup with k-mer-level dedup (roadmap point 5), and split the fused MPHF-find/matrix-fetch (point 4) so stage 1's output is bucketed by layer and MPHF slot (point 6).
- `obiskim/src/cmd/query.rs`:
- `obikmer/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.
- `obikindex/src/partition/query_layer.rs`:
@@ -351,7 +351,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
- New return shape for the partition-level query, replacing today's `on_hit(sk_idx, kmer_idx, row)` callback: `HashMap<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 `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.
- **Unit tests**: create `obikmer/src/cmd/tests/query.rs` (new `src/tests/` dir for this crate, following the project's `#[cfg(test)] #[path = "tests/query.rs"] mod tests;` convention) and `obikindex/src/partition/tests/query_layer.rs` (likewise new for this crate). Cover: the k-mer-level dedup map construction on synthetic sequences with known repeated/overlapping k-mers (assert unique-kmer count and occurrence lists); the `find_slot`/bucket-by-layer-and-slot construction against a small hand-built `QueryLayer` fixture, asserting the `(layer_idx, slot, seq_idx, pos)` tuples match what the old per-occurrence loop would have produced.
### Phase 4 — Column-major matrix fetch (roadmap points 7–8) — implemented, NUMA parallelism deferred
@@ -360,7 +360,7 @@ Performance measurement on the reference 192-core/8-NUMA machine is done by the
**What shipped:**
- `obicompactvec`: the per-column accessors this phase needed **already existed** — `PersistentCompactIntMatrix::col_view(c)` and `PersistentBitMatrix::col_view(c)` are public, and `IntSliceView::get(slot)`/`BitSliceView::get(slot)` are public — the original plan underestimated how much of this plumbing the pairwise-distance code (`dump`/`select`/`stats`) had already required. The one real gap: `PersistentBitMatrix::col_view()` panics on the `Implicit` variant (the documented mono-genome fast path, `bitmatrix.rs`). Added `PersistentBitMatrix::get(c, slot) -> u32` (`bitmatrix.rs`), a non-panicking column-major point lookup that returns `1` for `Implicit` regardless of `c` — the smallest surface needed, not a new `col_get` API from scratch.
- `obikindex/src/partition/query_layer.rs`: `query_partition_with` is now two explicit stages, matching roadmap points 6–8: **stage 1** (MPHF-only, per unique k-mer, bucket hits by `(layer_idx, slot)`, emits `QueryHit::Found`) then **stage 2** (per layer with ≥1 hit, column-major: for each genome column `g` in `0..layer.n_cols().min(n_genomes)`, scan that layer's bucketed slots and call `col_value(g, slot)`, emitting `QueryHit::Value(descs, g, value)` on nonzero). `QueryHit` is a single enum delivered through one `FnMut(QueryHit)` callback — an earlier two-closure design (`on_found` + `on_value`) didn't borrow-check, since the caller's single mutable accumulator (`KmerResults`) can't be captured by two separate `FnMut` closures passed to the same call.
- `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.
- `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.
- Total `get()`-equivalent calls are unchanged from the row-major version (`n_hits × n_cols` in the worst case, confirmed by `n_col_get_calls` in the debug log) — the win is locality (sequential access within one layer's column at a time, across `mmap`'d regions, instead of jumping across all columns per hit), exactly as predicted.
**What did not ship, and why — `PartitionRunner` is architecturally the wrong tool here:**
@@ -375,14 +375,14 @@ The column-major loop in stage 2 is therefore a **plain sequential loop** for no
**Goal**: replace the dense `KmerResults`/`win_min` sliding-window scan with one operating on phase 4's sparse per-genome output.
- `obiskim/src/cmd/query.rs`, `process_chunk`:
- `obikmer/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**: `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.
- **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.
- **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` (`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.
- **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.
- **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,45 +404,3 @@ 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).
+1 -1
View File
@@ -3,7 +3,7 @@
## Code couvert
- `obiskim/src/cmd/query.rs` — commande query, format de sortie
- `obikmer/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
File diff suppressed because it is too large. Load diff
@@ -2,8 +2,8 @@
`benchmark/Makefile` exercises indexing, merge, and phylo distance
reconstruction against simulated bacterial genomes. It now also covers
`obiskim query` — the read-matching path — and the sparse packed
presence-matrix format (`obiskim pack --sparse`), previously untested by
`obikmer query` — the read-matching path — and the sparse packed
presence-matrix format (`obikmer pack --sparse`), previously untested by
this pipeline.
## Motivation
@@ -12,9 +12,8 @@ this pipeline.
by `verify_presence`/`verify_merge_presence`, which only check index
*content* against the `.npz` truth, never the query API.
- `pack --sparse` produces a presence-matrix format documented (see
[obicompactvec.md](obicompactvec.md), "Sparse matrix formats") as faster
for single-row access (query) and slower for column-oriented access
(phylo `--metric`).
[siblings.md](../architecture/siblings.md)) as faster for single-row
access (query) and slower for column-oriented access (phylo `--metric`).
`global_index_presence/` built by `merge_presence.sh` is always packed
dense (packing is a stage inside `merge`, not a separate `pack`
invocation) — there was no dense/sparse regression check.
@@ -42,7 +41,7 @@ without duplicating the exhaustive per-specimen coverage
## Sparse global index
`global_index_presence_sparse/` is built by `pack_sparse.sh`: copy
`global_index_presence/` wholesale, then `obiskim pack --sparse` in place.
`global_index_presence/` wholesale, then `obikmer pack --sparse` in place.
This works directly because `merge`'s pack stage (`merge.rs:252`,
`pack_matrices(false)`) keeps the per-genome column files on disk after
dense-packing — `pack_sparse_bit_matrix` (`obicompactvec/src/bitmatrix/sparse.rs:447`)
@@ -52,7 +51,7 @@ afterward. No separate merge run needed.
## Query runs
`query_one.sh dense|sparse SPECIMEN` runs `obiskim query --count-missing`
`query_one.sh dense|sparse SPECIMEN` runs `obikmer query --count-missing`
against `global_index_presence` or `global_index_presence_sparse`, output
gzipped to `query_{dense,sparse}/SPECIMEN.fasta.gz`, Reporter wall/RSS
captured to `stats/query_{dense,sparse}/SPECIMEN.stats` (same
@@ -7,9 +7,9 @@
- `obikindex/src/layer/mphf_layer.rs` — build_approx_evidence(dir, b, z), find_approx()
- `obikindex/src/layer/meta.rs` — EvidenceKind::Approx { b, z }, LayerMeta
- `obikindex/src/reindex.rs` — KmerIndex::reindex(), conversion exact↔approx en place
- `obiskim/src/cmd/reindex.rs` — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size
- `obiskim/src/cmd/index.rs` — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp
- `obiskim/src/cmd/estimate.rs` — commande estimate (dry-run des paramètres)
- `obikmer/src/cmd/reindex.rs` — CLI reindex, options --approx, -z, --evidence-bits, --fp, --block-size
- `obikmer/src/cmd/index.rs` — resolve_approx_params(), options --approx, -z, --evidence-bits, --fp
- `obikmer/src/cmd/estimate.rs` — commande estimate (dry-run des paramètres)
## Notes
+11 -11
View File
@@ -206,7 +206,7 @@ Keep k-mers specific to *Betula nana* — present in at least 2 *B. nana* genome
and absent from every other genome in the index:
```sh
obiskim filter src --output dst \
obikmer filter src --output dst \
--ingroup "species=Betula_nana" \
--outgroup "*" \
--min-count 2 \
@@ -217,7 +217,7 @@ Keep k-mers found in at least 2 *Betula nana* genomes and absent from all
other *Betula*:
```sh
obiskim filter src --output dst \
obikmer filter src --output dst \
--ingroup "species=Betula_nana" \
--outgroup "genus=Betula" \
--min-count 2 \
@@ -228,7 +228,7 @@ Use taxonomic paths — keep k-mers present in ≥ 50 % of the *Betula* clade
and in fewer than 10 % of everything outside *Betulaceae*:
```sh
obiskim filter src --output dst \
obikmer filter src --output dst \
--ingroup "taxon~/Betulaceae/Betula" \
--outgroup "taxon!~/Betulaceae" \
--min-frac 0.5 \
@@ -238,7 +238,7 @@ obiskim filter src --output dst \
Multiple outgroup predicates (OR): exclude k-mers present in *Alnus* or *Carpinus*:
```sh
obiskim filter src --output dst \
obikmer filter src --output dst \
--ingroup "genus=Betula" \
--outgroup "genus=Alnus" \
--outgroup "genus=Carpinus" \
@@ -249,7 +249,7 @@ Noise-tolerant core — keep k-mers present in *all but one* ingroup genome
(`-1` = `n−1`) and absent from *all but one* of the outgroup:
```sh
obiskim filter src --output dst \
obikmer filter src --output dst \
--ingroup "genus=Betula" \
--outgroup "*" \
--min-count -1 \
@@ -259,7 +259,7 @@ obiskim filter src --output dst \
To dump only k-mers specific to *Betula nana*:
```sh
obiskim dump myindex \
obikmer dump myindex \
--ingroup "species=Betula_nana" \
--outgroup "*" \
--min-count 1 \
@@ -269,7 +269,7 @@ obiskim dump myindex \
To enumerate unitigs of the *Betula*-specific subgraph:
```sh
obiskim unitig myindex \
obikmer unitig myindex \
--ingroup "genus=Betula" \
--outgroup "*" \
--min-count 2 \
@@ -285,8 +285,8 @@ Iteration terminates immediately — subsequent partitions and layers are not sc
Useful for quick inspection of large indexes without loading the entire dataset.
```sh
obiskim dump myindex --head 100
obiskim dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1
obikmer dump myindex --head 100
obikmer dump myindex --head 20 --ingroup "species=Betula_nana" --min-count 1
```
### `phylo --presence-threshold N`
@@ -296,7 +296,7 @@ This option is independent of the `--presence-threshold` used in filtering.
```sh
# Jaccard treating kmers with count ≥ 2 as present
obiskim phylo myindex --metric jaccard --presence-threshold 2
obikmer phylo myindex --metric jaccard --presence-threshold 2
```
This parameter has no effect on presence/absence indexes (where values are already 0/1) or on metrics other than Jaccard.
@@ -309,7 +309,7 @@ This parameter has no effect on presence/absence indexes (where values are alrea
once before any iteration; each k-mer row evaluation is a simple index
lookup and counter.
- **`obiskim::cmd::predicate::FilterArgs`** — shared `clap` argument group
- **`obikmer::cmd::predicate::FilterArgs`** — shared `clap` argument group
embedded via `#[command(flatten)]` in `FilterArgs`, `DumpArgs`, and
`UnitigArgs`. `FilterArgs::build_filters()` returns a ready-to-use filter
list.
+1 -1
View File
@@ -299,7 +299,7 @@ pub fn sub_matrix(&self, slots: &[usize]) -> Vec<Vec<bool>>
pub fn fill_sub_matrix(&self, slots: &[usize], out: &mut [Vec<bool>])
```
Column-first to match the on-disk column-major layout. `fill_sub_matrix` sorts `slots` once, then calls each column's `fill_batch` in turn — no redundant per-column sort. On `PersistentSparseBitMatrix` (k-mer-major, no column method) this goes through `nonzero_iter` instead, decoding one row at a time; see [obicompactvec.md](obicompactvec.md), "Sparse matrix formats".
Column-first to match the on-disk column-major layout. `fill_sub_matrix` sorts `slots` once, then calls each column's `fill_batch` in turn — no redundant per-column sort. On `PersistentSparseBitMatrix` (k-mer-major, no column method) this degrades to a row-by-row decode; see [siblings.md](../architecture/siblings.md).
---
Loaded 100 of 557 files, more files were not shown because too many files have changed in this diff. Show more