diff --git a/.crate-kit/VERSION b/.crate-kit/VERSION index 2a701a9c..6dc41d38 100644 --- a/.crate-kit/VERSION +++ b/.crate-kit/VERSION @@ -1 +1 @@ -0.3.7+0.1.1 +0.3.12+0.1.1 diff --git a/.crate-kit/crate.mk b/.crate-kit/crate.mk index 88146c5e..2a3f024c 100644 --- a/.crate-kit/crate.mk +++ b/.crate-kit/crate.mk @@ -111,6 +111,12 @@ clean: @echo "$(YELLOW)→ Cleaning...$(NC)" $(CARGO) clean +## msrv-check: Does the declared rust-version name an installed toolchain on which the crate checks? (none declared: nothing) +msrv-check: + @$(KIT_DIR)/scripts/msrv-check.sh + +.PHONY: msrv-check + ## check: Code check (host, then EXTRA_TARGETS) check: @$(KIT_DIR)/scripts/publish-guard.sh @@ -138,8 +144,8 @@ clippy: 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 +## ci: Verification pipeline (deps-check fmt-check clippy msrv-check test doc-build) +ci: deps-check fmt-check clippy msrv-check test doc-build @echo "$(GREEN)✓ All CI checks passed$(NC)" ## deps: Outdated dependencies diff --git a/.crate-kit/scripts/bump-version.sh b/.crate-kit/scripts/bump-version.sh index 750724fb..9efd4460 100755 --- a/.crate-kit/scripts/bump-version.sh +++ b/.crate-kit/scripts/bump-version.sh @@ -3,8 +3,8 @@ # 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 ` = "x.y"` of README.md when they exist. +# RELEASE=x.y.z forces the version. Updates Cargo.toml, version.txt and the dependency +# lines of README.md (` = "x.y"` or ` = { version = "x.y", ... }`) when they exist. set -euo pipefail . "$(dirname "$0")/common.sh" @@ -61,7 +61,11 @@ 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 + short=$(echo "$new_version" | cut -d. -f1,2) + sed -E -i.bak \ + -e "s/^(${name}[[:space:]]*=[[:space:]]*\")[0-9][0-9.]*\"/\1$short\"/" \ + -e "s/^(${name}[[:space:]]*=[[:space:]]*\{([^}]*[ ,])?version[[:space:]]*=[[:space:]]*\")[0-9][0-9.]*\"/\1$short\"/" \ + README.md rm README.md.bak fi ok "✓ Version $new_version written to $CARGO_TOML (and version.txt, README.md if they exist)" diff --git a/.crate-kit/scripts/deps-check-external.sh b/.crate-kit/scripts/deps-check-external.sh index e39358b4..337dcf24 100755 --- a/.crate-kit/scripts/deps-check-external.sh +++ b/.crate-kit/scripts/deps-check-external.sh @@ -135,7 +135,7 @@ for manifest in "${manifests[@]}"; do new=$(floor_for "$latest") rewrite_req "$manifest" "$key" "$new" info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)" - updates+="$crate " + updates+="$crate@$latest " else bad "$crate ($manifest): the requirement \"$req\" does not accept the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)" fi @@ -150,21 +150,21 @@ for manifest in "${manifests[@]}"; do new=$(floor_for "$latest") rewrite_req "$manifest" "$key" "$new" info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)" - updates+="$crate " + updates+="$crate@$latest " 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 + if [ -f "$LOCKFILE" ]; 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 " + updates+="$crate@$latest " else - bad "$crate: Cargo.lock is on $locked, the latest version is $latest → cargo update -p $crate (make deps-bump)" + bad "$crate: $LOCKFILE is on $locked, the latest version is $latest → cargo update $(lock_update_args "$crate" "$latest" crates.io-index) (make deps-bump)" fi fi fi @@ -180,10 +180,8 @@ if [ "$offline" -eq 1 ]; then 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 + # shellcheck disable=SC2086 # list of words + lock_update crates.io-index $updates fi if [ "$fail" -ne 0 ]; then diff --git a/.crate-kit/scripts/deps-check.sh b/.crate-kit/scripts/deps-check.sh index 66749bb5..4ccabf95 100755 --- a/.crate-kit/scripts/deps-check.sh +++ b/.crate-kit/scripts/deps-check.sh @@ -88,7 +88,7 @@ while IFS=$'\t' read -r manifest line; do 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 " + updates+="$name@$latest " 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 @@ -99,13 +99,13 @@ while IFS=$'\t' read -r manifest line; do esac # Cargo.lock: on the latest version if the dependency comes from the registry. - if [ -f Cargo.lock ]; then + if [ -f "$LOCKFILE" ]; 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 " + updates+="$name@$latest " else - bad "$name: Cargo.lock is on $locked, the latest published version is $latest → cargo update -p $name (make deps-bump)" + bad "$name: $LOCKFILE is on $locked, the latest published version is $latest → cargo update $(lock_update_args "$name" "$latest" "/api/packages/$REGISTRY/") (make deps-bump)" fi fi fi @@ -132,14 +132,14 @@ if [ "$offline" -eq 1 ]; then fi # Cargo.lock: ignored patch and duplicates. -if [ -f Cargo.lock ]; then +if [ -f "$LOCKFILE" ]; then unused=$(awk ' /^\[\[patch.unused\]\]/ { u = 1; next } /^\[/ { u = 0 } u && /^name = / { gsub(/"/, "", $3); print $3 } - ' Cargo.lock | sort -u | paste -sd' ' -) + ' "$LOCKFILE" | 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" + bad "$LOCKFILE: 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 } @@ -147,16 +147,14 @@ if [ -f Cargo.lock ]; then ') 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" + bad "$LOCKFILE: 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 + # shellcheck disable=SC2086 # list of words + lock_update "/api/packages/$REGISTRY/" $updates fi if [ "$fail" -ne 0 ]; then diff --git a/.crate-kit/scripts/deps-lib.sh b/.crate-kit/scripts/deps-lib.sh index 9a6f5bfd..e7ac5855 100644 --- a/.crate-kit/scripts/deps-lib.sh +++ b/.crate-kit/scripts/deps-lib.sh @@ -1,6 +1,6 @@ #!/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. +# To be sourced after common.sh. Only lock_update writes a file (Cargo.lock, through cargo). index_url="${REGISTRY_INDEX#sparse+}" index_url="${index_url%/}" @@ -53,6 +53,15 @@ req_for() { esac } +# Cargo.lock of the project and the cargo option that designates its workspace. The workspace is the +# root, unless MEMBERS_DIR holds it (a Cargo.toml with a [workspace] table). +LOCKFILE=Cargo.lock +workspace_args="" +if [ -n "${MEMBERS_DIR:-}" ] && grep -q '^\[workspace[].]' "$MEMBERS_DIR/Cargo.toml" 2>/dev/null; then + LOCKFILE="$MEMBERS_DIR/Cargo.lock" + workspace_args="--manifest-path $MEMBERS_DIR/Cargo.toml " +fi + # Packages of Cargo.lock, one per line: "name version source" ("-" without source). The # [[patch.unused]] blocks are excluded. lock_entries() { @@ -64,7 +73,45 @@ lock_entries() { inpkg && /^version = / { gsub(/"/, "", $3); v = $3 } inpkg && /^source = / { gsub(/"/, "", $3); s = $3 } END { flush() } - ' Cargo.lock + ' "$LOCKFILE" +} + +# Semver-compatible series of version $1: x (≥ 1), 0.y, or 0.0.z itself. +series() { + case "$1" in + 0.0.*) echo "$1" ;; + 0.*) echo "$1" | cut -d. -f1,2 ;; + *) echo "$1" | cut -d. -f1 ;; + esac +} + +# Arguments of `cargo update` that move crate $1, taken from the sources containing $3, to its latest +# version $2. When Cargo.lock holds several versions of the crate, the bare name is ambiguous: the one +# of the series of $2 is named. If there is none (the requirement has just been raised to a new +# series), `--workspace` makes cargo resolve the new requirement. +lock_update_args() { + local count=0 v old="" + [ -f "$LOCKFILE" ] && count=$(lock_entries | awk -v n="$1" '$1 == n' | wc -l) + if [ "$count" -le 1 ]; then + echo "$workspace_args-p $1" + return + fi + for v in $(lock_entries | awk -v n="$1" -v s="$3" '$1 == n && index($3, s) { print $2 }'); do + [ "$(series "$v")" = "$(series "$2")" ] && old="$v" + done + if [ -n "$old" ]; then echo "$workspace_args-p $1@$old"; else echo "$workspace_args--workspace"; fi +} + +# Runs the `cargo update` of each "crate@latest" of $2…, taken from the sources containing $1. +lock_update() { + local source="$1" u args + shift + for u in $(printf '%s\n' "$@" | sort -u); do + args=$(lock_update_args "${u%@*}" "${u#*@}" "$source") + info " cargo update $args" + # shellcheck disable=SC2086 # list of words, without spaces inside + "$CARGO" update $args >/dev/null + done } manifests=("$CARGO_TOML") diff --git a/.crate-kit/scripts/msrv-check.sh b/.crate-kit/scripts/msrv-check.sh new file mode 100755 index 00000000..56c4f375 --- /dev/null +++ b/.crate-kit/scripts/msrv-check.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Checks the `rust-version` declared in Cargo.toml. It is a guarantee ("this crate builds with that toolchain"), +# so it must name a toolchain that is INSTALLED here and on which the crate really passes `cargo check`: +# a version nobody tested is a promise nobody can keep. +# - no rust-version: nothing to check (exit 0); +# - rust-version but no matching installed toolchain: refused, with the command to install it; +# - otherwise `cargo + check --all-targets` must pass. +# The toolchain is matched on the version as written: "1.100" matches 1.100.x, "1.100.0" matches only 1.100.0. +set -euo pipefail +. "$(dirname "$0")/common.sh" + +[ -f "$CARGO_TOML" ] || exit 0 +ver=$(sed -nE 's/^rust-version[[:space:]]*=[[:space:]]*"([^"]+)".*/\1/p' "$CARGO_TOML" | head -n 1) +[ -n "$ver" ] || exit 0 + +if ! command -v rustup >/dev/null; then + err "✗ rust-version = \"$ver\" but rustup is absent: the claim cannot be tested here" + exit 1 +fi +pat="^$(printf '%s' "$ver" | sed 's/\./\\./g')(\\.[0-9]+)?-" +tc=$(rustup toolchain list | awk '{print $1}' | grep -E "$pat" | head -n 1 || true) +if [ -z "$tc" ]; then + err "✗ rust-version = \"$ver\": no such toolchain installed, so it cannot be tested." + err " Install it (rustup toolchain install $ver) and re-run, or declare a version that is installed." + exit 1 +fi +info "→ Checking the code with toolchain $tc (rust-version = \"$ver\")..." +"$CARGO" "+$tc" check --all-targets diff --git a/.crate-kit/scripts/publish-guard.sh b/.crate-kit/scripts/publish-guard.sh index e38cc490..ab3d15bb 100755 --- a/.crate-kit/scripts/publish-guard.sh +++ b/.crate-kit/scripts/publish-guard.sh @@ -1,12 +1,30 @@ #!/usr/bin/env bash -# Safeguard: a crate published on a private registry declares `publish = [""]` in its -# Cargo.toml, so that cargo itself refuses any publication elsewhere (crates.io for example). +# Safeguards before a publication: +# 1. a crate published on a private registry declares `publish = [""]` in its Cargo.toml, so that +# cargo itself refuses any publication elsewhere (crates.io for example); +# 2. the published archive does not carry the kit's own files (.crate-kit/, .gitea/, api/, Makefile): +# development tooling, useless to the users of the crate. `exclude` in [package] keeps them out. # 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 +if ! grep -qE "^publish[[:space:]]*=[[:space:]]*\[[[:space:]]*\"$REGISTRY\"[[:space:]]*\]" "$CARGO_TOML"; then + err "✗ $CARGO_TOML : publish = [\"$REGISTRY\"] missing in [package] (without it, cargo publish would accept crates.io)" + exit 1 +fi + +# What cargo would really put in the archive (not a reading of Cargo.toml). +if ! listing=$("$CARGO" package --allow-dirty --list --manifest-path "$CARGO_TOML" 2>&1); then + err "✗ cannot list the files of the package, so its content cannot be checked:" + printf '%s\n' "$listing" >&2 + exit 1 +fi +internal=$(printf '%s\n' "$listing" | grep -E '^(\.crate-kit/|\.gitea/|api/|Makefile$)' || true) +if [ -n "$internal" ]; then + err "✗ the published archive would contain the kit's internal files:" + printf '%s\n' "$internal" | head -n 5 | sed 's/^/ /' >&2 + err " add to [package] of $CARGO_TOML: exclude = [\".crate-kit/\", \".gitea/\", \"api/\", \"Makefile\"]" + exit 1 +fi diff --git a/.crate-kit/scripts/publish.sh b/.crate-kit/scripts/publish.sh index 1fa66d01..4d550045 100755 --- a/.crate-kit/scripts/publish.sh +++ b/.crate-kit/scripts/publish.sh @@ -17,6 +17,8 @@ if [ "${PUBLISH:-yes}" = no ]; then fi [ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; } +# Same safeguards as `make check` (publish = [...] and no internal file in the archive): the CI runs this script. +"$(dirname "$0")/publish-guard.sh" version=$(current_version) name=$(crate_name) if [ -n "${DRY_RUN:-}" ]; then diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 6a43fd13..734e3c26 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -5,6 +5,11 @@ on: tags: - "v*" +# Private cargo registry `obi` (public read access): the index normally comes from `make` (obi-kit, org.mk), +# which these jobs do not use, and `.cargo/config.toml` is not versioned. +env: + CARGO_REGISTRIES_OBI_INDEX: sparse+https://forge.metabarcoding.org/api/packages/obi/cargo/ + jobs: create-release: runs-on: ubuntu-latest @@ -104,7 +109,9 @@ jobs: - name: Build macOS binary run: | + # The build runs in a container: the registry index of the workflow env must be passed explicitly. CID=$(docker create \ + -e CARGO_REGISTRIES_OBI_INDEX \ -w /src/src \ registry.metabarcoding.org/cibuilder/rustcrossosx:latest \ cargo build --release --target aarch64-apple-darwin --no-default-features) diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 18563de2..00000000 --- a/Cargo.lock +++ /dev/null @@ -1,7 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "obikseq" -version = "0.1.0" diff --git a/ReleaseNotes/version-1.4.10.md b/ReleaseNotes/version-1.4.10.md new file mode 100644 index 00000000..330cf490 --- /dev/null +++ b/ReleaseNotes/version-1.4.10.md @@ -0,0 +1,41 @@ +# Release notes for obiskim (Rust k-mer genomics tool), version 1.4.10 + +## Refactoring + +- **Dependency Migration**: Removed the local `obipipeline` crate. All dependent crates (`obikindexer`, `obikmerge`, `obikphylo`, `obiskim`) now depend on `obipipeline` version 0.2 from the `obi` registry. +- **Logic Migration**: + - Moved error handling (`pipeline_error`) to `obikindexer` for graph building. + - Moved batch iteration logic (`iter_canonical_kmer_batches_owned`) to `obiskio` for lazy canonical k-mer iteration. + - Refactored `obikmerge` to use `iter_canonical_kmer_batches_owned` for streaming batches in `merge_partition` and `run_pass2`. + - Refactored `obikphylo` to handle errors via `OKIError::InvalidData`. + - Refactored `obiskim` to use `.expect("pipeline error")` for batch processing in `query` and `superkmer` commands. +- **Internal API**: Removed the `sorted_slots` parameter from `nonzero_triples` in `obicompactvec`; slots are now sorted internally. Updated callers in `intmatrix` and `bitmatrix` modules. +- **Workspace**: Added `MEMBERS_DIR` variable to workspace scripts for scanning subdirectories for Cargo manifests. Removed `obikseq` and added `obifastwrite` to workspace members. Removed root `Cargo.lock`. + +## Documentation + +- **Renaming**: Renamed project references from "obikmer" to "obiskim" across all documentation, user guides, and developer notes. +- **K-mer Indexing**: Updated terminology and constraints to reflect obiskim's two-bit-per-nucleotide representation ($k \leq 32$, odd $k$) and deterministic hash ordering. +- **New Topics**: Added extensive documentation covering: + - Chance sharing across genomes + - Sibling partition unification + - Pair-coverage-biased family sampling + - MPHF batch queries + - Merge mmap audit and scaling + - Hot resume and memoization +- **Implementation Details**: + - Updated `by_partition` description to use `Vec` instead of `HashMap`. + - Updated merge bootstrap logic to select base source by largest `unitigs.bin` size. + - Changed `MAX_KMERS_PER_CHUNK` from 256 to 128. + - Clarified `obiskim phylo` sampling behavior and `--sibling-annex` usage. + - Clarified `select` command hard-linking mechanism and output directory behavior. +- **References**: Added BibTeX entries for Karlin et al. and Bennett et al. + +## Build & CI + +- **Scripts**: + - Added `.crate-kit/scripts/msrv-check.sh` for MSRV verification. + - Updated dependency management scripts (`deps-check.sh`, `deps-lib.sh`) for improved lockfile handling and `cargo update` support. + - Updated `bump-version.sh` to use `sed -E` for robust version string replacement. + - Updated publish scripts to enforce registry settings and exclude internal files. +- **CI**: Updated `.gitea/workflows/release.yml` to pass private cargo registry index environment variables during macOS binary builds. diff --git a/src/Cargo.lock b/src/Cargo.lock index 1c8ebc18..404f70b4 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -1657,7 +1657,7 @@ dependencies = [ [[package]] name = "obipipeline" -version = "0.1.0" +version = "0.2.0" dependencies = [ "crossbeam-channel", ] diff --git a/src/Cargo.toml b/src/Cargo.toml index b655e5f6..f328a066 100644 --- a/src/Cargo.toml +++ b/src/Cargo.toml @@ -1,5 +1,5 @@ [workspace] resolver = "3" -members = ["obikseq", "obiread", "obiskbuilder", "obifastwrite", "obiskim","obikrope","obipipeline", "obiskio","obidebruinj", "obicompactvec", "obisys", "obikindex", "obikindexer", "obikquery", "obikdump", "obikfilter", "obikselect", "obikrebuild", "obikmerge", "obikstats", "obikidxcache", "obitaxonomy", "obikentropy", "obikphylo", "obikalgorithm", "obiksession"] +members = ["obikseq", "obiread", "obiskbuilder", "obifastwrite", "obiskim","obikrope", "obiskio","obidebruinj", "obicompactvec", "obisys", "obikindex", "obikindexer", "obikquery", "obikdump", "obikfilter", "obikselect", "obikrebuild", "obikmerge", "obikstats", "obikidxcache", "obitaxonomy", "obikentropy", "obikphylo", "obikalgorithm", "obiksession"] [profile.release] debug = 1 diff --git a/src/obikidxcache/Cargo.toml b/src/obikidxcache/Cargo.toml index 25b1225e..65c74b47 100644 --- a/src/obikidxcache/Cargo.toml +++ b/src/obikidxcache/Cargo.toml @@ -9,7 +9,7 @@ repository = "https://forge.metabarcoding.org/obi/obiskim" obikindex = { path = "../obikindex"} obikseq = { path = "../obikseq"} obicompactvec = { path = "../obicompactvec" } -obipipeline = { path = "../obipipeline" } +obipipeline = { version = "0.2", registry = "obi" } ndarray = "0.17" rayon = "1" diff --git a/src/obikindexer/Cargo.toml b/src/obikindexer/Cargo.toml index 75f0615e..41736d00 100644 --- a/src/obikindexer/Cargo.toml +++ b/src/obikindexer/Cargo.toml @@ -13,7 +13,7 @@ obidebruinj = { path = "../obidebruinj" } obiskio = { path = "../obiskio" } obisys = { path = "../obisys", default-features = false } obicompactvec = { path = "../obicompactvec" } -obipipeline = { path = "../obipipeline" } +obipipeline = { version = "0.2", registry = "obi" } obiread = { path = "../obiread" } obiskbuilder = { path = "../obiskbuilder" } epserde = "0.13" diff --git a/src/obikindexer/src/algorithms/partitionner/router.rs b/src/obikindexer/src/algorithms/partitionner/router.rs index 852767e5..c7c66c87 100644 --- a/src/obikindexer/src/algorithms/partitionner/router.rs +++ b/src/obikindexer/src/algorithms/partitionner/router.rs @@ -308,6 +308,7 @@ impl Algorithm for PartitionRouter<'_> { const REPORT_INTERVAL: f64 = 0.1; for batch in pipe.apply(throttled, n_workers, 1) { + let batch = batch?; total_bases += batch .iter() .map(|sk| (sk.seql() as u64).saturating_sub(kmer_overlap)) diff --git a/src/obikindexer/src/graph_pipeline.rs b/src/obikindexer/src/graph_pipeline.rs index c351fd66..75c54ab3 100644 --- a/src/obikindexer/src/graph_pipeline.rs +++ b/src/obikindexer/src/graph_pipeline.rs @@ -2,7 +2,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use obipipeline::{ - Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, WorkerPool, make_sink, + Pipeline, PipelineError, Throttled, WorkerPool, make_flat_transform_fallible, make_sink, make_source, make_transform, throttle, }; use tracing::debug; @@ -24,59 +24,48 @@ enum KmerGraphData { /// Phase 1: pipeline that reads files, filters kmers, pushes into a GraphDeBruijn. /// -/// `flat_fn(path, emit)`: opens path, iterates kmers, calls `emit(batch)` for each batch. +/// `open(path)`: opens path and returns its k-mer batches, as a lazy iterator: a batch is only read when +/// the pipeline has room for it. At most `max_open` of these iterators are alive at once. /// `filter(kmer) -> bool`: secondary filter applied in the Transform stage. -pub fn build_graph( +pub fn build_graph( file_source: I, - flat_fn: F, + open: F, filter: G, n_workers: usize, max_open: usize, ) -> OKIResult where I: Iterator + Send + 'static, - F: Fn(PathBuf, &mut dyn FnMut(Vec)) -> OKIResult<()> + Send + Sync + 'static, + F: Fn(PathBuf) -> OKIResult + Send + Sync + 'static, + B: Iterator> + Send + 'static, G: Fn(CanonicalKmer) -> bool + Send + Sync + 'static, { let capacity = 2; - let flat_fn = Arc::new(flat_fn); let filter = Arc::new(filter); let g_shared = Arc::new(Mutex::new(GraphDeBruijn::new())); let g_sink = Arc::clone(&g_shared); - let err_cap: Arc>> = Arc::new(Mutex::new(None)); - let err_flat = Arc::clone(&err_cap); let throttled = throttle(file_source, max_open); let pipeline = Pipeline::new( make_source!(KmerGraphData, throttled, File), vec![ - Stage::Flat(Arc::new( - move |data: KmerGraphData, - push: &PipelineSender>, - delta: &PipelineSender| { - if let KmerGraphData::File(t) = data { - let path = t.item; - let _guard = t.guard; // released at end of block - let mut count: isize = 0; - let push_clone = push.clone(); - let result = flat_fn(path, &mut |batch: Vec| { - push_clone.send(Ok(KmerGraphData::RawBatch(batch))).ok(); - count += 1; - }); - match result { - Ok(()) => { - delta.send(count - 1).ok(); - } - Err(e) => { - *err_flat.lock().unwrap() = Some(e); - delta.send(-1).ok(); - } - } + make_flat_transform_fallible!( + KmerGraphData, + { + move |file: Throttled| { + let guard = file.guard; + open(file.item).map(|batches| { + batches.inspect(move |_| { + let _open_file = &guard; // slot held as long as the file is read + }) + }) } }, - ) as SharedFlatFn), + File, + RawBatch + ), make_transform!( KmerGraphData, { @@ -103,15 +92,16 @@ where ), ); - WorkerPool::new(pipeline, n_workers, capacity).run(); - - if let Some(e) = Arc::try_unwrap(err_cap) - .unwrap_or_else(|_| panic!("build_graph: err_cap not uniquely owned after pipeline")) - .into_inner() - .unwrap_or_else(|e| e.into_inner()) - { - return Err(e); - } + WorkerPool::new(pipeline, n_workers, capacity) + .run() + .map_err(|e| match e { + // An error of `open` is handed back as it was. + PipelineError::StepError(inner) => match inner.downcast::() { + Ok(e) => *e, + Err(other) => pipeline_error(other.to_string()), + }, + other => pipeline_error(other.to_string()), + })?; let g = Arc::try_unwrap(g_shared) .unwrap_or_else(|_| panic!("build_graph: g_shared not uniquely owned after pipeline")) @@ -121,6 +111,13 @@ where Ok(g) } +fn pipeline_error(detail: String) -> OKIError { + OKIError::InvalidData { + context: "build_graph pipeline", + detail, + } +} + // ── write_graph_as_unitigs ──────────────────────────────────────────────────── /// Phase 2 (write unitigs only): compute degrees, write unitigs to `layer_dir`, drop graph. diff --git a/src/obikmerge/Cargo.toml b/src/obikmerge/Cargo.toml index 91c9e81f..15826a88 100644 --- a/src/obikmerge/Cargo.toml +++ b/src/obikmerge/Cargo.toml @@ -12,7 +12,7 @@ obikalgorithm = { path = "../obikalgorithm" } obicompactvec = { path = "../obicompactvec" } obiskio = { path = "../obiskio" } obikseq = { path = "../obikseq" } -obipipeline = { path = "../obipipeline" } +obipipeline = { version = "0.2", registry = "obi" } obisys = { path = "../obisys", default-features = false } rayon = "1" tracing = "0.1.44" diff --git a/src/obikmerge/src/partition_merge/mod.rs b/src/obikmerge/src/partition_merge/mod.rs index 6d5412f2..d2eb97ac 100644 --- a/src/obikmerge/src/partition_merge/mod.rs +++ b/src/obikmerge/src/partition_merge/mod.rs @@ -21,7 +21,6 @@ use obicompactvec::{ColBuilder, MatrixBuilder}; use obikindex::layer::{IndexMode, KmerLayer, TypedLayer}; use obikindex::{KmerIndex, OKIError, OKIResult}; use obikindexer::{build_graph, materialize_layer}; -use obikseq::CanonicalKmer; use obiskio::UnitigFileReader; use crate::MergeMode; @@ -82,7 +81,7 @@ pub(crate) fn merge_partition( // ── Pass 1: pipeline — parallel file read + dst filter + graph fill ──── // // Source : list of unitigs.bin paths (one per source × layer) - // Flat : open file, emit Vec batches (BeeGFS parallel I/O) + // Flat : open file, stream Vec batches (BeeGFS parallel I/O) // Transform: filter via dst_layers — Arc<[KmerLayer]>: Sync // Sink : push new kmers into GraphDeBruijn (single thread, no locks needed) // @@ -106,28 +105,16 @@ pub(crate) fn merge_partition( const BATCH: usize = 4096; let n_workers = rayon::current_num_threads().clamp(4, 16); - // At most 2 files open simultaneously: keeps n_workers-2 workers free - // for the Transform stage. Each open file monopolises one worker for the - // full duration of its read, so this must stay well below n_workers. + // At most 2 files open simultaneously (I/O bound, not needed for the pipeline to progress). let max_open = 2; let dst_filter = Arc::clone(&dst_layers); let g = build_graph( unitig_paths.into_iter(), - move |path: PathBuf, emit: &mut dyn FnMut(Vec)| -> OKIResult<()> { - let reader = UnitigFileReader::open_sequential(&path)?; - let mut batch: Vec = Vec::with_capacity(BATCH); - for (kmer, _, _) in reader.iter_indexed_canonical_kmers() { - batch.push(kmer); - if batch.len() == BATCH { - emit(std::mem::replace(&mut batch, Vec::with_capacity(BATCH))); - } - } - if !batch.is_empty() { - emit(batch); - } - Ok(()) + move |path: PathBuf| -> OKIResult<_> { + let reader = Arc::new(UnitigFileReader::open_sequential(&path)?); + Ok(reader.iter_canonical_kmer_batches_owned(BATCH)) }, move |kmer| dst_filter.iter().all(|l| l.find_slot(kmer).is_none()), n_workers, diff --git a/src/obikmerge/src/partition_merge/pass2.rs b/src/obikmerge/src/partition_merge/pass2.rs index 669de1d2..228cd695 100644 --- a/src/obikmerge/src/partition_merge/pass2.rs +++ b/src/obikmerge/src/partition_merge/pass2.rs @@ -7,8 +7,8 @@ use std::path::PathBuf; use std::sync::{Arc, Mutex}; use obipipeline::{ - Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, ThrottleGuard, WorkerPool, - make_sink, make_source, make_transform, throttle, + Pipeline, ThrottleGuard, WorkerPool, make_flat_transform_fallible, make_sink, make_source, + make_transform, throttle, }; use obicompactvec::ColBuilder; @@ -88,8 +88,6 @@ pub(super) fn run_pass2( let new_sink: Vec>> = new_locked.iter().map(Arc::clone).collect(); let dst_layers_t2 = Arc::clone(dst_layers); let new_mphf_t2 = new_mphf.clone(); - let pass2_err: Arc>> = Arc::new(Mutex::new(None)); - let err_cap2 = Arc::clone(&pass2_err); let capacity = 2; let throttled_pass2 = throttle(items.into_iter(), max_open); @@ -104,58 +102,33 @@ pub(super) fn run_pass2( SrcLayer ), vec![ - Stage::Flat(Arc::new( - move |data: Pass2Data, - push: &PipelineSender>, - delta: &PipelineSender| { - if let Pass2Data::SrcLayer(( - col_offset, - src_n, - unitigs_path, - src_layer, - _guard, - )) = data - { - // _guard dropped at end of block, releasing the slot. + make_flat_transform_fallible!( + Pass2Data, + { + move |(col_offset, src_n, unitigs_path, src_layer, guard): ( + usize, + usize, + PathBuf, + Arc, + ThrottleGuard, + )| { // `src_layer` (MPHF + matrix) was already opened by // the caller — only the unitigs.bin stream itself is // opened (and throttled) here. - let reader = match UnitigFileReader::open_sequential(&unitigs_path) { - Ok(r) => r, - Err(e) => { - *err_cap2.lock().unwrap() = Some(e.to_string()); - delta.send(-1).ok(); - return; - } - }; - const BATCH: usize = 4096; - let mut batch: Vec = Vec::with_capacity(BATCH); - let mut count: isize = 0; - for (kmer, _, _) in reader.iter_indexed_canonical_kmers() { - batch.push(kmer); - if batch.len() == BATCH { - let b = std::mem::replace(&mut batch, Vec::with_capacity(BATCH)); - push.send(Ok(Pass2Data::RawBatch(( - col_offset, - src_n, - Arc::clone(&src_layer), - b, - )))) - .ok(); - count += 1; - } - } - if !batch.is_empty() { - push.send(Ok(Pass2Data::RawBatch(( - col_offset, src_n, src_layer, batch, - )))) - .ok(); - count += 1; - } - delta.send(count - 1).ok(); + UnitigFileReader::open_sequential(&unitigs_path).map(|reader| { + const BATCH: usize = 4096; + Arc::new(reader) + .iter_canonical_kmer_batches_owned(BATCH) + .map(move |kmers| { + let _open_file = &guard; // slot held as long as the file is read + (col_offset, src_n, Arc::clone(&src_layer), kmers) + }) + }) } }, - ) as SharedFlatFn), + SrcLayer, + RawBatch + ), make_transform!( Pass2Data, { @@ -239,18 +212,12 @@ pub(super) fn run_pass2( ), ); - WorkerPool::new(pipeline2, n_workers, capacity).run(); - - if let Some(msg) = Arc::try_unwrap(pass2_err) - .unwrap_or_else(|_| panic!("pass2: pass2_err not uniquely owned")) - .into_inner() - .unwrap_or_else(|e| e.into_inner()) - { - return Err(OKIError::InvalidData { - context: "merge pass2", - detail: msg, - }); - } + WorkerPool::new(pipeline2, n_workers, capacity) + .run() + .map_err(|e| OKIError::InvalidData { + context: "merge pass2 pipeline", + detail: e.to_string(), + })?; let unlock = |b: Arc>| -> ColBuilder { Arc::try_unwrap(b) diff --git a/src/obikphylo/Cargo.toml b/src/obikphylo/Cargo.toml index bfeda2fc..b99478c6 100644 --- a/src/obikphylo/Cargo.toml +++ b/src/obikphylo/Cargo.toml @@ -12,7 +12,7 @@ obiskio = { path = "../obiskio" } obisys = { path = "../obisys", default-features = false } obicompactvec = { path = "../obicompactvec" } obikidxcache = { path = "../obikidxcache" } -obipipeline = { path = "../obipipeline" } +obipipeline = { version = "0.2", registry = "obi" } kodama = "0.3.0" memmap2 = "0.9" ndarray = "0.17" diff --git a/src/obikphylo/src/siblings/algorithms/annex.rs b/src/obikphylo/src/siblings/algorithms/annex.rs index 933831d5..26123a0a 100644 --- a/src/obikphylo/src/siblings/algorithms/annex.rs +++ b/src/obikphylo/src/siblings/algorithms/annex.rs @@ -4,8 +4,8 @@ use std::sync::atomic::Ordering; use rayon::prelude::*; use obikidxcache::index_cache::IndexCache; -use obikindex::OKIResult; use obikindex::layer::KmerLayer; +use obikindex::{OKIError, OKIResult}; use obikseq::CanonicalKmer; use obipipeline::ThrottleGuard; @@ -181,6 +181,10 @@ pub(crate) fn build_layer_sibling_annex( let mut outgoing: Vec> = (0..n_parts).map(|_| Vec::new()).collect(); for vb in pipe.apply(throttled, n_workers, capacity) { + let vb = vb.map_err(|e| OKIError::InvalidData { + context: "sibling annex pipeline", + detail: e.to_string(), + })?; for (dest_partition, variant, source_order, base) in vb.items { outgoing[dest_partition].push((variant, source_order, base)); } diff --git a/src/obikphylo/src/siblings/algorithms/family_scan.rs b/src/obikphylo/src/siblings/algorithms/family_scan.rs index 17739098..ad608ac8 100644 --- a/src/obikphylo/src/siblings/algorithms/family_scan.rs +++ b/src/obikphylo/src/siblings/algorithms/family_scan.rs @@ -326,6 +326,10 @@ pub(crate) fn scan_layer_families( let mut next_expected = 0usize; let mut scratch = vec![0u8; n_genomes]; for generated in pipe.apply(throttled, n_workers, capacity) { + let generated = generated.map_err(|e| OKIError::InvalidData { + context: "family scan pipeline", + detail: e.to_string(), + })?; pending.insert(generated.start_family_idx, generated); while let Some(batch) = pending.remove(&next_expected) { let n = batch.masks.len(); diff --git a/src/obipipeline/Cargo.toml b/src/obipipeline/Cargo.toml deleted file mode 100644 index 7cceb381..00000000 --- a/src/obipipeline/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "obipipeline" -version = "0.1.0" -edition = "2024" -license = "CECILL-2.1" -repository = "https://forge.metabarcoding.org/obi/obiskim" - -[dependencies] -crossbeam-channel = "0.5.15" diff --git a/src/obipipeline/examples/sandbox_pipeline.rs b/src/obipipeline/examples/sandbox_pipeline.rs deleted file mode 100644 index cb3743c9..00000000 --- a/src/obipipeline/examples/sandbox_pipeline.rs +++ /dev/null @@ -1,79 +0,0 @@ -use obipipeline::{WorkerPool, make_pipeline}; -use std::io::Error; - -// ── Itérateur source ────────────────────────────────────────────────────────── - -struct Compteur { - count: u64, - stop: u64, -} - -impl Compteur { - fn new(start: u64, stop: u64) -> Self { - Self { count: start, stop } - } -} - -impl Iterator for Compteur { - type Item = u64; - - fn next(&mut self) -> Option { - if self.count > self.stop { - return None; - } - let result = self.count; - self.count += 1; - Some(result) - } -} - -// ── Fonctions de transformation ─────────────────────────────────────────────── - -fn to_f64(x: u64) -> f64 { - x as f64 -} - -fn step_1(number: f64) -> String { - format!("{}", number) -} - -fn step_2(text: String) -> String { - text.chars().rev().collect() -} - -fn step_3(text: String) -> u64 { - let mut hash: u64 = 5381; - for byte in text.bytes() { - hash = hash.wrapping_mul(33).wrapping_add(byte as u64); - } - hash -} - -fn step_4(hash: u64) -> Result<(), Error> { - println!("{}", hash); - Ok(()) -} - -// ── Type de données du pipeline ─────────────────────────────────────────────── - -enum PipelineData { - Unsigned(u64), - Number(f64), - Text(String), -} - -// ── Main ────────────────────────────────────────────────────────────────────── - -fn main() { - let pipeline = make_pipeline! { - PipelineData, - source Compteur::new(1000, 1010) => Unsigned, - | to_f64: Unsigned => Number, - | step_1: Number => Text, - | step_2: Text => Text, - | step_3: Text => Unsigned, - sink? step_4 @ Unsigned, - }; - - WorkerPool::new(pipeline, 4, 64).run(); -} diff --git a/src/obipipeline/src/lib.rs b/src/obipipeline/src/lib.rs deleted file mode 100644 index 099ea6ee..00000000 --- a/src/obipipeline/src/lib.rs +++ /dev/null @@ -1,27 +0,0 @@ -mod scheduler; -pub mod throttle; - -pub use scheduler::Pipe; -pub use scheduler::PipeIter; -pub use scheduler::Pipeline; -pub use scheduler::PipelineError; -pub use scheduler::SharedFlatFn; -pub use scheduler::SharedFn; -pub use scheduler::SinkFn; -pub use scheduler::SourceFn; -pub use scheduler::Stage; -pub use scheduler::WorkerPool; -pub use throttle::Throttle; -pub use throttle::ThrottleGuard; -pub use throttle::Throttled; -pub use throttle::throttle; - -/// Re-export de `crossbeam_channel::Sender` utilisé dans les macros flat transform. -/// Permet aux macros `make_flat_transform!` / `make_flat_transform_fallible!` d'utiliser -/// `$crate::PipelineSender` sans que le crate appelant n'ait besoin de dépendre -/// directement de `crossbeam_channel`. -pub use crossbeam_channel::Sender as PipelineSender; - -// make_sink, make_sink_fallible, make_source, make_source_fallible, -// make_transform, make_transform_fallible, make_flat_transform, -// make_flat_transform_fallible sont exportés à la racine du crate via #[macro_export] diff --git a/src/obipipeline/src/scheduler/error.rs b/src/obipipeline/src/scheduler/error.rs deleted file mode 100644 index fc4a0128..00000000 --- a/src/obipipeline/src/scheduler/error.rs +++ /dev/null @@ -1,35 +0,0 @@ -use std::error::Error; -use std::fmt; - -/// Error type for pipeline operations. -#[derive(Debug)] -pub enum PipelineError { - /// A stage received a `PipelineData` variant it did not expect. - TypeMismatch, - /// The step kind is not compatible with the data type. - StepKindMismatch(&'static str), - /// The source has no more data to produce. - EndOfStream, - /// An error occurred inside a stage (e.g., I/O, parsing, custom logic). - StepError(Box), -} - -impl fmt::Display for PipelineError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - PipelineError::TypeMismatch => write!(f, "data type mismatch in pipeline stage"), - PipelineError::StepKindMismatch(s) => write!(f, "step kind mismatch: {}", s), - PipelineError::EndOfStream => write!(f, "end of input stream"), - PipelineError::StepError(e) => write!(f, "stage error: {}", e), - } - } -} - -impl Error for PipelineError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - PipelineError::StepError(e) => Some(e.as_ref()), - _ => None, - } - } -} diff --git a/src/obipipeline/src/scheduler/macros.rs b/src/obipipeline/src/scheduler/macros.rs deleted file mode 100644 index 0164c352..00000000 --- a/src/obipipeline/src/scheduler/macros.rs +++ /dev/null @@ -1,357 +0,0 @@ -// ── Macros ──────────────────────────────────────────────────────────────────── - -/// Creates a `SourceFn` from an iterator of plain values. -#[macro_export] -macro_rules! make_source { - ($enum:ident, $iterator:expr, $output:ident) => {{ - let mut iter = $iterator.into_iter(); - Box::new( - move || -> ::std::result::Result<$enum, $crate::PipelineError> { - match iter.next() { - Some(x) => Ok($enum::$output(x)), - None => Err($crate::PipelineError::EndOfStream), - } - }, - ) as Box ::std::result::Result<$enum, $crate::PipelineError> + Send> - }}; -} - -/// Creates a `SourceFn` from an iterator of `Result`. -#[macro_export] -macro_rules! make_source_fallible { - ($enum:ident, $iterator:expr, $output:ident) => {{ - let mut iter = $iterator.into_iter(); - Box::new( - move || -> ::std::result::Result<$enum, $crate::PipelineError> { - match iter.next() { - Some(Ok(x)) => Ok($enum::$output(x)), - Some(Err(e)) => Err($crate::PipelineError::StepError(Box::new(e))), - None => Err($crate::PipelineError::EndOfStream), - } - }, - ) as Box ::std::result::Result<$enum, $crate::PipelineError> + Send> - }}; -} - -/// Creates a `Stage::Transform` from a pure (non-fallible) function `Fn(T) -> U`. -#[macro_export] -macro_rules! make_transform { - ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ - let __f = $func; - $crate::Stage::Transform(::std::sync::Arc::from(Box::new( - move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> { - match data { - $enum::$input(x) => Ok($enum::$output(__f(x))), - _ => Err($crate::PipelineError::TypeMismatch), - } - }, - ) - as Box< - dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync, - >)) - }}; -} - -/// Creates a `Stage::Transform` from a fallible function `Fn(T) -> Result`. -#[macro_export] -macro_rules! make_transform_fallible { - ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ - let __f = $func; - $crate::Stage::Transform(::std::sync::Arc::from(Box::new( - move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> { - match data { - $enum::$input(inner) => { - let result = __f(inner) - .map_err(|e| $crate::PipelineError::StepError(Box::new(e)))?; - Ok($enum::$output(result)) - } - _ => Err($crate::PipelineError::TypeMismatch), - } - }, - ) - as Box< - dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync, - >)) - }}; -} - -/// Creates a `Stage::Flat` from a function `Fn(T) -> impl IntoIterator`. -/// -/// Pour chaque item produit par l'itérateur, il est poussé individuellement dans -/// le canal de sortie, permettant au scheduler de dispatcher les items en parallèle -/// dès qu'un worker est disponible. -#[macro_export] -macro_rules! make_flat_transform { - ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ - let __f = $func; - $crate::Stage::Flat(::std::sync::Arc::new( - move |data: $enum, - push: &$crate::PipelineSender< - ::std::result::Result<$enum, $crate::PipelineError>, - >, - delta: &$crate::PipelineSender| { - match data { - $enum::$input(inner) => { - let mut count: isize = 0; - for item in __f(inner) { - push.send(Ok($enum::$output(item))).ok(); - count += 1; - } - delta.send(count - 1).ok(); - } - _ => { - push.send(Err($crate::PipelineError::TypeMismatch)).ok(); - delta.send(0).ok(); - } - } - }, - ) as $crate::SharedFlatFn<$enum>) - }}; -} - -/// Creates a `Stage::Flat` from a fallible function -/// `Fn(T) -> Result, E>`. -/// -/// Si la fonction retourne `Err`, une erreur est poussée dans le canal et aucun -/// item normal n'est produit. -#[macro_export] -macro_rules! make_flat_transform_fallible { - ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ - let __f = $func; - $crate::Stage::Flat(::std::sync::Arc::new( - move |data: $enum, - push: &$crate::PipelineSender< - ::std::result::Result<$enum, $crate::PipelineError>, - >, - delta: &$crate::PipelineSender| { - match data { - $enum::$input(inner) => match __f(inner) { - Ok(iter) => { - let mut count: isize = 0; - for item in iter { - push.send(Ok($enum::$output(item))).ok(); - count += 1; - } - delta.send(count - 1).ok(); - } - Err(e) => { - push.send(Err($crate::PipelineError::StepError(Box::new(e)))) - .ok(); - delta.send(0).ok(); - } - }, - _ => { - push.send(Err($crate::PipelineError::TypeMismatch)).ok(); - delta.send(0).ok(); - } - } - }, - ) as $crate::SharedFlatFn<$enum>) - }}; -} - -/// Creates a `SinkFn` from a function that consumes a concrete value and returns `()`. -#[macro_export] -macro_rules! make_sink { - ($enum:ident, $func:tt, $input:ident) => {{ - let __f = $func; - Box::new( - move |data: $enum| -> ::std::result::Result<(), $crate::PipelineError> { - match data { - $enum::$input(x) => { - __f(x); - Ok(()) - } - _ => Err($crate::PipelineError::TypeMismatch), - } - }, - ) as Box ::std::result::Result<(), $crate::PipelineError> + Send> - }}; -} - -/// Creates a `SinkFn` from a fallible function that returns `Result<(), E>`. -#[macro_export] -macro_rules! make_sink_fallible { - ($enum:ident, $func:tt, $input:ident) => {{ - let __f = $func; - Box::new( - move |data: $enum| -> ::std::result::Result<(), $crate::PipelineError> { - match data { - $enum::$input(inner) => { - __f(inner).map_err(|e| $crate::PipelineError::StepError(Box::new(e))) - } - _ => Err($crate::PipelineError::TypeMismatch), - } - }, - ) as Box ::std::result::Result<(), $crate::PipelineError> + Send> - }}; -} - -/// Construit un `Pipeline` à partir d'une source, d'une liste de stages et d'un sink. -/// -/// Syntaxe : -/// ```ignore -/// make_pipeline! { -/// MyData, -/// source my_iter => Variant, // source non-fallible -/// source? my_iter => Variant, // source fallible (Result) -/// | func: In => Out, // transform 1→1 non-fallible -/// |? func: In => Out, // transform 1→1 fallible -/// || func: In => Out, // flat transform 1→N non-fallible -/// ||? func: In => Out, // flat transform 1→N fallible -/// sink my_func @ Variant, // sink non-fallible -/// sink? my_func @ Variant, // sink fallible -/// } -/// ``` -#[macro_export] -macro_rules! make_pipeline { - // ── Points d'entrée ────────────────────────────────────────────────── - - ($enum:ident, source $src:expr => $src_out:ident, $($rest:tt)*) => { - $crate::make_pipeline!(@build $enum, - { $crate::make_source!($enum, $src, $src_out) }, - [], - $($rest)*) - }; - ($enum:ident, source? $src:expr => $src_out:ident, $($rest:tt)*) => { - $crate::make_pipeline!(@build $enum, - { $crate::make_source_fallible!($enum, $src, $src_out) }, - [], - $($rest)*) - }; - - // ── Accumulation des stages ────────────────────────────────────────── - - // transform 1→1 non-fallible - (@build $enum:ident, $source:tt, [$($acc:tt)*], - | $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => { - $crate::make_pipeline!(@build $enum, $source, - [$($acc)* $crate::make_transform!($enum, $tf, $t_in, $t_out),], - $($rest)*) - }; - - // transform 1→1 fallible - (@build $enum:ident, $source:tt, [$($acc:tt)*], - |? $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => { - $crate::make_pipeline!(@build $enum, $source, - [$($acc)* $crate::make_transform_fallible!($enum, $tf, $t_in, $t_out),], - $($rest)*) - }; - - // flat transform 1→N non-fallible - (@build $enum:ident, $source:tt, [$($acc:tt)*], - || $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => { - $crate::make_pipeline!(@build $enum, $source, - [$($acc)* $crate::make_flat_transform!($enum, $tf, $t_in, $t_out),], - $($rest)*) - }; - - // flat transform 1→N fallible - (@build $enum:ident, $source:tt, [$($acc:tt)*], - ||? $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => { - $crate::make_pipeline!(@build $enum, $source, - [$($acc)* $crate::make_flat_transform_fallible!($enum, $tf, $t_in, $t_out),], - $($rest)*) - }; - - // ── Terminaison : sink ─────────────────────────────────────────────── - - (@build $enum:ident, $source:tt, [$($acc:tt)*], - sink $sink_fn:tt @ $sink_in:ident $(,)?) => { - $crate::Pipeline::new( - $source, - vec![$($acc)*], - $crate::make_sink!($enum, $sink_fn, $sink_in), - ) - }; - (@build $enum:ident, $source:tt, [$($acc:tt)*], - sink? $sink_fn:tt @ $sink_in:ident $(,)?) => { - $crate::Pipeline::new( - $source, - vec![$($acc)*], - $crate::make_sink_fallible!($enum, $sink_fn, $sink_in), - ) - }; -} - -/// Builds a typed `Pipe` — sourceless and sinkless. -/// -/// Syntax: -/// ```ignore -/// make_pipe! { -/// MyData : InType => OutType, -/// | func : InVariant => OutVariant, // transform 1→1 -/// |? func : InVariant => OutVariant, // transform 1→1 fallible -/// || func : InVariant => OutVariant, // flat transform 1→N -/// ||? func : InVariant => OutVariant, // flat transform 1→N fallible -/// } -/// ``` -#[macro_export] -macro_rules! make_pipe { - // ── Entry: first stage | ───────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - | $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_transform!($enum, $tf, $fi, $fo),], $fo, $($rest)*) - }; - // ── Entry: first stage |? ──────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - |? $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_transform_fallible!($enum, $tf, $fi, $fo),], $fo, $($rest)*) - }; - // ── Entry: first stage || ──────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - || $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_flat_transform!($enum, $tf, $fi, $fo),], $fo, $($rest)*) - }; - // ── Entry: first stage ||? ─────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - ||? $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_flat_transform_fallible!($enum, $tf, $fi, $fo),], $fo, $($rest)*) - }; - - // ── Accumulation: | ────────────────────────────────────────────────── - (@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident, - [$($acc:tt)*], $lo:ident, - | $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$($acc)* $crate::make_transform!($enum, $tf, $ti, $to),], $to, $($rest)*) - }; - // ── Accumulation: |? ───────────────────────────────────────────────── - (@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident, - [$($acc:tt)*], $lo:ident, - |? $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$($acc)* $crate::make_transform_fallible!($enum, $tf, $ti, $to),], $to, $($rest)*) - }; - // ── Accumulation: || ───────────────────────────────────────────────── - (@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident, - [$($acc:tt)*], $lo:ident, - || $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$($acc)* $crate::make_flat_transform!($enum, $tf, $ti, $to),], $to, $($rest)*) - }; - // ── Accumulation: ||? ──────────────────────────────────────────────── - (@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident, - [$($acc:tt)*], $lo:ident, - ||? $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$($acc)* $crate::make_flat_transform_fallible!($enum, $tf, $ti, $to),], $to, $($rest)*) - }; - - // ── Termination ─────────────────────────────────────────────────────── - (@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident, - [$($acc:tt)*], $lo:ident $(,)?) => { - $crate::Pipe::new( - vec![$($acc)*], - ::std::sync::Arc::new(|x: $in_ty| $enum::$fi(x)), - ::std::sync::Arc::new(|d: $enum| -> $out_ty { - if let $enum::$lo(x) = d { x } - else { ::std::unreachable!("unexpected pipeline data variant in make_pipe!") } - }), - ) - }; -} diff --git a/src/obipipeline/src/scheduler/mod.rs b/src/obipipeline/src/scheduler/mod.rs deleted file mode 100644 index 59d88bb6..00000000 --- a/src/obipipeline/src/scheduler/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -//! Scheduler: a channel/thread-based pipeline runtime with typed, composable -//! stages (`Pipe`), plus the macro-based `PipelineData`-enum runtime it grew -//! out of (`Pipeline`/`WorkerPool`). -//! -//! Submodules: [`error`] (`PipelineError`), [`types`] (function types, `Stage`), -//! [`runner`] (thread bodies), [`pool`] (`Pipeline`/`WorkerPool` scheduler -//! loop), [`pipe`] (`Pipe`/`PipeIter`), [`macros`] (`make_pipe!` and friends). - -mod error; -mod macros; -mod pipe; -mod pool; -mod runner; -mod types; - -pub use error::PipelineError; -pub use pipe::{Pipe, PipeIter}; -pub use pool::{Pipeline, WorkerPool}; -pub use types::{SharedFlatFn, SharedFn, SinkFn, SourceFn, Stage}; diff --git a/src/obipipeline/src/scheduler/pipe.rs b/src/obipipeline/src/scheduler/pipe.rs deleted file mode 100644 index 32e27a3c..00000000 --- a/src/obipipeline/src/scheduler/pipe.rs +++ /dev/null @@ -1,125 +0,0 @@ -use crossbeam_channel::{Receiver, bounded}; -use std::marker::PhantomData; -use std::sync::Arc; -use std::thread; - -use super::error::PipelineError; -use super::pool::{Pipeline, WorkerPool}; -use super::types::{SinkFn, SourceFn, Stage}; - -// ── Pipe ────────────────────────────────────────────────────────────────────── - -/// Typed, composable iterator transformer. -/// -/// A `Pipe` is a pure description of pipeline stages — no threads, -/// no channels, no scheduler. Call `.apply(iter, n_workers, capacity)` to start -/// execution and get back a `PipeIter`. -/// -/// Compose two pipes with `.then()`: the resulting `Pipe` holds the concatenated -/// stage list, so a single scheduler is created when `.apply()` is eventually called. -pub struct Pipe { - stages: Vec>, - wrap: Arc D + Send + Sync>, - unwrap: Arc Out + Send + Sync>, - _phantom: PhantomData<(In, Out)>, -} - -impl Pipe { - /// Build a `Pipe` from stages and wrap/unwrap converters. - /// Prefer the `make_pipe!` macro. - pub fn new( - stages: Vec>, - wrap: Arc D + Send + Sync>, - unwrap: Arc Out + Send + Sync>, - ) -> Self { - Self { - stages, - wrap, - unwrap, - _phantom: PhantomData, - } - } - - /// Concatenate stages from two pipes into one. - /// - /// Requires `Out` of `self` == `In` of `other`. The single scheduler - /// created at `.apply()` time sees the full combined stage list. - pub fn then(self, other: Pipe) -> Pipe { - Pipe { - stages: self.stages.into_iter().chain(other.stages).collect(), - wrap: self.wrap, - unwrap: other.unwrap, - _phantom: PhantomData, - } - } -} - -impl Pipe -where - D: Send + Sync + 'static, - In: Send + 'static, - Out: Send + 'static, -{ - /// Run the pipeline in a background thread; returns an iterator over the output. - pub fn apply( - self, - input: impl Iterator + Send + 'static, - n_workers: usize, - capacity: usize, - ) -> PipeIter { - let wrap = Arc::clone(&self.wrap); - let unwrap = Arc::clone(&self.unwrap); - - let mut iter = input; - let source: SourceFn = Box::new(move || match iter.next() { - Some(x) => Ok(wrap(x)), - None => Err(PipelineError::EndOfStream), - }); - - let (out_tx, out_rx) = bounded::(capacity); - let sink: SinkFn = Box::new(move |data: D| { - out_tx.send(unwrap(data)).map_err(|_| { - PipelineError::StepError(Box::new(std::io::Error::new( - std::io::ErrorKind::BrokenPipe, - "output channel closed", - ))) - }) - }); - - let pipeline = Pipeline::new(source, self.stages, sink); - let handle = thread::spawn(move || { - WorkerPool::new(pipeline, n_workers, capacity).run(); - }); - - PipeIter { - rx: out_rx, - handle: Some(handle), - } - } -} - -// ── PipeIter ────────────────────────────────────────────────────────────────── - -/// Iterator over the output of `Pipe::apply()`. -pub struct PipeIter { - rx: Receiver, - handle: Option>, -} - -impl Iterator for PipeIter { - type Item = Out; - - fn next(&mut self) -> Option { - self.rx.recv().ok() - } -} - -impl Drop for PipeIter { - fn drop(&mut self) { - // Drain buffered items so the scheduler can unblock if the channel is full. - while self.rx.try_recv().is_ok() {} - if let Some(h) = self.handle.take() { - let _ = h.join(); - } - } -} diff --git a/src/obipipeline/src/scheduler/pool.rs b/src/obipipeline/src/scheduler/pool.rs deleted file mode 100644 index d98bef3e..00000000 --- a/src/obipipeline/src/scheduler/pool.rs +++ /dev/null @@ -1,201 +0,0 @@ -use crossbeam_channel::{Receiver, Select, Sender, bounded}; - -use super::error::PipelineError; -use super::runner::{dispatch, sink_runner, source_runner, transform_runner}; -use super::types::{SinkFn, SourceFn, Stage, WorkerTask}; - -// ── Pipeline ────────────────────────────────────────────────────────────────── - -pub struct Pipeline { - source: SourceFn, - stages: Vec>, - sink: SinkFn, -} - -impl Pipeline { - pub fn new(source: SourceFn, stages: Vec>, sink: SinkFn) -> Self { - Self { - source, - stages, - sink, - } - } -} - -// ── WorkerPool ──────────────────────────────────────────────────────────────── - -pub struct WorkerPool { - pipeline: Pipeline, - handles: Vec>, - n_workers: usize, - capacity: usize, -} - -impl WorkerPool -where - DATA: Send + Sync + 'static, -{ - pub fn new(pipeline: Pipeline, n_workers: usize, capacity: usize) -> Self { - Self { - pipeline, - handles: Vec::new(), - n_workers, - capacity, - } - } - - pub fn run(mut self) { - let n = self.pipeline.stages.len(); - - // ── Canaux inter-stages ──────────────────────────────────────────── - // stage_txs[i] / stage_rxs[i] : sortie du stage i - let mut stage_txs: Vec>> = Vec::new(); - let mut stage_rxs: Vec>> = Vec::new(); - for _ in 0..n { - let (tx, rx) = bounded(self.capacity); - stage_txs.push(tx); - stage_rxs.push(rx); - } - - // ── Source thread ────────────────────────────────────────────────── - let (source_rx, src_handle) = source_runner(self.pipeline.source, self.capacity); - self.handles.push(src_handle); - - let stages = self.pipeline.stages; - - // ── Canal delta pour les flat stages ─────────────────────────────── - // Chaque flat worker envoie `N-1` ici après avoir poussé N items. - // Le scheduler ajuste `in_flight` en conséquence. - let (flat_delta_tx, flat_delta_rx) = bounded::(self.capacity); - - // ── Worker pool ──────────────────────────────────────────────────── - let (worker_tx, worker_rx): (Sender>, Receiver>) = - bounded(self.capacity); - - for _ in 0..self.n_workers { - self.handles.push(transform_runner( - worker_rx.clone(), - stages.iter().map(Stage::clone).collect(), - stage_txs.clone(), - flat_delta_tx.clone(), - )); - } - // Le scheduler ne tient plus flat_delta_tx : les workers le détiennent. - // On le drop ici pour que le canal se ferme quand les workers terminent. - drop(flat_delta_tx); - - // ── Sink thread ──────────────────────────────────────────────────── - let (sink_tx, sink_err_rx, sink_handle) = sink_runner(self.pipeline.sink, self.capacity); - self.handles.push(sink_handle); - - // ── Boucle principale ────────────────────────────────────────────── - // - // `in_flight` (isize) = nb d'items qui doivent encore atteindre le sink. - // Peut temporairement être négatif si un flat worker a poussé ses items - // avant que le scheduler ait reçu le delta correspondant. - // - // `flat_workers_active` = nb de flat workers en cours d'exécution. - // Empêche la terminaison prématurée quand in_flight vaut 0 mais qu'un - // flat worker n'a pas encore envoyé son delta. - // - // Priorités du Select biaisé (index le plus bas = priorité la plus haute) : - // 0 → sink_err_rx (arrêt immédiat sur erreur sink) - // 1 → flat_delta_rx (mettre à jour in_flight avant de dispatcher) - // 2..=n+1 → stage_rxs[n-1..0] (vider le pipeline en priorité) - // n+2 → source_rx (dernier recours : nouvelles données) - // - // Quand k = 0 : erreur du sink - // Quand k = 1 : delta d'un flat worker - // Quand 2 ≤ k ≤ n+1 : résultat du stage n+1-k - // Quand k = n+2 : item source - // - // Terminaison : source tarie ET in_flight == 0 ET aucun flat worker actif. - { - let mut source_done = false; - let mut in_flight: isize = 0; - let mut flat_workers_active: usize = 0; - - loop { - if source_done && in_flight == 0 && flat_workers_active == 0 { - break; - } - - let mut sel = Select::new_biased(); - sel.recv(&sink_err_rx); // index 0 - sel.recv(&flat_delta_rx); // index 1 - for rx in stage_rxs.iter().rev() { - sel.recv(rx); // indices 2..=n+1 - } - let src_idx = if !source_done { - Some(sel.recv(&source_rx)) // index n+2 - } else { - None - }; - - let oper = sel.select(); - let k = oper.index(); - - if k == 0 { - // ── Erreur du sink ──────────────────────────────────── - match oper.recv(&sink_err_rx) { - Ok(e) => { - eprintln!("Sink error: {:?}", e); - break; - } - Err(_) => break, - } - } else if k == 1 { - // ── Delta d'un flat worker ──────────────────────────── - // delta = N - 1 (N items poussés, 1 item consommé) - if let Ok(delta) = oper.recv(&flat_delta_rx) { - in_flight += delta; - flat_workers_active -= 1; - } - } else if src_idx == Some(k) { - // ── Nouvel item depuis la source ────────────────────── - match oper.recv(&source_rx) { - Ok(Ok(data)) => { - if n == 0 { - let _ = sink_tx.send(data); - } else { - in_flight += 1; - dispatch(data, 0, &stages, &worker_tx, &mut flat_workers_active); - } - } - Ok(Err(e)) => eprintln!("Source error: {:?}", e), - Err(_) => source_done = true, - } - } else { - // ── Résultat d'un stage intermédiaire ───────────────── - // k ∈ [2, n+1] → stage = n+1 - k - let stage = n + 1 - k; - match oper.recv(&stage_rxs[stage]) { - Ok(Ok(data)) => { - if stage == n - 1 { - in_flight -= 1; - let _ = sink_tx.send(data); - } else { - dispatch( - data, - stage + 1, - &stages, - &worker_tx, - &mut flat_workers_active, - ); - } - } - Ok(Err(e)) => eprintln!("Stage {} error: {:?}", stage, e), - Err(_) => break, - } - } - } - } - - drop(worker_tx); - drop(sink_tx); - - for h in self.handles { - let _ = h.join(); - } - } -} diff --git a/src/obipipeline/src/scheduler/runner.rs b/src/obipipeline/src/scheduler/runner.rs deleted file mode 100644 index 4d0202e8..00000000 --- a/src/obipipeline/src/scheduler/runner.rs +++ /dev/null @@ -1,118 +0,0 @@ -use crossbeam_channel::{Receiver, Sender, bounded}; -use std::thread; - -use super::error::PipelineError; -use super::types::{SinkFn, SourceFn, Stage, WorkerTask}; - -// ── Thread runners ──────────────────────────────────────────────────────────── - -pub(super) fn source_runner( - mut source: SourceFn, - capacity: usize, -) -> ( - Receiver>, - thread::JoinHandle<()>, -) -where - DATA: Send + Sync + 'static, -{ - let (tx, rx) = bounded(capacity); - let handle = thread::spawn(move || { - loop { - match source() { - Ok(data) => { - if tx.send(Ok(data)).is_err() { - break; - } - } - Err(PipelineError::EndOfStream) => break, - Err(e) => { - eprintln!("Source error: {:?}", e); - let _ = tx.send(Err(e)); - break; - } - } - } - }); - (rx, handle) -} - -/// Lance un thread worker du pool. -/// -/// Gère deux types de tâches : -/// - `Transform` : applique `f(data)` et envoie le résultat dans `result_tx`. -/// - `Flat` : appelle `f(data, &push_tx, &delta_tx)` ; la fonction elle-même -/// pousse ses items dans `push_tx` et envoie `N-1` dans `delta_tx`. -pub(super) fn transform_runner( - task_rx: Receiver>, - stages: Vec>, - stage_txs: Vec>>, - flat_delta_tx: Sender, -) -> thread::JoinHandle<()> -where - DATA: Send + Sync + 'static, -{ - thread::spawn(move || { - while let Ok(task) = task_rx.recv() { - match task { - WorkerTask::Transform(data, idx) => { - if let Stage::Transform(f) = &stages[idx] { - let _ = stage_txs[idx].send(f(data)); - } - } - WorkerTask::Flat(data, idx) => { - if let Stage::Flat(f) = &stages[idx] { - f(data, &stage_txs[idx], &flat_delta_tx); - } - } - } - } - }) -} - -/// Lance le thread sink. -pub(super) fn sink_runner( - sink: SinkFn, - capacity: usize, -) -> ( - Sender, - Receiver, - thread::JoinHandle<()>, -) -where - DATA: Send + Sync + 'static, -{ - let (data_tx, data_rx) = bounded(capacity); - let (err_tx, err_rx) = bounded(capacity); - let handle = thread::spawn(move || { - for data in data_rx { - if let Err(e) = sink(data) { - let _ = err_tx.send(e); - break; - } - } - }); - (data_tx, err_rx, handle) -} - -/// Envoie `data` au stage `stage_idx`. -/// Pour un `Transform`, empile une `WorkerTask::Transform`. -/// Pour un `Flat`, incrémente `flat_workers_active` et empile une `WorkerTask::Flat`. -#[inline] -pub(super) fn dispatch( - data: DATA, - stage_idx: usize, - stages: &[Stage], - worker_tx: &Sender>, - flat_workers_active: &mut usize, -) { - match &stages[stage_idx] { - Stage::Transform(_) => { - let _ = worker_tx.send(WorkerTask::Transform(data, stage_idx)); - } - Stage::Flat(_) => { - *flat_workers_active += 1; - let _ = worker_tx.send(WorkerTask::Flat(data, stage_idx)); - } - } -} diff --git a/src/obipipeline/src/scheduler/types.rs b/src/obipipeline/src/scheduler/types.rs deleted file mode 100644 index daeca394..00000000 --- a/src/obipipeline/src/scheduler/types.rs +++ /dev/null @@ -1,49 +0,0 @@ -use crossbeam_channel::Sender; -use std::sync::Arc; - -use super::error::PipelineError; - -// ── Function types ──────────────────────────────────────────────────────────── - -/// Fonction source : appelée répétitivement, retourne le prochain item ou EndOfStream. -/// `FnMut` car elle maintient un état interne (position dans l'itérateur). -pub type SourceFn = Box Result + Send>; - -/// Fonction sink : consomme un item final, peut échouer (erreur d'I/O, etc.). -pub type SinkFn = Box Result<(), PipelineError> + Send>; - -/// Fonction de transformation partagée entre workers via Arc. -pub type SharedFn = Arc Result + Send + Sync>; - -/// Fonction de transformation 1→N (flat map) partagée entre workers via Arc. -/// -/// La fonction reçoit l'item d'entrée, un canal `push` pour envoyer chaque item -/// produit, et un canal `delta` pour signaler au scheduler combien d'items -/// supplémentaires sont entrés dans le pipeline (N-1 si N items produits). -/// Elle doit appeler `delta.send(N - 1)` **après** avoir poussé tous les items. -pub type SharedFlatFn = - Arc>, &Sender) + Send + Sync>; - -// ── Stage enum ──────────────────────────────────────────────────────────────── - -/// Une étape du pipeline : transform classique (1→1) ou flat transform (1→N). -pub enum Stage { - Transform(SharedFn), - Flat(SharedFlatFn), -} - -impl Clone for Stage { - fn clone(&self) -> Self { - match self { - Stage::Transform(f) => Stage::Transform(Arc::clone(f)), - Stage::Flat(f) => Stage::Flat(Arc::clone(f)), - } - } -} - -// ── Worker task ─────────────────────────────────────────────────────────────── - -pub(super) enum WorkerTask { - Transform(D, usize), - Flat(D, usize), -} diff --git a/src/obipipeline/src/throttle.rs b/src/obipipeline/src/throttle.rs deleted file mode 100644 index 1dca89f6..00000000 --- a/src/obipipeline/src/throttle.rs +++ /dev/null @@ -1,106 +0,0 @@ -use std::sync::{Arc, Condvar, Mutex}; - -// ── Throttle ────────────────────────────────────────────────────────────────── - -/// Counting semaphore: limits how many items from a source are in-flight -/// simultaneously through the Flat stage of a pipeline. -/// -/// Slots are acquired in the source thread before an item is emitted, and -/// released when the corresponding `ThrottleGuard` is dropped (i.e. when the -/// Flat worker finishes processing the item). Acquisition must never happen -/// inside a worker — only in the source thread — to prevent deadlocks. -pub struct Throttle { - count: Mutex, - condvar: Condvar, - max: usize, -} - -impl Throttle { - pub fn new(max: usize) -> Self { - Self { - count: Mutex::new(0), - condvar: Condvar::new(), - max, - } - } - - pub fn acquire(&self) { - let mut count = self.count.lock().unwrap(); - while *count >= self.max { - count = self.condvar.wait(count).unwrap(); - } - *count += 1; - } - - fn release(&self) { - let mut count = self.count.lock().unwrap(); - *count -= 1; - self.condvar.notify_one(); - } -} - -impl Throttle { - /// Acquire one slot and return a guard that releases it on drop — - /// for callers with no natural "source iterator" to wrap via - /// [`throttle`] (e.g. bounding concurrency inside a `rayon` parallel - /// iterator's own closure, one call per item, rather than up front in - /// a single source thread). Blocks the calling thread until a slot is - /// free, same as [`throttle`]'s own per-item acquisition. - pub fn acquire_guard(self: &Arc) -> ThrottleGuard { - self.acquire(); - ThrottleGuard(Arc::clone(self)) - } -} - -// ── ThrottleGuard ───────────────────────────────────────────────────────────── - -/// RAII guard: releases one slot in the `Throttle` when dropped. -pub struct ThrottleGuard(Arc); - -impl Drop for ThrottleGuard { - fn drop(&mut self) { - self.0.release(); - } -} - -// ── Throttled ────────────────────────────────────────────────────────────── - -/// An item paired with its throttle guard. -/// -/// The guard keeps a slot acquired until this value is dropped. In a Flat -/// pipeline stage, carry the guard inside the worker closure until the item -/// is fully processed, then let it drop. -pub struct Throttled { - pub item: T, - pub guard: ThrottleGuard, -} - -// ── throttle() ──────────────────────────────────────────────────────────────── - -/// Wrap `source` so that at most `max_concurrent` items are emitted before -/// earlier ones have been fully processed (i.e. their `ThrottleGuard` dropped). -/// -/// Acquisition blocks the source thread until a slot is available. This must -/// be called in the source thread, never inside a pipeline worker. -/// -/// # Example -/// -/// ```ignore -/// let throttled = obipipeline::throttle(file_paths, n_workers - 1); -/// // Use `throttled` as the pipeline source; carry `item.guard` through the -/// // Flat stage and let it drop when the file is fully read. -/// ``` -pub fn throttle(source: I, max_concurrent: usize) -> impl Iterator> -where - I: Iterator, - I::Item: Send + 'static, -{ - let t = Arc::new(Throttle::new(max_concurrent)); - source.map(move |item| { - t.acquire(); - Throttled { - item, - guard: ThrottleGuard(Arc::clone(&t)), - } - }) -} diff --git a/src/obiskim/Cargo.toml b/src/obiskim/Cargo.toml index f754e2c7..6f52a9d0 100644 --- a/src/obiskim/Cargo.toml +++ b/src/obiskim/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "obiskim" -version = "1.4.9" +version = "1.4.10" edition = "2024" license = "CECILL-2.1" repository = "https://forge.metabarcoding.org/obi/obiskim" @@ -12,7 +12,7 @@ path = "src/main.rs" [dependencies] obikseq = { path = "../obikseq" } obiread = { path = "../obiread" } -obipipeline = { path = "../obipipeline" } +obipipeline = { version = "0.2", registry = "obi" } obisys = { path = "../obisys", default-features = false } obikindex = { path = "../obikindex", default-features = false } obikindexer = { path = "../obikindexer" } diff --git a/src/obiskim/src/cmd/query/mod.rs b/src/obiskim/src/cmd/query/mod.rs index 72bbc056..2c4131a0 100644 --- a/src/obiskim/src/cmd/query/mod.rs +++ b/src/obiskim/src/cmd/query/mod.rs @@ -286,13 +286,12 @@ pub fn run(args: QueryArgs) { let path_str = path.to_str().unwrap_or("").to_owned(); files_open.fetch_add(1, Ordering::Relaxed); let open_start = Instant::now(); - // Hard-exit on file-open failure (mirrors the previous behaviour): - // propagating this as a pipeline Err would hit a known scheduler - // hang on early stage errors (obipipeline::scheduler::WorkerPool::run - // breaks its main loop without unblocking the still-running source - // thread, so the final `h.join()` never returns) — worth fixing in - // obipipeline itself, but out of scope here; sidestepping it like the - // original code already did is the safe choice for this change. + // Hard-exit on file-open failure (mirrors the previous behaviour). + // The scheduler hang on early stage errors that once forbade + // returning a pipeline Err here is fixed in obipipeline (a stage + // error now stops the pipeline and comes out of the iterator as its + // last item); the hard exit is kept to preserve the message and exit + // code. let iter = read_sequence_chunks_sized(&path_str, chunk_bytes).unwrap_or_else(|e| { eprintln!("error opening {path_str}: {e}"); std::process::exit(1); @@ -346,6 +345,7 @@ pub fn run(args: QueryArgs) { let mut out = BufWriter::new(io::stdout()); for block in pipe.apply(path_source, n_workers, 2) { + let block = block.expect("pipeline error"); if !block.is_empty() { out.write_all(&block).expect("write error"); } diff --git a/src/obiskim/src/cmd/superkmer/mod.rs b/src/obiskim/src/cmd/superkmer/mod.rs index 51abdcc7..7e841f2d 100644 --- a/src/obiskim/src/cmd/superkmer/mod.rs +++ b/src/obiskim/src/cmd/superkmer/mod.rs @@ -65,6 +65,7 @@ pub fn run(args: SuperkmerArgs) { let mut out = BufWriter::new(io::stdout()); for batch in pipe.apply(path_source, n_workers, 1) { + let batch = batch.expect("pipeline error"); write_batch(batch, &mut out, partition_bits, k, m).expect("write error"); } out.flush().expect("flush error"); diff --git a/src/obiskio/src/unitig_index/reader.rs b/src/obiskio/src/unitig_index/reader.rs index 78ffa2d0..3f9150c2 100644 --- a/src/obiskio/src/unitig_index/reader.rs +++ b/src/obiskio/src/unitig_index/reader.rs @@ -268,7 +268,7 @@ impl UnitigFileReader { /// through the `Arc` on every step; no data is duplicated up front. pub fn iter_indexed_canonical_kmers_owned( self: &Arc, - ) -> impl Iterator + Send + 'static { + ) -> impl Iterator + Send + 'static + use<> { let this = Arc::clone(self); let k = this.k; let n = this.n_unitigs; @@ -290,6 +290,28 @@ impl UnitigFileReader { .map(move |(rank, kmer)| (kmer, chunk_id, rank)) }) } + + /// The canonical k-mers of [`iter_indexed_canonical_kmers_owned`](Self::iter_indexed_canonical_kmers_owned), + /// without their positions, grouped in batches of `size` (the last one may be shorter). Lazy: a batch is + /// read when it is asked for, so a pipeline stage can return this iterator and stream a whole file. + /// + /// # Panics + /// + /// Panics if `size` is `0`. + pub fn iter_canonical_kmer_batches_owned( + self: &Arc, + size: usize, + ) -> impl Iterator> + Send + 'static + use<> { + assert!(size > 0, "a k-mer batch needs at least one slot"); + let mut kmers = self + .iter_indexed_canonical_kmers_owned() + .map(|(kmer, _, _)| kmer); + std::iter::from_fn(move || { + let mut batch = Vec::with_capacity(size); + batch.extend(kmers.by_ref().take(size)); + (!batch.is_empty()).then_some(batch) + }) + } } /// Block offsets of a `.idx` file, read in place from its memory map: nothing