Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions slurm/p2/mine_round.sbatch
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@
# SUBMIT (per round — each is one CLAUDE.md §9.3 submit-ack; SYNC FIRST, STAGE SECOND, SUBMIT THIRD):
# ssh two 'bash -lc "cd ~/tbox-finder && git fetch origin && git checkout p2-10e && git reset --hard origin/p2-10e"'
# # …stage the checkpoint + genome dirs (see INPUT)…
# ssh two 'bash -lc "cd ~/tbox-finder && sbatch slurm/p2/mine_round.sbatch"'
# # ⚠ THREE REQUIRED EXPORTS — all `:?` below, and `sbatch --test-only` validates HEADERS ONLY,
# # so it catches none of them. ALIGN_TIMEOUT_S is forwarded to leg (c); a value absent here
# # cannot be recovered downstream, and the producer array would abort every one of its tasks.
# ssh two 'bash -lc "cd ~/tbox-finder && sbatch \
# --export=ALL,ARRAY_WIDTH=48,ALIGN_TIMEOUT_S=600,STRUCTURAL_YIELD_ACK=1 \
# slurm/p2/mine_round.sbatch"'
# PREFLIGHT: ssh two 'bash -lc "sbatch --test-only slurm/p2/mine_round.sbatch"'
# VERIFY (artifact-based; sacct off): the torch legs write stderr on success, so the per-round
# .err is NOT gated on zero bytes — gate on the DONE marker + the self-validating round report
Expand Down Expand Up @@ -124,6 +129,11 @@ fi
# (measured by mine_round_measure.sbatch); ARRAY_WIDTH is passed in, no silent default guess.
ROUND="${ROUND:-0}"
ARRAY_WIDTH="${ARRAY_WIDTH:?set ARRAY_WIDTH (the A10 Phase-2-pinned producer array width) via --export}"
# The producer array's per-candidate mlocarna bound. Required here too, and forwarded to leg (c)
# below: mine_round_producer.sbatch declares it `:?`, so a round that omitted it would submit an
# array whose every task aborts on the first line of its own config — a 48-task no-op that reports
# nothing. Exceeding the bound ⇒ no MSA ⇒ `unavailable` ⇒ SPARED (D14), never a mined negative.
ALIGN_TIMEOUT_S="${ALIGN_TIMEOUT_S:?set ALIGN_TIMEOUT_S (per-candidate mlocarna bound, s) via --export}"
# The structural-yield ack (header ⛔). Readiness passing is NOT permission to mine: with (b)
# and (c) unbacked, mining's conjunction cannot be satisfied by any candidate and this round's
# yield is provably 0 — ~8 GPU × 6 h to change nothing. Required, no default, so the no-op
Expand Down Expand Up @@ -182,7 +192,7 @@ PYTHONPATH=src python -m tbox_finder.mining.covariation_producer make-shards \
# LEG c: submit the decoupled producer array (CPU-only, partition=gpu no --gres); LEG d: the retrain,
# afterok-dependent on the whole array. Each is its own §9.3 artifact-verified job.
PRODUCER_JOB="$(sbatch --parsable --array="0-$((ARRAY_WIDTH - 1))" \
--export=ALL,ROUND="$ROUND",SHARD_DIR="$SHARD_DIR",ROUND_DIR="$ROUND_DIR" \
--export=ALL,ROUND="$ROUND",SHARD_DIR="$SHARD_DIR",ROUND_DIR="$ROUND_DIR",ALIGN_TIMEOUT_S="$ALIGN_TIMEOUT_S" \
slurm/p2/mine_round_producer.sbatch)"
echo "LEG c: submitted producer array job $PRODUCER_JOB (width $ARRAY_WIDTH)"
RETRAIN_JOB="$(sbatch --parsable --dependency="afterok:$PRODUCER_JOB" \
Expand Down
18 changes: 16 additions & 2 deletions slurm/p2/mine_round_measure.sbatch
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@
# # REAL split table by rsync from the laptop AFTER the reset (which reverts it to the pointer):
# # rsync -avzP data/processed/splits/split_assignments.parquet two:~/tbox-finder/data/processed/splits/
# # …create the two envs (above); stage the checkpoint + genome dirs + homolog DB (see INPUT)…
# ssh two 'bash -lc "cd ~/tbox-finder && sbatch slurm/p2/mine_round_measure.sbatch"'
# # ⚠ ALIGN_TIMEOUT_S is REQUIRED (`:?` below) and `--test-only` validates headers only, so it
# # catches nothing here. It also CENSORS this measurement — see the note at its declaration.
# ssh two 'bash -lc "cd ~/tbox-finder && sbatch \
# --export=ALL,ALIGN_TIMEOUT_S=600 slurm/p2/mine_round_measure.sbatch"'
# PREFLIGHT: ssh two 'bash -lc "cd ~/tbox-finder && sbatch --test-only slurm/p2/mine_round_measure.sbatch"'
# INPUT (staged by rsync — the ml/cluster checkout carries no DVC data):
# rsync -avzP data/processed/checkpoints/stage1_production/ two:~/tbox-finder/data/processed/checkpoints/stage1_production/
Expand Down Expand Up @@ -113,6 +116,16 @@ CTRL_MIN_PIDENT="40" # ignored on the nhmmer path; kept for the CLI-required a
CTRL_MIN_COV="0.5"
K_SAMPLE="50" # A10 Pin 1 bounded sample (K >= 50); accession-sorted, deterministic

# ⚠ THE ALIGN BOUND CENSORS THE MEASUREMENT THIS JOB EXISTS TO MAKE — required, no default, so the
# operator names the censoring point rather than inheriting one. `align-shard` bounds each mlocarna
# call (P3-15'-e-ii); any candidate exceeding ALIGN_TIMEOUT_S is recorded `align_timeout` with no
# MSA, so its true align wall is *right-censored* and every envelope derived downstream (core-h,
# wall/round) is a LOWER BOUND, not an estimate. This is not hypothetical: A10 Pin 2 priced the
# round from a K=50 sample whose max align was 47.5 s, and the full corpus then produced a single
# 8500 s alignment (depth 844) — 69 % of all align wall-clock in one candidate. Read any report
# this job writes as "≥", and re-derive the envelope from a completed full run, not from here.
ALIGN_TIMEOUT_S="${ALIGN_TIMEOUT_S:?set ALIGN_TIMEOUT_S (per-candidate mlocarna bound, s) via --export — it censors this measurement; see the note above}"

# NOTE: name this JOB_SCRATCH, never BUILD/HOST — `conda activate tbox-ml-dna` (the compiler
# toolchain) exports BUILD=HOST=x86_64-conda-linux-gnu, which would clobber a $BUILD scratch path
# the instant LEG a's env activates (job 789 died here: $BUILD/accessions.txt → a bad relative path).
Expand Down Expand Up @@ -196,7 +209,8 @@ command -v mlocarna >/dev/null || { echo "FATAL: mlocarna not on PATH — tbox-l
MLOCARNA_VERSION="$(mlocarna --version 2>&1 || true)"
echo "$MLOCARNA_VERSION" | grep -q "LocARNA 2.0.1" || { echo "FATAL: mlocarna != LocARNA 2.0.1 (ADR-0002 A13): $MLOCARNA_VERSION" >&2; exit 2; }
PYTHONHASHSEED=0 PYTHONPATH=src python -m tbox_finder.mining.covariation_producer align-shard \
--shard "$JOB_SCRATCH/sample.json" --workroot "$JOB_SCRATCH/work" --cpu 2
--shard "$JOB_SCRATCH/sample.json" --workroot "$JOB_SCRATCH/work" --cpu 2 \
--align-timeout-s "$ALIGN_TIMEOUT_S"

# ── PRODUCE Stage 3: SCORE (tbox-rscape) ──────────────────────────────────────────────────────────
conda activate tbox-rscape
Expand Down
21 changes: 18 additions & 3 deletions slurm/p2/mine_round_producer.sbatch
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,19 @@
# been measured (the K=50 Phase-1 job ran ONE task at --mem=128G), and lowering it on a guess would
# risk an OOM mid-array. Quote the wall from the run, never from A10's CPU-only arithmetic.
#
# ── SUBMITTED BY mine_round.sbatch (leg c) with --export ROUND/SHARD_DIR/ROUND_DIR and --array=0-(W-1).
# Standalone (debug) submit: `sbatch --array=0-0 --export=ALL,SHARD_DIR=…,ROUND_DIR=… mine_round_producer.sbatch`
# ⚠ ONE CANDIDATE CAN CONSUME THE WHOLE SHARD'S WALL — HENCE ALIGN_TIMEOUT_S (P3-15'-e-ii).
# Job 1205 (the full-corpus run) lost shard 016 to the 12 h wall having completed 1 of its 8
# alignable candidates: a single mlocarna ran 6h11m without finishing. Across the 47 shards that
# DID finish, 271 of 272 successful alignments took ≤ 353 s and one took 8500 s at depth 844 — that
# one candidate is 69 % of all align wall-clock in the corpus. LocARNA's cost climbs steeply in MSA
# depth (A10 Pin 2's own "scaling caveat"), so the distribution has no useful tail bound and a
# longer --time is not a fix. ALIGN_TIMEOUT_S bounds each alignment; exceeding it leaves no MSA ⇒
# `unavailable` ⇒ SPARED (ADR-0005 D14), which costs yield and never correctness.
#
# ── SUBMITTED BY mine_round.sbatch (leg c) with --export ROUND/SHARD_DIR/ROUND_DIR/ALIGN_TIMEOUT_S
# and --array=0-(W-1).
# Standalone (debug) submit:
# `sbatch --array=0-0 --export=ALL,SHARD_DIR=…,ROUND_DIR=…,ALIGN_TIMEOUT_S=600 mine_round_producer.sbatch`
# VERIFY (artifact-based, §9.3): every task's $ROUND_DIR/status/shard_<t>.SHARD_OK present + its .err
# zero bytes; the retrain leg (d) merges the per-shard status tables and fails loud on a gap.

Expand All @@ -55,6 +66,10 @@ cd "$REPO"
TASK="${SLURM_ARRAY_TASK_ID:-0}"
SHARD_DIR="${SHARD_DIR:?set SHARD_DIR (the make-shards output dir) via --export}"
ROUND_DIR="${ROUND_DIR:?set ROUND_DIR via --export}"
# Per-candidate mlocarna wall-clock bound; exceeding it ⇒ no MSA ⇒ `unavailable` ⇒ SPARED (D14).
# Required, no default: it decides which candidates yield a consensus, so the round names it and
# `--test-only` cannot catch its absence (headers only) — the `:?` is what actually catches it.
ALIGN_TIMEOUT_S="${ALIGN_TIMEOUT_S:?set ALIGN_TIMEOUT_S (per-candidate mlocarna bound, s) via --export}"
# Zero-pad the task id to match make-shards' `shard_{i:03d}.json` (covariation_producer.py:199).
# Build these paths with plain interpolation, NOT `$(printf …)`: the tracked-path gate
# (tests/unit/test_sbatch_rm_targets.py) cannot resolve a command substitution, so a `rm` on a
Expand Down Expand Up @@ -101,7 +116,7 @@ conda activate tbox-locarna
command -v mlocarna >/dev/null || { echo "FATAL: mlocarna not on PATH — tbox-locarna not created?" >&2; exit 2; }
mlocarna --version 2>&1 | grep -q "LocARNA 2.0.1" || { echo "FATAL: mlocarna != LocARNA 2.0.1 (ADR-0002 A13)" >&2; exit 2; }
PYTHONHASHSEED=0 PYTHONPATH=src python -m tbox_finder.mining.covariation_producer align-shard \
--shard "$SHARD" --workroot "$BUILD/work" --cpu 2
--shard "$SHARD" --workroot "$BUILD/work" --cpu 2 --align-timeout-s "$ALIGN_TIMEOUT_S"

# ── PROMOTE the per-candidate #=GC SS_cons consensus OUT of node-local scratch ────────────────────
# ADR-0006 A4 makes this artifact load-bearing for criterion (b) as well as (a): (b)'s
Expand Down
75 changes: 72 additions & 3 deletions src/tbox_finder/mining/covariation_producer.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
from pathlib import Path
from typing import Any

from tbox_finder.mining.homolog_db import ToolTimeoutError, assert_usable_timeout
from tbox_finder.mining.homolog_msa import (
BLAST_PREFIX,
FM_INDEX,
Expand Down Expand Up @@ -307,8 +308,24 @@ def search_shard(
# ═════════════════════════════════════════════════════════════════════════════
# Stage 2 — ALIGN (runs in tbox-locarna; mlocarna comparative consensus)
# ═════════════════════════════════════════════════════════════════════════════
def _discard_msa(msa: Path) -> None:
"""Make "a failed align leaves no MSA" true **by construction** rather than by convention.

Every non-success branch of :func:`align_shard` relies on the absence of ``msa.sto`` to reach
``unavailable`` ⇒ spared, but that absence was only ever an accident of the workroot being
freshly created per array task. A stale MSA under a re-used workdir would be promoted by the
sbatch (which tests ``[ -s .../msa.sto ]``, not this run's verdict) and scored as if this run
had produced it — a *fabricated* consensus for a candidate whose alignment did not finish.
"""
msa.unlink(missing_ok=True)


def align_shard(
specs: Sequence[CandidateSpec], *, workroot: str | Path, cpu: int = 2
specs: Sequence[CandidateSpec],
*,
workroot: str | Path,
cpu: int = 2,
align_timeout_s: float,
) -> list[dict[str, Any]]:
"""mlocarna-align each candidate whose search stage found a **sufficient** homolog set.

Expand All @@ -317,13 +334,25 @@ def align_shard(
reads ``unavailable`` for it (⇒ spared). An ``align_candidate`` :class:`HomologMsaError` (e.g.
mlocarna emitted no ``#=GC SS_cons``) is recorded ``aligned=False``, not raised, for the same
fail-closed reason. Writes ``<workdir>/msa.sto`` on success and ``<workdir>/align.json`` always.

``align_timeout_s`` is **keyword-required with no default** (the ADR-0006 A4 rule-parameter
shape): it decides which candidates get a consensus at all, so every caller must name it and
the round must record it. A candidate whose mlocarna exceeds it is recorded
``reason="align_timeout"`` and, like the other two spare branches, leaves no MSA behind ⇒
``unavailable`` ⇒ **spared**. This is the branch that exists because one candidate in job 1205
ran 6h11m without finishing and took its whole 20-candidate shard down with the 12 h wall.
"""
# Validate the bound ONCE, up front — not on the first sufficient candidate. A shard whose
# bound is unusable must die before the run, not after however many alignments happened to
# precede the first one that would have used it.
assert_usable_timeout(align_timeout_s)
rows: list[dict[str, Any]] = []
for spec in specs:
wd = candidate_workdir(workroot, spec.candidate_id)
search = _read_json(wd / "search.json")
row: dict[str, Any] = {CANDIDATE_ID_KEY: spec.candidate_id}
if not search.get("sufficient"):
_discard_msa(wd / MSA_FILENAME) # the THIRD spare branch — same absence, same reason
row.update(aligned=False, reason="insufficient_homologs", align_wall_s=0.0)
(wd / "align.json").write_text(
json.dumps(row, indent=2, sort_keys=True) + "\n", encoding="utf-8"
Expand All @@ -338,10 +367,15 @@ def align_shard(
out_sto=wd / MSA_FILENAME,
work_dir=wd / "align",
cpu=cpu,
timeout_s=align_timeout_s,
)
row["aligned"] = True
except ToolTimeoutError as exc:
row.update(aligned=False, reason="align_timeout", error=str(exc))
_discard_msa(wd / MSA_FILENAME)
except HomologMsaError as exc:
row.update(aligned=False, reason="align_failed", error=str(exc))
_discard_msa(wd / MSA_FILENAME)
row["align_wall_s"] = round(time.perf_counter() - t0, 4)
(wd / "align.json").write_text(
json.dumps(row, indent=2, sort_keys=True) + "\n", encoding="utf-8"
Expand Down Expand Up @@ -600,11 +634,36 @@ def _cmd_search_shard(args: argparse.Namespace) -> int:
return 0


def _usable_timeout_arg(text: str) -> float:
"""argparse type for ``--align-timeout-s``: a positive, FINITE number of seconds.

``type=float`` alone accepts ``nan`` and ``inf``. ``nan`` is the dangerous one — every
comparison against it is False, so it slips past a ``<= 0`` check and
``communicate(timeout=nan)`` never fires: the bound would be declared, recorded in the round's
provenance, and completely inert. Refusing it here means the shard dies at argparse, before the
~37 min search stage, rather than after it.
"""
try:
value = float(text)
except ValueError:
raise argparse.ArgumentTypeError(f"not a number: {text!r}") from None
try:
assert_usable_timeout(value)
except ValueError as exc:
raise argparse.ArgumentTypeError(str(exc)) from None
return value


def _cmd_align_shard(args: argparse.Namespace) -> int:
specs = read_candidate_manifest(args.shard)
rows = align_shard(specs, workroot=args.workroot, cpu=args.cpu)
rows = align_shard(
specs, workroot=args.workroot, cpu=args.cpu, align_timeout_s=args.align_timeout_s
)
n_aln = sum(1 for r in rows if r.get("aligned"))
print(f"align-shard: {n_aln}/{len(rows)} candidates aligned")
n_out = sum(1 for r in rows if r.get("reason") == "align_timeout")
# Report the timed-out count on its own: it is the one non-success branch that is a *choice*
# this run made (the bound), so a silent zero and a silent five must not read the same.
print(f"align-shard: {n_aln}/{len(rows)} candidates aligned ({n_out} timed out ⇒ spared)")
return 0


Expand Down Expand Up @@ -671,6 +730,16 @@ def main(argv: Sequence[str] | None = None) -> int:
p_align.add_argument("--shard", required=True)
p_align.add_argument("--workroot", required=True)
p_align.add_argument("--cpu", type=int, default=2)
# Keyword-required, NO default (the ADR-0006 A4 rule-parameter shape): the bound decides which
# candidates produce a consensus, so a caller that forgets it must fail loudly at argparse
# rather than silently inherit an unbounded align and re-run job 1205's 12 h shard death.
p_align.add_argument(
"--align-timeout-s",
type=_usable_timeout_arg,
required=True,
help="per-candidate mlocarna wall-clock bound in seconds; exceeding it ⇒ unavailable "
"⇒ spared (ADR-0005 D14). No default — the round must name it.",
)
p_align.set_defaults(func=_cmd_align_shard)

p_score = sub.add_parser("score-shard", help="STAGE 3 (tbox-rscape): covariation status")
Expand Down
Loading
Loading