Upload folder using huggingface_hub
Browse filesFiles changed (9)
31 unmodified lines3233343535363738383940411 unmodified line43444546474849503 unmodified lines5455565557585960616263616465666768697016 unmodified lines878889848590919293941 unmodified line969798939910010110210310410510699100101102103107108109110111112113114115116117219 unmodified lines33733833932934034134234331 unmodified lines
```
python -B tools/run_gates.py
GATES: CONFIRMED (12 gates: 12 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
GATES: CONFIRMED (13 gates: 13 CONFIRMED, 0 REJECTED, 0 ABSTAIN)
```
The gate runner is where this bundle states its numbers out loud: 12 gates, 159 tests across 15 files,
The gate runner is where this bundle states its numbers out loud: 13 gates, 167 tests across 15 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 disagrees.1 unmodified lineThe report names the tree it describes. `results/gates.json` embeds a digest of every byte of the bundle
except the reports folder itself, and the publisher refuses to upload a tree that the report does not
describe byte for byte; `tests/test_self_lint.py` holds the report sitting in this folder to that bar.
The runner takes that digest before the first gate and asks it again before writing: a tree that moved
while the gates ran gets no report, and the report says how many seconds each gate took.
## Contents
3 unmodified lines- `lingologos_python/adapter.py`: `PythonLanguageAdapter` and `StrictPythonLanguageAdapter`
implementing the five-method `lingologos_codex.adapter_contract.LanguageAdapter` contract.
- `lingologos_python/ast_graph.py`: AST symbol, method, inheritance, relative/absolute import, and call
graph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`). A file whose bytes
graph extraction (`discover_python_files`, `extract_python_graph`, `importers_of`, `reexported_names`,
`hardlinked_file`). A file whose bytes
are not UTF-8 text is named as a file and given no symbols, rather than decoded into inventions.
An aliased `from x import y as z` keeps its edge to the submodule `x.y` even though the name is
renamed, and a dotted relative import crosses the same number of packages in the graph as in the
source.
`discover_python_files` prunes a symlinked or junctioned directory instead of walking into it, and
`is_linked_path` answers for both kinds of link on every platform.
`is_linked_path` answers for both kinds of link on every platform, and `hardlinked_file` answers for
a file whose bytes sit under two names in the tree. A package that re-exports through its `__init__`
is read as a table from name to file, so a change behind the re-export still selects the test that
only named the package.
- `lingologos_python/test_selector.py`: import-aware Python test selection (`select_python_tests`).
A changed `conftest.py` selects every test under its folder, because a conftest carries fixtures no
import edge shows.16 unmodified lines- `lingologos_python/session.py`: `PythonWorkspaceSession` for safe staged verification and atomic disk
commits via `lingologos_codex.fsadapter` (`verify`, `edit_file`, `create_file`, `delete_file`,
`apply_pattern`, `run_retry_loop`, and `run_topology_subprocesses`). A proposer that accepts a third argument is handed a `RetryContext`
with the attempts so far, their traces and their reasons; a two-argument proposer keeps its
signature. A commit re-reads what is on disk
with the attempts so far, their traces, their reasons, and the patch signatures the loop detector compares, which read the fate of
a patch and not its words; a two-argument proposer keeps its signature. A commit re-reads what is on disk
and refuses with `PATCH_NOT_APPLIED` when the workspace moved while the six nodes were running. A
write the disk refuses part way is undone from the in-memory originals, so a run never reports a
change it did not land. A delete names the surviving files that import the module being removed,1 unmodified line symlink or a Windows junction anywhere in the workspace makes the session refuse with
`LINKED_PATH_IN_WORKSPACE`, naming the linked path: the staging copy refuses it, `verify` refuses
before any node runs, and every commit re-asks the question before it writes, so a link that appeared
while the six nodes were running is refused too, not landed through. In
while the six nodes were running is refused too, not landed through. A hardlinked pair, two names carrying the same disk
bytes, is refused the same three ways with `HARDLINKED_PATH_IN_WORKSPACE`, because a staged copy
would silently break what the workspace holds as one file. In
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`. 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`. The lock names its holder by process
number, and a number recycled by a young process can keep a tree locked past the death of the run
that planted it; deleting the lock file is the operator's remedy, not an unlock verb the bundle offers.
anything and releases it in a finally even when the run was refused. The lock record names its
holder three times over: the process number, the birth time that process had when the lock was
taken, and a token that only that acquisition knows. A live number whose birth time does not match
is not the holder the lock recorded, so a recycled process id cannot keep a tree locked past the
death of its run; a leftover lock is claimed by renaming it first, so two runs racing over one
corpse leave exactly one holder; and release deletes the lock only while the token in it is the one
this run wrote, so a run never unlinks a lock another run took over. A live holder is answered
REFUSED with the reason `SESSION_LOCKED`, and one whose owner cannot be read is never stolen.
- `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 and219 unmodified linesof the package defines.
- Refusals the session raises itself: `PATH_POLICY`, `PATCH_NOT_APPLIED`, `NODE_TIMEOUT`,
`LINKED_PATH_IN_WORKSPACE`, `SESSION_LOCKED`.
`LINKED_PATH_IN_WORKSPACE`, `HARDLINKED_PATH_IN_WORKSPACE`, `SESSION_LOCKED`.
- Verdicts the codex kernel brings back: `GATE_REJECTED`, `GATE_ABSTAIN`, `GATE_MISSING`, `CHECKER_REJECTED`, `CHECKER_ABSTAIN`, `NOT_APPLIED`, `PROTECTED_PATH`, `NO_INDEPENDENT_CONFIRMATION`.
- The refusal the catalog layer adds above the rules: `AMBIGUOUS_TARGET`.
- Preflight and shape refusals of the rules: `MISSING_TARGET_FILE`, `NO_SUCH_FUNCTION`,56 unmodified lines575859606162636465666768697071727374757669 unmodified lines14614714814915015113715215315415515615715815916016116216316469 unmodified lines23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529699 unmodified lines39639739839940040140240340440540640740856 unmodified lines return False
def hardlinked_file(path: Path) -> bool: """True when one file stands under two names (its link count is above one).
A hard link is not a reparse point: both names are real, both lead to the same bytes on the disk. A copy of one name makes two files out of what the disk held as one, and a commit through the other name leaves the first at the old bytes. The tree is honest about links only if it also counts names. """ try: return path.stat().st_nlink > 1 except OSError: return False
def discover_python_files(workspace: Path) -> List[str]: """Return sorted POSIX relative paths for all Python source files in workspace.
69 unmodified lines except (SyntaxError, ValueError): continue modules, _ = _extract_imports(rel, tree) hit = False for name in modules: if name in wanted or name.rsplit(".", 1)[0] in wanted: found.append(rel) hit = True break if not hit: # The file binds a name the package re-exports from the target. for dotted in _reexport_dotted_names(workspace, tree): if dotted in wanted: hit = True break if hit: found.append(rel) return found
69 unmodified lines return ".".join(base_parts)
def reexported_names(workspace: Path, init_rel: str) -> Dict[str, List[str]]: """External name -> dotted candidates, for a package __init__ that re-exports names.
A package that answers for a function living in another file is ordinary and honest: the __init__ imports the name from where it stands. A caller binding to pkg.name never names the file holding the code, so the naming check follows this table and still credits the file the code lives in. """ source = _read_source(workspace, init_rel) if source is None: return {} try: tree = ast.parse(source, filename=init_rel) except (SyntaxError, ValueError): return {} parts = [p for p in init_rel.replace("\\", "/").split("/") if p] prefix = ".".join(parts[:-1]) # empty for a package sitting at the workspace root table: Dict[str, List[str]] = {} for node in tree.body: if not isinstance(node, ast.ImportFrom) or node.level != 1: continue if node.module: base = f"{prefix}.{node.module}" if prefix else node.module elif prefix: base = prefix # from . import name: name may be a sibling module else: continue for alias in node.names: if alias.name == "*": continue key = alias.asname or alias.name options = table.setdefault(key, []) # The from-import can name a submodule (pkg.deep) or a name defined # inside one (pkg.deep.thing), and the two resolve to different files. for dotted in (base, f"{base}.{alias.name}"): if dotted not in options: options.append(dotted) return table
def _reexport_dotted_names(workspace: Path, tree: ast.Module) -> List[str]: """Dotted submodules a file reaches through a package __init__ re-export.""" reached: List[str] = [] for node in ast.walk(tree): if not isinstance(node, ast.ImportFrom) or node.level > 0 or not node.module: continue table = reexported_names(workspace, node.module.replace(".", "/") + "/__init__.py") for alias in node.names: if alias.name == "*": continue key = alias.asname or alias.name for dotted in table.get(key, ()): if dotted not in reached: reached.append(dotted) return reached
def _extract_imports( rel_posix: str, tree: ast.Module) -> Tuple[List[str], Dict[str, Tuple[str, str]]]:99 unmodified lines if target_file: edges.add((rel, target_file))
# Re-export edges: a package __init__ can hand a name over to the file # that defines it, and the caller never names that file itself. for dotted in _reexport_dotted_names(workspace, parsed[rel]): target_file = _match_module_file(dotted, files_by_module, normalized_files, rel) if target_file: edges.add((rel, target_file))
# Inheritance edges for cls_name, base_list in bases_by_file.get(rel, {}).items(): src_sym = f"{rel}::{cls_name}"16 unmodified lines171819202122231 unmodified line2526272829303116 unmodified linesPATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"NODE_TIMEOUT = "NODE_TIMEOUT"LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"HARDLINKED_PATH_IN_WORKSPACE = "HARDLINKED_PATH_IN_WORKSPACE"SESSION_LOCKED = "SESSION_LOCKED"
SESSION_REASONS: Tuple[str, ...] = (1 unmodified line PATCH_NOT_APPLIED, NODE_TIMEOUT, LINKED_PATH_IN_WORKSPACE, HARDLINKED_PATH_IN_WORKSPACE, SESSION_LOCKED,)
20 unmodified lines2122232425262728 unmodified lines5657585960616263646566676817 unmodified lines8687888689909192939495963 unmodified lines1001011029610310410510610710810911011111215 unmodified lines12812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421548 unmodified lines264265266173174267268269270271272273274275276277278279144 unmodified lines42442542633142742842943043143215 unmodified lines448449450451452453454455456457458237 unmodified lines6966976985966997007017027037047056037067077087096077107117127137145 unmodified lines7207217227236197247257267277287297307 unmodified lines7387397407417427437447457467477487497504 unmodified lines75575675764464564664764875875976076165165276276376465476576676776876965966066166277077177277377477577677777877978078178278378478578678778878979079166967067179279379479567379679767579879980080180280367880480580680780880981081181281381481581681781881982082182282382482582682782868668768868969069182983083183283383483583683745 unmodified lines883884885886887888889890891743892893894895702 unmodified lines159815991600160116021603160420 unmodified linesimport sysimport tempfileimport timeimport uuidfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple28 unmodified linesfrom lingologos_python.ast_graph import ( # noqa: E402 IGNORED_DIRS, discover_python_files, hardlinked_file, importers_of, is_linked_path,)from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402from lingologos_python.reasons import ( # noqa: E402 HARDLINKED_PATH_IN_WORKSPACE, LINKED_PATH_IN_WORKSPACE, NODE_TIMEOUT, PATCH_NOT_APPLIED,17 unmodified lines
class WorkspaceLinkError(ValueError): """The workspace holds a symlink or a junction whose copy cannot match the disk.""" """The workspace holds a link, or a name counted twice, whose copy cannot match the disk."""
def __init__(self, message: str, reason: str = LINKED_PATH_IN_WORKSPACE) -> None: super().__init__(message) self.reason = reason
class SessionLockError(RuntimeError):3 unmodified lines# 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.# finally even when the run was refused. The lock file names the holder's pid,# the creation time of that pid, and a token unique to the acquisition: the pid# separates live from dead, the birth time separates the holder that was# written down from a recycled pid wearing the same number, and the token keeps# a run from unlinking a lock another run retook after it stalled.SESSION_LOCK_NAME = ".lingologos-session.lock"SESSION_LOCK_CLAIM_SUFFIX = ".stale"
def _process_alive(pid: int) -> bool:15 unmodified lines return True
def _process_creation_time(pid: int) -> Optional[int]: """When the process behind this pid was born, or None when the host will not say.
A pid alone says a number is answered; it does not say the answering process is the one that was written down. Birth times are the cheapest witness of a recycled pid. """ if pid <= 0: return None if os.name == "nt": kernel32 = ctypes.windll.kernel32 kernel32.OpenProcess.restype = ctypes.c_void_p kernel32.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_bool, ctypes.c_ulong] handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION if not handle: return None try: low = ctypes.c_ulong(0) high = ctypes.c_ulong(0) unused = ctypes.c_ulong(0) kernel32.GetProcessTimes.argtypes = [ ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), ] if not kernel32.GetProcessTimes( handle, ctypes.byref(low), ctypes.byref(high), ctypes.byref(unused), ctypes.byref(unused) ): return None return (int(high.value) << 32) | int(low.value) finally: kernel32.CloseHandle(handle) try: # Field 22 of /proc/<pid>/stat is the start time in clock ticks; the # comm field before it may itself hold spaces, so count from the last. with open("/proc/%d/stat" % pid, encoding="ascii") as handle: after_name = handle.read().rsplit(")", 1)[-1].split() return int(after_name[19]) except (OSError, ValueError, IndexError): return None
def _read_lock_record(lock: Path) -> Optional[Tuple[int, Optional[int], Optional[str]]]: """The (pid, birth, token) a lock file names, or None when it names nothing readable.""" try: parts = lock.read_text(encoding="ascii").split() except (OSError, UnicodeDecodeError): return None if not parts: return None try: pid = int(parts[0]) except ValueError: return None birth: Optional[int] = None if len(parts) > 1 and parts[1] != "-": try: birth = int(parts[1]) except ValueError: return None token = parts[2] if len(parts) > 2 else None return (pid, birth, token)
def _lock_holder_is_alive(record: Tuple[int, Optional[int], Optional[str]]) -> bool: """A holder lives when its pid answers and is the same process it was when written.
A pid recycled by a young process looks alive; the recorded birth time says the process now wearing the number is somebody else. """ pid, birth, _token = record if not _process_alive(pid): return False if birth is not None: now = _process_creation_time(pid) if now is not None and now != birth: return False return True
DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ( "*.env", ".env*",48 unmodified lines A loop that hands the proposer only the index and the last result teaches it nothing about why the nodes refused. A proposer that accepts a third argument receives all of it: every prior result with its verdict, reason, trace lines and the dossier the kernel returned. A two-argument proposer keeps working unchanged. trace lines and the dossier the kernel returned, plus the patch signatures the loop detector compares, which read the fate of a patch and not its words. A two-argument proposer keeps working unchanged. """
attempt: int rel_path: str attempts: Tuple[SessionResult, ...] = () failure_reasons: Tuple[str, ...] = () patch_signatures: Tuple[str, ...] = ()
def _disk_text(root: Path, rel_posix: str) -> str:144 unmodified lines
A symlink or a junction anywhere under the root is refused by name: a copy that quietly omits a link is not the workspace the six nodes were asked to judge, and a copy that follows one reaches files outside the workspace. judge, and a copy that follows one reaches files outside the workspace. A file standing under two names is refused too: the copy would split one file into two, and a later commit could not tell the names apart. """ root = src_root.resolve() for dirpath, dirnames, filenames in os.walk(src_root):15 unmodified lines raise WorkspaceLinkError( "linked file in the workspace: '%s'" % (rel_dir / name).as_posix() ) if hardlinked_file(src_file): raise WorkspaceLinkError( "hardlinked file in the workspace: '%s'" % (rel_dir / name).as_posix(), HARDLINKED_PATH_IN_WORKSPACE, ) shutil.copy2(src_file, target_dir / name)
237 unmodified lines case_id=case_id, verdict="REFUSED", assurance=0, reason=LINKED_PATH_IN_WORKSPACE, reason=getattr(exc, "reason", LINKED_PATH_IN_WORKSPACE), detail=str(exc), committed=False, touched_files=(rel_posix,), )
def _linked_path_in_workspace(self) -> Optional[Tuple[str, str]]: """Return ('directory'|'file', rel_posix) for the first link under the root. """Return ('directory'|'file'|'hardlink', rel_posix) for the first anomaly under the root.
Verify judges the workspace where it stands, with no staging copy to refuse for it, so it asks the same question the copy asks: is any part of this tree somewhere else. of this tree somewhere else, or does any single file answer under two names. """ root = Path(self.workspace_root).resolve() for dirpath, dirnames, filenames in os.walk(root):5 unmodified lines if is_linked_path(Path(dirpath) / name): return ("directory", (rel_dir / name).as_posix()) for name in filenames: entry = Path(dirpath) / name if is_linked_path(Path(dirpath) / name): if is_linked_path(entry): return ("file", (rel_dir / name).as_posix()) if hardlinked_file(entry): return ("hardlink", (rel_dir / name).as_posix()) return None
def _late_link_at_commit(self) -> Optional[Tuple[str, int, str, str]]:7 unmodified lines if linked is None: return None kind, rel = linked if kind == "hardlink": return ( "REFUSED", 0, HARDLINKED_PATH_IN_WORKSPACE, "a hardlinked file appeared in the workspace before the commit: '%s'" % rel, ) return ( "REFUSED", 0,4 unmodified lines 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 def _lock_owner(self) -> Optional[Tuple[int, Optional[int], Optional[str]]]: return _read_lock_record(self._lock_path())
@staticmethod def _lock_detail(lock: Path, owner: Optional[int]) -> str: if owner is None: def _lock_detail(lock: Path, record: Optional[Tuple[int, Optional[int], Optional[str]]]) -> str: if record 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) return "another session run holds the workspace: '%s' names process %d" % (lock, record[0])
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. The lock names the holder's pid, its birth time, and a token unique to this acquisition. A lock left behind by a process that no longer runs is taken over through a rename: two runs that find the same leftover race for the rename, only one proceeds, and the loser is refused rather than handed a second silent holder. A lock whose owner is alive, or that has recycled only its pid number, or whose owner cannot even be read, is a refusal the caller can read. """ lock = self._lock_path() claim = Path(str(lock) + SESSION_LOCK_CLAIM_SUFFIX) if claim.exists(): try: # Bookkeeping of a takeover that finished or died mid-step; the # exclusive create below is what actually grants the workspace. claim.unlink() except OSError: pass token = uuid.uuid4().hex 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)) record = self._lock_owner() if attempt or record is None or _lock_holder_is_alive(record): raise SessionLockError(self._lock_detail(lock, record)) try: lock.unlink() os.rename(str(lock), str(claim)) except OSError: raise SessionLockError("the leftover lock at '%s' could not be cleared" % lock) raise SessionLockError( "the leftover lock at '%s' is being taken over by another run" % lock ) continue birth = _process_creation_time(os.getpid()) try: os.write(handle, str(os.getpid()).encode("ascii")) os.write( handle, ("%d %s %s" % (os.getpid(), "-" if birth is None else birth, token)).encode("ascii"), ) finally: os.close(handle) self._held_lock = lock self._lock_token = token if claim.exists(): try: claim.unlink() except OSError: pass return
def _release_session_lock(self) -> None: lock = getattr(self, "_held_lock", None) if lock is None: return self._held_lock = None token = getattr(self, "_lock_token", None) self._lock_token = None record = _read_lock_record(lock) if token is None or record is None or record[2] != token: # The lock under this name is no longer ours: a takeover happened if lock is not None: self._held_lock = None try: lock.unlink() except OSError: pass # while this run stalled, and unlinking it would steal that holder. return try: lock.unlink() except OSError: pass
def _lock_refusal( self, case_id: str, rel_posix: Optional[str], exc: SessionLockError45 unmodified lines linked = self._linked_path_in_workspace() if linked is not None: kind, rel = linked if kind == "hardlink": exc = WorkspaceLinkError( "hardlinked file in the workspace: '%s'" % rel, HARDLINKED_PATH_IN_WORKSPACE, ) else: exc = WorkspaceLinkError("linked %s in the workspace: '%s'" % (kind, rel)) exc = WorkspaceLinkError("linked %s in the workspace: '%s'" % (kind, rel)) return self._link_refusal(case_id, rel, exc) py_files = self.list_files() chosen = (target_file or (py_files[0] if py_files else "src/__init__.py")).replace("\\", "/")702 unmodified lines rel_path=rel_path, attempts=tuple(attempts), failure_reasons=tuple(r.reason for r in attempts), patch_signatures=tuple(history), ), ) else:123445667891 unmodified line111213141516171 unmodified line192021222324251 unmodified line272829303132331 unmodified line353637383940411 unmodified line43444546474849505152535455565758596061626364651 unmodified line676869707172731 unmodified line757677787980811 unmodified line838485868788891 unmodified line919293949596971 unmodified line991001011021031041051 unmodified line10710810911011192112113114115{ "schema": "lingologos-python-gates-1", "verdict": "CONFIRMED", "sources_sha256": "b65bae4a72d222f72e68b45b176d7dfa814de9314cf604e7cc497e063dac5125", "sources_sha256": "c67f159b042510540c5ceaeed6cb105d706b1af6c84c4956460676ed22d85bcf", "counts": { "CONFIRMED": 12, "CONFIRMED": 13, "REJECTED": 0, "ABSTAIN": 0 },1 unmodified line { "name": "adapter_contract", "verdict": "CONFIRMED", "seconds": 0.829, "check": "check_adapter_contract on PythonLanguageAdapter", "note": "no violations for lingologos-python", "failed_targets": []1 unmodified line { "name": "ast_symbol_graph", "verdict": "CONFIRMED", "seconds": 0.002, "check": "Python AST symbol, method, inheritance, and import graph", "note": "13 symbols, 10 edges extracted", "failed_targets": []1 unmodified line { "name": "test_selection", "verdict": "CONFIRMED", "seconds": 0.003, "check": "import-aware Python test selection", "note": "selected 2 dependent test file(s)", "failed_targets": []1 unmodified line { "name": "strict_abstain_control", "verdict": "CONFIRMED", "seconds": 0.848, "check": "missing optional tools produce ABSTAIN and block verdict", "note": "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN", "failed_targets": []1 unmodified line { "name": "session_transactions", "verdict": "CONFIRMED", "seconds": 3.11, "check": "staged edit commit on VERIFIED and disk isolation on refusal", "note": "clean edit committed VERIFIED (3); syntax error and protected path refused", "failed_targets": [] }, { "name": "session_sweep", "verdict": "CONFIRMED", "seconds": 6.659, "check": "fixed-seed sweep of session verbs over a copied package", "note": "12 seeded operations: 3 committed, 9 refused or raised, tree state compared after each one", "failed_targets": [] }, { "name": "external_topology", "verdict": "CONFIRMED", "seconds": 1.887, "check": "external topology.json, node folders, and six subprocess turns", "note": "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)", "failed_targets": []1 unmodified line { "name": "pattern_corpus_schema", "verdict": "CONFIRMED", "seconds": 0.0, "check": "patterns/pattern_cases.jsonl is a valid case-1 corpus with one pair per card", "note": "16 rows over 8 cards, each with its lock test and its refusal", "failed_targets": []1 unmodified line { "name": "pattern_round_trip", "verdict": "CONFIRMED", "seconds": 0.01, "check": "every row of the pattern corpus re-plans on the fixture as written", "note": "16 rows re-planned: 8 pairs land and compile, 8 refusals repeat with the same code", "failed_targets": []1 unmodified line { "name": "pattern_pair_honesty", "verdict": "CONFIRMED", "seconds": 5.182, "check": "each card's lock test fails until the source edit of its pair lands", "note": "8 cards: every lock test fails while its source edit is missing, so the pair is not decoration", "failed_targets": []1 unmodified line { "name": "pattern_coverage", "verdict": "CONFIRMED", "seconds": 0.003, "check": "patterns/coverage.json states a denominator this fixture still supports", "note": "8 cards over 8 source files and 21 module level functions, denominator stated as the fixture", "failed_targets": []1 unmodified line { "name": "cli_card_agreement", "verdict": "CONFIRMED", "seconds": 0.005, "check": "every verb and flag the card prints exists in the real parser", "note": "13 printed command lines agree with the 8 verbs of the parser", "failed_targets": []1 unmodified line { "name": "self_lint", "verdict": "CONFIRMED", "seconds": 0.145, "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 168 symbols and 350 edges; 45 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 175 symbols and 361 edges; 46 reason codes, every one named in the card; 36 names promised in the Contents, all defined", "failed_targets": [] } ]4 unmodified lines5678891011121314151673 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271284 unmodified linesfrom pathlib import Pathfrom typing import List, Tuple
from lingologos_python.ast_graph import discover_python_files, extract_python_graphfrom lingologos_python.ast_graph import ( discover_python_files, extract_python_graph, importers_of, reexported_names,)from lingologos_python.test_selector import select_python_tests
73 unmodified lines _hard_package(tmp_path) selected = select_python_tests(tmp_path, ["app/plugins/extra.py"]) assert selected == ["tests/test_ns.py"]
def _reexport_package(root: Path) -> None: """One package that answers with names its __init__ imports from inside itself.""" _write(root, "app/__init__.py", "from .impl import helper\nfrom . import tools\n") _write(root, "app/impl.py", "def helper() -> int:\n return 2\n") _write(root, "app/tools.py", "X = 1\n") _write( root, "tests/test_app.py", "from app import helper\n\n\ndef test_helper():\n assert helper() == 2\n", ) _write( root, "tests/test_tools.py", "from app.tools import X\n\n\ndef test_x():\n assert X == 1\n", )
def test_a_reexport_table_names_every_file_a_package_answer_for(tmp_path: Path) -> None: _reexport_package(tmp_path) table = reexported_names(tmp_path, "app/__init__.py") assert "app.impl" in table["helper"] assert "app.tools" in table["tools"]
def test_a_change_behind_a_reexport_reaches_the_test_that_never_named_the_file( tmp_path: Path,) -> None: _reexport_package(tmp_path) files = discover_python_files(tmp_path) assert "tests/test_app.py" in importers_of(tmp_path, files, "app/impl.py") edges = set(_file_edges(tmp_path)) assert ("tests/test_app.py", "app/impl.py") in edges selected = select_python_tests(tmp_path, ["app/impl.py"]) assert "tests/test_app.py" in selected12 unmodified lines1314151617181919 unmodified lines3940414243444524 unmodified lines70717271737475767778798081828312 unmodified lines GATE_ABSTAIN, GATE_MISSING, GATE_REJECTED, HARDLINKED_PATH_IN_WORKSPACE, KERNEL_REASONS, LINKED_PATH_IN_WORKSPACE, NODE_TIMEOUT,19 unmodified lines PATCH_NOT_APPLIED, NODE_TIMEOUT, LINKED_PATH_IN_WORKSPACE, HARDLINKED_PATH_IN_WORKSPACE, SESSION_LOCKED, } assert set(KERNEL_REASONS) == {24 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", "SESSION_LOCKED"): for name in ( "PATH_POLICY", "PATCH_NOT_APPLIED", "NODE_TIMEOUT", "LINKED_PATH_IN_WORKSPACE", "HARDLINKED_PATH_IN_WORKSPACE", "SESSION_LOCKED", ): assert getattr(session_module, name) in REASON_CODES assert getattr(session_module, name) == name
2 unmodified lines34567895 unmodified lines15161718192021105 unmodified lines1271281291301311321332 unmodified lines136137138139140141142143144145462 unmodified lines6086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307312 unmodified linesfrom __future__ import annotations
import osimport threadingimport timefrom pathlib import Pathfrom typing import Any, Dict, Tuple5 unmodified linesimport lingologos_python.session as session_modulefrom lingologos_python.adapter import GATE_TIMEOUT_ENVfrom lingologos_python.session import ( HARDLINKED_PATH_IN_WORKSPACE, LINKED_PATH_IN_WORKSPACE, NODE_TIMEOUT, NodeTimeoutError,105 unmodified lines seen["trace"] = context.attempts[0].trace seen["attempt"] = context.attempt seen["path"] = context.rel_path seen["signatures"] = tuple(context.patch_signatures) return ("return left + right", "return left + right # proposed again")
final, _attempts = session.run_retry_loop("src/mathops.py", learning_proposer, max_attempts=3)2 unmodified lines assert len(seen["trace"]) >= 6 assert seen["attempt"] == 2 assert seen["path"] == "src/mathops.py" # The fate of the first patch, not its words: the signature the stall # detector read is handed to the proposer that should learn from it. assert len(seen["signatures"]) == 1 assert seen["signatures"][0].startswith("sha256:") or len(seen["signatures"][0]) == 40
def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None:462 unmodified lines assert res.reason == session_module.SESSION_LOCKED assert "cannot be read" in res.detail lock.unlink()
def test_the_lock_file_names_pid_birth_and_a_token_this_run_can_prove( sample_pkg: Path, monkeypatch) -> None: """The written record carries three fields, and the token belongs to this acquisition.""" lock = sample_pkg / session_module.SESSION_LOCK_NAME seen: Dict[str, str] = {} real_pipeline = session_module.run_pipeline
def spy_pipeline(case): seen["record"] = lock.read_text(encoding="ascii") return real_pipeline(case)
monkeypatch.setattr(session_module, "run_pipeline", spy_pipeline) session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "VERIFIED" parts = seen["record"].split() assert parts[0] == str(os.getpid()) assert parts[1] != "-" and int(parts[1]) > 0 assert len(parts[2]) == 32 assert not lock.exists()
def test_a_recycled_pid_with_a_different_birth_is_not_the_recorded_holder( sample_pkg: Path,) -> None: """A live pid is not proof: the birth time written in the lock has to match.""" birth = session_module._process_creation_time(os.getpid()) if birth is None: pytest.skip("this host does not report process birth times") lock = sample_pkg / session_module.SESSION_LOCK_NAME lock.write_text("%d %d t0k0n\n" % (os.getpid(), birth + 10**9), encoding="ascii", newline="") session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") # The number answers, the birth does not: the holder recorded is gone and # the takeover is honest. assert res.verdict == "VERIFIED" assert not lock.exists()
def test_two_runs_taking_over_one_leftover_lock_leave_a_single_holder(sample_pkg: Path) -> None: """The takeover renames the corpse first: the loser of the rename is refused.""" lock = sample_pkg / session_module.SESSION_LOCK_NAME lock.write_text("99999999\n", encoding="ascii", newline="") sessions = [PythonWorkspaceSession(sample_pkg) for _ in range(2)] outcomes: Dict[int, str] = {} gate = threading.Barrier(2)
def grab(index: int) -> None: try: gate.wait() sessions[index]._acquire_session_lock() outcomes[index] = "held" except session_module.SessionLockError: outcomes[index] = "refused"
threads = [threading.Thread(target=grab, args=(i,)) for i in range(2)] for thread in threads: thread.start() for thread in threads: thread.join() assert sorted(outcomes.values()) == ["held", "refused"] record = session_module._read_lock_record(lock) assert record is not None and record[0] == os.getpid() winner = sessions[next(i for i, v in outcomes.items() if v == "held")] winner._release_session_lock() assert not lock.exists() stale = sample_pkg / (session_module.SESSION_LOCK_NAME + session_module.SESSION_LOCK_CLAIM_SUFFIX) assert not stale.exists()
def test_a_run_never_unlinks_a_lock_another_run_retook( sample_pkg: Path, monkeypatch) -> None: """Release checks its own token: a lock rewritten while we run is not ours to delete.""" lock = sample_pkg / session_module.SESSION_LOCK_NAME real_pipeline = session_module.run_pipeline
def hijack_pipeline(case): # Mid-run, a different holder takes the workspace over under our name. lock.write_text("99999999 - someone-elses-token\n", encoding="ascii", newline="") return real_pipeline(case)
monkeypatch.setattr(session_module, "run_pipeline", hijack_pipeline) session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "VERIFIED" # Our release read the token, found it was not ours, and left the lock alone. assert lock.exists() assert "someone-elses-token" in lock.read_text(encoding="ascii") lock.unlink()
def test_a_hardlinked_pair_in_the_workspace_is_refused_by_name(sample_pkg: Path) -> None: """Two names, one file: the copy would split what the disk holds as one.""" twin = sample_pkg / "src" / "mathops_twin.py" os.link(sample_pkg / "src" / "mathops.py", twin) session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "REFUSED" assert res.reason == HARDLINKED_PATH_IN_WORKSPACE assert "src/mathops" in res.detail twin.unlink()
def test_an_edit_does_not_commit_through_a_hardlinked_name(sample_pkg: Path) -> None: """The staging copy refuses the hardlink and the real file keeps its bytes.""" twin = sample_pkg / "src" / "mathops_twin.py" os.link(sample_pkg / "src" / "mathops.py", twin) session = PythonWorkspaceSession(sample_pkg) res = session.edit_file( "src/mathops.py", "return left + right", "return left * right", commit=True ) assert res.verdict == "REFUSED" assert res.reason == HARDLINKED_PATH_IN_WORKSPACE assert res.committed is False text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="") assert "return left + right" in text twin.unlink()5 unmodified lines67891011121314151617181918 unmodified lines3839403841424344132 unmodified lines177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320423 unmodified lines74474574674774874975011 unmodified lines76276376476576676776876977077177277377477577677777877910 unmodified lines7907917927937947957967977987998008018028038046478058068078088098108118128138145 unmodified linesimport astimport hashlibimport jsonimport osimport randomimport reimport shutilimport subprocessimport sysimport tempfileimport timefrom pathlib import Pathfrom typing import Callable, Dict, List, Sequence, Set, Tuple
18 unmodified linesfrom lingologos_python.ast_graph import discover_python_files, extract_python_graph # noqa: E402from lingologos_python.patterns import PATTERNS, module_level_functions, plan_pattern # noqa: E402from lingologos_python.reasons import REASON_CODES # noqa: E402from lingologos_python.session import PythonWorkspaceSession # noqa: E402from lingologos_python.session import SESSION_LOCK_NAME, PythonWorkspaceSession # noqa: E402from lingologos_python.test_selector import select_python_tests # noqa: E402
FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"132 unmodified lines return _confirmed(check, "clean edit committed VERIFIED (3); syntax error and protected path refused")
# The sweep the fuzz test runs at full length gets a short, seeded twin here:# the same invariant, a dozen operations, a fixed seed so the gate answers the# same way on every machine. It exists because the card promises that no change# lands without a commit and no refusal leaves a trace, and a gate, not only a# test file, has to keep that promise under review.SESSION_SWEEP_SEED = 20260301SESSION_SWEEP_PLAN: List[str] = ( ["valid_edit_commit"] * 2 + ["valid_create_commit"] + ["verify"] + ["traversal_edit"] * 2 + ["protected_create"] + ["missing_edit"] + ["missing_delete"] + ["create_existing"] + ["empty_edit"] + ["bad_pattern"])
def _sweep_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 gate_session_sweep() -> GateResult: check = "fixed-seed sweep of session verbs over a copied package" rng = random.Random(SESSION_SWEEP_SEED) kinds = list(SESSION_SWEEP_PLAN) rng.shuffle(kinds) files = ["src/mathops.py", "src/textops.py", "tests/test_mathops.py", "tests/test_textops.py"] ops = [(kind, rng.choice(files)) for kind in kinds]
with tempfile.TemporaryDirectory(prefix="lingologos_python_sweep_") as tmp_dir: ws = Path(tmp_dir) / "pkg" shutil.copytree(FIXTURE_PKG, ws) failures: List[str] = [] committed = 0 refused = 0 raised = 0 for index, (kind, rel) in enumerate(ops): session = PythonWorkspaceSession(ws) lock_held = False if index == 5: # Plant a live holder: our own process is alive, so the lock is real. (ws / SESSION_LOCK_NAME).write_text(str(os.getpid()), encoding="ascii") lock_held = True before = _sweep_tree_state(ws) try: res = None if kind == "valid_edit_commit": path = ws / Path(*rel.split("/")) text = path.read_text(encoding="utf-8", newline="") anchor = [line for line in text.split("\n") if line.strip()][-1] res = session.edit_file(rel, anchor, anchor + "\n# swept", commit=True) 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(rel) 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 == "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 elif kind == "create_existing": try: res = session.create_file(rel, "x = 1\n", commit=True) except FileExistsError: raised += 1 elif kind == "empty_edit": res = session.edit_file(rel, "", "", commit=True) elif kind == "bad_pattern": try: res = session.apply_pattern("ghost-card-%d" % index, commit=True) except KeyError: raised += 1 after = _sweep_tree_state(ws) 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 res.verdict not in ("VERIFIED", "SINGLE_PROVER") or not res.accepted: failures.append("%d %s: committed with verdict %s" % (index, kind, res.verdict)) changed = {r for r in set(before) | set(after) if before.get(r) != after.get(r)} if changed and not changed <= set(res.touched_files): failures.append("%d %s: changed files the result did not name" % (index, kind)) 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 is a finding, not a pass failures.append("%d %s: %s: %s" % (index, kind, type(exc).__name__, exc)) finally: if lock_held: (ws / SESSION_LOCK_NAME).unlink(missing_ok=True) if failures: return _rejected(check, "; ".join(failures), failures) if committed < 2 or refused + raised < len(SESSION_SWEEP_PLAN) - 3: return _rejected( check, "sweep landed %d commits and %d refusals out of %d operations" % (committed, refused + raised, len(SESSION_SWEEP_PLAN)), ) return _confirmed( check, "%d seeded operations: %d committed, %d refused or raised, tree state compared after each one" % (len(ops), committed, refused + raised), )
def gate_external_topology() -> GateResult: check = "external topology.json, node folders, and six subprocess turns" topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))423 unmodified lines ("test_selection", gate_test_selection), ("strict_abstain_control", gate_strict_abstain_control), ("session_transactions", gate_session_transactions), ("session_sweep", gate_session_sweep), ("external_topology", gate_external_topology), ("pattern_corpus_schema", gate_pattern_corpus_schema), ("pattern_round_trip", gate_pattern_round_trip),11 unmodified lines parser.add_argument("--report", default=None, help="Optional path to write JSON report.") args = parser.parse_args(argv)
# The digest anchors the report to a tree, so it is taken before the first # gate runs and asked for again when the report is written: the numbers # inside describe the tree that was judged at the start, and a tree that # moved while the gates ran earns no report at all. opening_digest = bundle_digest(digest_input_files(ROOT))
results: Dict[str, GateResult] = {} seconds: Dict[str, float] = {} for name, fn in GATES: started = time.monotonic() results[name] = fn() seconds[name] = round(time.monotonic() - started, 3)
counts = {v: 0 for v in VERDICTS} for res in results.values():10 unmodified lines )
if args.report: closing_digest = bundle_digest(digest_input_files(ROOT)) if closing_digest != opening_digest: print( "REPORT: REFUSED (the tree changed while the gates ran, before %s and after %s): " "rerun on a quiet tree" % (opening_digest[:12], closing_digest[:12]) ) return 1 out_path = Path(args.report) out_path.parent.mkdir(parents=True, exist_ok=True) payload = { "schema": "lingologos-python-gates-1", "verdict": overall, "sources_sha256": bundle_digest(digest_input_files(ROOT)), "sources_sha256": opening_digest, "counts": counts, "gates": [ { "name": name, "verdict": results[name].verdict, "seconds": seconds[name], "check": results[name].command, "note": results[name].note, "failed_targets": list(results[name].failed_targets),README.md+24-13
lingologos_python/ast_graph.py+88-1
lingologos_python/reasons.py+2
lingologos_python/session.py+184-34
results/gates.json+23-3
tests/test_ast_imports.py+42-1
tests/test_reasons.py+10-1
tests/test_session.py+128
tools/run_gates.py+161-2