Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
feat(provenance): capture bounded startup training-file hash (#2024)
Nurkhan Esenbek64c44b00a2a8
diff --git a/changelog.d/0.76.0/2024.added.md b/changelog.d/0.76.0/2024.added.mdnew file mode 100644index 00000000..9d9458d3--- /dev/null+++ b/changelog.d/0.76.0/2024.added.md@@ -0,0 +1 @@+- Capture a bounded complete local text-training source SHA-256 at `soup train` startup, retain unknown identities for unsupported/incomplete inputs, and preserve the historical digest through final artifacts and registry registration. (#1764 part 2 by @kok-o in #2024)diff --git a/docs/training.md b/docs/training.mdindex 019f2196..871f4bf2 100644--- a/docs/training.md+++ b/docs/training.md@@ -2280,3 +2280,32 @@ a conflicting combo is rejected loudly at config load. Scans cache under `~/.sou`all` default) is recommended for very large models — it skips the giant embedding/lm_head matrices.The SNR kernel is pure-numpy and transpose-invariant, so GPT-2 `Conv1D` weights score the same asLinear weights. (v0.71.23)++## Training source identity++`soup train` captures `training_data_sha256` before loading or transforming a+supported single local raw text-training file. The digest is SHA-256 of the+complete file bytes, including any BOM and original newline encoding. It records+source bytes at startup; it does not prove which transformed examples, external+assets or later streaming reads trained the model. The source is not frozen.++Capture uses 1 MiB reads, a 256 MiB byte limit and a 5-second time budget checked+between filesystem operations. An operation already blocked on I/O cannot be+interrupted by that budget. Larger, unreadable, changing or incomplete files are+recorded as unknown (`NULL`), never as the hash of a prefix. Descriptor and path+metadata detect accidental replacement/modification during capture; this is not+an adversarial filesystem snapshot.++Mixed/interleaved/replay, remote, streaming, tokenized and directory inputs remain+unknown. The initial scope is text input through `data.train`; TTS, unlearning and+non-text modalities remain unknown. No unknown component is silently omitted to+manufacture an identity for a composite input. Dry runs do not capture a digest.++The recorded value is retained in `soup_run.json` beside the final artifact and+copied by `soup registry push --run-id` without reopening today's source. Explicit+`--data` still describes the file registered now: its hash takes precedence for+`data_hash` and the entry fingerprint, while `training_data_sha256` keeps the+historical startup digest. Copied artifacts retain that digest without the+original dataset. Existing runs stay unknown; no historical identity is inferred+from today's files. Sweep and other training entry points do not gain capture in+this change.diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex ec535c28..92a68f76 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -1754,6 +1754,11 @@ def train(console.print("[green]Config valid. Ready to train![/]")raise typer.Exit()+ # Capture the source before loading/transformation, never at verdict/registration time.+ from soup_cli.utils.training_identity import capture_training_data_hash++ training_data_sha256 = capture_training_data_hash(cfg)+# Load dataconsole.print("[dim]Loading dataset...[/]")if val_notice:@@ -1791,6 +1796,7 @@ def train(# _reconcile_orphaned_run to ever notice the process is gone — the# rescue path #401 built for MCP-spawned runs was otherwise inert here.tracker.mark_running(run_id, pid=os.getpid())+ tracker.record_training_data_hash(run_id, training_data_sha256)console.print(f"[dim]Run ID: {run_id}[/]")try:diff --git a/src/soup_cli/experiment/tracker.py b/src/soup_cli/experiment/tracker.pyindex dbade4c0..facc2aa6 100644--- a/src/soup_cli/experiment/tracker.py+++ b/src/soup_cli/experiment/tracker.py@@ -269,6 +269,17 @@ class ExperimentTracker:conn.commit()return run_id+ def record_training_data_hash(self, run_id: str, digest: Optional[str]) -> None:+ """Record startup source bytes, leaving unsupported/incomplete sources unknown."""+ from soup_cli.utils.run_provenance import validate_training_hash++ validate_training_hash(digest)+ conn = self._get_conn()+ conn.execute(+ "UPDATE runs SET training_data_sha256=? WHERE run_id=?", (digest, run_id),+ )+ conn.commit()+def record_base_revision(self, run_id: str, *, revision: Optional[str], source: str,) -> None:diff --git a/src/soup_cli/utils/run_provenance.py b/src/soup_cli/utils/run_provenance.pyindex 7fd9679d..93b1b9e7 100644--- a/src/soup_cli/utils/run_provenance.py+++ b/src/soup_cli/utils/run_provenance.py@@ -95,7 +95,7 @@ class BaseRevision:return {"schema_version": 1, "run_id": run_id, "base_model": self.base,"base_revision": self.revision, "base_revision_source": self.source,- # Reserved shared storage contract; hash capture is #1764 part 2.+ # The train command fills this from the recorded startup source hash."training_data_sha256": None,}diff --git a/src/soup_cli/utils/training_identity.py b/src/soup_cli/utils/training_identity.pynew file mode 100644index 00000000..822c1e83--- /dev/null+++ b/src/soup_cli/utils/training_identity.py@@ -0,0 +1,98 @@+"""Bounded startup identity of one local raw text-training source file.++This describes source bytes at capture time, not transformed examples consumed.+Unsupported, changing or incompletely read inputs have no digest.+"""++from __future__ import annotations++import hashlib+import os+import stat+import time+from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from soup_cli.config.schema import SoupConfig++MAX_HASH_BYTES = 256 * 1024 * 1024+HASH_TIMEOUT_SECONDS = 5.0+_CHUNK_BYTES = 1024 * 1024+++def _identity(info: os.stat_result) -> tuple[int, ...]:+ """Metadata with the same meaning for path and descriptor APIs."""+ return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns)+++def _signature(info: os.stat_result) -> tuple[int, ...]:+ """Compare ctime only within one API; Windows path/fd values can differ."""+ return _identity(info) + (info.st_ctime_ns,)+++def capture_training_data_hash(+ config: SoupConfig, *, max_bytes: int = MAX_HASH_BYTES,+ timeout_seconds: float = HASH_TIMEOUT_SECONDS,+) -> str | None:+ """Hash complete supported bytes, or return unknown without changing training.++ The time budget is checked between bounded reads; it cannot interrupt a+ blocking filesystem operation. No network dataset is opened. Replaced or+ modified files are detected by descriptor/path metadata checks, which are+ not a filesystem snapshot or protection against deliberate timestamp replay.+ """+ from soup_cli.data.loader import SUPPORTED_EXTENSIONS++ data = config.data+ source = data.train+ if (config.modality != "text" or config.task in {"unlearn", "tts"}+ or not isinstance(source, str) or not source or "://" in source+ or source.startswith(("\\\\", "//"))+ or data.format == "pre_tokenized" or data.tokenized_path+ or data.replay or data.forget_set or data.retain_set+ or data.interleave is not None or data.streaming):+ return None+ if Path(source).suffix.lower() not in SUPPORTED_EXTENSIONS:+ return None+ if max_bytes < 0 or timeout_seconds <= 0:+ return None+ started = time.monotonic()+ descriptor = None+ try:+ initial = os.stat(source)+ if not stat.S_ISREG(initial.st_mode) or initial.st_size > max_bytes:+ return None+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0)+ descriptor = os.open(source, flags)+ with os.fdopen(descriptor, "rb") as handle:+ descriptor = None # the context owns it, including on early return+ opened = os.fstat(handle.fileno())+ if not stat.S_ISREG(opened.st_mode) or _identity(initial) != _identity(opened):+ return None+ digest = hashlib.sha256()+ count = 0+ while True:+ if time.monotonic() - started >= timeout_seconds:+ return None+ chunk = handle.read(min(_CHUNK_BYTES, max_bytes - count + 1))+ if not chunk:+ break+ count += len(chunk)+ if count > max_bytes:+ return None+ digest.update(chunk)+ if (time.monotonic() - started >= timeout_seconds+ or count != opened.st_size+ or _signature(os.fstat(handle.fileno())) != _signature(opened)+ or _signature(os.stat(source)) != _signature(initial)):+ return None+ if time.monotonic() - started >= timeout_seconds:+ return None+ return digest.hexdigest()+ except (OSError, ValueError):+ # A provenance gap must not introduce a new refusal or expose paths.+ return None+ finally:+ if descriptor is not None:+ os.close(descriptor)diff --git a/tests/test_base_revision_loading.py b/tests/test_base_revision_loading.pyindex dd0e9f8c..937303c6 100644--- a/tests/test_base_revision_loading.py+++ b/tests/test_base_revision_loading.py@@ -2,6 +2,7 @@from __future__ import annotations+import hashlibimport jsonimport shutilfrom pathlib import Path@@ -16,6 +17,65 @@ BASE = "owner/base"REVISION = "a" * 40[email protected]("suffix", [".jsonl", ".bin"])+def test_capture_happens_before_the_loader_reads_the_file(+ tmp_path, monkeypatch, moving_hub, suffix,+):+ pytest.importorskip("torch")+ from typer.testing import CliRunner++ from soup_cli.cli import app+ from soup_cli.commands import train as train_module+ from soup_cli.experiment.tracker import ExperimentTracker++ monkeypatch.chdir(tmp_path)+ monkeypatch.setenv("SOUP_DB_PATH", str(tmp_path / "runs.db"))+ monkeypatch.setattr("soup_cli.utils.launcher.is_in_distributed", lambda: False)+ monkeypatch.setattr("soup_cli.utils.gpu.detect_device", lambda: ("cpu", "CPU"))+ monkeypatch.setattr("soup_cli.utils.gpu.get_gpu_info", lambda: {})+ original_bytes = b'{"instruction":"hi", "output":"hello"}\n'+ source = tmp_path / ("data" + suffix)+ source.write_bytes(original_bytes)+ # A stand-in loader accepts an unsupported extension too, so the CLI can+ # complete and persist unknown without introducing a hash producer there.+ (tmp_path / "loader.jsonl").write_bytes(original_bytes)+ (tmp_path / "soup.yaml").write_text(+ f"base: {BASE}\ndata: {{train: data{suffix}, format: alpaca, val_split: 0}}\n"+ "training: {epochs: 1, quantization: none, batch_size: 1}\noutput: final\n",+ encoding="utf-8",+ )+ real_loader = train_module.load_dataset++ def rewriting_loader(data_config, *args, **kwargs):+ source.write_bytes(b'{"instruction":"later", "output":"bytes"}\n')+ return real_loader(+ data_config.model_copy(update={"train": "loader.jsonl"}), *args, **kwargs,+ )++ monkeypatch.setattr(train_module, "load_dataset", rewriting_loader)+ output = tmp_path / "final"++ class Trainer:+ def setup(self, dataset):+ assert dataset["train"]++ def train(self, **kwargs):+ output.mkdir()+ return {"output_dir": str(output), "initial_loss": 1.0, "final_loss": 0.5,+ "total_steps": 1, "duration_secs": 1.0}++ monkeypatch.setattr("soup_cli.trainer.dispatch.build_trainer", lambda cfg, **kw: Trainer())+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--yes"])+ assert result.exit_code == 0, (result.output, result.exception)+ tracker = ExperimentTracker(tmp_path / "runs.db")+ try:+ expected = hashlib.sha256(original_bytes).hexdigest() if suffix == ".jsonl" else None+ assert tracker.list_runs()[0]["training_data_sha256"] == expected+ assert provenance.read_run_provenance(output)["training_data_sha256"] == expected+ finally:+ tracker.close()++@pytest.fixturedef moving_hub(monkeypatch):monkeypatch.delenv("HF_HUB_OFFLINE", raising=False)@@ -143,10 +203,32 @@ def test_copied_adapter_pins_live_eval_and_export_loaders(tmp_path, monkeypatch,assert calls == expected_calls + [("model", expected_revision), ("model", expected_revision)]+def test_dry_run_does_not_capture_training_identity(tmp_path, monkeypatch):+ from typer.testing import CliRunner++ from soup_cli.cli import app++ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr("soup_cli.utils.gpu.detect_device", lambda: ("cpu", "CPU"))+ monkeypatch.setattr("soup_cli.utils.gpu.get_gpu_info", lambda: {})+ capture = Mock(side_effect=AssertionError("dry-run must not hash the training source"))+ monkeypatch.setattr("soup_cli.utils.training_identity.capture_training_data_hash", capture)+ (tmp_path / "data.jsonl").write_text(+ '{"instruction":"hi", "output":"hello"}\n', encoding="utf-8",+ )+ (tmp_path / "soup.yaml").write_text(+ "base: owner/base\ndata: {train: data.jsonl, format: alpaca, val_split: 0}\n"+ "training: {epochs: 1, quantization: none, batch_size: 1}\n", encoding="utf-8",+ )+ result = CliRunner().invoke(app, ["train", "--config", "soup.yaml", "--dry-run"])+ assert result.exit_code == 0, (result.output, result.exception)+ capture.assert_not_called()++@pytest.mark.parametrize("mode", ["bound", "offline", "distributed", "non-hf"])[email protected]("stored_hash", [None, "c" * 64], ids=["unknown-data", "stored-data"])[email protected]("source_state", ["unchanged", "changed", "deleted"])def test_train_cli_records_identity_and_writes_final_artifact(- tmp_path, monkeypatch, moving_hub, mode, stored_hash,+ tmp_path, monkeypatch, moving_hub, mode, source_state,):pytest.importorskip("torch")from typer.testing import CliRunner@@ -184,22 +266,27 @@ def test_train_cli_records_identity_and_writes_final_artifact(f"hub: {'modelscope' if mode == 'non-hf' else 'hf'}}}\noutput: final\n",encoding="utf-8",)+ import hashlib++ stored_hash = hashlib.sha256((tmp_path / "data.jsonl").read_bytes()).hexdigest()expected = {"revision": REVISION} if mode == "bound" else {}class Trainer:def setup(self, dataset):assert dataset["train"]+ tracker = ExperimentTracker(tmp_path / "runs.db")+ try:+ assert tracker.list_runs()[0]["training_data_sha256"] == stored_hash+ finally:+ tracker.close()assert provenance.base_revision_kwargs(BASE) == expecteddef train(self, **kwargs):assert provenance.base_revision_kwargs(BASE) == expected- # Emulate a separate producer of the reserved historical hash field.- conn = kwargs["tracker"]._get_conn()- conn.execute(- "UPDATE runs SET training_data_sha256=? WHERE run_id=?",- (stored_hash, kwargs["run_id"]),- )- conn.commit()+ if source_state == "changed":+ (tmp_path / "data.jsonl").write_text("later bytes", encoding="utf-8")+ elif source_state == "deleted":+ (tmp_path / "data.jsonl").unlink()output.mkdir()return {"output_dir": str(output), "initial_loss": 1.0, "final_loss": 0.5,"total_steps": 1, "duration_secs": 1.0}diff --git a/tests/test_training_identity.py b/tests/test_training_identity.pynew file mode 100644index 00000000..e7d7313f--- /dev/null+++ b/tests/test_training_identity.py@@ -0,0 +1,394 @@+"""Complete bounded source-byte hashes; unknown is never a partial digest."""++from __future__ import annotations++import hashlib+import os+import shutil+from types import SimpleNamespace++import pytest++from soup_cli.config.schema import SoupConfig+from soup_cli.experiment.tracker import ExperimentTracker+from soup_cli.registry import RegistryStore, hash_entry+from soup_cli.utils import training_identity as identity+from soup_cli.utils.run_provenance import (+ BaseRevision,+ read_run_provenance,+ write_run_provenance,+)+++def _config(source, **data):+ cfg = SoupConfig(base="local/model", data={"train": str(source)})+ return cfg.model_copy(update={"data": cfg.data.model_copy(update=data)})++[email protected]("suffix", [".jsonl", ".json", ".csv", ".parquet", ".txt", ".JSONL"])[email protected]("payload", [b"", b"\xef\xbb\xbfraw\r\n\x00bytes\xff"])+def test_exact_complete_bytes(tmp_path, suffix, payload):+ source = tmp_path / ("data" + suffix)+ source.write_bytes(payload)+ expected = hashlib.sha256(payload).hexdigest()+ assert identity.capture_training_data_hash(_config(source)) == expected++[email protected]("updates", [+ {"train": ["first.jsonl", "second.jsonl"]}, {"format": "pre_tokenized"},+ {"tokenized_path": "cache"}, {"replay": "old.jsonl"}, {"interleave": "concat"},+ {"forget_set": "forget.jsonl"}, {"retain_set": "retain.jsonl"}, {"streaming": True},+ {"train": "https://example.invalid/data.jsonl"}, {"train": "owner/dataset"},+ {"train": "\\\\server\\share\\data.jsonl"}, {"train": "//server/share/data.jsonl"},+])+def test_unsupported_source_never_opens_a_member(tmp_path, monkeypatch, updates):+ source = tmp_path / "data.jsonl"+ source.write_text("present", encoding="utf-8")+ cfg = _config(source, **updates)+ monkeypatch.setattr(identity.os, "open", lambda *args: pytest.fail("unsupported input opened"))+ assert identity.capture_training_data_hash(cfg) is None+++ "field,value", [("modality", "vision"), ("task", "unlearn"), ("task", "tts")],+)+def test_external_source_modes_are_unknown(tmp_path, field, value):+ source = tmp_path / "data.jsonl"+ source.write_text("present", encoding="utf-8")+ cfg = _config(source).model_copy(update={field: value})+ assert identity.capture_training_data_hash(cfg) is None+++def test_missing_directory_and_unknown_suffix(tmp_path):+ assert identity.capture_training_data_hash(_config(tmp_path / "missing.jsonl")) is None+ directory = tmp_path / "directory.jsonl"+ directory.mkdir()+ assert identity.capture_training_data_hash(_config(directory)) is None+ unknown = tmp_path / "data.bin"+ unknown.write_bytes(b"not a raw loader input")+ assert identity.capture_training_data_hash(_config(unknown)) is None+++def test_byte_budget_and_boundary(tmp_path, monkeypatch):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"12345")+ assert identity.capture_training_data_hash(_config(source), max_bytes=5) == hashlib.sha256(+ b"12345",+ ).hexdigest()+ monkeypatch.setattr(identity.os, "open", lambda *args: pytest.fail("oversized input opened"))+ assert identity.capture_training_data_hash(_config(source), max_bytes=4) is None+++def test_time_limit_after_partial_read_is_unknown(tmp_path, monkeypatch):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"12345")+ monkeypatch.setattr(identity, "_CHUNK_BYTES", 2)+ ticks = iter([0.0, 0.0, 6.0])+ monkeypatch.setattr(identity.time, "monotonic", lambda: next(ticks, 6.0))+ assert identity.capture_training_data_hash(_config(source), timeout_seconds=5) is None++[email protected]("operation", ["fstat", "stat"])[email protected]("elapsed", [0.0, 4.999, 5.0, 6.0])+def test_deadline_after_final_metadata_read(tmp_path, monkeypatch, operation, elapsed):+ source = tmp_path / "data.jsonl"+ payload = b"complete source bytes\n"+ source.write_bytes(payload)+ config = _config(source)+ original = getattr(identity.os, operation)+ clock = {"now": 0.0}+ calls = 0++ def metadata(*args, **kwargs):+ nonlocal calls+ info = original(*args, **kwargs)+ # Keep the real metadata unchanged; only account for time spent in the+ # final descriptor/path operation after the last pre-metadata check.+ if operation == "fstat" or str(args[0]) == str(source):+ calls += 1+ if calls == 2:+ clock["now"] = elapsed+ return info++ monkeypatch.setattr(identity.os, operation, metadata)+ monkeypatch.setattr(identity.time, "monotonic", lambda: clock["now"])+ digest = identity.capture_training_data_hash(config, timeout_seconds=5)+ assert calls == 2+ expected = hashlib.sha256(payload).hexdigest() if elapsed < 5 else None+ assert digest == expected++[email protected]("mode", ["grow", "truncate", "rewrite", "read-error"])+def test_changes_or_read_failure_do_not_publish_a_digest(tmp_path, monkeypatch, mode):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"123456")+ monkeypatch.setattr(identity, "_CHUNK_BYTES", 2)+ fdopen = identity.os.fdopen+ reads = []+ handles = []++ class Reader:+ def __init__(self, handle):+ self.handle = handle++ def __enter__(self):+ return self++ def __exit__(self, *args):+ self.handle.close()++ def fileno(self):+ return self.handle.fileno()++ def read(self, size):+ reads.append(size)+ chunk = self.handle.read(size)+ if len(reads) == 1:+ if mode == "read-error":+ raise OSError("unreadable remainder")+ payload = {"grow": b"12345678", "truncate": b"1", "rewrite": b"abcdef"}[mode]+ source.write_bytes(payload)+ # Explicitly change metadata; this is an accidental-mutation check.+ os.utime(source, ns=(1_000_000_000, 2_000_000_000))+ return chunk++ def wrap(*args):+ handle = fdopen(*args)+ handles.append(handle)+ return Reader(handle)++ monkeypatch.setattr(identity.os, "fdopen", wrap)+ assert identity.capture_training_data_hash(_config(source), max_bytes=7) is None+ assert reads and max(reads) <= 2+ assert handles and all(handle.closed for handle in handles)+++def test_path_replacement_metadata_is_checked(tmp_path, monkeypatch):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"12345")+ real_stat = identity.os.stat+ calls = 0++ def replaced(path, *args, **kwargs):+ nonlocal calls+ info = real_stat(path, *args, **kwargs)+ if str(path) == str(source):+ calls += 1+ if calls == 2:+ return SimpleNamespace(**{+ field: getattr(info, field) + (1 if field == "st_ino" else 0)+ for field in ("st_dev", "st_ino", "st_size", "st_mtime_ns", "st_ctime_ns")+ })+ return info++ monkeypatch.setattr(identity.os, "stat", replaced)+ assert identity.capture_training_data_hash(_config(source)) is None+ assert calls == 2+++def test_produced_digest_survives_copy_and_registry_override(tmp_path):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"original source\n")+ config = _config(source)+ digest = identity.capture_training_data_hash(config)+ assert digest == hashlib.sha256(b"original source\n").hexdigest()+ tracker = ExperimentTracker(tmp_path / "runs.db")+ try:+ run_id = tracker.start_run(config.model_dump(), "cpu", "CPU", {})+ tracker.record_training_data_hash(run_id, digest)+ metadata = BaseRevision(config.base).metadata(run_id)+ metadata["training_data_sha256"] = tracker.get_run(run_id)["training_data_sha256"]+ artifact = tmp_path / "artifact"+ write_run_provenance(artifact, metadata)+ copied = tmp_path / "copy"+ shutil.copytree(artifact, copied)+ source.write_bytes(b"later registered file\n")+ assert read_run_provenance(copied)["training_data_sha256"] == digest+ with RegistryStore(tmp_path / "registry.db") as store:+ historical = store.get(store.register_from_run(+ tracker, run_id, name="model", tag="old",+ ))+ assert historical["data_hash"] == historical["training_data_sha256"] == digest+ assert historical["entry_hash"] == hash_entry(+ config=config.model_dump(), data_path=None, base_model=config.base,+ data_sha256=digest,+ )+ explicit = store.get(store.register_from_run(+ tracker, run_id, name="model", tag="new", data_path=str(source),+ ))+ assert explicit["data_hash"] == hashlib.sha256(source.read_bytes()).hexdigest()+ assert explicit["training_data_sha256"] == digest+ finally:+ tracker.close()+++_FIELDS = ("st_mode", "st_dev", "st_ino", "st_size", "st_mtime_ns", "st_ctime_ns")+++def _with(info, **changes):+ values = {name: getattr(info, name) for name in _FIELDS}+ values.update(changes)+ return SimpleNamespace(**values)+++def _source(tmp_path):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"complete source bytes\n")+ return source, hashlib.sha256(b"complete source bytes\n").hexdigest()+++def test_path_and_descriptor_ctime_may_differ_for_an_unchanged_file(tmp_path, monkeypatch):+ source, expected = _source(tmp_path)+ real_stat = identity.os.stat++ def path_stat(path, *args, **kwargs):+ info = real_stat(path, *args, **kwargs)+ # Windows: os.stat(path) and os.fstat(fd) can disagree on ctime for the SAME file.+ if str(path) == str(source):+ return _with(info, st_ctime_ns=info.st_ctime_ns + 1_000_000)+ return info++ monkeypatch.setattr(identity.os, "stat", path_stat)+ assert identity.capture_training_data_hash(_config(source)) == expected++[email protected]("field", ["st_mtime_ns", "st_size", "st_ino"])+def test_path_versus_descriptor_identity_still_refuses(tmp_path, monkeypatch, field):+ source, _ = _source(tmp_path)+ real_stat = identity.os.stat++ def path_stat(path, *args, **kwargs):+ info = real_stat(path, *args, **kwargs)+ if str(path) == str(source):+ return _with(info, **{field: getattr(info, field) + 1})+ return info++ monkeypatch.setattr(identity.os, "stat", path_stat)+ assert identity.capture_training_data_hash(_config(source)) is None+++def test_descriptor_ctime_change_during_the_read_is_unknown(tmp_path, monkeypatch):+ source, _ = _source(tmp_path)+ real_fstat = identity.os.fstat+ calls = 0++ def fd_stat(fd):+ nonlocal calls+ calls += 1+ info = real_fstat(fd)+ return _with(info, st_ctime_ns=info.st_ctime_ns + 1_000_000) if calls == 2 else info++ monkeypatch.setattr(identity.os, "fstat", fd_stat)+ assert identity.capture_training_data_hash(_config(source)) is None+ assert calls == 2+++def test_path_ctime_change_during_the_read_is_unknown(tmp_path, monkeypatch):+ source, _ = _source(tmp_path)+ real_stat = identity.os.stat+ calls = 0++ def path_stat(path, *args, **kwargs):+ nonlocal calls+ info = real_stat(path, *args, **kwargs)+ if str(path) == str(source):+ calls += 1+ if calls == 2:+ return _with(info, st_ctime_ns=info.st_ctime_ns + 1_000_000)+ return info++ monkeypatch.setattr(identity.os, "stat", path_stat)+ assert identity.capture_training_data_hash(_config(source)) is None+ assert calls == 2+++class _Stub:+ """Wraps the real handle; `script(size)` decides what each read returns."""++ def __init__(self, handle, script):+ self.handle = handle+ self.script = script++ def __enter__(self):+ return self++ def __exit__(self, *args):+ self.handle.close()++ def fileno(self):+ return self.handle.fileno()++ def read(self, size):+ return self.script(size, self.handle)++[email protected]("train", [+ "https://example.invalid/data.jsonl",+ "\\\\server\\share\\data.jsonl",+ "//server/share/data.jsonl",+])+def test_remote_and_network_paths_never_reach_the_filesystem(monkeypatch, tmp_path, train):+ real_stat = identity.os.stat++ def guarded(path, *args, **kwargs):+ if str(path) == train:+ pytest.fail("network path was stat-ed")+ return real_stat(path, *args, **kwargs)++ monkeypatch.setattr(identity.os, "stat", guarded)+ assert identity.capture_training_data_hash(_config(tmp_path / "x.jsonl", train=train)) is None+++def test_embedded_nul_in_the_path_is_unknown_not_a_crash(tmp_path):+ assert identity.capture_training_data_hash(_config(tmp_path / "bad\x00.jsonl")) is None++[email protected]("elapsed", [5.0, 6.0])+def test_deadline_stops_reading_before_the_next_chunk(tmp_path, monkeypatch, elapsed):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"123456")+ monkeypatch.setattr(identity, "_CHUNK_BYTES", 2)+ reads = []+ clock = {"now": 0.0}++ def script(size, handle):+ reads.append(size)+ clock["now"] = elapsed+ return handle.read(size)++ fdopen = identity.os.fdopen+ monkeypatch.setattr(identity.os, "fdopen", lambda *args: _Stub(fdopen(*args), script))+ monkeypatch.setattr(identity.time, "monotonic", lambda: clock["now"])+ assert identity.capture_training_data_hash(_config(source), timeout_seconds=5) is None+ assert len(reads) == 1+++def test_a_source_that_keeps_growing_is_cut_off_at_the_byte_limit(tmp_path, monkeypatch):+ source = tmp_path / "data.jsonl"+ source.write_bytes(b"1234")+ monkeypatch.setattr(identity, "_CHUNK_BYTES", 2)+ requested = []++ def script(size, handle):+ assert size >= 0, "a negative size would read to EOF without a bound"+ requested.append(size)+ return b"x" * size++ fdopen = identity.os.fdopen+ monkeypatch.setattr(identity.os, "fdopen", lambda *args: _Stub(fdopen(*args), script))+ assert identity.capture_training_data_hash(_config(source), max_bytes=4) is None+ assert sum(requested) <= 5+++def test_record_unknown_and_reject_partial_or_malformed_hash(tmp_path):+ tracker = ExperimentTracker(tmp_path / "runs.db")+ try:+ run_id = tracker.start_run({"base": "local/model", "task": "sft"}, "cpu", "CPU", {})+ tracker.record_training_data_hash(run_id, None)+ assert tracker.get_run(run_id)["training_data_sha256"] is None+ for invalid in ("partial", "A" * 64, True):+ with pytest.raises(ValueError, match="SHA-256"):+ tracker.record_training_data_hash(run_id, invalid)+ assert tracker.get_run(run_id)["training_data_sha256"] is None+ finally:+ tracker.close()