File size: 7,884 Bytes
da61666
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""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