Coverage for src/romfarmer/planner/passes/sample.py: 64%
14 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""sample pass — deterministic random subset for test builds.
3``romfarmer build run … --test-sample N --seed S`` sets ``manifest.sample_n``
4and ``manifest.sample_seed``. Selection is by ``sorted(unit_id)`` under a
5seeded ``random.Random`` so the same (catalog, seed) always yields the same
6subset — the plan stays a pure function of (manifest, catalog).
8Runs last, after every real selection pass, so the sample is drawn from what
9the build would actually have produced.
10"""
12from __future__ import annotations
14import random
15from typing import TYPE_CHECKING
17from romfarmer.ir.catalog import Catalog, PassResult, PassTrace, UnitId
19if TYPE_CHECKING:
20 from romfarmer.analysis.knowledge import KnowledgeBase
21 from romfarmer.ir.manifest import BuildManifest
22 from romfarmer.planner.costmodel import CostModel
24PASS_NAME = "sample"
27def run(
28 catalog: Catalog,
29 manifest: BuildManifest,
30 kb: KnowledgeBase,
31 cost_model: CostModel,
32) -> PassResult:
33 """Keep a seeded random sample of ``manifest.sample_n`` units."""
34 n = manifest.sample_n
35 if n is None or n >= len(catalog.units):
36 return PassResult(catalog=catalog, trace=PassTrace(pass_name=PASS_NAME, removed=()))
38 ordered = sorted(catalog.units, key=lambda u: str(u.unit_id))
39 rng = random.Random(manifest.sample_seed)
40 chosen: set[UnitId] = {u.unit_id for u in rng.sample(ordered, n)}
41 removed = tuple(
42 (u.unit_id, f"sample: not in --test-sample {n} (seed={manifest.sample_seed})")
43 for u in ordered
44 if u.unit_id not in chosen
45 )
46 return PassResult(
47 catalog=catalog.keep(chosen),
48 trace=PassTrace(pass_name=PASS_NAME, removed=removed),
49 )