Upload folder using huggingface_hub
Browse filesFiles changed (8)
34 unmodified lines35363738383940414142434440 unmodified lines85868788888990919293949550 unmodified lines146147148149150151152153154155156157158138 unmodified lines29729829928930030130230334 unmodified linesGATES: CONFIRMED (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 11 gates, 138 tests across 11 files,
The gate runner is where this bundle states its numbers out loud: 11 gates, 145 tests across 12 files,
18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every
one of those numbers from the tree it is standing in and stops the upload when the card and the code
beside it disagree.
beside it disagrees.
## Contents
40 unmodified lines subprocess mode each node has a budget (one hundred and twenty seconds by default) and an exhausted
node is killed together with the gates it had started, because a budget that leaks the node's own
children is not a budget; `--total-timeout SEC` caps the sum of the six waits. A run that exhausts
either budget answers UNKNOWN with the reason `NODE_TIMEOUT`.
either budget answers UNKNOWN with the reason `NODE_TIMEOUT`. One tree is judged by one
run at a time: every verb takes an exclusive lock at the workspace root before it reads
anything and releases it in a finally even when the run was refused; a lock left behind
by a process that no longer runs is taken over, one whose owner cannot be read is never
stolen, and a live holder is answered REFUSED with the reason `SESSION_LOCKED`.
- `lingologos_python/cli.py`: `lingologos_python` CLI (`verify`, `edit`, `create`, `delete`, `symbols`,
`select-tests`, `patterns list|show|scan|apply`, `check-adapter`).
- `fixtures/pattern_lab/`: a small package with one function planted in the shape of each card and50 unmodified lineswith `inspect` and asserts on the text the rewrite leaves behind and the text it removes, so the lock
still fails while the old shape stands, but it answers about the source and not about a behavior.
The sixteen pairs are what the bundle ships, not the only check the rules face: `tests/test_rules_fuzz.py`
sweeps, with a fixed seed, shapes the corpus never visits: randomly assembled modules carrying mutations
(tabs, CRLF, non-ASCII, a class wrapper, a tail no parser accepts), companion tests missing or silent,
names that are not in the file. For every candidate and every rule the answer must be one of two things:
a hit whose anchors are ASCII LF text, apply, and leave the file parsing, or a refusal naming one of the
codes below. A crash, or a name the registry does not hold, fails the sweep.
The pair then goes through the six nodes of the kernel as any other change does: the proposing roles
claim it, `gate_checker` runs the syntax gate and the selected tests, `adversary` reproduces the
result by another path, and the arbiter returns `VERIFIED` with assurance 3 only when both trusted138 unmodified linesof the package defines.
- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,
`LINKED_PATH_IN_WORKSPACE`.
`LINKED_PATH_IN_WORKSPACE`, `SESSION_LOCKED`.
- Verdicts the codex kernel brings back: `GATE_REJECTED`, `GATE_ABSTAIN`.
- The refusal the catalog layer adds above the rules: `AMBIGUOUS_TARGET`.
- Preflight and shape refusals of the rules: `MISSING_TARGET_FILE`, `NO_SUCH_FUNCTION`,16 unmodified lines171819202122232425262728293016 unmodified linesPATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"NODE_TIMEOUT = "NODE_TIMEOUT"LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"SESSION_LOCKED = "SESSION_LOCKED"
SESSION_REASONS: Tuple[str, ...] = ( PATH_POLICY, PATCH_NOT_APPLIED, NODE_TIMEOUT, LINKED_PATH_IN_WORKSPACE, SESSION_LOCKED,)
# Verdicts the codex kernel brings back when the gates fail or decline to answer.9 unmodified lines1011121314151646 unmodified lines6364656667686913 unmodified lines8384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120499 unmodified lines6206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896904 unmodified lines69569669769869970070170270370470570670770870971071171271371471571671771871972072172250 unmodified lines773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809120 unmodified lines930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964204 unmodified lines1169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411954 unmodified lines1200120112021001120312041205120679 unmodified lines1286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091 unmodified line131113121313109413141315131613179 unmodified linesfrom __future__ import annotations
import astimport ctypesimport hashlibimport jsonimport os46 unmodified lines NODE_TIMEOUT, PATCH_NOT_APPLIED, PATH_POLICY, SESSION_LOCKED,)
PYTHON_ROOT = Path(__file__).resolve().parent.parent13 unmodified lines
class WorkspaceLinkError(ValueError): """The workspace holds a symlink or a junction whose copy cannot match the disk."""
class SessionLockError(RuntimeError): """Another run holds the workspace lock, or its owner cannot be verified."""
# Two sessions committing to one workspace corrupt each other: each staged its# own copy from a disk the other has already rewritten. The lock is taken with# an exclusive create, so claiming it is never a polite ask, and released in a# finally even when the run was refused.SESSION_LOCK_NAME = ".lingologos-session.lock"
def _process_alive(pid: int) -> bool: """Best effort: is a process with this pid still running on this machine?""" if pid <= 0: return False if os.name == "nt": handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION if not handle: return False ctypes.windll.kernel32.CloseHandle(handle) return True try: os.kill(pid, 0) except ProcessLookupError: return False except PermissionError: return True return True
DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ( "*.env", ".env*",499 unmodified lines "a linked %s appeared in the workspace before the commit: '%s'" % (kind, rel), )
def _lock_path(self) -> Path: return Path(self.workspace_root) / SESSION_LOCK_NAME
def _lock_owner(self) -> Optional[int]: try: return int(self._lock_path().read_text(encoding="ascii")) except (OSError, ValueError): return None
@staticmethod def _lock_detail(lock: Path, owner: Optional[int]) -> str: if owner is None: return "a lock file sits at '%s' and its owner cannot be read" % lock return "another session run holds the workspace: '%s' names process %d" % (lock, owner)
def _acquire_session_lock(self) -> None: """Take the workspace lock with an exclusive create, never a polite ask.
A lock left behind by a process that no longer runs is taken over; a lock whose owner is alive, or whose owner cannot even be read, is a refusal the caller can read: the lock file names the process holding the workspace. """ lock = self._lock_path() for attempt in (0, 1): try: handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) except FileExistsError: owner = self._lock_owner() if attempt or owner is None or _process_alive(owner): raise SessionLockError(self._lock_detail(lock, owner)) try: lock.unlink() except OSError: raise SessionLockError("the leftover lock at '%s' could not be cleared" % lock) continue try: os.write(handle, str(os.getpid()).encode("ascii")) finally: os.close(handle) self._held_lock = lock return
def _release_session_lock(self) -> None: lock = getattr(self, "_held_lock", None) if lock is not None: self._held_lock = None try: lock.unlink() except OSError: pass
def _lock_refusal( self, case_id: str, rel_posix: Optional[str], exc: SessionLockError ) -> SessionResult: return SessionResult( case_id=case_id, verdict="REFUSED", assurance=0, reason=SESSION_LOCKED, detail=str(exc), committed=False, touched_files=() if rel_posix is None else (rel_posix,), )
def list_files(self) -> List[str]: """Return all Python source files in the workspace.""" return discover_python_files(self.workspace_root)4 unmodified lines *, case_id: str = "python-verify", note: str = "verify Python workspace against codex gates", ) -> SessionResult: """Judge the workspace, holding the session lock for the whole run.
Two sessions committing to one tree each staged its copy from a disk the other had already rewritten, so the lock is taken before anything is read and released in a finally even when the run was refused. """ try: self._acquire_session_lock() except SessionLockError as exc: return self._lock_refusal(case_id, target_file, exc) try: return self._verify_run(target_file, case_id=case_id, note=note) finally: self._release_session_lock()
def _verify_run( self, target_file: Optional[str] = None, *, case_id: str = "python-verify", note: str = "verify Python workspace against codex gates", ) -> SessionResult: """Verify an existing file or the whole Python workspace without modifying disk.""" linked = self._linked_path_in_workspace()50 unmodified lines commit: bool = True, attempt_signatures: Sequence[str] = (), patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Stage a search-and-replace edit, verify via codex, and commit atomically on pass.""" try: self._acquire_session_lock() except SessionLockError as exc: return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc) try: return self._edit_run( rel_path, search, replace, case_id=case_id, note=note, commit=commit, attempt_signatures=attempt_signatures, patch_config=patch_config, ) finally: self._release_session_lock()
def _edit_run( self, rel_path: str, search: str, replace: str, *, case_id: str = "python-edit", note: str = "apply controlled search-and-replace edit", commit: bool = True, attempt_signatures: Sequence[str] = (), patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Stage a search-and-replace edit, verify via codex, and commit atomically on pass.""" rel_posix = rel_path.replace("\\", "/")120 unmodified lines note: Optional[str] = None, commit: bool = True, patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Apply one catalog card under the session lock, pair of files and all.""" try: self._acquire_session_lock() except SessionLockError as exc: return self._lock_refusal( case_id or "python-pattern-%s" % pattern_id, target, exc ) try: return self._apply_pattern_run( pattern_id, target=target, case_id=case_id, note=note, commit=commit, patch_config=patch_config, ) finally: self._release_session_lock()
def _apply_pattern_run( self, pattern_id: str, *, target: Optional[str] = None, case_id: Optional[str] = None, note: Optional[str] = None, commit: bool = True, patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Apply one catalog card to one target, primary edit and lock test together.
204 unmodified lines case_id: str = "python-create", note: str = "create verified Python module", commit: bool = True, ) -> SessionResult: """Create a new Python file, verifying it in isolation before committing.""" try: self._acquire_session_lock() except SessionLockError as exc: return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc) try: return self._create_run( rel_path, content, case_id=case_id, note=note, commit=commit ) finally: self._release_session_lock()
def _create_run( self, rel_path: str, content: str, *, case_id: str = "python-create", note: str = "create verified Python module", commit: bool = True, ) -> SessionResult: """Create a new Python file, verifying it in isolation before committing.""" rel_posix = rel_path.replace("\\", "/")4 unmodified lines # The policy answers first. Probing the named path before the guard would let # an absolute path replace the workspace root on Windows and touch a file # outside the workspace, naming it back in the error. return self.edit_file(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False) return self._edit_run(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False)
# The guard has resolved the path inside the workspace by now; build the target # from the resolved rel path, never from the raw input.79 unmodified lines case_id: str = "python-delete", note: str = "delete Python module with full regression check", commit: bool = True, ) -> SessionResult: """Delete a Python file only if the full regression passes after removal.""" try: self._acquire_session_lock() except SessionLockError as exc: return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc) try: return self._delete_run(rel_path, case_id=case_id, note=note, commit=commit) finally: self._release_session_lock()
def _delete_run( self, rel_path: str, *, case_id: str = "python-delete", note: str = "delete Python module with full regression check", commit: bool = True, ) -> SessionResult: """Delete a Python file only if the full regression passes after removal.""" rel_posix = rel_path.replace("\\", "/")1 unmodified line try: plan = guard.plan_transaction([PlannedOp(op=OP_DELETE, rel_posix=rel_posix)]) except PathSecurityError: return self.edit_file(rel_posix, "# DELETE", "", case_id=case_id, note=note, commit=False) return self._edit_run(rel_posix, "# DELETE", "", case_id=case_id, note=note, commit=False)
target = self.workspace_root / Path(*rel_posix.split("/")) if not target.is_file():80 unmodified lines818283848485868780 unmodified lines "name": "self_lint", "verdict": "CONFIRMED", "check": "the package reads itself: modules compile, the graph spans them, the reason registry matches the card, the promised names exist", "note": "12 modules parse, compile, and carry docstrings; own graph has 153 symbols and 321 edges; 38 reason codes, every one named in the card; 34 names promised in the Contents, all defined", "note": "12 modules parse, compile, and carry docstrings; own graph has 166 symbols and 348 edges; 39 reason codes, every one named in the card; 34 names promised in the Contents, all defined", "failed_targets": [] } ]17 unmodified lines181920212223247 unmodified lines3233343536373814 unmodified lines535455545657585917 unmodified lines PATTERN_REASONS, REASON_CODES, RULE_REASONS, SESSION_LOCKED, SESSION_REASONS,)
7 unmodified lines PATCH_NOT_APPLIED, NODE_TIMEOUT, LINKED_PATH_IN_WORKSPACE, SESSION_LOCKED, } assert set(KERNEL_REASONS) == {GATE_REJECTED, GATE_ABSTAIN} assert set(PATTERN_REASONS) == {AMBIGUOUS_TARGET}14 unmodified lines
def test_the_session_still_answers_with_registered_codes() -> None: """The names the session and its tests import are the registry names, not copies.""" for name in ("PATH_POLICY", "PATCH_NOT_APPLIED", "NODE_TIMEOUT", "LINKED_PATH_IN_WORKSPACE"): for name in ("PATH_POLICY", "PATCH_NOT_APPLIED", "NODE_TIMEOUT", "LINKED_PATH_IN_WORKSPACE", "SESSION_LOCKED"): assert getattr(session_module, name) in REASON_CODES assert getattr(session_module, name) == name
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169"""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 assembledmodules, mutated shapes, missing companions, run through all eight rules witha fixed seed, so the sweep itself is part of the corpus of evidence. Everycandidate, for every rule, must answer one of exactly two ways: a hit whoseanchors are ASCII LF text that apply and leave the file compiling, or a missnaming one registered reason code. A crash or an unregistered name is a lie."""
from __future__ import annotations
import astimport randomfrom typing import Callable, Dict, List, Optional, Tuple
from lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch
from lingologos_python import rulesfrom lingologos_python.reasons import REASON_CODES
SEED = 20261126CANDIDATES = 240MODULE = "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 answers493 unmodified lines494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580493 unmodified lines assert res.assurance == 0 assert "vendor" in res.detail assert res.touched_files == ("vendor",)
def test_a_second_session_on_one_workspace_is_answered_session_locked( sample_pkg: Path,) -> None: """The lock is an exclusive create, so claiming a held workspace is a refusal, not a queue.""" session = PythonWorkspaceSession(sample_pkg) lock = sample_pkg / session_module.SESSION_LOCK_NAME assert not lock.exists() handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY) try: os.write(handle, str(os.getpid()).encode("ascii")) finally: os.close(handle) res = session.verify("src/mathops.py") assert res.verdict == "REFUSED" assert res.reason == session_module.SESSION_LOCKED assert res.committed is False assert str(os.getpid()) in res.detail lock.unlink() again = session.verify("src/mathops.py") assert again.verdict == "VERIFIED"
def test_a_locked_edit_refuses_before_reading_anything(sample_pkg: Path) -> None: """The refusal precedes the edit machinery: no staging copy, no disk read of the pair.""" session = PythonWorkspaceSession(sample_pkg) lock = sample_pkg / session_module.SESSION_LOCK_NAME handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY) try: os.write(handle, str(os.getpid()).encode("ascii")) finally: os.close(handle) res = session.edit_file( "src/mathops.py", "return left + right", "return left * right", commit=True ) assert res.verdict == "REFUSED" assert res.reason == session_module.SESSION_LOCKED assert res.touched_files == ("src/mathops.py",) text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="") assert "return left + right" in text lock.unlink()
def test_the_lock_lives_for_exactly_the_length_of_a_run( sample_pkg: Path, monkeypatch) -> None: """Held while the six nodes judge, gone the moment the run ends, refusal included.""" session = PythonWorkspaceSession(sample_pkg) lock = sample_pkg / session_module.SESSION_LOCK_NAME seen = {} real_pipeline = session_module.run_pipeline
def spy_pipeline(case): seen["held_mid_run"] = lock.exists() return real_pipeline(case)
monkeypatch.setattr(session_module, "run_pipeline", spy_pipeline) res = session.verify("src/mathops.py") assert res.verdict == "VERIFIED" assert seen.get("held_mid_run") is True assert not lock.exists()
def test_a_lock_left_by_a_dead_process_is_taken_over(sample_pkg: Path) -> None: """A leftover lock names a process that no longer runs; the takeover is honest, not rude.""" lock = sample_pkg / session_module.SESSION_LOCK_NAME lock.write_text("99999999\n", encoding="ascii", newline="") session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "VERIFIED" assert not lock.exists()
def test_a_lock_whose_owner_cannot_be_read_is_never_stolen(sample_pkg: Path) -> None: """Unreadable owner means a live holder we cannot name: the refusal stands.""" lock = sample_pkg / session_module.SESSION_LOCK_NAME lock.write_text("not a pid\n", encoding="ascii", newline="") session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "REFUSED" assert res.reason == session_module.SESSION_LOCKED assert "cannot be read" in res.detail lock.unlink()13 unmodified lines141516171819171819202122238 unmodified lines323334353637383 unmodified lines4243444344454647484945464736 unmodified lines84858692939495969798998788898 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613769 unmodified lines20720820918921021121221321421525 unmodified lines2412422432442452462472482492502512522532542552562572222582592602612622632642292302652662332672682692362372702712722732742752402762772782796 unmodified lines28628728825325428929029129229318 unmodified lines31231331431531631731813 unmodified lines3323333342982993353363373013023033043053383393403413423103113433443453463163473483493503 unmodified lines35435535632632735735835936036127 unmodified lines38939039136139239339439514 unmodified lines41041141238241341441541613 unmodified linesThis bundle carries no kernel. It carries one corpus of its own, the sixteen pattern cases under`patterns/`, generated from the rules and the fixture beside them, and the card states theirdenominator rather than letting sixteen rows look like a benchmark. Every number the card states(11 gates, 138 tests, 18 node files, the staged file count) is re-derived from this tree before asingle object is uploaded. A card that contradicts the code beside it stops the run instead ofpublishing.(gates, tests and the files holding them, node files) is re-derived from this tree, the cardsentence that states them is parsed back and compared, and no constant in this file duplicatesany of them: a number can only change here by changing the code that produces it. A card thatcontradicts the code beside it stops the run instead of publishing.
The folder README is the body of the dataset card. A short list of wording pairs turns the sentencesthat only make sense inside a LingoLOGOS checkout, and four sections are added for readers who met8 unmodified linesimport hashlibimport jsonimport osimport reimport shutilimport sysimport tempfile3 unmodified linesROOT = Path(__file__).resolve().parents[1]
REPO = "tailot/codex-python"EXPECTED_FILES = 75 # the staged tree: 75 files of this folder, the card replacing README.mdEXPECTED_HUB_OBJECTS = 76 # those 75 plus the .gitattributes the hub addsEXPECTED_GATES = 11EXPECTED_TESTS = 138EXPECTED_TEST_FILES = 11EXPECTED_NODE_FILES = 18EXPECTED_GATE_LINE = "GATES: CONFIRMED (11 gates: 11 CONFIRMED, 0 REJECTED, 0 ABSTAIN)"ROLES = ("planner", "retriever", "executor", "gate_checker", "adversary", "arbiter")ENVELOPE_KIND = "lingologos-codex-envelope-1"IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git", ".venv", ".venv-train"}36 unmodified lines "https://huggingface.co/datasets/tailot/lingologos-codex, and the section\n" "\"What this bundle needs from the codex kernel\" below says how the two find each other.", ), ( "The gate runner is where this bundle states its numbers out loud: 11 gates, 138 tests across 11 files,\n" "18 files under `nodes/`, and a kernel it does not carry.", "The gate runner is where this bundle states its numbers out loud: 11 gates, 138 tests across 11 files,\n" "18 files under `nodes/`, and a kernel it does not carry. `tools/publish_dataset.py` re-derives every\n" "one of those numbers from the tree it is standing in and stops the upload when the card and the code\n" "beside it disagree.", ), ( "From `datasets/codex-python`:", "From the folder of this dataset, with `LINGOLOGOS_CODEX_ROOT` pointing at the folder of the kernel\n"8 unmodified lines ),]
# The one sentence of the card that states the running numbers, parsed rather than copied: the four# numbers it holds are compared with the ones re-derived from this tree, and the card keeps the# sentence with a line added about what produced it.NUMBERS_SENTENCE = re.compile( r"The gate runner is where this bundle states its numbers out loud: " r"([0-9]+) gates, ([0-9]+) tests across ([0-9]+) files,\n" r"([0-9]+) files under `nodes/`, and a kernel it does not carry\.")NUMBERS_TAIL = ( " `tools/publish_dataset.py` re-derives every\n" "one of those numbers from the tree it is standing in and stops the upload when the card and the code\n" "beside it disagrees.")
def state_numbers(text: str, derived: Tuple[int, int, int, int]) -> str: """Check the card's number sentence against the tree, then carry it onto the card."""
match = NUMBERS_SENTENCE.search(text) if match is None: raise SystemExit( "the README no longer states its numbers in the one sentence this tool knows:\n" "The gate runner is where this bundle states its numbers out loud: ..." ) stated = tuple(int(group) for group in match.groups()) if stated != derived: raise SystemExit( "the card states %d gates, %d tests in %d files, %d node files; " "the tree holds %d gates, %d tests in %d files, %d node files" % (stated + derived) ) return text[: match.end()] + NUMBERS_TAIL + text[match.end() :]
# Sections a reader who found the bundle here needs and a reader inside a checkout does not.CARD_TAIL = """
69 unmodified lines return sorted(files)
def build_card() -> str:def build_card(derived: Tuple[int, int, int, int]) -> str: text = (ROOT / "README.md").read_text(encoding="utf-8").replace("\r\n", "\n") text = state_numbers(text, derived) for here, there in REPLACEMENTS: if here not in text: raise SystemExit(25 unmodified lines return hashlib.sha256(data).hexdigest()
def gate_verdict_line(payload: dict) -> str: """The verdict line the gate runner prints, rebuilt from the report it wrote."""
gates = payload.get("gates") or [] counts = payload.get("counts") or {} return "GATES: %s (%d gates: %d CONFIRMED, %d REJECTED, %d ABSTAIN)" % ( payload.get("verdict"), len(gates), counts.get("CONFIRMED", 0), counts.get("REJECTED", 0), counts.get("ABSTAIN", 0), )
def check_gates_report() -> None:def check_gates_report() -> int: """The committed gate report has to agree with what this folder claims."""
payload = json.loads((ROOT / "results" / "gates.json").read_text(encoding="utf-8")) if payload.get("verdict") != "CONFIRMED": raise SystemExit(f"results/gates.json holds verdict '{payload.get('verdict')}'") gates = payload.get("gates") or [] if len(gates) != EXPECTED_GATES: raise SystemExit(f"results/gates.json holds {len(gates)} gates, the card states {EXPECTED_GATES}") if any(g.get("verdict") != "CONFIRMED" for g in gates): raise SystemExit("results/gates.json holds a gate that is not CONFIRMED") if sum((payload.get("counts") or {}).values()) != EXPECTED_GATES: if sum((payload.get("counts") or {}).values()) != len(gates): raise SystemExit("results/gates.json counts do not add up to the gates it lists") readme = (ROOT / "README.md").read_text(encoding="utf-8") if EXPECTED_GATE_LINE not in readme: raise SystemExit(f"the README no longer prints this gate verdict line: {EXPECTED_GATE_LINE}") line = gate_verdict_line(payload) if line not in readme: raise SystemExit(f"the README no longer prints the verdict line the report gives: {line}") return len(gates)
def check_topology_and_nodes() -> None:def check_topology_and_nodes() -> int: """Six roles in the topology, six node folders of three files each, ASCII everywhere."""
topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))6 unmodified lines raise SystemExit("topology.json routing matrix does not hold six rows")
node_files = [p for role in ROLES for p in (ROOT / "nodes" / role).glob("*") if p.is_file()] if len(node_files) != EXPECTED_NODE_FILES: raise SystemExit(f"nodes/ holds {len(node_files)} files, the card states {EXPECTED_NODE_FILES}") if len(node_files) < len(ROLES) * 3: raise SystemExit(f"nodes/ holds {len(node_files)} files, fewer than three per role") for role in ROLES: for name in ("grammar.gf", "ontology.smt2", "seed_payload.json"): if not (ROOT / "nodes" / role / name).is_file():18 unmodified lines offenders.append(str(path.relative_to(ROOT))) if offenders: raise SystemExit(f"non-ASCII text in {offenders}: this repository keeps every byte of prose ASCII") return len(node_files)
def main(argv: List[str] | None = None) -> int:13 unmodified lines if notes: raise SystemExit(f"README.md still holds working notes: {notes}")
check_gates_report() check_topology_and_nodes() gate_count = check_gates_report() node_files = check_topology_and_nodes() tests, holders = count_tests() if tests != EXPECTED_TESTS or holders != EXPECTED_TEST_FILES: raise SystemExit( f"tests/ holds {tests} test functions in {holders} files, " f"the card states {EXPECTED_TESTS} in {EXPECTED_TEST_FILES}" ) derived = (gate_count, tests, holders, node_files)
staging = Path(tempfile.mkdtemp(prefix="publish-codex-python-")) try: files = local_files() if len(files) != EXPECTED_FILES: raise SystemExit(f"the staged tree has {len(files)} files, the tool expects {EXPECTED_FILES}") for path in files: target = staging / path.relative_to(ROOT) target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, target) (staging / "README.md").write_text(build_card(), encoding="utf-8") (staging / "README.md").write_text(build_card(derived), encoding="utf-8")
sources = sorted(p for p in staging.rglob("*.py")) for path in sources:3 unmodified lines raise SystemExit("the staged tree is missing agents/python_agent.py")
print( f"{EXPECTED_GATES} gates CONFIRMED, {tests} tests in {holders} files, " f"{EXPECTED_NODE_FILES} node files" f"{gate_count} gates CONFIRMED, {tests} tests in {holders} files, " f"{node_files} node files" ) print(f"staged tree: {len(files)} files, sources compiled: {len(sources)}") if args.plan:27 unmodified lines if local != hub: differ.append(name)
print(f"{len(remote)} objects on the hub, expected {EXPECTED_HUB_OBJECTS}, missing {missing}") print(f"{len(remote)} objects on the hub, expected {len(files) + 1}, missing {missing}") print(f"extra {extra}, content differs {differ}")
if args.prune and extra:14 unmodified lines finally: shutil.rmtree(staging, ignore_errors=True)
ok = (len(remote) == EXPECTED_HUB_OBJECTS and not missing and not extra and not differ) ok = (len(remote) == len(files) + 1 and not missing and not extra and not differ) print("RESULT: %s" % ("ok" if ok else "check the numbers above")) return 0 if ok else 1
README.md+15-4
lingologos_python/reasons.py+2
lingologos_python/session.py+222-2
results/gates.json+1-1
tests/test_reasons.py+3-1
tests/test_rules_fuzz.pyAdded+169
tests/test_session.py+84
tools/publish_dataset.py+73-42