Download tests/test_rules_fuzz.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 7.88 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/main/tests/test_rules_fuzz.py
- Command line
-
hf download hf://datasets/tailot/codex-python/tests/test_rules_fuzz.py
-
curl -L -o test_rules_fuzz.py https://huggingface.co/datasets/tailot/codex-python/resolve/main/tests/test_rules_fuzz.py
7.88 kB
| """Fuzz for the eight rules: never a crash, never a nameless refusal, never a lying hit. | |
| The catalog gate proves the shipped corpus is honest, sixteen rows at a time. | |
| This test sweeps the space the corpus does not visit: randomly assembled | |
| modules, mutated shapes, missing companions, run through all eight rules with | |
| a fixed seed, so the sweep itself is part of the corpus of evidence. Every | |
| candidate, for every rule, must answer one of exactly two ways: a hit whose | |
| anchors are ASCII LF text that apply and leave the file compiling, or a miss | |
| naming one registered reason code. A crash or an unregistered name is a lie. | |
| """ | |
| from __future__ import annotations | |
| import ast | |
| import random | |
| from typing import Callable, Dict, List, Optional, Tuple | |
| from lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch | |
| from lingologos_python import rules | |
| from lingologos_python.reasons import REASON_CODES | |
| SEED = 20261126 | |
| CANDIDATES = 240 | |
| MODULE = "src/cand.py" | |
| BODY_SHAPES: Tuple[str, ...] = ( | |
| "def NAME(items=[]):\n items.append(1)\n return items\n", | |
| "def NAME(x=None):\n if x == None:\n return 0\n return 1\n", | |
| "def NAME(path):\n fh = open(path)\n data = fh.read()\n fh.close()\n return data\n", | |
| "def NAME(value):\n assert value\n return value\n", | |
| "def NAME(numbers):\n if len(numbers) == 0:\n return 0\n return numbers[0]\n", | |
| "def NAME(kind):\n try:\n return int(kind)\n except:\n raise\n", | |
| "def NAME(name, greeting=\"hello\"):\n return greeting + name\n", | |
| "def NAME(kind, a, b):\n if kind == \"a\":\n return a\n elif kind == \"b\":\n return b\n return a\n", | |
| "def NAME(items: list = []):\n return items\n", | |
| "def NAME(x):\n if x != None:\n return x\n return 0\n", | |
| "def NAME(text=\"\", unit=\"word\"):\n return text.split(unit)\n", | |
| "def NAME(rows):\n return [row for row in rows if len(rows) > 0]\n", | |
| ) | |
| MUTATIONS: Tuple[Callable[[str], str], ...] = ( | |
| lambda text: text, | |
| lambda text: text.replace("def NAME(", "async def NAME(", 1), | |
| lambda text: text.replace("\n", "\r\n"), | |
| lambda text: text.replace(" ", "\t"), | |
| lambda text: text + "# caf\u00e9\n", | |
| lambda text: text + "def broken(:\n pass\n", | |
| lambda text: "class Wrapper:\n " + text.replace("\n", "\n ").rstrip() + "\n", | |
| ) | |
| TEST_COMPANIONS: Tuple[Optional[str], ...] = ( | |
| "import cand\n\n\ndef test_NAME():\n assert cand.NAME is not None\n", | |
| "def test_other():\n assert 1 == 1\n", | |
| None, | |
| ) | |
| def _candidate(rng: random.Random) -> Tuple[Dict[str, Optional[str]], str]: | |
| """One assembled workspace: a module, a mutated shape, maybe a companion test.""" | |
| body = rng.choice(BODY_SHAPES) | |
| body = rng.choice(MUTATIONS)(body) | |
| symbol = rng.choice(["NAME", "NAME", "NAME", "ghost"]) | |
| files: Dict[str, Optional[str]] = {MODULE: body.replace("NAME", symbol)} | |
| if rng.random() < 0.25: | |
| body = body.replace("NAME", symbol) + "def helper(flag=[]):\n flag.append(1)\n" | |
| files[MODULE] = body | |
| companion = rng.choice(TEST_COMPANIONS) | |
| if companion is not None: | |
| files["tests/test_cand.py"] = companion.replace("NAME", symbol) | |
| return files, symbol | |
| def _reader(files: Dict[str, Optional[str]]) -> Callable[[str], Optional[str]]: | |
| def read(rel_posix: str) -> Optional[str]: | |
| return files.get(rel_posix) | |
| return read | |
| def test_random_shapes_never_break_the_rules_and_never_answer_without_a_name() -> None: | |
| """Sweep with a fixed seed: every answer is a clean hit or a miss naming a registered code.""" | |
| rng = random.Random(SEED) | |
| failures: List[str] = [] | |
| hits = 0 | |
| miss_codes = set() | |
| for round_index in range(CANDIDATES): | |
| files, symbol = _candidate(rng) | |
| read = _reader(files) | |
| target, open_miss = rules.open_target(MODULE, symbol, read) | |
| if target is None: | |
| if open_miss is None or open_miss.reason_code not in REASON_CODES: | |
| failures.append("round %d: targetless answer without a registered code" % round_index) | |
| if open_miss is not None: | |
| miss_codes.add(open_miss.reason_code) | |
| continue | |
| for rule_id in rules.RULE_IDS: | |
| try: | |
| outcome = rules.RULES[rule_id](target) | |
| except Exception as exc: # a rule that crashes is a rule that lied | |
| failures.append("round %d: %s raised %r" % (round_index, rule_id, exc)) | |
| continue | |
| if isinstance(outcome, rules.RuleMiss): | |
| if outcome.reason_code not in REASON_CODES: | |
| failures.append( | |
| "round %d: %s refused with the unregistered name '%s'" | |
| % (round_index, rule_id, outcome.reason_code) | |
| ) | |
| miss_codes.add(outcome.reason_code) | |
| continue | |
| if not isinstance(outcome, rules.RuleHit): | |
| failures.append("round %d: %s answered %r" % (round_index, rule_id, outcome)) | |
| continue | |
| hits += 1 | |
| if not outcome.edits: | |
| failures.append("round %d: %s hit with no edits" % (round_index, rule_id)) | |
| for edit in outcome.edits: | |
| original = files.get(edit.file) | |
| if original is None: | |
| failures.append("round %d: %s edits a file it was never given" % (round_index, rule_id)) | |
| continue | |
| for anchor in (edit.search, edit.replace): | |
| if any(ord(ch) > 127 for ch in anchor) or "\r" in anchor or "\t" in anchor: | |
| failures.append( | |
| "round %d: %s anchors are not ASCII LF text in %s" | |
| % (round_index, rule_id, edit.file) | |
| ) | |
| result = apply_controlled_fuzzy_patch( | |
| original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig() | |
| ) | |
| if not result.applied: | |
| failures.append("round %d: %s hit whose anchor does not apply" % (round_index, rule_id)) | |
| continue | |
| try: | |
| ast.parse(result.updated_text) | |
| except SyntaxError: | |
| failures.append("round %d: %s hit whose result no longer parses" % (round_index, rule_id)) | |
| assert failures == [], "rule fuzz found %d lies, first: %s" % (len(failures), failures[0]) | |
| assert hits >= 10, "the sweep produced only %d hits: it tested almost nothing" % hits | |
| assert len(miss_codes) >= 6, "the sweep only ever refused with %d names" % len(miss_codes) | |
| def test_two_sweeps_of_one_seed_answer_identically() -> None: | |
| """Same shapes, same seed: the rules answer identically, anchor offsets and all.""" | |
| first = _sweep(40) | |
| second = _sweep(40) | |
| assert first == second | |
| def _sweep(rounds: int) -> List[str]: | |
| rng = random.Random(SEED + 7) | |
| answers: List[str] = [] | |
| for round_index in range(rounds): | |
| files, symbol = _candidate(rng) | |
| target, open_miss = rules.open_target(MODULE, symbol, _reader(files)) | |
| if target is None: | |
| answers.append("round %d: target %s" % (round_index, open_miss.reason_code)) | |
| continue | |
| for rule_id in rules.RULE_IDS: | |
| outcome = rules.RULES[rule_id](target) | |
| if isinstance(outcome, rules.RuleMiss): | |
| answers.append("round %d: %s miss %s" % (round_index, rule_id, outcome.reason_code)) | |
| else: | |
| answers.append( | |
| "round %d: %s hit %s" | |
| % (round_index, rule_id, [(e.file, e.search, e.replace) for e in outcome.edits]) | |
| ) | |
| assert len(answers) >= rounds | |
| return answers | |