Download tests/test_session_fuzz.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 7.37 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/main/tests/test_session_fuzz.py
- Command line
-
hf download hf://datasets/tailot/codex-python/tests/test_session_fuzz.py
-
curl -L -o test_session_fuzz.py https://huggingface.co/datasets/tailot/codex-python/resolve/main/tests/test_session_fuzz.py
7.37 kB
| """A fixed-seed sweep of random session operations over one sample package. | |
| The property under test is the one the session card makes: no change lands on | |
| disk unless a verified verdict committed it, and no refusal leaves a trace. | |
| Every operation answers with a verdict: accepted runs carry the kernel's | |
| confirmation phrase, and every REFUSED or UNKNOWN names a registered reason. | |
| The disk state is checked after every single operation. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import random | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| from lingologos_python.reasons import REASON_CODES | |
| from lingologos_python.session import SESSION_LOCK_NAME, PythonWorkspaceSession | |
| SEED = 20261203 | |
| # Pipeline runs are not free, so the expensive kinds are capped and the rest of | |
| # the sweep is made of operations that must refuse before any node runs. | |
| PLAN: List[str] = ( | |
| ["valid_edit_commit"] * 4 | |
| + ["valid_edit_dry"] * 4 | |
| + ["valid_create_commit"] * 3 | |
| + ["verify"] * 3 | |
| + ["traversal_edit"] * 6 | |
| + ["protected_create"] * 5 | |
| + ["non_python_create"] * 5 | |
| + ["missing_edit"] * 5 | |
| + ["missing_delete"] * 5 | |
| + ["bad_pattern"] * 4 | |
| + ["create_existing"] * 4 | |
| + ["empty_edit"] * 5 | |
| ) | |
| def _build_ops(rng: random.Random) -> List[Tuple[str, str]]: | |
| kinds = list(PLAN) | |
| rng.shuffle(kinds) | |
| files = [ | |
| "src/mathops.py", | |
| "src/textops.py", | |
| "tests/test_mathops.py", | |
| "tests/test_textops.py", | |
| ] | |
| return [(kind, rng.choice(files)) for kind in kinds] | |
| def _tree_state(root: Path) -> Dict[str, bytes]: | |
| state: Dict[str, bytes] = {} | |
| for path in root.rglob("*"): | |
| if not path.is_file(): | |
| continue | |
| rel = path.relative_to(root).as_posix() | |
| parts = rel.split("/") | |
| if any(part in ("__pycache__", ".pytest_cache") for part in parts[:-1]): | |
| continue | |
| if path.suffix in (".pyc", ".pyo"): | |
| continue | |
| state[rel] = path.read_bytes() | |
| return state | |
| def _anchor_pair(path: Path) -> Tuple[str, str]: | |
| text = path.read_text(encoding="utf-8", newline="") | |
| lines = [line for line in text.split("\n") if line.strip()] | |
| anchor = lines[-1] | |
| return anchor, anchor + "\n# swept" | |
| def _check_committed(result, before: Dict[str, bytes], after: Dict[str, bytes]) -> List[str]: | |
| problems: List[str] = [] | |
| changed = {rel for rel in set(before) | set(after) if before.get(rel) != after.get(rel)} | |
| named = set(result.touched_files) | |
| if not named: | |
| problems.append("a commit named no touched files") | |
| if changed != changed & named: | |
| problems.append( | |
| "files changed that the result did not name: " + ", ".join(sorted(changed - named)) | |
| ) | |
| return problems | |
| def test_the_same_seed_always_sweeps_the_same_operations() -> None: | |
| assert _build_ops(random.Random(SEED)) == _build_ops(random.Random(SEED)) | |
| def test_a_seeded_sweep_never_lands_a_change_it_did_not_verify(sample_pkg: Path) -> None: | |
| rng = random.Random(SEED) | |
| ops = _build_ops(rng) | |
| failures: List[str] = [] | |
| committed = 0 | |
| refused = 0 | |
| raised = 0 | |
| for index, (kind, rel) in enumerate(ops): | |
| session = PythonWorkspaceSession(str(sample_pkg)) | |
| lock_held = False | |
| if index == 10: | |
| # Plant a live holder: our own process is alive, so the lock is real. | |
| (sample_pkg / SESSION_LOCK_NAME).write_text(str(os.getpid()), encoding="ascii") | |
| lock_held = True | |
| before = _tree_state(sample_pkg) | |
| try: | |
| if kind == "valid_edit_commit" or kind == "valid_edit_dry": | |
| path = sample_pkg / Path(*rel.split("/")) | |
| search, replace = _anchor_pair(path) | |
| res = session.edit_file(rel, search, replace, commit=(kind.endswith("commit"))) | |
| elif kind == "valid_create_commit": | |
| res = session.create_file( | |
| "src/extra_%d.py" % index, | |
| "def extra_%d() -> int:\n return %d\n" % (index, index), | |
| commit=True, | |
| ) | |
| elif kind == "verify": | |
| res = session.verify(target_file=rel if index % 2 else None) | |
| elif kind == "traversal_edit": | |
| res = session.edit_file("../outside_the_tree.py", "a", "b", commit=True) | |
| elif kind == "protected_create": | |
| res = session.create_file(".env", "SECRET=1\n", commit=True) | |
| elif kind == "non_python_create": | |
| res = session.create_file("notes_%d.txt" % index, "prose\n", commit=True) | |
| elif kind == "missing_edit": | |
| res = session.edit_file("src/absent_%d.py" % index, "a", "b", commit=True) | |
| elif kind == "missing_delete": | |
| try: | |
| res = session.delete_file("src/gone_%d.py" % index, commit=True) | |
| except FileNotFoundError: | |
| raised += 1 | |
| res = None | |
| elif kind == "bad_pattern": | |
| try: | |
| res = session.apply_pattern("ghost-card-%d" % index, commit=True) | |
| except KeyError: | |
| raised += 1 | |
| res = None | |
| elif kind == "create_existing": | |
| try: | |
| res = session.create_file(rel, "x = 1\n", commit=True) | |
| except FileExistsError: | |
| raised += 1 | |
| res = None | |
| elif kind == "empty_edit": | |
| res = session.edit_file(rel, "", "", commit=True) | |
| else: | |
| raise AssertionError("unknown op kind %s" % kind) | |
| after = _tree_state(sample_pkg) | |
| if res is None: | |
| if after != before: | |
| failures.append("%d %s: an expected exception still wrote to disk" % (index, kind)) | |
| continue | |
| if res.verdict in ("REFUSED", "UNKNOWN") and res.reason not in REASON_CODES: | |
| failures.append("%d %s: unregistered reason %s" % (index, kind, res.reason)) | |
| if res.committed: | |
| committed += 1 | |
| if not (res.verdict in ("VERIFIED", "SINGLE_PROVER") and res.accepted): | |
| failures.append( | |
| "%d %s: committed with verdict %s" % (index, kind, res.verdict) | |
| ) | |
| failures.extend(_check_committed(res, before, after)) | |
| else: | |
| refused += 1 | |
| if after != before: | |
| failures.append( | |
| "%d %s (%s): disk moved without a commit" % (index, kind, res.reason) | |
| ) | |
| if lock_held and res.verdict != "REFUSED": | |
| failures.append("%d %s: a planted lock did not refuse the run" % (index, kind)) | |
| except Exception as exc: # a crash of the sweep itself is a finding, not a pass | |
| failures.append("%d %s: %s: %s" % (index, kind, type(exc).__name__, exc)) | |
| finally: | |
| if lock_held: | |
| (sample_pkg / SESSION_LOCK_NAME).unlink(missing_ok=True) | |
| assert failures == [] | |
| assert committed >= 7 | |
| # Most of the sweep must be made of refusals: half the plan plus the | |
| # three pipeline kinds that can refuse honestly when the workspace moved. | |
| assert refused + raised >= len(PLAN) - 8 | |