Repository navigation
Phase 17: forgelm audit --workers N + determinism contract #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,12 +11,13 @@ | |
|
|
||
| import json | ||
| import logging | ||
| import multiprocessing | ||
| import os | ||
| import tempfile | ||
| from dataclasses import asdict | ||
| from datetime import datetime, timezone | ||
| from pathlib import Path | ||
| from typing import Any, Dict, List, Optional | ||
| from typing import Any, Dict, List, Optional, Tuple | ||
|
|
||
| from ._croissant import _build_croissant_metadata | ||
|
|
||
|
|
@@ -179,6 +180,20 @@ def _atomic_write_json(target: Path, payload: Dict[str, Any]) -> None: | |
| pass | ||
|
|
||
|
|
||
| def _process_split_for_pool( | ||
| args_tuple: Tuple[str, Path, Dict[str, Any]], | ||
| ): | ||
| """Module-level wrapper: dispatches to :func:`_process_split` from a tuple. | ||
|
|
||
| ``multiprocessing.Pool.map`` requires the worker callable + its arguments | ||
| to be picklable. Lambdas and ``functools.partial`` over keyword-only | ||
| args don't pickle cleanly across spawn-method workers, so we accept a | ||
| single positional tuple and unpack the kwargs inside the worker. | ||
| """ | ||
| split_name, path, kwargs = args_tuple | ||
| return _process_split(split_name, path, **kwargs) | ||
|
|
||
|
|
||
| def audit_dataset( # NOSONAR — cognitive complexity is inherent to the audit orchestration logic; extraction would fragment cohesive pipeline steps | ||
| source: str, | ||
| *, | ||
|
|
@@ -191,6 +206,7 @@ def audit_dataset( # NOSONAR — cognitive complexity is inherent to the audit | |
| enable_pii_ml: bool = False, | ||
| pii_ml_language: str = "en", | ||
| emit_croissant: bool = False, | ||
| workers: int = 1, | ||
| ) -> AuditReport: | ||
| """Run the audit pipeline over a JSONL file or split-keyed directory. | ||
|
|
||
|
|
@@ -233,6 +249,15 @@ def audit_dataset( # NOSONAR — cognitive complexity is inherent to the audit | |
| enable_quality_filter: Phase 12 opt-in flag — when ``True``, run | ||
| the heuristic quality checks (Gopher / C4 / RefinedWeb-style) | ||
| and surface findings under ``quality_summary``. | ||
| workers: Phase 17 — number of worker processes used for the | ||
| split-level pipeline. ``1`` (default) keeps the pre-Phase-17 | ||
| single-process behaviour exactly. ``> 1`` distributes the | ||
| per-split processing over ``min(workers, len(splits))`` | ||
| ``multiprocessing.Pool`` workers; the merge step that builds | ||
| the final report stays single-threaded so the determinism | ||
| contract (byte-identical JSON across worker counts) is | ||
| preserved. Speed-up scales with the number of *splits*, not | ||
| row count — single-split corpora ignore values >1. | ||
|
|
||
| Returns: | ||
| :class:`AuditReport`. JSON-serialize via ``asdict(report)``. | ||
|
|
@@ -260,6 +285,9 @@ def audit_dataset( # NOSONAR — cognitive complexity is inherent to the audit | |
| # for per-row resilience on pathological strings). | ||
| _require_presidio(language=pii_ml_language) | ||
|
|
||
| if not isinstance(workers, int) or isinstance(workers, bool) or workers < 1: | ||
| raise ValueError(f"workers must be a positive integer; got {workers!r}.") | ||
|
|
||
| splits_paths, resolution_notes = _resolve_input(source) | ||
|
|
||
| splits_info: Dict[str, Dict[str, Any]] = {} | ||
|
|
@@ -276,18 +304,61 @@ def audit_dataset( # NOSONAR — cognitive complexity is inherent to the audit | |
| parse_errors_total = 0 | ||
| decode_errors_total = 0 | ||
|
|
||
| for split_name, path in splits_paths.items(): | ||
| outcome = _process_split( | ||
| split_name, | ||
| path, | ||
| near_dup_threshold=near_dup_threshold, | ||
| dedup_method=dedup_method, | ||
| minhash_jaccard=minhash_jaccard, | ||
| minhash_num_perm=minhash_num_perm, | ||
| enable_quality_filter=enable_quality_filter, | ||
| enable_pii_ml=enable_pii_ml, | ||
| pii_ml_language=pii_ml_language, | ||
| # Determinism contract: regardless of ``workers``, every aggregate is | ||
| # built up by walking the splits in the exact order ``splits_paths`` | ||
| # yields them. Multiprocessing only changes how the per-split outcomes | ||
| # are *computed*; the merge step below is single-threaded so byte- | ||
| # equivalent output is guaranteed across worker counts. See the | ||
| # ``test_data_audit_workers.py`` regression suite for the test that | ||
| # pins this invariant. | ||
| split_kwargs: Dict[str, Any] = { | ||
| "near_dup_threshold": near_dup_threshold, | ||
| "dedup_method": dedup_method, | ||
| "minhash_jaccard": minhash_jaccard, | ||
| "minhash_num_perm": minhash_num_perm, | ||
| "enable_quality_filter": enable_quality_filter, | ||
| "enable_pii_ml": enable_pii_ml, | ||
| "pii_ml_language": pii_ml_language, | ||
| } | ||
| effective_workers = min(workers, len(splits_paths)) if splits_paths else 1 | ||
| if effective_workers > 1: | ||
| # Pool.map preserves input order so ``outcomes`` lines up with | ||
| # ``splits_paths.items()`` 1:1. We bound the pool to | ||
| # ``len(splits_paths)`` — extra workers would idle since the unit | ||
| # of work is one split. | ||
| # | ||
| # Wave 2a Round-1 review (F-26-03): pin the start method to | ||
| # ``"spawn"`` so the determinism contract is platform-independent. | ||
| # ``Pool()`` defaults to fork on Linux + spawn on macOS / Windows; | ||
| # Linux CI never exercises the spawn path otherwise. Spawn also | ||
| # gives every worker a fresh interpreter (no shared | ||
| # langdetect.DetectorFactory state, no copied open file handles) | ||
| # which is exactly what the byte-identical contract requires. | ||
| logger.info( | ||
| "audit: spawning %d worker process(es) over %d split(s)", | ||
| effective_workers, | ||
| len(splits_paths), | ||
| ) | ||
| ctx = multiprocessing.get_context("spawn") | ||
| pool_args = [(name, path, split_kwargs) for name, path in splits_paths.items()] | ||
| with ctx.Pool(effective_workers) as pool: | ||
| try: | ||
| outcomes_list = pool.map(_process_split_for_pool, pool_args) | ||
| except Exception: # noqa: BLE001 — best-effort: re-raise unchanged so the operator sees the worker traceback through Pool.map's wrapping; we log at ERROR first so the contextual "which split failed" hint lands even when the traceback is opaque. | ||
| logger.error( | ||
| "audit: parallel worker raised inside the pool; the original " | ||
| "traceback is wrapped — re-run with --workers 1 to surface it " | ||
| "with full context." | ||
| ) | ||
| raise | ||
| outcomes_iter = zip(splits_paths.keys(), outcomes_list) | ||
|
Comment on lines
+323
to
+354
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 2. Schema order nondeterminism When audit_dataset(workers>1) runs splits in separate processes, schema column ordering can differ from workers=1 because _record_schema_for_dict iterates a frozenset(row.keys()). This can change splits[*].columns / schema_drift_columns ordering and break the PR’s “byte-identical across worker counts” contract for multi-column rows. Agent Prompt
|
||
| else: | ||
| logger.info("audit: sequential mode (workers=%d, splits=%d)", workers, len(splits_paths)) | ||
| outcomes_iter = ( | ||
| (split_name, _process_split(split_name, path, **split_kwargs)) for split_name, path in splits_paths.items() | ||
| ) | ||
|
|
||
| for split_name, outcome in outcomes_iter: | ||
| splits_info[split_name] = outcome.info | ||
| signatures_by_split[split_name] = outcome.signatures | ||
| total_samples += outcome.row_count | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.