Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Scan package archives across cores instead of one at a time (#9024)
Daniel Han47dcad27c099
diff --git a/scripts/scan_packages.py b/scripts/scan_packages.pyindex 5a86bd7938e..fea7b1e3402 100644--- a/scripts/scan_packages.py+++ b/scripts/scan_packages.py@@ -57,9 +57,11 @@ Exit codes:import argparseimport atexitimport bisect+import contextlibimport hashlibimport ioimport json+import multiprocessingimport osimport reimport shutil@@ -1907,6 +1909,25 @@ def scan_archive(archive_path: str, package: str) -> list[Finding]:return findings+def _scan_one(task: tuple[str, str]) -> tuple[str, list[Finding]]:+ """Pool worker: ``scan_archive`` over one (archive_path, package) pair.++ Module-level and pickle-clean on purpose, so the pool can use the "spawn"+ start method. ``Finding`` is a plain dataclass, so results travel as-is.++ The archive-limit ``[WARN]`` lines go to stderr from deep inside+ ``iter_archive_files``. Left alone they land in the parent's stream whenever+ the worker happens to reach them, so two runs of the same input produce logs+ that differ only in where those lines sit. They are returned instead and the+ caller prints them in task order, which keeps the whole report reproducible.+ """+ archive_path, package = task+ buf = io.StringIO()+ with contextlib.redirect_stderr(buf):+ findings = scan_archive(archive_path, package)+ return buf.getvalue(), findings++# Download packages@@ -3154,6 +3175,12 @@ def main() -> int:action = "store_true",help = "Also download and scan transitive dependencies (full dependency tree)",)+ parser.add_argument(+ "--jobs",+ type = int,+ default = 0,+ help = "Archive-scanning worker processes (default: min(4, cpu count); 1 = serial)",+ )parser.add_argument("--fix",action = "store_true",@@ -3250,6 +3277,11 @@ def main() -> int:tmpdir = tempfile.mkdtemp(prefix = "pth_scan_")atexit.register(lambda d = tmpdir: shutil.rmtree(d, ignore_errors = True))download_errors: list[str] = []+ # Scan-side failures, kept beside the download ones so both reach the SCAN+ # INCOMPLETE block below. A stall has to exit 2 like any other partial scan:+ # exit 1 is reserved for "non-baselined CRITICAL or HIGH findings detected",+ # so exiting 1 on a dead worker reports an infrastructure failure as a threat.+ scan_errors: list[str] = []try:downloaded, download_errors = download_packages(specs,@@ -3258,15 +3290,57 @@ def main() -> int:)print(f" Downloaded {len(downloaded)} archive(s).")- for spec, archive_path in downloaded:- pkg_name = _extract_pkg_name(spec)- findings = scan_archive(archive_path, pkg_name)- all_findings.extend(findings)- # Delete archive immediately after scanning- try:- os.remove(archive_path)- except OSError:- pass+ # Scanning, not downloading, is the cost here: on the hf-stack shard the+ # `pip download` above takes 9.7s and the pass below took 306s of a 316s+ # total. It is pure CPU (regex over decompressed archive members) and+ # every archive is independent, so it fans out across cores.+ #+ # `imap` with chunksize=1 yields in submission order, so the findings+ # list is assembled in exactly the order the serial loop produced it and+ # the report is unchanged. chunksize=1 is also what makes `next(timeout=)`+ # available at all: above 1, CPython's Pool.imap returns a bare generator+ # with no timeout support (Lib/multiprocessing/pool.py).+ tasks = [(archive_path, _extract_pkg_name(spec)) for spec, archive_path in downloaded]+ jobs = args.jobs if args.jobs else max(1, min(4, os.cpu_count() or 1))+ if jobs > 1 and len(tasks) > 1:+ print(f" Scanning {len(tasks)} archive(s) across {jobs} workers...")+ ctx = multiprocessing.get_context("spawn")+ with ctx.Pool(processes = jobs) as pool:+ results = pool.imap(_scan_one, tasks, chunksize = 1)+ for i, (archive_path, _pkg) in enumerate(tasks):+ try:+ captured, findings = results.next(timeout = 900)+ except multiprocessing.TimeoutError:+ # A worker died (OOM or segfault on a hostile archive).+ # Without this the iterator blocks forever and the job+ # only ends at the workflow timeout, with no reason given.+ #+ # Recorded rather than raised: `raise SystemExit(<str>)`+ # prints the string and exits 1, and 1 already means+ # "CRITICAL or HIGH findings detected". Routing it here+ # gets the SCAN INCOMPLETE report and exit 2, which is+ # what a partial scan is supposed to return.+ scan_errors.append(+ f"scan stalled after {i}/{len(tasks)} archive(s) with no "+ f"result for 900s; a pool worker most likely died"+ )+ break+ if captured:+ sys.stderr.write(captured)+ all_findings.extend(findings)+ # Delete archive immediately after scanning+ try:+ os.remove(archive_path)+ except OSError:+ pass+ else:+ for archive_path, pkg_name in tasks:+ all_findings.extend(scan_archive(archive_path, pkg_name))+ # Delete archive immediately after scanning+ try:+ os.remove(archive_path)+ except OSError:+ passfinally:shutil.rmtree(tmpdir, ignore_errors = True)@@ -3307,15 +3381,15 @@ def main() -> int:# Surface pip-download failures BEFORE the exit code so a partial download# can't masquerade as "0 findings, all clean" (silent-failure hardening 4).# Also keeps us from writing a baseline from an incomplete scan.- if download_errors:+ incomplete_errors = download_errors + scan_errors+ if incomplete_errors:print(f"\n {'=' * 72}\n"- f" SCAN INCOMPLETE: {len(download_errors)} pip download "- f"failure(s):\n"+ f" SCAN INCOMPLETE: {len(incomplete_errors)} failure(s):\n"f" {'=' * 72}",file = sys.stderr,)- for err in download_errors:+ for err in incomplete_errors:print(f" [ERROR] {err}", file = sys.stderr)print(" Refusing to report 'all clean' on a partial scan; exiting 2.",diff --git a/tests/security/test_scan_packages.py b/tests/security/test_scan_packages.pyindex 4554a08b7f8..03af6c35018 100644--- a/tests/security/test_scan_packages.py+++ b/tests/security/test_scan_packages.py@@ -1898,3 +1898,153 @@ def test_the_duplicate_check_sees_through_normalization(tmp_path):path = tmp_path / "baseline.json"path.write_text(json.dumps({"version": 1, "entries": entries}))assert len(sp._load_baseline(str(path))) == 1+++def test_the_pool_worker_returns_what_the_serial_call_returns():+ """`_scan_one` is the only thing the pool runs, so it must be `scan_archive`.++ It also swallows the archive-limit `[WARN]` lines and hands them back, so the+ caller can print them in task order instead of whenever a worker happened to+ reach them. Pin both halves: identical findings, and stderr captured rather+ than leaked.+ """+ for name in ("malicious_wheel.whl", "clean_wheel.whl", "malicious_sdist.tar.gz"):+ archive = str(FIXTURES / name)+ captured, findings = sp._scan_one((archive, "fixture"))+ assert findings == sp.scan_archive(archive, "fixture"), name+ assert isinstance(captured, str), name+++def _oversized_member_wheel(path):+ """A wheel whose declared member size trips the scanner's per-file cap.++ Written rather than committed: the member is 70 MB of zeros, which deflates+ to a few KB, so the archive on disk is small but `info.file_size` is well+ over HARD_MAX_FILE_BYTES and `iter_archive_files` emits its `[WARN]` skip.+ That warning is the thing `_scan_one` captures and the caller replays in+ order, so without it in the corpus the stderr half of the comparison below+ would be comparing two empty strings.+ """+ import zipfile++ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:+ zf.writestr("pkg/huge.py", b"\0" * (sp.HARD_MAX_FILE_BYTES + 4096))+ zf.writestr("pkg/__init__.py", "x = 1\n")+ return path+++def test_scanning_in_parallel_finds_exactly_what_scanning_in_series_finds(+ tmp_path, monkeypatch, capsys+):+ """The whole safety argument for the pool is that it changes nothing.++ Drives `main()` over the same corpus at `--jobs 1` (serial branch) and+ `--jobs 4` (pool branch) and demands byte-identical stdout and stderr.+ `download_packages` is stubbed because the parallel loop sits behind it and+ the real one needs PyPI.++ The corpus is deliberately wide rather than the three committed fixtures:++ - 24 archives, so completion order across 4 workers genuinely diverges from+ submission order. `imap(chunksize=1)` yields in submission order, so this+ is what makes the ordering claim real -- with only three instant archives+ `imap_unordered` returns them in order anyway and the check proves nothing.+ - one archive that trips the per-file size cap, so there is a `[WARN]` line+ on stderr to compare. Otherwise the stderr assertion compares "" to "".+ """+ import shutil++ def run(jobs):+ # main() deletes each archive once scanned, so each arm gets its own copies.+ stage = tmp_path / f"stage{jobs}"+ stage.mkdir()+ copies = []+ for i in range(24):+ src = ("malicious_wheel.whl", "clean_wheel.whl", "malicious_sdist.tar.gz")[i % 3]+ dest = stage / f"pkg{i:02d}-{src}"+ shutil.copy(FIXTURES / src, dest)+ copies.append((f"pkg{i:02d}", str(dest)))+ copies.append(("oversized", str(_oversized_member_wheel(stage / "oversized.whl"))))++ monkeypatch.setattr(sp, "download_packages", lambda *a, **k: (copies, []))+ monkeypatch.setattr(+ sys,+ "argv",+ ["scan_packages.py", "--no-baseline", "--jobs", str(jobs)]+ + [name for name, _ in copies],+ )+ capsys.readouterr()+ rc = sp.main()+ captured = capsys.readouterr()+ return rc, captured.out, captured.err++ rc_serial, out_serial, err_serial = run(1)+ rc_parallel, out_parallel, err_parallel = run(4)++ # The pool branch prints one extra progress banner. That line is the only+ # licensed difference; everything below it is the report and must match.+ banner = re.compile(r"^ Scanning \d+ archive\(s\) across \d+ workers\.\.\.\n", re.M)+ assert banner.search(out_parallel), "the pool branch did not run"+ out_parallel = banner.sub("", out_parallel)++ assert out_serial == out_parallel, "parallel scan reported different findings"+ assert err_serial == err_parallel, "parallel scan reported different warnings"+ assert rc_serial == rc_parallel+ # Guard against either half being trivially empty.+ assert "CRITICAL" in out_serial+ assert "[WARN]" in err_serial+++def test_a_stalled_pool_exits_2_not_1(tmp_path, monkeypatch, capsys):+ """A dead worker is an incomplete scan, and incomplete scans exit 2.++ Exit 1 already means "non-baselined CRITICAL or HIGH findings detected", so a+ stall that exits 1 reports an infrastructure failure as a detected threat, and+ skips the SCAN INCOMPLETE report that tells the operator coverage was lost.++ The first version of the pool raised `SystemExit(<message>)`, which does exactly+ that: CPython prints a non-integer SystemExit value and exits 1.+ """+ import shutil++ stage = tmp_path / "archives"+ stage.mkdir()+ copies = []+ for i, name in enumerate(("malicious_wheel.whl", "clean_wheel.whl")):+ dest = stage / f"pkg{i}-{name}"+ shutil.copy(FIXTURES / name, dest)+ copies.append((f"pkg{i}", str(dest)))++ monkeypatch.setattr(sp, "download_packages", lambda *a, **k: (copies, []))++ class _StalledResults:+ def next(self, timeout = None):+ raise sp.multiprocessing.TimeoutError()++ class _StalledPool:+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def imap(self, *a, **k):+ return _StalledResults()++ monkeypatch.setattr(+ sp.multiprocessing,+ "get_context",+ lambda _method: type("C", (), {"Pool": lambda _s, processes = None: _StalledPool()})(),+ )+ monkeypatch.setattr(+ sys,+ "argv",+ ["scan_packages.py", "--no-baseline", "--jobs", "4", "pkg0", "pkg1"],+ )++ rc = sp.main()+ captured = capsys.readouterr()++ assert rc == 2, f"a stalled scan must exit 2 (incomplete), got {rc}"+ assert "SCAN INCOMPLETE" in captured.err+ assert "scan stalled" in captured.err