diff --git a/src/inferrsi/box/README.md b/src/inferrsi/box/README.md index 8f365a91e..2830fc4a2 100644 --- a/src/inferrsi/box/README.md +++ b/src/inferrsi/box/README.md @@ -30,38 +30,52 @@ verified reversal advances the generation and creates a fresh activation. `accept_evidence(receipt)` admits only a settled check from the current activation. Call `close()` when finished and inspect its cleanup result. -Box parses and compiles candidates in `prepare`. It resolves imports and -decorators from already loaded namespaces or staged declarations without -running them. During commit, new functions use the actual module dictionary -as their global namespace. A journal restores prior object identities on -uninstall or rollback, including the inverse of a partially settled group -uninstall. +Box checks import policy and compiles candidate code during `prepare`. +At the commit safe point, CPython evaluates imports, constants, annotations, +and decorators. New functions use the live module dictionary as their global +namespace. The journal restores prior bindings on uninstall or rollback and +restores escaped nested functions when a compatible earlier version exists. +An unverifiable reversal isolates the participant until verified respawn. - A nonempty `targets` list keeps the original body-only admission, including unchanged signatures, defaults, decorators, closures, and module bindings. Omit `targets` on the wire or pass `targets=()` for structural discovery. Box applies the enrolled target policy to the discovered definitions. - Structural edits support compatible function signatures and defaults, - declared constants, imports from loaded or same-patch modules, and added - functions and methods. Supported auxiliary classes and decorators use - verified construction semantics. A surviving reference to a removed method + declared constants, added functions and methods, and new auxiliary classes. + New imports may use loaded modules, the standard library, same-patch created + modules, or sources admitted by the adapter's import policy. A surviving + reference to a removed method must resolve to a callable fallback. Box also checks ordinary Python fallback signatures for unambiguous direct calls with fixed argument counts and names. - In-place constructor or JIT signature changes, direct JIT deletion, and - unresolved cold imports require a restart. + Constructor changes on existing classes, in-place JIT signature changes, + and unauthorized cold imports require a restart. JIT deletion requires the + same caller and alias checks as Python definitions and clears launch hooks + and caches. To switch a JIT signature in a live process, add a renamed kernel and update the wrapper in the same patch. - `PatchSpec(action="create", base_hash=None, targets=())` creates a dotted, - previously unused module in memory. `CompoundPatchSpec` orders staged - dependencies before their callers and retires them in reverse. CPU workers + previously unused module in memory and executes its source at commit. + `CompoundPatchSpec` orders both created and edited modules by their new + imports and retires them in reverse. CPU workers opt in through an `Endpoint` `create_module_policy` callback returning the approved virtual source path. Native adapters derive that approval from their module allowlist or prefixes and source roots. The Lab declares reset items, admits trusted candidate sources, and owns -quiescence. Each managed workload stays within its admitted lifetime. Python -witnesses count AST-inserted hits and keep the canonical `code_hash`. Native -JIT witnesses report launches and compiled cache entries. Source receipts +quiescence. During native construction and journal reversal, Box checks existing containers +reachable through built-in containers in managed namespaces, including dict key order. +A failed construction also checks the attribute dicts of live objects reachable from +managed namespaces. The profile's `RequestState` snapshots, restores, and resets the +state it owns. A clean `rolled_back` receipt requires all of these checks; any other +observed change returns `in_doubt` and isolates the Box until a verified respawn. +Effects Box cannot observe, such as files, devices, or objects reachable only through +C extensions, remain the responsibility of the Lab's candidate admission. + +Python witnesses count AST-inserted hits and keep the canonical `code_hash`. Native +JIT witnesses report launches and compiled cache entries. The JIT rebuild runs +after Python declarations have been bound so caller discovery sees new kernels. +Device launches occur in the admitted workload. Source receipts include a deterministic `structure_hash`, and mutation receipts include `structure_hashes` by module. The native coordinator checks those hashes across worker ranks. Box controls registered Python bindings and the reset diff --git a/src/inferrsi/box/endpoint.py b/src/inferrsi/box/endpoint.py index 295655e36..328c81808 100644 --- a/src/inferrsi/box/endpoint.py +++ b/src/inferrsi/box/endpoint.py @@ -38,6 +38,7 @@ def __init__( module_resolver: Callable[[str], ManagedModule] | None = None, create_module_policy=None, allowed_target=None, + allowed_import=None, observe_check: Callable[[Command, dict], dict] | None = None, ): if not modules and module_resolver is None and create_module_policy is None: @@ -51,6 +52,7 @@ def __init__( module_resolver=module_resolver, create_module_policy=create_module_policy, allowed_target=allowed_target, + allowed_import=allowed_import, ) self._lock = Lock() self._journal: dict[str, tuple[bytes, bytes]] = {} diff --git a/src/inferrsi/box/kernel/jit.py b/src/inferrsi/box/kernel/jit.py index d92aade64..56a331547 100644 --- a/src/inferrsi/box/kernel/jit.py +++ b/src/inferrsi/box/kernel/jit.py @@ -15,6 +15,7 @@ from types import FunctionType, ModuleType from ..protocol import BoxError +from .journal import MISSING from .witness import record_hit _REQUIRED = ( @@ -174,16 +175,6 @@ def discover_callers(value): ) -def merge_scopes(first, second): - def unique(items): - return tuple({id(item): item for item in items}.values()) - - return JitScope( - unique((*first.kernels, *second.kernels)), - unique((*first.tuners, *second.tuners)), - ) - - def _site_key(key, kernel): return f"{key}#launch:{id(kernel)}" @@ -248,7 +239,6 @@ def compilation_proof(scope, key, counts): _TEXT_FIELDS = ("raw_src", "starting_line_number", "def_file_line_number") -_MISSING = object() def _source_values(kernel): @@ -277,12 +267,12 @@ def _set_source(kernel, text, attributes): @contextmanager def _source_cache(filename, source): - previous = linecache.cache.get(filename, _MISSING) + previous = linecache.cache.get(filename, MISSING) linecache.cache[filename] = (len(source), None, source.splitlines(keepends=True), filename) try: yield finally: - if previous is _MISSING: + if previous is MISSING: linecache.cache.pop(filename, None) else: linecache.cache[filename] = previous @@ -323,13 +313,12 @@ def prepare(kernel, filename, source, node): class JitSnapshot: kernel: object scope: JitScope - active_scope: JitScope | None text: tuple attributes: tuple hooks: tuple @classmethod - def take(cls, kernel, scope, active_scope): + def take(cls, kernel, scope): attributes = tuple( (item, {name: getattr(item, name) for name in names if hasattr(item, name)}) for item, names in ( @@ -340,7 +329,6 @@ def take(cls, kernel, scope, active_scope): return cls( kernel, scope, - active_scope, _source_values(kernel), attributes, tuple(tuple(item.pre_run_hooks) for item in scope.kernels), @@ -375,6 +363,8 @@ def _same_hooks(first, second): def enroll_new(scope, kernel, key): # A later launch populates the owned cache, independently of the undo snapshot. _clear_caches(kernel) + for tuner in scope.tuners: + tuner.cache = {} arm(scope, key) @@ -389,3 +379,49 @@ def same_source(first, second): for (a, x), (b, y) in zip(first.attributes, second.attributes, strict=True) ) ) + + +def record_change(journal, binding, apply): + scope = discover_callers(binding.value) + journal.change( + lambda: JitSnapshot.take(binding.kernel, scope), + JitSnapshot.restore, + lambda: apply(scope), + same=same_source, + ) + return scope + + +def registry(): + runtime = sys.modules.get("triton.runtime.jit") + return vars(runtime).get("_triton_jit_function_registry") if runtime is not None else None + + +def record_registrations(journal, registered, before, namespace, additions): + if registered is None: + return + for target, compiled in additions.items(): + key = f"{namespace['__name__']}:{target}" + value = registered.get(key, MISSING) + old = before.get(key, MISSING) + function = getattr(value, "fn", None) + if ( + value is not old + and isinstance(function, FunctionType) + and function.__globals__ is namespace + and function.__code__ == compiled.canonical + ): + journal.record_mapping(registered, key, old) + + +def retire(journal, binding): + def detach(scope): + disarm(scope, binding.witness_key) + _clear_caches(binding.kernel) + for tuner in scope.tuners: + tuner.cache = {} + + record_change(journal, binding, detach) + registered = registry() + if registered is not None and registered.get(binding.witness_key) is binding.kernel: + journal.mapping(registered, binding.witness_key, MISSING) diff --git a/src/inferrsi/box/kernel/journal.py b/src/inferrsi/box/kernel/journal.py index 4156d37c3..62f4e1cd3 100644 --- a/src/inferrsi/box/kernel/journal.py +++ b/src/inferrsi/box/kernel/journal.py @@ -1,9 +1,14 @@ """Reversible writes at a Box transaction safe point.""" +from collections import Counter, defaultdict from dataclasses import dataclass +from itertools import chain from operator import is_ +from sys import getrefcount +from types import FunctionType, GetSetDescriptorType from ..protocol import BoxError +from .syntax import raw_namespace MISSING = object() @@ -15,8 +20,67 @@ def _put(mapping, name, value): mapping[name] = value -def same_objects(first, second): - return all(a is b for a, b in zip(first, second, strict=True)) +def _get(mapping, name): + return mapping.get(name, MISSING) + + +def _get_class(owner, name): + return _get(raw_namespace(owner), name) + + +def _put_class(owner, name, value): + if value is MISSING: + delattr(owner, name) + else: + setattr(owner, name, value) + + +def same_mapping(first, second): + return first.keys() == second.keys() and all( + first[key] is value for key, value in second.items() + ) + + +def instance_dict(value): + """Return an instance's plain attribute dict without running user descriptors.""" + mro = type.__dict__["__mro__"].__get__(type(value)) + getter = next((s["__dict__"] for s in map(raw_namespace, mro) if "__dict__" in s), None) + state = getter.__get__(value) if type(getter) is GetSetDescriptorType else None + return state if type(state) is dict else None + + +def walk_containers(roots, *, defaults=None, instances=None): + pending, seen = list(roots), set() + while pending: + value = pending.pop() + key = id(value) + if key in seen: + continue + seen.add(key) + kind = type(value) + if kind is FunctionType and defaults is not None: + pending.extend(defaults(value)) + if instances is not None and (state := instance_dict(value)) is not None: + instances.append((value, state, state.copy())) + pending.extend(state.values()) + if kind in (dict, tuple, list, set, frozenset): + children = tuple(chain.from_iterable(value.items())) if kind is dict else value + yield value, children + pending.extend(children) + + +@dataclass(frozen=True) +class Slot: + owner: object + name: str + get: object + put: object + + def read(self): + return self.get(self.owner, self.name) + + def write(self, value): + self.put(self.owner, self.name, value) @dataclass(frozen=True) @@ -26,10 +90,47 @@ class Entry: before: object after: object same: object = is_ - - def verify(self): - if not self.same(self.read(), self.after): - raise BoxError("in_doubt", "journaled binding was changed outside Box") + slot: Slot | None = None + + +class OwnedReferences: + """Attribute incoming references from journal values and their Python containers.""" + + def __init__(self, roots, counts, slots): + self.counts = counts + self.containers = {} + self.parents = defaultdict(set) + + def defaults(function): + for name in ("__defaults__", "__kwdefaults__"): + value = getattr(function, name) + if value is not None: + if (id(function), name) not in slots: + counts[id(value)] += 1 + yield value + + for value, items in walk_containers(roots, defaults=defaults): + key = id(value) + self.containers[key] = value + counts[key] += 1 # This index itself retains the container. + for item in items: + counts[id(item)] += 1 + self.parents[id(item)].add(key) + + def escaped(self, key, direct_references): + if direct_references > self.counts[key]: + return True + seen = set() + pending = list(self.parents[key]) + while pending: + parent = pending.pop() + if parent in seen: + continue + seen.add(parent) + if getrefcount(self.containers[parent]) > self.counts[parent] + 1: + return True + pending.extend(self.parents[parent]) + return False class Journal: @@ -44,36 +145,43 @@ def mark(self): def commit_slice(self, mark): return tuple(self._entries[mark:]) - def change(self, read, write, apply, *, same=is_): + def change(self, read, write, apply, *, same=is_, slot=None): before = read() try: apply() finally: - self._entries.append(Entry(read, write, before, read(), same)) + self._entries.append(Entry(read, write, before, read(), same, slot)) - def set(self, read, write, value, *, same=is_): - self.change(read, write, lambda: write(value), same=same) - if not same(self._entries[-1].after, value): + def set(self, slot, value): + self.change(slot.read, slot.write, lambda: slot.write(value), slot=slot) + if self._entries[-1].after is not value: raise BoxError("in_doubt", "journaled write did not settle") def mapping(self, mapping, name, value): - self.set(lambda: mapping.get(name, MISSING), lambda item: _put(mapping, name, item), value) + self.set(Slot(mapping, name, _get, _put), value) - def attr(self, obj, name, value): - self.set(lambda: getattr(obj, name), lambda item: setattr(obj, name, item), value) + def record_mapping(self, mapping, name, before): + slot = Slot(mapping, name, _get, _put) + self._entries.append(Entry(slot.read, slot.write, before, slot.read(), slot=slot)) + + def track_mapping(self, mapping, before): + for name in mapping.keys() | before.keys(): + if mapping.get(name, MISSING) is not before.get(name, MISSING): + self.record_mapping(mapping, name, before.get(name, MISSING)) - def class_attr(self, owner, name, value): - def write(item): - if item is MISSING: - delattr(owner, name) - else: - setattr(owner, name, item) + def attr(self, obj, name, value): + self.set(Slot(obj, name, getattr, setattr), value) - self.set(lambda: vars(owner).get(name, MISSING), write, value) + def member(self, owner, name, value): + if isinstance(owner, type): + self.set(Slot(owner, name, _get_class, _put_class), value) + else: + self.mapping(vars(owner), name, value) @staticmethod def _undo(entry): - entry.verify() + if not entry.same(entry.read(), entry.after): + raise BoxError("in_doubt", "journaled binding was changed outside Box") entry.write(entry.before) if not entry.same(entry.read(), entry.before): raise BoxError("in_doubt", "journal did not restore the original binding") @@ -84,5 +192,40 @@ def undo_to(self, mark): self._entries.pop() def revert(self, entries): - for entry in reversed(entries): - self.change(entry.read, entry.write, lambda: self._undo(entry), same=entry.same) + for e in reversed(entries): + self.change(e.read, e.write, lambda: self._undo(e), same=e.same, slot=e.slot) + + def owned_references(self, retained, snapshots, containers): + entries = {id(entry): entry for entry in chain(retained, self._entries)}.values() + roots = [value for entry in entries for value in (entry.before, entry.after)] + slot_refs = {id(entry.slot): entry.slot for entry in entries if entry.slot is not None} + slots = {(id(slot.owner), slot.name): slot for slot in slot_refs.values()} + # Inverse writes share their slots with the original entries. + counts = Counter(map(id, roots)) + counts.update(id(slot.read()) for slot in slots.values()) + counts.update(id(slot.owner) for slot in slot_refs.values()) + for value, before in snapshots: + counts[id(value)] += 1 + counts.update(id(item) for pair in before.items() for item in pair) + for value, before in containers: + counts[id(value)] += 1 + counts.update(map(id, before)) + return OwnedReferences(roots, counts, slots) + + def verify_mappings(self, snapshots, *, ordered=False): + """Project owned writes onto checkpoint bindings, including inverse writes.""" + expected = {id(space): before.copy() for space, before in snapshots} + written = set() + for entry in self._entries: + if slot := entry.slot: + if (values := expected.get(id(slot.owner))) is not None: + key = slot.name + if values.get(key, MISSING) is not entry.before: + raise BoxError("in_doubt", "a binding changed before a journaled write") + _put(values, key, entry.after) + written.add(id(slot.owner)) + if any(not same_mapping(space, expected[id(space)]) for space, _ in snapshots): + raise BoxError("in_doubt", "mutation made unjournaled binding changes") + # Callers observe dict order, so an unjournaled reorder is not a restore either. + if ordered and any(id(s) not in written and [*s] != [*b] for s, b in snapshots): + raise BoxError("in_doubt", "mutation reordered a live dict") diff --git a/src/inferrsi/box/kernel/swap.py b/src/inferrsi/box/kernel/swap.py index 4639bfdab..2d33c14c4 100644 --- a/src/inferrsi/box/kernel/swap.py +++ b/src/inferrsi/box/kernel/swap.py @@ -14,26 +14,28 @@ import sys import tokenize from collections import ChainMap, Counter -from collections.abc import Callable, Iterable, Mapping -from copy import deepcopy +from collections.abc import Callable, Mapping +from copy import copy from dataclasses import dataclass, field +from functools import cache, lru_cache from importlib.machinery import ModuleSpec from itertools import chain, pairwise from pathlib import Path -from types import CellType, CodeType, FunctionType, MethodType, ModuleType, new_class +from types import CodeType, FunctionType, MethodType, ModuleType from uuid import uuid4 +from weakref import ref from ..patch import PatchSpec, validate_source from ..protocol import MAX_SOURCE_BYTES, BoxError, source_hash from . import jit, syntax -from .journal import MISSING, same_objects +from .journal import MISSING, Journal from .witness import HIT_HOOK, ensure_hook, record_hit _UNSUPPORTED_FLAGS = inspect.CO_GENERATOR | inspect.CO_COROUTINE | inspect.CO_ASYNC_GENERATOR _FORBIDDEN_METHOD_NAMES = frozenset({"__init__", "__new__", "__post_init__"}) -_MISSING = MISSING _LEGACY_GLOBALS = (MISSING, vars, globals, locals, exec, eval, setattr, delattr) -_FUTURE_ANNOTATIONS = __future__.annotations.compiler_flag +_FUTURES = sum(getattr(__future__, name).compiler_flag for name in __future__.all_feature_names) +_SHELL_METACLASS = "__inferrsi_box_live_body__" def _read_source(path: Path) -> str: @@ -51,9 +53,11 @@ def _parse(source: str, filename: str) -> ast.Module: raise BoxError("restart_required", "module cannot be parsed") from exc -def _compile(tree: ast.Module, filename: str) -> CodeType: +def _compile(tree: ast.Module, filename: str, flags: int = 0) -> CodeType: try: - return compile(tree, filename, "exec", dont_inherit=True, optimize=sys.flags.optimize) + return compile( + tree, filename, "exec", flags=flags, dont_inherit=True, optimize=sys.flags.optimize + ) except (SyntaxError, ValueError, RecursionError) as exc: raise BoxError("restart_required", "module cannot be compiled") from exc @@ -63,7 +67,7 @@ def _node(tree: ast.Module, name: str) -> list[ast.ClassDef | ast.FunctionDef]: path = [] parent = tree for i, part in enumerate(parts): - kind = ast.FunctionDef if i == len(parts) - 1 else ast.ClassDef + kind = (ast.FunctionDef, ast.AsyncFunctionDef) if i == len(parts) - 1 else ast.ClassDef matches = [node for node in parent.body if isinstance(node, kind) and node.name == part] if len(matches) != 1: raise BoxError("restart_required", "target has no unique direct source definition") @@ -123,7 +127,10 @@ def _class_mro(owner): def _staged_class_mro(definition): # C3 uses only the already resolved bases and their real MROs. bases = definition.bases or (object,) - pending = [*map(_class_mro, bases), bases] + pending = [ + *(_staged_class_mro(b) if isinstance(b, ClassPlan) else _class_mro(b) for b in bases), + bases, + ] mro = [definition] while pending: for head, *_ in pending: @@ -235,7 +242,7 @@ def _loses_method(mro, name, removed, planned, call, on_instance): if name in methods: return not _accepts_method_call(methods[name], call, on_instance) if isinstance(cls, ClassPlan): - if any(action == "fields" and name in data[0] for action, data in cls.body): + if name in cls.fields: return True continue if name in removed.get(id(cls), ()): @@ -361,13 +368,30 @@ def reads(instructions, *, receiver, lexical): ) -def _prospective_method_shape(module, plan, target, signature): +def _static_reference(node, namespace): + if isinstance(node, ast.Name): + return namespace.get(node.id, vars(builtins).get(node.id, MISSING)) + if isinstance(node, ast.Attribute): + owner = _static_reference(node.value, namespace) + if isinstance(owner, (type, ModuleType)): + return syntax.raw_namespace(owner).get(node.attr, MISSING) + return MISSING + + +def _prospective_method_shape(module, plan, target, node, namespace): + signature = _declared_signature(node.args) if target in plan.additions: - decorators = [item[0] for item in plan.additions[target][3]] - descriptor = decorators[0] if decorators else FunctionType - known = all(item is staticmethod or item is classmethod for item in decorators) - callable_value = all(item is not property for item in decorators) - return callable_value, descriptor, signature if known else None + decorators = [ + _static_reference(item.func if isinstance(item, ast.Call) else item, namespace) + for item in node.decorator_list + ] + outer = decorators[0] if decorators else None + descriptor = outer if outer is staticmethod or outer is classmethod else FunctionType + known = all( + any(item is supported for supported in (staticmethod, classmethod, cache, lru_cache)) + for item in decorators + ) + return known, descriptor, signature if known else None owner, name = _location(module.module, target) return _live_method_shape(syntax.raw_namespace(owner)[name], signature) @@ -387,34 +411,38 @@ def validate_method_removals(entries): views, classes, planned = [], {}, {} for module, plan, source in entries: live = syntax.raw_namespace(module.module) - exports = plan.exported if plan is not None else {} - classes.update( - (id(value), value) - for value in chain(live.values(), exports.values()) - if isinstance(value, type) - ) tree = _parse(source, str(module.path)) namespace = live targets = dict.fromkeys(module.bindings) if plan is not None: - namespace = { - name: value - for name, value in live.items() - if plan.writes.get(name) is not MISSING and name not in plan.removals - } - namespace.update(exports) - namespace.update(plan.classes) - classes.update((id(value), value) for value in plan.classes.values()) + namespace = dict(live) + for name in plan.deleted | set(plan.removals): + namespace.pop(name, None) + for name, (dependency, member) in plan.imports.items(): + imported = sys.modules.get(dependency) + if imported is not None: + namespace[name] = ( + syntax.raw_namespace(imported).get(member, MISSING) if member else imported + ) + for name, node in plan.classes.items(): + bases = tuple(_static_reference(base, namespace) for base in node.bases) + if not all(isinstance(base, (type, ClassPlan)) for base in bases): + syntax.reject("cannot verify a new class MRO alongside method removal") + namespace[name] = ClassPlan(bases, syntax.declarations(node.body)) targets.update(dict.fromkeys(plan.additions)) for target in plan.removals: targets.pop(target) for target in chain(plan.additions, plan.codes): owner, name = _location(module.module, target, namespace=namespace) if isinstance(owner, (type, ClassPlan)): - signature = _declared_signature(_node(tree, target)[-1].args) planned.setdefault(id(owner), {})[name] = _prospective_method_shape( - module, plan, target, signature + module, plan, target, _node(tree, target)[-1], namespace ) + classes.update( + (id(value), value) + for value in namespace.values() + if isinstance(value, (type, ClassPlan)) + ) locations = { target: _location(module.module, target, namespace=namespace) for target in targets } @@ -458,7 +486,11 @@ def validate_method_removals(entries): def _global_value(function: FunctionType, name: str): - return function.__globals__.get(name, function.__builtins__.get(name, _MISSING)) + return function.__globals__.get(name, function.__builtins__.get(name, MISSING)) + + +def _global_bindings(function, code): + return {key: _global_value(function, key) for key in _globals(code)} def _uses_hook_name(node: ast.FunctionDef) -> bool: @@ -469,21 +501,13 @@ def _uses_hook_name(node: ast.FunctionDef) -> bool: ) -def _docstring(body: list[ast.stmt]) -> str | None: - if body and isinstance(body[0], ast.Expr): - value = body[0].value - if isinstance(value, ast.Constant) and isinstance(value.value, str): - return value.value - return None - - def _body(body: list[ast.stmt]) -> tuple[str, ...]: return tuple(ast.dump(statement) for statement in body) def _inject_witness_hook(node: ast.FunctionDef, witness_key: str) -> None: """Insert ``__inferrsi_box_hit__(witness_key)`` before the first non-docstring statement.""" - index = 1 if _docstring(node.body) is not None else 0 + index = 1 if syntax.docstring(node.body) is not None else 0 statement = ast.Expr( value=ast.Call( func=ast.Name(id=HIT_HOOK, ctx=ast.Load()), @@ -497,19 +521,9 @@ def _inject_witness_hook(node: ast.FunctionDef, witness_key: str) -> None: node.body.insert(index, statement) -def _compile_live_codes( - source: str, - filename: str, - module_name: str, - target_names: Iterable[str], -) -> dict[str, CodeType]: - names = tuple(target_names) - tree = _parse(source, filename) - paths: dict[str, list[ast.ClassDef | ast.FunctionDef]] = {} - for name in names: - path = _node(tree, name) - _inject_witness_hook(path[-1], f"{module_name}:{name}") - paths[name] = path +def _compile_witnesses(tree, filename, module, paths): + for name, path in paths.items(): + _inject_witness_hook(path[-1], f"{module}:{name}") compiled = _compile(tree, filename) return {name: _code(compiled, path) for name, path in paths.items()} @@ -560,26 +574,24 @@ def _code_hash(code: CodeType) -> str: return hashlib.sha256(marshal.dumps(_code_value(code), _MARSHAL_VALUE_FORMAT)).hexdigest() +def _unwrapped_member(value): + if isinstance(value, (staticmethod, classmethod)): + return value.__func__ + if isinstance(value, property): + return value.fget + return value + + def _resolve(owner: ModuleType | type | None, name: str): - value = owner - parts = name.split(".") - for index, part in enumerate(parts): - if not isinstance(value, (ModuleType, type)): + for part in name.split("."): + if not isinstance(owner, (ModuleType, type)): return None - value = syntax.raw_namespace(value).get(part) - if index == len(parts) - 1: - if isinstance(value, (staticmethod, classmethod)): - value = value.__func__ - elif isinstance(value, property): - value = value.fget - return value + owner = syntax.raw_namespace(owner).get(part) + return _unwrapped_member(owner) def _function(value): - if isinstance(value, (staticmethod, classmethod)): - value = value.__func__ - elif isinstance(value, property): - value = value.fget + value = _unwrapped_member(value) if isinstance(value, MethodType): return value.__func__ if isinstance(value, FunctionType): @@ -607,6 +619,28 @@ def _module_origin(module: ModuleType, source_root: Path) -> Path: return path +def _source_binding(module, name, path, parsed): + value = _resolve(module, name) + function = _function(value) + if ( + name.rsplit(".", 1)[-1] in _FORBIDDEN_METHOD_NAMES + or not isinstance(function, FunctionType) + or function.__globals__ is not vars(module) + or function.__code__.co_flags & _UNSUPPORTED_FLAGS + ): + syntax.reject("target is not a registered synchronous binding") + code = function.__code__ + if Path(code.co_filename).resolve() != path: + raise BoxError("binding_mismatch", "target code was loaded outside the source file") + tree, compiled = parsed(code.co_filename) + ast_path = _node(tree, name) + if _code(compiled, ast_path) != code: + raise BoxError("binding_mismatch", "loaded code differs from source definition") + if _uses_hook_name(ast_path[-1]) or HIT_HOOK in _globals(code): + syntax.reject("target references reserved witness hook") + return value, function, ast_path + + def discover_targets( source_root: Path, module: ModuleType, @@ -619,9 +653,8 @@ def discover_targets( if HIT_HOOK in vars(module): raise BoxError("binding_mismatch", "module shadows reserved witness hook") source = _read_source(path) - filename = str(path) - tree = _parse(source, filename) - compiled = _compile(tree, filename) + parsed = _source_parser(source) + tree, _ = parsed(str(path)) candidates: list[str] = [] for node in tree.body: if isinstance(node, ast.FunctionDef): @@ -637,25 +670,11 @@ def discover_targets( continue if allow_target is not None and not allow_target(name): continue - function = _function(_resolve(module, name)) - if ( - not isinstance(function, FunctionType) - or function.__globals__ is not vars(module) - or function.__code__.co_flags & _UNSUPPORTED_FLAGS - ): - continue - code = function.__code__ try: - if Path(code.co_filename).resolve() != path: - continue - ast_path = _node(tree, name) - expected_code = _code(compiled, ast_path) + _, function, _ = _source_binding(module, name, path, parsed) except (OSError, RuntimeError, BoxError): continue - if expected_code != code: - continue - if _uses_hook_name(ast_path[-1]) or HIT_HOOK in _globals(code): - continue + code = function.__code__ if code in seen_codes: continue seen_codes.add(code) @@ -663,6 +682,15 @@ def discover_targets( return discovered +def _source_parser(source): + @cache + def parsed(filename): + tree = _parse(source, filename) + return tree, _compile(tree, filename) + + return parsed + + @dataclass(frozen=True) class CompiledCode: """Pair of uninstrumented canonical bytecode and AST-instrumented live bytecode.""" @@ -670,35 +698,96 @@ class CompiledCode: canonical: CodeType live: CodeType native: jit.JitEdit | None = None - metadata: object = None + stub: CodeType | None = None nested: tuple = () @dataclass class SourcePlan: codes: dict[str, CompiledCode] = field(default_factory=dict) - writes: dict = field(default_factory=dict) - additions: dict = field(default_factory=dict) + additions: dict[str, CompiledCode] = field(default_factory=dict) + units: list = field(default_factory=list) classes: dict = field(default_factory=dict) - class_docs: dict = field(default_factory=dict) - definition_order: list = field(default_factory=list) + deleted: set = field(default_factory=set) + removed_annotations: set = field(default_factory=set) removals: tuple = () imports: dict = field(default_factory=dict) - annotations: dict = field(default_factory=dict) - exported: dict = field(default_factory=dict) + requested_imports: tuple = () + exports: set = field(default_factory=set) + created_code: CodeType | None = None + reversals: list = field(default_factory=list) @dataclass(frozen=True) class ClassPlan: bases: tuple - body: tuple - decorators: tuple + fields: Counter -def _decorated(value, decorators): - for decorator, args, kwargs, factory in reversed(decorators): - value = decorator(*args, **kwargs)(value) if factory else decorator(value) - return value +class _LiveBody: + """Read existing class locals when Python evaluates a method definition.""" + + def __init__(self, owner): + self.owner = owner + + def __prepare__(self, name, bases): + return ChainMap({}, syntax.raw_namespace(self.owner)) + + def __call__(self, name, bases, body): + return body.maps[0] + + +def _definition_unit(node, flags, filename, *, shell=None, stub=False): + if stub: + node = copy(node) + node.decorator_list = [] + node.body = [ast.copy_location(ast.Pass(), node)] + if shell is not None: + shell = copy(shell) + shell.bases = [] + shell.decorator_list = [] + shell.keywords = [ + ast.keyword(arg="metaclass", value=ast.Name(_SHELL_METACLASS, ast.Load())) + ] + shell.body = [node] + node = ast.fix_missing_locations(shell) + return _compile(ast.Module(body=[node], type_ignores=[]), filename, flags) + + +def _member_functions(value, seen=None): + if seen is None: + seen = set() + if id(value) in seen: + return + seen.add(id(value)) + if isinstance(value, (classmethod, staticmethod)): + yield from _member_functions(value.__func__, seen) + elif isinstance(value, property): + for function in (value.fget, value.fset, value.fdel): + yield from _member_functions(function, seen) + elif isinstance(value, FunctionType): + yield value + for cell in value.__closure__ or (): + try: + inner = cell.cell_contents + except ValueError: + continue + if isinstance(inner, FunctionType): + yield from _member_functions(inner, seen) + wrapped = getattr(value, "__wrapped__", None) + if wrapped is not None: + yield from _member_functions(wrapped, seen) + + +def _constructed_function(value, compiled, namespace): + return next( + ( + function + for function in _member_functions(value) + if function.__globals__ is namespace and function.__code__ == compiled + ), + None, + ) def _location(module, name, *, namespace=None): @@ -712,62 +801,40 @@ def _location(module, name, *, namespace=None): return (_resolve(owner, nested) if nested else owner), leaf -def _bind_metadata(node, namespace, future): - args = node.args - defaults = tuple(syntax.expression(item, namespace, reference=True) for item in args.defaults) - kwdefaults = { - arg.arg: syntax.expression(item, namespace, reference=True) - for arg, item in zip(args.kwonlyargs, args.kw_defaults, strict=True) - if item is not None - } - annotated = { - arg.arg: arg.annotation - for arg in (*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg) - if arg is not None and arg.annotation is not None - } - if node.returns is not None: - annotated["return"] = node.returns - annotations = { - name: syntax.annotation(item, namespace, future=future) for name, item in annotated.items() - } +def _import_bindings(nodes, package): + for node in nodes: + if isinstance(node, ast.Import): + for item in node.names: + root = item.name.partition(".")[0] + yield item.asname or root, (item.name if item.asname else root, None) + elif isinstance(node, ast.ImportFrom) and node.module != "__future__": + ((module, names),) = syntax.import_sources(node, package) + yield from zip(syntax.names(node), ((module, name) for name in names), strict=True) + - def resolve(live): +def inactive_typing(tree, namespace, package): + for node in reversed(tree.body): + if "TYPE_CHECKING" not in syntax.declarations((node,)): + continue return ( - tuple(value(live) for value in defaults) or None, - {name: value(live) for name, value in kwdefaults.items()} or None, - _docstring(node.body), - {name: value(live) for name, value in annotations.items()}, + dict(_import_bindings((node,), package)).get("TYPE_CHECKING") + == ("typing", "TYPE_CHECKING") + or isinstance(getattr(node, "value", None), ast.Constant) + and node.value.value is False ) - - return resolve - - -def _set_function(function, metadata): - function.__defaults__, function.__kwdefaults__, function.__doc__, function.__annotations__ = ( - metadata - ) + return namespace.get("TYPE_CHECKING") is False def _check_body(node, after, before=None): - if node.name in _FORBIDDEN_METHOD_NAMES: - syntax.reject("constructors require restart") if _uses_hook_name(node) or HIT_HOOK in _globals(after): syntax.reject("candidate references reserved witness hook") previous_writes = _global_writes(before) if before is not None else Counter() - if after.co_flags & _UNSUPPORTED_FLAGS or _global_writes(after) - previous_writes: - syntax.reject("generator, async or new global writes require restart") - after_imports = {op.argval for op in _instructions(after) if op.opname == "IMPORT_NAME"} - before_imports = ( - {op.argval for op in _instructions(before) if op.opname == "IMPORT_NAME"} - if before is not None - else set() - ) - if after_imports - before_imports: - syntax.reject("new imports must be declarative and accounted for at commit") + if _global_writes(after) - previous_writes: + syntax.reject("new global writes require restart") if before is not None and ( after.co_freevars != before.co_freevars or after.co_cellvars != before.co_cellvars ): - syntax.reject("candidate changes the target closure layout") + syntax.reject("candidate changes the target function kind or closure layout") def _children(code): @@ -802,36 +869,80 @@ def _nested_signatures(root): return signatures -def _live_nested(old, new, namespace, old_signatures, new_signatures): - children = _children(new) if new is not None else {} - for path, previous in _children(old).items(): - candidate = children.get(path) - for function in gc.get_referrers(previous): - if not isinstance(function, FunctionType) or function.__globals__ is not namespace: - continue - if function.__code__ is not previous: - continue - if ( - candidate is None - or any( - getattr(candidate, field) != getattr(previous, field) - for field in ( - "co_argcount", - "co_posonlyargcount", - "co_kwonlyargcount", - "co_freevars", - "co_cellvars", - ) - ) - or (candidate.co_flags ^ previous.co_flags) - & (_UNSUPPORTED_FLAGS | inspect.CO_VARARGS | inspect.CO_VARKEYWORDS) - or old_signatures.get((previous.co_name, previous.co_firstlineno)) - != new_signatures.get((candidate.co_name, candidate.co_firstlineno)) - or len(old_signatures.get((previous.co_name, previous.co_firstlineno), ())) > 1 - ): +def _nested_compatible(previous, candidate, old_signatures, new_signatures): + if candidate is None or previous is None: + return False + old = old_signatures.get((previous.co_name, previous.co_firstlineno)) + return ( + all( + getattr(previous, field) == getattr(candidate, field) + for field in ( + "co_argcount", + "co_posonlyargcount", + "co_kwonlyargcount", + "co_freevars", + "co_cellvars", + ) + ) + and (candidate.co_flags ^ previous.co_flags) + & (_UNSUPPORTED_FLAGS | inspect.CO_VARARGS | inspect.CO_VARKEYWORDS) + == 0 + and old == new_signatures.get((candidate.co_name, candidate.co_firstlineno)) + and len(old or ()) <= 1 + ) + + +def _nested_pairs(old, new): + previous = _children(old) if old is not None else {} + candidate = _children(new) if new is not None else {} + for key in previous.keys() | candidate.keys(): + a, b = previous.get(key), candidate.get(key) + yield a, b + yield from _nested_pairs(a, b) + + +def _functions_with_code(code, namespace): + return [ + value + for value in gc.get_referrers(code) + if isinstance(value, FunctionType) + and value.__code__ is code + and value.__globals__ is namespace + ] + + +def _live_nested(pairs, namespace): + for previous, candidate, compatible in pairs: + if previous is None: + continue + for function in _functions_with_code(previous, namespace): + if not compatible: syntax.reject("a live nested function has an incompatible signature or closure") - yield function, candidate - yield from _live_nested(previous, candidate, namespace, old_signatures, new_signatures) + yield ref(function), candidate + + +@dataclass +class ClosureReversal: + code: CodeType + before: CodeType | None + namespace: dict + migrated: frozenset + baseline: int = 0 + + def arm(self): + self.baseline = sys.getrefcount(self.code) + + def restore(self, journal, ownership): + if sys.getrefcount(self.code) <= self.baseline: + return + for function in _functions_with_code(self.code, self.namespace): + if ref(function) in self.migrated: + continue + if self.before is not None: + journal.attr(function, "__code__", self.before) + # Exclude the function list, loop variable and getrefcount argument. + elif ownership().escaped(id(function), sys.getrefcount(function) - 3): + raise BoxError("in_doubt", "an escaped nested function has no old code") def _namespace_retains(owner, identities, defining_slot=None): @@ -850,30 +961,14 @@ def _namespace_retains(owner, identities, defining_slot=None): return False -def _has_alias(value, owner, name): - identities = {id(value)} - defining_slot = (owner, name) - return ( - any( - _namespace_retains(module, identities, defining_slot) - for module in tuple(sys.modules.values()) - if isinstance(module, ModuleType) - ) - or isinstance(owner, type) - and _namespace_retains(owner, identities, defining_slot) +def _has_alias(identities, *, defining_slot=None): + return any( + _namespace_retains(module, identities, defining_slot) + for module in tuple(sys.modules.values()) + if isinstance(module, ModuleType) ) -def _qualified_function(module, name, code, owner, metadata, *, class_cell=None): - closure = None - if code.co_freevars: - closure = (class_cell if class_cell is not None else CellType(owner),) - function = FunctionType(code, vars(module), name.rsplit(".", 1)[-1], closure=closure) - function.__qualname__ = name - _set_function(function, metadata) - return function - - @dataclass class _Binding: function: FunctionType @@ -889,9 +984,21 @@ class _Binding: jit_scope: jit.JitScope | None = None origin: str = "base" - @property - def code(self) -> CodeType: - return self.live_code + @classmethod + def from_function(cls, name, function, canonical, value, kernel, *, aliases=(), origin="base"): + return cls( + function, + canonical, + function.__code__, + aliases, + _global_bindings(function, canonical), + uuid4().hex, + f"{function.__globals__['__name__']}:{name}", + value, + kernel, + kernel._src if kernel is not None else None, + origin=origin, + ) def jit_witness_keys(self): if self.kernel is None: @@ -936,55 +1043,20 @@ def __init__( instrument: bool = True, allow_target=None, ): - self.module = module - self.allow_target = allow_target or (lambda _: True) + self._init_bindings(module, allow_target) self.ephemeral = False - self._declarations = {} - self._imports = {} - self._removed = set() self.source_root = source_root.resolve(strict=True) - self.path = self._origin() + self.path = _module_origin(module, self.source_root) if HIT_HOOK in vars(module): raise BoxError("binding_mismatch", "module shadows reserved witness hook") self.source = self.base_source = _read_source(self.path) - pending: list[ - tuple[ - str, - FunctionType, - CodeType, - tuple[tuple[Callable[[], object], object], ...], - dict[str, object], - object, - object | None, - ] - ] = [] + by_filename: dict[str, list[str]] = {} seen_codes: list[CodeType] = [] - canonical_trees: dict[str, tuple[ast.Module, CodeType]] = {} + parsed = _source_parser(self.source) for name, aliases in targets.items(): - value = _resolve(module, name) + value, function, ast_path = _source_binding(module, name, self.path, parsed) kernel, _ = jit.unwrap(value) - function = _function(value) - if ( - name.rsplit(".", 1)[-1] in _FORBIDDEN_METHOD_NAMES - or not isinstance(function, FunctionType) - or function.__globals__ is not vars(module) - or function.__code__.co_flags & _UNSUPPORTED_FLAGS - ): - raise BoxError("restart_required", "target is not a registered synchronous binding") code = function.__code__ - if Path(code.co_filename).resolve() != self.path: - raise BoxError("binding_mismatch", "target code was loaded outside the source file") - cached = canonical_trees.get(code.co_filename) - if cached is None: - tree = _parse(self.source, code.co_filename) - cached = (tree, _compile(tree, code.co_filename)) - canonical_trees[code.co_filename] = cached - tree, compiled = cached - ast_path = _node(tree, name) - if _code(compiled, ast_path) != code: - raise BoxError("binding_mismatch", "loaded code differs from source definition") - if _uses_hook_name(ast_path[-1]) or HIT_HOOK in _globals(code): - raise BoxError("restart_required", "target references reserved witness hook") if kernel is not None: live_tree = _parse(kernel._src, code.co_filename) expression = _node(live_tree, function.__name__)[-1] @@ -998,38 +1070,30 @@ def __init__( "restart_required", "registered binding shares code with another target" ) seen_codes.append(code) - dependencies = {key: _global_value(function, key) for key in _globals(code)} - pending.append((name, function, code, retained, dependencies, value, kernel)) - - # Compile live code in memory; only attach to function.__code__ when activated. - by_filename: dict[str, list[str]] = {} - for name, _, code, _, _, _, kernel in pending: + self.bindings[name] = _Binding.from_function( + name, function, code, value, kernel, aliases=retained + ) if kernel is None: by_filename.setdefault(code.co_filename, []).append(name) - live_codes: dict[str, CodeType] = {} - for filename, group_names in by_filename.items(): - live_codes.update( - _compile_live_codes(self.source, filename, self.module.__name__, group_names) - ) - self.bindings: dict[str, _Binding] = {} - for name, function, canonical_code, retained, dependencies, value, kernel in pending: - live_code = live_codes.get(name, canonical_code) - self.bindings[name] = _Binding( - function=function, - canonical_code=canonical_code, - live_code=live_code, - aliases=retained, - globals=dependencies, - binding_id=uuid4().hex, - witness_key=f"{self.module.__name__}:{name}", - value=value, - kernel=kernel, - kernel_text=kernel._src if kernel is not None else None, - ) - self._instrumented = False + + # Compile in memory and attach to functions only on activation. + for filename, names in by_filename.items(): + tree, _ = parsed(filename) + paths = {name: _node(tree, name) for name in names} + for name, code in _compile_witnesses(tree, filename, module.__name__, paths).items(): + self.bindings[name].live_code = code if instrument: self.activate() + def _init_bindings(self, module, allow_target): + self.module = module + self.allow_target = allow_target or (lambda _: True) + self.bindings: dict[str, _Binding] = {} + self._declarations = {} + self._imports = {} + self._removed = set() + self._instrumented = False + @classmethod def inspect( cls, @@ -1045,17 +1109,12 @@ def inspect( @classmethod def staged(cls, name, path, *, package=False, allow_target=None): managed = cls.__new__(cls) - managed.module = module = ModuleType(name) - managed.allow_target = allow_target or (lambda _: True) + module = ModuleType(name) + managed._init_bindings(module, allow_target) managed.ephemeral = True managed.path = path.resolve() managed.source_root = managed.path.parent managed.source = managed.base_source = "" - managed._declarations = {} - managed._imports = {} - managed._removed = set() - managed.bindings = {} - managed._instrumented = False managed._source_cache = None module.__file__ = str(managed.path) module.__spec__ = managed._virtual_spec = ModuleSpec( @@ -1078,24 +1137,19 @@ def activate(self) -> None: if self._instrumented: return ensure_hook() - updated: list[_Binding] = [] + journal = Journal() try: for binding in self.bindings.values(): if binding.kernel is None: - binding.function.__code__ = binding.live_code - updated.append(binding) + journal.attr(binding.function, "__code__", binding.live_code) except BaseException: - for binding in reversed(updated): - try: - binding.function.__code__ = binding.canonical_code - except BaseException: - pass + journal.undo_to(0) raise self._instrumented = True def deactivate(self) -> None: """Restore uninstrumented canonical code onto all targets of an unregistered module.""" - for binding in reversed(list(self.bindings.values())): + for binding in reversed(self.bindings.values()): if binding.kernel is None: binding.function.__code__ = binding.canonical_code elif binding.jit_scope is not None: @@ -1103,9 +1157,6 @@ def deactivate(self) -> None: binding.jit_scope = None self._instrumented = False - def _origin(self) -> Path: - return _module_origin(self.module, self.source_root) - def verify(self, *, quiescent: bool = False) -> None: if self.ephemeral: parent, _, leaf = self.module.__name__.rpartition(".") @@ -1119,7 +1170,10 @@ def verify(self, *, quiescent: bool = False) -> None: or linecache.cache.get(str(self.path)) is not self._source_cache ): raise BoxError("binding_mismatch", "created module identity changed") - elif self._origin() != self.path or _read_source(self.path) != self.base_source: + elif ( + _module_origin(self.module, self.source_root) != self.path + or _read_source(self.path) != self.base_source + ): raise BoxError("binding_mismatch", "managed source origin changed") if any( vars(self.module).get(name, MISSING) is not value @@ -1142,15 +1196,10 @@ def verify(self, *, quiescent: bool = False) -> None: raise BoxError("binding_mismatch", "live target, alias, or dependency changed") if quiescent: codes = set() - pending = [ - code - for binding in self.bindings.values() - for code in (binding.live_code, binding.canonical_code) - ] - while pending: - code = pending.pop() - codes.add(id(code)) - pending.extend(_children(code).values()) + for binding in self.bindings.values(): + for code in (binding.live_code, binding.canonical_code): + codes.add(id(code)) + codes.update(map(id, _nested_codes(code))) for frame in sys._current_frames().values(): while frame is not None: if id(frame.f_code) in codes: @@ -1168,22 +1217,17 @@ def normalize(value, path=frozenset()): def item(content): return normalize(content, nested) - if kind in (list, tuple): - return kind.__name__, tuple(map(item, value)) - if kind in (set, frozenset): - return kind.__name__, tuple( - sorted( - marshal.dumps(item(member), _MARSHAL_VALUE_FORMAT) for member in value - ) - ) if kind is dict: - return "dict", tuple( - sorted( - marshal.dumps((item(key), item(member)), _MARSHAL_VALUE_FORMAT) - for key, member in value.items() - ) + members = ((item(key), item(member)) for key, member in value.items()) + elif kind is slice: + members = map(item, (value.start, value.stop, value.step)) + else: + members = map(item, value) + if kind in (set, frozenset, dict): + members = sorted( + marshal.dumps(member, _MARSHAL_VALUE_FORMAT) for member in members ) - return "slice", tuple(map(item, (value.start, value.stop, value.step))) + return kind.__name__, tuple(members) if kind in (int, float, bool, bytes, str, complex, type(None), type(Ellipsis)): return "value", value if isinstance(value, (type, FunctionType)): @@ -1224,29 +1268,35 @@ def describe(self) -> dict: "bindings": {name: binding.describe() for name, binding in self.bindings.items()}, } - def prepare(self, patch: PatchSpec, *, staged=None, enrolled=()) -> SourcePlan: - if patch.action == "edit": + def prepare(self, patch: PatchSpec, *, enrolled=()) -> SourcePlan: + creating = patch.action == "create" + if not creating: self.verify() if patch.base_hash != source_hash(self.source): raise BoxError("base_mismatch", "effective source differs from expected base") filename = str(self.path) - name = self.module.__name__ - old, new = _parse(self.source, filename), _parse(patch.source, filename) - if ast.dump(old) == ast.dump(new): - raise BoxError("no_change", "candidate has no semantic change") + old, new = (_parse(source, filename) for source in (self.source, patch.source)) compiled = _compile(new, filename) - future = bool(compiled.co_flags & _FUTURE_ANNOTATIONS) - changes = list(syntax.differences(old.body, new.body)) - names = {} - classes = {} - if not changes: + flags = compiled.co_flags & _FUTURES + changes = [] if creating else list(syntax.differences(old.body, new.body)) + if not creating and not changes: raise BoxError("no_change", "candidate has no declarative change") - plan = SourcePlan() - namespace = dict(syntax.raw_namespace(self.module)) - modules = ChainMap(staged or {}, sys.modules) - before_declarations, after_declarations = ( - syntax.declarations(tree.body) for tree in (old, new) + package = self.module.__package__ + namespace = syntax.raw_namespace(self.module) + typing = inactive_typing(new, namespace, package) + plan = SourcePlan( + created_code=compiled if creating else None, + requested_imports=tuple( + source + for node in syntax.additions( + old, new, old_typing=inactive_typing(old, namespace, package), new_typing=typing + ) + for source in syntax.import_sources(node, package) + ), ) + names = {} + before_declarations = syntax.declarations(old.body) + after_declarations = syntax.declarations(new.body) annotations = { node.target.id for node in new.body @@ -1257,143 +1307,120 @@ def prepare(self, patch: PatchSpec, *, staged=None, enrolled=()) -> SourcePlan: for node in new.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) } - removed_globals = before_declarations.keys() - after_declarations.keys() - for removed in removed_globals: - namespace.pop(removed, None) + + plan.exports = definitions | after_declarations.keys() + + def function_unit(name, before, after, *, shell=None): + names[name] = before, after, shell + if after is not None: + code = None if before else _definition_unit(after, flags, filename, shell=shell) + plan.units.append((("definition", name), code)) + + def new_class_members(node, prefix): + for member in node.body: + if isinstance(member, (ast.FunctionDef, ast.AsyncFunctionDef)): + names[f"{prefix}.{member.name}"] = None, member, None + elif isinstance(member, ast.ClassDef): + new_class_members(member, f"{prefix}.{member.name}") + elif isinstance(member, ast.AnnAssign) and not isinstance(member.target, ast.Name): + syntax.reject("class annotation writes outside its namespace") + + def new_class(node): + plan.classes[node.name] = node + new_class_members(node, node.name) + + if creating: + for node in new.body: + if isinstance(node, ast.ClassDef): + new_class(node) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + names[node.name] = None, node, None + for name in plan.exports - {"__all__"}: + syntax.check_name(name) + plan.imports.update(_import_bindings(new.body, self.module.__package__)) for key, before, after in changes: kind = key[0] if kind == "function": - names[key[1]] = (before, after) - if before is None: - plan.definition_order.append(key[1]) - namespace[key[1]] = syntax.DEFERRED - elif after is None: - removed_globals.add(key[1]) - namespace.pop(key[1], None) + function_unit(key[1], before, after) elif kind == "class": if before is None: syntax.check_name(after.name) self._check_slot(self.module, after.name) - classes[after.name] = after - plan.definition_order.append(after.name) - namespace[after.name] = syntax.DEFERRED - names.update( - { - f"{after.name}.{node.name}": (None, node) - for node in after.body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - } - ) + new_class(after) + plan.units.append((key, _definition_unit(after, flags, filename))) elif after is None: syntax.reject("removing a class requires restart") else: - shell = deepcopy(before), deepcopy(after) - for node in shell: - node.body = [] - if syntax.shape(shell[0]) != syntax.shape(shell[1]): + if any( + _body(getattr(before, field, ())) != _body(getattr(after, field, ())) + for field in ("bases", "keywords", "decorator_list", "type_params") + ): syntax.reject("existing class bases, metaclass and decorators are fixed") + if not isinstance(_resolve(self.module, after.name), type): + syntax.reject("existing class has no live class binding") for (member_kind, *parts), a, b in syntax.differences( - before.body, - after.body, - methods=True, + before.body, after.body, methods=True ): if member_kind == "doc": - owner = _resolve(self.module, after.name) - if type(owner) is not type: - syntax.reject("class docstring requires a standard metaclass") - plan.class_docs[owner] = b.value.value if b is not None else None - continue - if member_kind != "function": - syntax.reject("existing class fields are fixed") - qualified = f"{after.name}.{parts[0]}" - names[qualified] = (a, b) - if a is None: - plan.definition_order.append(qualified) + doc = b.value.value if b is not None else None + plan.units.append((("class_doc", after.name), doc)) + else: + function_unit(f"{after.name}.{parts[0]}", a, b, shell=after) elif kind == "doc": - value = after.value.value if after is not None else None - plan.writes["__doc__"] = lambda _, value=value: value + plan.units.append((key, after.value.value if after is not None else None)) elif kind == "typing": - # TYPE_CHECKING is checked with the rest of the staged namespace below. - continue + if not typing: + syntax.reject("TYPE_CHECKING must be the inactive typing guard") + elif kind == "future": + syntax.reject("existing future compiler settings require restart") else: - if kind == "future" and patch.action == "edit": - syntax.reject("existing future compiler settings require restart") old_names = syntax.names(before) if before is not None else () new_names = syntax.names(after) if after is not None else () if definitions.intersection(new_names): syntax.reject("declaration would replace a source definition") - for binding in new_names: - if binding in namespace and not before_declarations[binding]: + for name in new_names: + if name in namespace and not before_declarations[name]: syntax.reject("declaration would replace a live binding without source") - for binding in {*old_names, *new_names}: - if before_declarations[binding] > 1 or after_declarations[binding] > 1: + for name in (*old_names, *new_names): + if before_declarations[name] > 1 or after_declarations[name] > 1: syntax.reject("changed declaration has more than one source binding") - syntax.check_name(binding) - for binding in old_names: - if binding not in after_declarations: - plan.writes[binding] = MISSING + syntax.check_name(name) + plan.deleted.update(name for name in old_names if name not in after_declarations) if isinstance(before, ast.AnnAssign) and before.target.id not in annotations: - plan.annotations[before.target.id] = MISSING - if after is None: - continue - if kind == "constant": - if isinstance(after, ast.AnnAssign): - plan.annotations[after.target.id] = syntax.annotation( - after.annotation, - namespace, - future=future, - ) - value = syntax.expression(after.value, namespace) - for binding in syntax.names(after): - syntax.check_name(binding) - plan.writes[binding] = value - namespace[binding] = value(namespace) - else: - for dependency, item in syntax.imports(after, self.module.__package__): - if dependency not in modules: - syntax.reject("import needs an already loaded or staged module") - syntax.check_name(item.binding) - if item.member and f"{item.module}.{item.member}" in (staged or {}): - item = syntax.Import(item.binding, f"{item.module}.{item.member}") - namespace[item.binding] = item.read(modules) - plan.writes[item.binding] = item - plan.imports[item.binding] = (item.module, item.member) + plan.removed_annotations.add(before.target.id) + if after is not None: + plan.units.append((key, _definition_unit(after, flags, filename))) + plan.imports.update(_import_bindings((after,), self.module.__package__)) - if ( - any(key[0] == "typing" for key, _, _ in changes) - and namespace.get("TYPE_CHECKING") is not False - ): - syntax.reject("TYPE_CHECKING must be the inactive typing guard") if patch.targets and ( set(patch.targets) != names.keys() - or plan.class_docs + or any(key[0] == "class_doc" for key, _ in plan.units) or any(key[0] not in ("function", "class") for key, _, _ in changes) - or any(before is None or after is None for before, after in names.values()) + or any(before is None or after is None for before, after, _ in names.values()) ): syntax.reject("candidate changes outside the declared function targets") - for class_name, node in classes.items(): - plan.classes[class_name] = self._class_plan(node, namespace, future) - - new_nodes = {} - jitted = set() + python = {} removals = [] - for target, (before, after) in names.items(): - owner, leaf = _location(self.module, target) - top = target.partition(".")[0] + for target, (before, after, shell) in names.items(): + top, _, member = target.partition(".") if not self.allow_target(target): syntax.reject("target is outside the enrolled target policy") + if member in _FORBIDDEN_METHOD_NAMES and top not in plan.classes: + syntax.reject("constructors of existing classes require restart") + binding = self.bindings.get(target) if after is None: - if before.name in _FORBIDDEN_METHOD_NAMES or target not in self.bindings: + if binding is None: syntax.reject("removed definition is outside managed synchronous bindings") - binding = self.bindings[target] - if binding.kernel is not None: - syntax.reject("direct deletion of a native JIT binding requires restart") - identities = {id(binding.value)} + owner, leaf = _location(self.module, target) + extra = (binding.kernel, binding.function) if binding.kernel is not None else () + identities = {id(item) for item in (binding.value, *extra)} if ( binding.aliases - or _has_alias(binding.value, owner, leaf) + or _has_alias(identities, defining_slot=(owner, leaf)) + or isinstance(owner, type) + and _namespace_retains(owner, identities, (owner, leaf)) or any( module.retains_definition(identities, defining_slot=(owner, leaf)) for module in chain((self,), enrolled) @@ -1402,123 +1429,90 @@ def prepare(self, patch: PatchSpec, *, staged=None, enrolled=()) -> SourcePlan: syntax.reject("removed definition has an external alias") removals.append(target) continue - if not isinstance(after, ast.FunctionDef): - syntax.reject("async definitions require restart") - canonical = _code(compiled, _node(new, target)) - if before is not None: - binding = self.bindings.get(target) - if binding is None: - syntax.reject("changed definition is outside managed bindings") - _check_body(after, canonical, binding.canonical_code) - if _body(before.decorator_list) != _body(after.decorator_list): - syntax.reject("existing decorators are fixed") - changed_signature = syntax.shape(before.args) != syntax.shape( - after.args - ) or syntax.shape(before.returns) != syntax.shape(after.returns) - if patch.targets and ( - changed_signature - or _docstring(before.body) != _docstring(after.body) - or syntax.legacy_body_changes(before, after) - or canonical.co_flags != binding.canonical_code.co_flags - or _global_writes(canonical) - or any( - binding.globals.get(key, MISSING) is forbidden - for key in _globals(canonical) - for forbidden in _LEGACY_GLOBALS - ) - ): - syntax.reject("explicit targets accept only compatible function-body changes") - if binding.kernel is not None: - if changed_signature: - syntax.reject("existing JIT signature is fixed; add a renamed kernel") - jitted.add(target) - defaults = ( - _bind_metadata( - after, - ChainMap(syntax.raw_namespace(owner), namespace) - if isinstance(owner, type) - else namespace, - future, - ) - if changed_signature - else None - ) - new_nodes[target] = canonical, after, defaults, None - else: - _check_body(after, canonical) - if any(free != "__class__" for free in canonical.co_freevars): - syntax.reject("new definition has an unsupported closure") - if top not in classes: + + path = _node(new, target) + canonical = _code(compiled, path) + _check_body(after, canonical, binding.canonical_code if binding else None) + if before is None: + if not creating and top not in plan.classes: + owner, leaf = _location(self.module, target) syntax.check_name(leaf) self._check_slot(owner, leaf) - decorator_scope = ( - ChainMap(syntax.raw_namespace(owner), namespace) - if isinstance(owner, type) - else namespace + if canonical.co_flags & _UNSUPPORTED_FLAGS: + continue + python[target] = path, canonical, None, None + continue + if binding is None or canonical.co_flags & _UNSUPPORTED_FLAGS: + syntax.reject("changed definition is outside managed synchronous bindings") + if _body(before.decorator_list) != _body(after.decorator_list): + syntax.reject("existing decorators are fixed") + changed_signature = any( + syntax.shape(getattr(before, key)) != syntax.shape(getattr(after, key)) + for key in ("args", "returns") + ) + if patch.targets and ( + changed_signature + or syntax.docstring(before.body) != syntax.docstring(after.body) + or syntax.legacy_body_changes(before, after) + or canonical.co_flags != binding.canonical_code.co_flags + or _global_writes(canonical) + or any( + binding.globals.get(key, MISSING) is forbidden + for key in _globals(canonical) + for forbidden in _LEGACY_GLOBALS ) - if top in plan.classes: - _, defaults, decorators = next( - data - for action, data in plan.classes[top].body - if action == "method" and data[0] == leaf - ) - else: - decorators = syntax.decorators(after.decorator_list, decorator_scope) - defaults = _bind_metadata(after, decorator_scope, future) - if any(syntax.native_decorator(item) for item in decorators): - jitted.add(target) - new_nodes[target] = canonical, after, defaults, decorators - - if missing := removed_globals - namespace.keys(): - unchanged = ( - binding.canonical_code - for target, binding in self.bindings.items() - if target not in names + ): + syntax.reject("explicit targets accept only compatible function-body changes") + if binding.kernel is not None: + if changed_signature: + syntax.reject("existing JIT signature is fixed; add a renamed kernel") + plan.codes[target] = CompiledCode( + canonical, + binding.live_code, + jit.prepare(binding.kernel, filename, patch.source, after), + ) + continue + stub = ( + _definition_unit(after, flags, filename, shell=shell, stub=True) + if changed_signature + else None ) - changed = (code for code, *_ in new_nodes.values()) - if any(_globals(code) & missing for code in chain(unchanged, changed)): + python[target] = path, canonical, stub, before + + plan.removals = tuple(removals) + missing = plan.deleted | {target for target in removals if "." not in target} + if missing: + alive = { + name: binding.canonical_code + for name, binding in self.bindings.items() + if name not in removals + } + alive.update((name, code.canonical) for name, code in plan.codes.items()) + alive.update((name, canonical) for name, (_, canonical, _, _) in python.items()) + if any(_globals(code) & missing for code in alive.values()): syntax.reject("a surviving binding depends on a removed module global") - live = _compile_live_codes(patch.source, filename, name, new_nodes.keys() - jitted) - for target, (canonical, after, defaults, decorators) in new_nodes.items(): - if decorators is None: - binding = self.bindings[target] - if target in jitted: - code = CompiledCode( - canonical, - binding.live_code, - jit.prepare(binding.kernel, filename, patch.source, after), - ) - else: - replacement = live[target] - code = CompiledCode( - canonical, - replacement, - metadata=(defaults, _docstring(after.body)), - nested=tuple( - _live_nested( - binding.live_code, - replacement, - vars(self.module), - _nested_signatures(names[target][0]), - _nested_signatures(after), - ) - ), - ) - plan.codes[target] = code - else: - plan.additions[target] = ( - canonical, - live.get(target, canonical), - defaults, - decorators, + if python: + paths = {target: entry[0] for target, entry in python.items()} + live = _compile_witnesses(new, filename, self.module.__name__, paths) + for target, (path, canonical, stub, before) in python.items(): + replacement = live[target] + original = self.bindings[target].live_code if before is not None else None + old_signatures = _nested_signatures(before) if before is not None else {} + new_signatures = _nested_signatures(path[-1]) + pairs = tuple( + (a, b, _nested_compatible(a, b, old_signatures, new_signatures)) + for a, b in _nested_pairs(original, replacement) ) - plan.removals = tuple(removals) - plan.exported = { - key: namespace[key] - for key in (*plan.writes, *plan.additions, *plan.classes) - if "." not in key and key in namespace - } + nested = tuple(_live_nested(pairs, namespace)) + migrated = frozenset(reference for reference, _ in nested) + plan.reversals.extend( + ClosureReversal(b, a if compatible else None, namespace, migrated) + for a, b, compatible in pairs + if b is not None + ) + plans = plan.codes if before is not None else plan.additions + plans[target] = CompiledCode(canonical, replacement, stub=stub, nested=nested) return plan def retains_definition(self, identities, *, defining_slot=None): @@ -1532,232 +1526,139 @@ def retains_definition(self, identities, *, defining_slot=None): ) def _check_slot(self, owner, leaf): - if isinstance(owner, type): - if type(owner) is not type or any( - inspect.isdatadescriptor(syntax.raw_namespace(base).get(leaf)) - for base in owner.__mro__[1:] - ): - syntax.reject("existing class cannot safely accept this method") + if isinstance(owner, type) and any( + inspect.isdatadescriptor(syntax.raw_namespace(base).get(leaf)) + for base in _class_mro(owner)[1:] + ): + syntax.reject("existing class cannot safely accept this method") if leaf in syntax.raw_namespace(owner): syntax.reject("new definition would replace a live binding") - def _class_plan(self, node, namespace, future): - bases = [] - for base in node.bases: - obj = syntax.expression(base, namespace, reference=True)(namespace) - if ( - type(obj) is not type - or inspect.getattr_static(obj, "__init_subclass__") - is not vars(object)["__init_subclass__"] - ): - syntax.reject("class base has unmanaged construction") - bases.append(obj) - if node.keywords: - syntax.reject("custom class keywords or metaclasses require restart") - decorators = syntax.decorators(node.decorator_list, namespace, classes=True) - scope = dict(namespace) - body = [] - for index, statement in enumerate(node.body): - if isinstance(statement, ast.FunctionDef): - syntax.check_name(statement.name) - body.append( - ( - "method", - ( - statement.name, - _bind_metadata(statement, scope, future), - syntax.decorators(statement.decorator_list, scope), - ), - ) - ) - scope[statement.name] = syntax.DEFERRED - elif isinstance(statement, (ast.Assign, ast.AnnAssign)): - fields = syntax._constant_names(statement) - if isinstance(statement, ast.AnnAssign): - if not isinstance(statement.target, ast.Name): - syntax.reject("new class contains a non-declarative annotation") - name = statement.target.id - syntax.check_name(name) - annotation = syntax.annotation(statement.annotation, scope, future=future) - body.append(("annotation", (name, annotation))) - elif not fields: - syntax.reject("new class contains a non-declarative assignment") - for name in fields: - syntax.check_name(name) - if statement.value is not None: - value = syntax.expression(statement.value, scope) - scope.update(dict.fromkeys(fields, value(scope))) - body.append(("fields", (fields, value))) - elif index == 0 and syntax.docstring(statement): - body.append(("doc", statement.value.value)) - elif not isinstance(statement, ast.Pass): - syntax.reject("new class contains unmanaged construction") - return ClassPlan(tuple(bases), tuple(body), tuple(decorators)) - - def _build_class(self, name, definition, methods): - module = self.module - class_cell = CellType() - namespace = syntax.raw_namespace(module) - - def populate(body): - body["__module__"] = module.__name__ - body["__qualname__"] = name - body["__classcell__"] = class_cell - live = ChainMap(body, namespace) - for action, data in definition.body: - if action == "method": - leaf, defaults, decorators = data - target = f"{name}.{leaf}" - _, code, _, _ = methods[target] - function = _qualified_function( - module, - target, - code, - None, - defaults(live), - class_cell=class_cell, - ) - body[leaf] = _decorated(function, decorators) - elif action == "fields": - names, value = data - body.update(dict.fromkeys(names, value(live))) - elif action == "annotation": - key, value = data - body.setdefault("__annotations__", {})[key] = value(live) - else: - body["__doc__"] = data + def _run_definition(self, name, code, run, *, journal=None): + owner, leaf = _location(self.module, name) + namespace = vars(self.module) + method = isinstance(owner, type) + scratch = {_SHELL_METACLASS: _LiveBody(owner)} if method else {} + run(code, namespace, scratch) + body = scratch[name.partition(".")[0]] if method else scratch + if "__classcell__" in body: + body["__classcell__"].cell_contents = owner + value = body[leaf] + if journal is not None: + journal.member(owner, leaf, value) + return value - return _decorated( - new_class(name, definition.bases, exec_body=populate), definition.decorators + def _enroll(self, name, compiled, journal): + value = _resolve(self.module, name) + namespace = vars(self.module) + kernel, _ = jit.unwrap(value) + if kernel is None: + function = _constructed_function(value, compiled.canonical, namespace) + if function is None: + raise BoxError("restart_required", "decorator did not retain its source function") + journal.attr(function, "__code__", compiled.live) + else: + function = kernel.fn + binding = _Binding.from_function( + name, function, compiled.canonical, value, kernel, origin="added" ) + if kernel is not None: + binding.jit_scope = jit.record_change( + journal, binding, lambda scope: jit.enroll_new(scope, kernel, binding.witness_key) + ) + journal.mapping(self.bindings, name, binding) - def apply(self, plan: SourcePlan, source, journal) -> None: - namespace = vars(self.module) - for name, writer in plan.writes.items(): - value = ( - MISSING - if writer is MISSING - else writer.read(sys.modules) - if isinstance(writer, syntax.Import) - else writer(namespace) + def _apply_code(self, name, compiled, journal, run): + binding = self.bindings[name] + if compiled.native is not None: + scope = jit.record_change( + journal, binding, lambda scope: compiled.native.apply(scope, binding.witness_key) ) - journal.mapping(namespace, name, value) - if name != "__doc__": - journal.mapping(self._declarations, name, value) - journal.mapping(self._imports, name, plan.imports.get(name, MISSING)) - if plan.annotations: - annotations = namespace.get("__annotations__") - if annotations is None: - annotations = {} - journal.mapping(namespace, "__annotations__", annotations) - for name, writer in plan.annotations.items(): - journal.mapping( - annotations, name, MISSING if writer is MISSING else writer(namespace) - ) - for owner, doc in plan.class_docs.items(): - journal.class_attr(owner, "__doc__", doc) + journal.attr(binding, "jit_scope", scope) + journal.attr(binding, "kernel_text", binding.kernel._src) + else: + function = binding.function + defaults = self._run_definition(name, compiled.stub, run) if compiled.stub else None + journal.attr(function, "__code__", compiled.live) + for reference, code in compiled.nested: + if (nested := reference()) is not None: + journal.attr(nested, "__code__", code) + if defaults is not None: + for attr in ("__defaults__", "__kwdefaults__", "__annotations__"): + journal.attr(function, attr, getattr(defaults, attr)) + journal.attr(function, "__doc__", compiled.canonical.co_consts[0]) + journal.attr(binding, "canonical_code", compiled.canonical) + journal.attr(binding, "live_code", compiled.live) + + def apply(self, plan: SourcePlan, source, journal, run) -> None: + namespace = vars(self.module) if plan.additions or self.ephemeral: filename = str(self.path) cache = (len(source), None, source.splitlines(keepends=True), filename) journal.mapping(linecache.cache, filename, cache) if self.ephemeral: journal.attr(self, "_source_cache", cache) - for name in plan.definition_order: - if name in plan.classes: - value = self._build_class(name, plan.classes[name], plan.additions) - journal.mapping(namespace, name, value) + + def declaration(name, item): + journal.mapping(self._declarations, name, item) + journal.mapping(self._imports, name, plan.imports.get(name, MISSING)) + + if plan.created_code is not None: + before = namespace.copy() + run(plan.created_code, namespace, namespace) + for name in namespace.keys() - before.keys() - {"__builtins__", "__annotations__"}: + declaration(name, namespace[name]) + + for name in plan.deleted: + journal.mapping(namespace, name, MISSING) + declaration(name, MISSING) + for name in plan.removed_annotations: + journal.mapping(namespace["__annotations__"], name, MISSING) + for key, code in plan.units: + kind = key[0] + if kind == "doc": + journal.mapping(namespace, "__doc__", code) + elif kind == "class_doc": + journal.member(_resolve(self.module, key[1]), "__doc__", code) + elif kind in ("definition", "class"): + name = key[1] + if code is None: + compiled = plan.codes[name] + if compiled.native is None: + self._apply_code(name, compiled, journal, run) + continue + self._run_definition(name, code, run, journal=journal) else: - _, live, defaults, decorators = plan.additions[name] - owner, leaf = _location(self.module, name) - live_names = ChainMap(syntax.raw_namespace(owner), namespace) - value = _qualified_function(self.module, name, live, owner, defaults(live_names)) - value = _decorated(value, decorators) - if isinstance(owner, type): - journal.class_attr(owner, leaf, value) - else: - journal.mapping(namespace, leaf, value) - for name, (canonical, live, _, _) in plan.additions.items(): - value = _resolve(self.module, name) - function = _function(value) - kernel, _ = jit.unwrap(value) - if kernel is None and function.__code__ is not live: - journal.attr(function, "__code__", live) - binding = _Binding( - function, - canonical, - live, - (), - {}, - uuid4().hex, - f"{self.module.__name__}:{name}", - value, - kernel, - kernel._src if kernel is not None else None, - origin="added", - ) - if kernel is not None: - scope = jit.discover_callers(value) - journal.change( - lambda k=kernel, s=scope: jit.JitSnapshot.take(k, s, None), - lambda saved: saved.restore(), - lambda s=scope, b=binding: jit.enroll_new(s, b.kernel, b.witness_key), - same=jit.same_source, - ) - binding.jit_scope = scope - journal.mapping(self.bindings, name, binding) + scratch = {} + run(code, namespace, scratch) + for name in key[1]: + journal.mapping(namespace, name, scratch[name]) + declaration(name, scratch[name]) + annotations = scratch.get("__annotations__", {}) + for name in annotations: + if "__annotations__" not in namespace: + journal.mapping(namespace, "__annotations__", {}) + journal.mapping(namespace["__annotations__"], name, annotations[name]) + del scratch, annotations + for name, compiled in plan.additions.items(): + self._enroll(name, compiled, journal) + # Discover native callers after all new definitions have been bound. for name, compiled in plan.codes.items(): - binding = self.bindings[name] if compiled.native is not None: - scope = jit.discover_callers(binding.value) - journal.change( - lambda b=binding, s=scope: jit.JitSnapshot.take(b.kernel, s, b.jit_scope), - lambda saved: saved.restore(), - lambda edit=compiled.native, b=binding, s=scope: edit.apply(s, b.witness_key), - same=jit.same_source, - ) - journal.attr(binding, "jit_scope", scope) - journal.attr(binding, "kernel_text", binding.kernel._src) - else: - journal.attr(binding.function, "__code__", compiled.live) - for function, code in compiled.nested: - journal.attr(function, "__code__", code) - defaults, doc = compiled.metadata - if defaults is None: - journal.attr(binding.function, "__doc__", doc) - else: - owner, _ = _location(self.module, name) - metadata = defaults(ChainMap(syntax.raw_namespace(owner), namespace)) - function = binding.function - journal.set( - lambda f=function: ( - f.__defaults__, - f.__kwdefaults__, - f.__doc__, - f.__annotations__, - ), - lambda value, f=function: _set_function(f, value), - metadata, - same=same_objects, - ) - journal.attr(binding, "canonical_code", compiled.canonical) - journal.attr(binding, "live_code", compiled.live) + self._apply_code(name, compiled, journal, run) for name in plan.removals: owner, leaf = _location(self.module, name) - if isinstance(owner, type): - journal.class_attr(owner, leaf, MISSING) - else: - journal.mapping(namespace, leaf, MISSING) + binding = self.bindings[name] + if binding.kernel is not None: + jit.retire(journal, binding) + journal.member(owner, leaf, MISSING) + if not isinstance(owner, type): + declaration(leaf, MISSING) journal.mapping(self.bindings, name, MISSING) if plan.removals or plan.additions: journal.attr( self, "_removed", (self._removed | set(plan.removals)) - plan.additions.keys() ) for binding in self.bindings.values(): - journal.attr( - binding, - "globals", - { - key: _global_value(binding.function, key) - for key in _globals(binding.canonical_code) - }, - ) + dependencies = _global_bindings(binding.function, binding.canonical_code) + journal.attr(binding, "globals", dependencies) diff --git a/src/inferrsi/box/kernel/syntax.py b/src/inferrsi/box/kernel/syntax.py index f7dcf71ee..66d088380 100644 --- a/src/inferrsi/box/kernel/syntax.py +++ b/src/inferrsi/box/kernel/syntax.py @@ -3,39 +3,13 @@ from __future__ import annotations import ast -import builtins -import dataclasses -import functools -import sys from collections import Counter -from dataclasses import dataclass from importlib.util import resolve_name -from types import GenericAlias, ModuleType +from types import ModuleType from ..protocol import BoxError -from .journal import MISSING from .witness import HIT_HOOK -DEFERRED = object() -_CONSTRUCTORS = { - name: vars(builtins)[name] - for name in ( - "frozenset", - "tuple", - "list", - "set", - "dict", - "int", - "float", - "str", - "bytes", - "bool", - "complex", - "slice", - ) -} -_SCALAR = (int, float, bool, str, bytes, complex, type(None), type(Ellipsis)) - def reject(reason): raise BoxError("restart_required", reason) @@ -45,10 +19,12 @@ def shape(node): return ast.dump(node) if node is not None else None -def docstring(node): - if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant): - return isinstance(node.value.value, str) - return False +def docstring(body): + if body and isinstance(body[0], ast.Expr): + value = body[0].value + if isinstance(value, ast.Constant) and isinstance(value.value, str): + return value.value + return None def _constant_names(node): @@ -96,23 +72,24 @@ def _key(node, methods): def _declarations(body, methods): counts = Counter(_key(node, methods) for node in body) - names = {} - protected = [] - order = [] + names, anchors, protected, order = {}, {}, [], [] for index, node in enumerate(body): - key = ("doc",) if index == 0 and docstring(node) else _key(node, methods) + key = ("doc",) if index == 0 and docstring(body) is not None else _key(node, methods) if key is None or counts[key] > 1: - order.append(("protected", len(protected))) + key = ("protected", len(protected)) protected.append(shape(node)) else: - order.append(key) names[key] = node - return names, protected, order + if key[0] in ("constant", "import"): + for name in key[1]: + anchors.setdefault(name, []).append(len(protected)) + order.append(key) + return names, protected, order, anchors def differences(before, after, *, methods=False): - previous, old_protected, old_order = _declarations(before, methods) - current, new_protected, new_order = _declarations(after, methods) + previous, old_protected, old_order, old_anchors = _declarations(before, methods) + current, new_protected, new_order, new_anchors = _declarations(after, methods) if old_protected != new_protected: reject("candidate changes a non-declarative statement or an existing class field") shared = previous.keys() & current.keys() @@ -121,18 +98,6 @@ def differences(before, after, *, methods=False): ]: reject("candidate reorders existing declarations or top-level effects") - def anchors(order): - positions = {} - protected = 0 - for key in order: - if key[0] == "protected": - protected += 1 - elif key[0] in ("constant", "import"): - for name in key[1]: - positions.setdefault(name, []).append(protected) - return positions - - old_anchors, new_anchors = anchors(old_order), anchors(new_order) if any( old_anchors[name] != new_anchors[name] for name in old_anchors.keys() & new_anchors.keys() ): @@ -144,216 +109,58 @@ def anchors(order): def names(node): - return _constant_names(node) or _import_names(node) + return ( + _import_names(node) + if isinstance(node, (ast.Import, ast.ImportFrom)) + else _constant_names(node) + ) def declarations(nodes): - return Counter( - name - for node in nodes - if isinstance( - node, - ( - ast.Assign, - ast.AnnAssign, - ast.Import, - ast.ImportFrom, - ), - ) - for name in ( - _constant_names(node) - if not isinstance(node, (ast.Import, ast.ImportFrom)) - else _import_names(node) - ) - ) + return Counter(name for node in nodes for name in names(node)) def raw_namespace(obj): """Read a real module or class dictionary without descriptor lookup on its type.""" - owner = ModuleType if isinstance(obj, ModuleType) else type + owner = ModuleType if issubclass(type(obj), ModuleType) else type return owner.__dict__["__dict__"].__get__(obj) -def _lookup(node, namespace): - if isinstance(node, ast.Name): - result = namespace.get(node.id, vars(builtins).get(node.id, MISSING)) - elif isinstance(node, ast.Attribute): - base = _lookup(node.value, namespace) - result = ( - DEFERRED - if base is DEFERRED - else ( - raw_namespace(base).get(node.attr, MISSING) - if isinstance(base, (ModuleType, type)) - else MISSING - ) - ) - else: - reject("expression needs a static name") - if result is MISSING: - reject("expression has an unresolved binding") - return result - - -def _data(value): - if type(value) in _SCALAR: - return True - if type(value) in (tuple, list, set, frozenset): - return all(_data(item) for item in value) - if type(value) is dict: - return all(_data(k) and _data(v) for k, v in value.items()) - if type(value) is slice: - return all(_data(x) for x in (value.start, value.stop, value.step)) - return False - - -def expression(node, namespace, *, reference=False): - """Return a constant or a late lookup of a proven name or module member.""" - if reference and isinstance(node, (ast.Name, ast.Attribute)): - _lookup(node, namespace) - return lambda live: _lookup(node, live) - - values = {} - - def check(expr): - if isinstance(expr, ast.Constant): - if not _data(expr.value): - reject("expression is not pure data") - elif isinstance(expr, ast.Name): - value = _lookup(expr, namespace) - if not _data(value): - reject("constant expression refers to non-data state") - values[expr.id] = value - elif isinstance(expr, (ast.Tuple, ast.List, ast.Set)): - for element in expr.elts: - check(element) - elif isinstance(expr, ast.Dict): - for value in (*expr.keys, *expr.values): - check(value) - elif isinstance(expr, ast.UnaryOp): - check(expr.operand) - elif isinstance(expr, ast.BinOp): - check(expr.left) - check(expr.right) - elif ( - isinstance(expr, ast.Call) - and isinstance(expr.func, ast.Name) - and _CONSTRUCTORS.get(expr.func.id) is _lookup(expr.func, namespace) - ): - for value in (*expr.args, *(keyword.value for keyword in expr.keywords)): - check(value) - else: - reject("expression is outside the pure data grammar") - - try: - check(node) - literal = eval( - compile(ast.Expression(node), "", "eval"), - {"__builtins__": _CONSTRUCTORS}, - values, - ) - except (ValueError, ArithmeticError, TypeError, RecursionError) as exc: - raise BoxError("restart_required", "constant expression could not be evaluated") from exc - if not _data(literal): - reject("declaration did not produce pure data") - return lambda _: literal - - -def annotation(node, namespace, *, future): - if future: - value = ast.unparse(node) - return lambda _: value - if isinstance(node, ast.Subscript): - target = _lookup(node.value, namespace) - if not any(target is item for item in (list, dict, tuple, set, frozenset, type)): - reject("annotation subscript does not name a trusted generic type") - subscripts = node.slice.elts if isinstance(node.slice, ast.Tuple) else (node.slice,) - members = [annotation(part, namespace, future=False) for part in subscripts] - return lambda live: GenericAlias(target, tuple(item(live) for item in members)) - return expression(node, namespace, reference=True) - - -@dataclass(frozen=True) -class Import: - binding: str - module: str - member: str | None = None - - def read(self, modules): - obj = modules.get(self.module) - if not isinstance(obj, ModuleType): - reject("import needs an already loaded or staged module") - if self.member is None: - return obj - value = raw_namespace(obj).get(self.member, MISSING) - if value is MISSING: - reject("import member is not statically available") - return value - - -def imports(node, package): +def import_sources(node, package): + """Yield the source module and, for from-imports, its requested members.""" if isinstance(node, ast.Import): for alias in node.names: - # The complete target must be loaded even when Python binds its root name. - yield ( - alias.name, - Import( - alias.asname or alias.name.split(".")[0], - alias.name if alias.asname else alias.name.split(".")[0], - ), - ) + yield alias.name, () return if any(alias.name == "*" for alias in node.names): - reject("star imports are outside the declarative profile") + reject("star imports require restart") try: name = resolve_name("." * node.level + (node.module or ""), package) except ImportError as exc: raise BoxError("restart_required", "relative import is outside its package") from exc - for alias in node.names: - yield name, Import(alias.asname or alias.name, name, alias.name) - - -def decorators(nodes, namespace, *, classes=False): - """Resolve decorator identity from the current namespace without running it.""" - allowed = ( - (dataclasses.dataclass,) - if classes - else ( - staticmethod, - classmethod, - property, - functools.lru_cache, - functools.cache, - ) - ) - triton = sys.modules.get("triton") - native = raw_namespace(triton).get("jit") if triton is not None else None - result = [] - for node in nodes: - target = node.func if isinstance(node, ast.Call) else node - value = _lookup(target, namespace) - args, kwargs = (), {} - if not classes and native is not None and value is native: - if isinstance(node, ast.Call): - reject("parameterized JIT decorators are outside the structural profile") - elif not any(value is choice for choice in allowed): - reject("decorator has no enrolled construction semantics") - elif isinstance(node, ast.Call): - if value not in (dataclasses.dataclass, functools.lru_cache): - reject("decorator arguments are outside the structural profile") - args = tuple(expression(arg, namespace)(namespace) for arg in node.args) - kwargs = { - item.arg: expression(item.value, namespace)(namespace) for item in node.keywords - } - if None in kwargs: - reject("decorator cannot expand keyword arguments") - result.append((value, args, kwargs, isinstance(node, ast.Call))) - return result - - -def native_decorator(decorator): - triton = sys.modules.get("triton") - return triton is not None and decorator[0] is raw_namespace(triton).get("jit") + yield name, tuple(alias.name for alias in node.names) + + +def additions(before, after, *, old_typing, new_typing): + """Find imports added to a lexical scope.""" + + def imports(node, inactive, scope=()): + if isinstance(node, (ast.Import, ast.ImportFrom)): + if getattr(node, "module", None) != "__future__": + yield (scope, shape(node)), node + if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + scope = (*scope, node.name) + for child in ast.iter_child_nodes(node): + if inactive and isinstance(node, ast.Module) and _key(child, False) == ("typing",): + continue + yield from imports(child, inactive, scope) + + old = Counter(key for key, _ in imports(before, old_typing)) + for key, node in imports(after, new_typing): + if old[key]: + old[key] -= 1 + else: + yield node _LEGACY_MUTATORS = frozenset( diff --git a/src/inferrsi/box/kernel/transaction.py b/src/inferrsi/box/kernel/transaction.py index 674acdc37..f280e07e1 100644 --- a/src/inferrsi/box/kernel/transaction.py +++ b/src/inferrsi/box/kernel/transaction.py @@ -5,8 +5,10 @@ import sys from collections.abc import Callable, Iterable from dataclasses import dataclass, field +from functools import cache, partial from graphlib import CycleError, TopologicalSorter from importlib.machinery import all_suffixes +from itertools import chain from pathlib import Path from time import monotonic from types import ModuleType @@ -15,9 +17,16 @@ from ..patch import PatchSpec, install_summary from ..protocol import BoxError, source_hash -from . import syntax -from .journal import Journal -from .swap import ManagedModule, SourcePlan, _has_alias, _parse, _resolve, validate_method_removals +from . import jit, syntax +from .journal import MISSING, Journal, instance_dict, same_mapping, walk_containers +from .swap import ManagedModule, SourcePlan, _has_alias, _resolve, validate_method_removals + + +def _verify_contents(snapshots): + for value, before in snapshots: + identities = tuple if type(value) is list else frozenset + if identities(map(id, value)) != identities(map(id, before)): + raise BoxError("in_doubt", "native effects changed a live container") class RequestState(Protocol): @@ -37,10 +46,7 @@ class Change: plan: SourcePlan creates: bool = False structural: bool = True - - @property - def codes(self): - return self.plan.codes + imports: frozenset[str] = frozenset() @dataclass @@ -49,6 +55,7 @@ class Installed: changes: tuple[Change, ...] undo: tuple = () effects: dict[str, object] = field(default_factory=dict) + closures: tuple = () @dataclass @@ -56,8 +63,13 @@ class Checkpoint: changes: list[Change] stack: list[Installed] state: object - modules: dict + mappings: tuple + registry: dict | None + container_mappings: tuple + containers: tuple + instances: tuple = () journal: Journal = field(default_factory=Journal) + closures: tuple = () class TransactionLog: @@ -69,12 +81,14 @@ def __init__( module_resolver: Callable[[str], ManagedModule] | None = None, create_module_policy=None, allowed_target=None, + allowed_import=None, ): self.modules = modules self.state = state self.module_resolver = module_resolver self.create_module_policy = create_module_policy self.allowed_target = allowed_target + self.allowed_import = allowed_import or (lambda _: False) self.stack: list[Installed] = [] self._id_namespace = uuid4() @@ -116,25 +130,24 @@ def register_module(self, managed: ManagedModule) -> ManagedModule: def _created_modules(self, candidates): created = {} - declarations = {} - for name, patch in candidates.items(): + for name in candidates: if self.create_module_policy is None: syntax.reject("no module creation policy is enrolled") root = Path(self.create_module_policy(name)) if name in sys.modules: syntax.reject("new module would shadow an existing source or module") parent, _, leaf = name.rpartition(".") + locations = [root.with_suffix("")] if parent not in candidates: package = sys.modules.get(parent) - if not isinstance(package, ModuleType) or "__path__" not in syntax.raw_namespace( - package - ): + parent_namespace = ( + syntax.raw_namespace(package) if isinstance(package, ModuleType) else {} + ) + if "__path__" not in parent_namespace: syntax.reject("new module needs an already loaded or staged parent package") - if leaf in syntax.raw_namespace(package): + if leaf in parent_namespace: syntax.reject("new module would shadow a parent package attribute") - locations = [root.with_suffix("")] - if parent not in candidates: - paths = syntax.raw_namespace(package)["__path__"] + paths = parent_namespace["__path__"] if type(paths) not in (list, tuple) or not all( isinstance(item, str) for item in paths ): @@ -157,24 +170,47 @@ def _created_modules(self, candidates): else lambda target, name=name: self.allowed_target(name, target) ), ) - declarations[name] = _parse(patch.source, str(root)) + return created + def _order_changes(self, changes, created): order = TopologicalSorter() - for name, tree in declarations.items(): - dependencies = {name.rpartition(".")[0]} - for statement in tree.body: - if syntax._key(statement, False) and syntax._key(statement, False)[0] == "import": - imports = syntax.imports(statement, created[name].module.__package__) - for module, item in imports: - dependencies.add(module) - if item.member is not None: - dependencies.add(f"{item.module}.{item.member}") - order.add(name, *(dependencies & candidates.keys())) + + def allowed(name): + return ( + sys.modules.get(name) is not None + or name in created + or name.partition(".")[0] in sys.stdlib_module_names + or self.allowed_import(name) + ) + + for name, change in changes.items(): + names = set() + for source, members in change.plan.requested_imports: + names.add(source) + loaded = sys.modules.get(source) + namespace = syntax.raw_namespace(loaded) if loaded is not None else {} + exports = changes[source].plan.exports if source in changes else () + for member in members: + child = f"{source}.{member}" + if child in changes or ( + "__path__" in namespace + and member not in namespace + and member not in exports + ): + names.add(child) + if any(not allowed(item) for item in names): + syntax.reject( + "import needs an already loaded or staged module or an allowed source" + ) + change.imports = frozenset(names) + dependencies = (names | {name.rpartition(".")[0]}) & changes.keys() + if not change.creates: + dependencies.discard(name) + order.add(name, *sorted(dependencies)) try: - ordered = tuple(order.static_order()) + return [changes[name] for name in order.static_order()] except CycleError as exc: - raise BoxError("invalid_request", "new module imports form a cycle") from exc - return created, ordered + raise BoxError("invalid_request", "compound patch imports form a cycle") from exc def install(self, patch: PatchSpec): return self.install_group(patch.patch_id, (patch,), install_summary(patch.payload())) @@ -184,28 +220,27 @@ def install_group( ) -> tuple[list[Change], list[Installed], dict]: if any(entry.patch_id == patch_id for entry in self.stack): raise BoxError("conflict", "patch ID is already installed") - edits = tuple(edits) - candidates = {patch.module: patch for patch in edits if patch.action == "create"} - created, order = self._created_modules(candidates) - staged = {name: ModuleType(name) for name in order} - changes = [] - for name in order: - patch = candidates[name] - module = created[name] - plan = module.prepare(patch, staged=staged) - vars(staged[name]).update(plan.exported) - changes.append(Change(module, patch.source, plan, creates=True)) - for patch in edits: - if patch.action == "edit": - module = self.inspect_module(patch.module) - changes.append( - Change( - module, - patch.source, - module.prepare(patch, staged=staged, enrolled=self.modules.values()), - structural=not patch.targets, - ) + edits = {patch.module: patch for patch in edits} + created = self._created_modules( + {name for name, patch in edits.items() if patch.action == "create"} + ) + modules = { + name: created[name] if name in created else self.inspect_module(name) for name in edits + } + enrolled = (*self.modules.values(), *modules.values()) + changes = self._order_changes( + { + name: Change( + module, + edits[name].source, + module.prepare(edits[name], enrolled=enrolled), + creates=name in created, + structural=not edits[name].targets, ) + for name, module in modules.items() + }, + created, + ) prospective = {name: (module, None, module.source) for name, module in self.modules.items()} prospective.update( (change.module.module.__name__, (change.module, change.plan, change.source)) @@ -216,22 +251,18 @@ def install_group( return changes, stack, details def uninstall(self, patch_id: str | None) -> tuple[list[Change], list[Installed], dict]: - if patch_id is None: - if not self.stack: - raise BoxError("unknown_patch", "patch stack is empty") - keep = len(self.stack) - 1 - else: - indices = [i for i, entry in enumerate(self.stack) if entry.patch_id == patch_id] - if not indices: - raise BoxError("unknown_patch", "patch is not installed") - keep = indices[0] + keep = next( + (i for i, entry in enumerate(self.stack) if entry.patch_id == patch_id), + len(self.stack) - 1 if patch_id is None else -1, + ) + if keep < 0: + reason = "patch stack is empty" if patch_id is None else "patch is not installed" + raise BoxError("unknown_patch", reason) removed = list(reversed(self.stack[keep:])) return ( [change for entry in removed for change in reversed(entry.changes)], self.stack[:keep], - { - "removed_patch_ids": [entry.patch_id for entry in removed], - }, + {"removed_patch_ids": [entry.patch_id for entry in removed]}, ) def verify( @@ -240,11 +271,8 @@ def verify( quiescent: bool = False, extra: Iterable[ManagedModule] = (), ) -> None: - seen: set[int] = set() - for module in (*self.modules.values(), *extra): - if id(module) in seen: - continue - seen.add(id(module)) + modules = {id(module): module for module in (*self.modules.values(), *extra)} + for module in modules.values(): if not module.ephemeral or module.module.__name__ in self.modules: module.verify(quiescent=quiescent) @@ -260,19 +288,81 @@ def verify_plan(self, changes, stack): raise BoxError("in_doubt", "uninstall could not prove its live bindings") from exc raise + def _namespaces(self, changes): + modules = {name: module.module for name, module in self.modules.items()} + for change in changes: + module = change.module.module + name = module.__name__ + modules[name] = module + parent = module.__package__ + if parent in sys.modules: + modules[parent] = sys.modules[parent] + return tuple(syntax.raw_namespace(module) for module in modules.values()) + def checkpoint(self, changes: list[Change]): try: - return Checkpoint(changes, self.stack, self.state.snapshot(), sys.modules.copy()) + registry = jit.registry() + namespaces = self._namespaces(changes) + spaces = (sys.modules, *namespaces, *(() if registry is None else (registry,))) + containers, instances = (), [] + if any(change.structural for change in changes): + visible = ( + value + for space in namespaces + for key, value in space.items() + if key != "__builtins__" + ) + retained = (entry.before for installed in self.stack for entry in installed.undo) + # Failed construction must also leave live objects' attribute dicts intact. + containers = tuple( + value + for value, _ in walk_containers(chain(visible, retained), instances=instances) + if type(value) in (dict, list, set) + ) + return Checkpoint( + changes, + self.stack, + self.state.snapshot(), + tuple((space, space.copy()) for space in spaces), + registry, + tuple((value, value.copy()) for value in containers if type(value) is dict), + tuple((value, tuple(value)) for value in containers if type(value) is not dict), + instances, + ) except Exception as exc: raise BoxError("in_doubt", "could not record request state before mutation") from exc + def _restore_closures(self, closures, checkpoint, journal): + @cache + def owners(): + return checkpoint.journal.owned_references( + chain.from_iterable(entry.undo for entry in self.stack), + (*checkpoint.mappings, *checkpoint.container_mappings), + (*checkpoint.containers, *((obj, ()) for obj, _, _ in checkpoint.instances)), + ) + + for closure in closures: + closure.restore(journal, owners) + def _restore(self, checkpoint): - checkpoint.journal.undo_to(0) + try: + self._restore_closures(checkpoint.closures, checkpoint, Journal()) + finally: + checkpoint.journal.undo_to(0) self.state.restore(checkpoint.state) self.stack = checkpoint.stack self.verify(quiescent=True) - if not self._same_modules(checkpoint.modules): - raise BoxError("in_doubt", "untracked module changes survived reversal") + checkpoint.journal.verify_mappings(checkpoint.mappings) + checkpoint.journal.verify_mappings(checkpoint.container_mappings, ordered=True) + if ( + sys.modules is not checkpoint.mappings[0][0] + or jit.registry() is not checkpoint.registry + ): + raise BoxError("in_doubt", "untracked bindings survived reversal") + _verify_contents(checkpoint.containers) + instances = checkpoint.instances # Re-read: a replaced __dict__ is not a restore. + if not all(instance_dict(o) is d and same_mapping(d, b) for o, d, b in instances): + raise BoxError("in_doubt", "native effects changed live object attributes") if self.state.snapshot() != checkpoint.state: raise BoxError("in_doubt", "request state reversal did not verify") @@ -301,11 +391,36 @@ def reverse(self, checkpoint) -> dict: except BaseException as exc: raise BoxError("in_doubt", "could not verify group reversal") from exc - @staticmethod - def _same_modules(expected): - return sys.modules.keys() == expected.keys() and all( - sys.modules[name] is value for name, value in expected.items() - ) + def _run_source(self, code, namespace, scratch, *, change, journal): + cold = change.imports - sys.modules.keys() + modules = sys.modules.copy() if cold else {} + packages = { + name: space.copy() + for name, module in modules.items() + if isinstance(module, ModuleType) + and "__path__" in (space := syntax.raw_namespace(module)) + } + fresh = namespace.copy() if namespace is scratch else None + registered = jit.registry() if change.plan.additions else None + before = registered.copy() if registered is not None else None + try: + exec(code, namespace, scratch) + finally: + if fresh is not None: + journal.track_mapping(namespace, fresh) + for name in sys.modules.keys() - modules.keys() if cold else (): + module = sys.modules[name] + space = syntax.raw_namespace(module) if isinstance(module, ModuleType) else {} + spec = space.get("__spec__") + if spec is None or spec.name != name or spec.loader is None: + continue + journal.record_mapping(sys.modules, name, MISSING) + parent, _, leaf = name.rpartition(".") + if parent in packages: + space = syntax.raw_namespace(modules[parent]) + if space.get(leaf) is module: + journal.record_mapping(space, leaf, packages[parent].get(leaf, MISSING)) + jit.record_registrations(journal, registered, before, namespace, change.plan.additions) @staticmethod def _activate(journal, module): @@ -332,7 +447,6 @@ def execute( self.verify_plan(changes, stack) if monotonic() >= deadline: raise BoxError("deadline_exceeded", "command expired before mutation") - modules = checkpoint.modules try: if len(stack) > len(self.stack): for change in changes: @@ -341,6 +455,11 @@ def execute( if not change.creates and name not in self.modules: self._activate(journal, module) journal.mapping(self.modules, name, module) + stack[-1].closures = checkpoint.closures = tuple( + chain.from_iterable(change.plan.reversals for change in changes) + ) + for closure in checkpoint.closures: + closure.arm() mark = journal.mark() for change in changes: module = change.module @@ -354,59 +473,53 @@ def execute( journal.mapping(syntax.raw_namespace(package), leaf, module.module) self._activate(journal, module) journal.mapping(self.modules, name, module) - journal.attr(module, "source", change.source) - module.apply(change.plan, change.source, journal) - if not change.creates: - journal.attr(module, "source", change.source) + module.apply( + change.plan, + change.source, + journal, + partial(self._run_source, change=change, journal=journal), + ) + journal.attr(module, "source", change.source) stack[-1].undo = journal.commit_slice(mark) elif len(stack) < len(self.stack): for entry in reversed(self.stack[len(stack) :]): - retired, exports = [], [] + retired, exports = set(), set() for change in entry.changes: module = change.module.module - definitions = [ - _resolve(module, name) + definitions = { + id(_resolve(module, name)) for name in (*change.plan.additions, *change.plan.classes) - ] - retired.extend(definitions) + } + retired.update(definitions) if change.creates: - exports.extend((module, *definitions)) - exports.extend( - value - for name in change.plan.writes + exports.update(definitions) + exports.add(id(module)) + exports.update( + id(value) + for name, value in change.module._declarations.items() if name not in change.plan.imports - and isinstance( - value := vars(module).get(name), (list, dict, set, frozenset) - ) + and isinstance(value, (list, dict, set, frozenset)) ) + self._restore_closures(entry.closures, checkpoint, journal) journal.revert(entry.undo) - if retired: - identities = {id(value) for value in retired} - if any( - module.retains_definition(identities) - for module in self.modules.values() - ): - raise BoxError( - "in_doubt", "retired definitions escaped the transaction" - ) - if any(_has_alias(value, None, "") for value in exports): + if retired and any( + module.retains_definition(retired) for module in self.modules.values() + ): + raise BoxError("in_doubt", "retired definitions escaped the transaction") + if exports and _has_alias(exports): raise BoxError("in_doubt", "created module exports escaped the transaction") + journal.verify_mappings(checkpoint.container_mappings, ordered=True) + _verify_contents(checkpoint.containers) reset_items = list(self.state.reset()) if tuple(reset_items) != self.state.reset_items: raise ValueError("actual reset items do not match the state profile") self.verify(quiescent=True) - expected_modules = modules.copy() - for change in changes: - module = change.module - if change.creates: - name = module.module.__name__ - if name in self.modules: - expected_modules[name] = module.module - else: - expected_modules.pop(name, None) proof = {**details, **self._proof(stack=stack), "reset_items": reset_items} - if not self._same_modules(expected_modules): - raise BoxError("in_doubt", "mutation made unjournaled changes to sys.modules") + journal.verify_mappings(checkpoint.mappings) + if sys.modules is not checkpoint.mappings[0][0]: + raise BoxError("in_doubt", "sys.modules identity changed") + if checkpoint.registry is not None and jit.registry() is not checkpoint.registry: + raise BoxError("in_doubt", "JIT registry identity changed") if monotonic() >= deadline: raise BoxError("deadline_exceeded", "command expired during mutation") except BaseException as exc: @@ -415,8 +528,7 @@ def execute( if isinstance(exc, BoxError) and exc.code == "in_doubt": raise exc proof = self._reverse_proof( - checkpoint, - exc.code if isinstance(exc, BoxError) else "mutation failed", + checkpoint, exc.code if isinstance(exc, BoxError) else "mutation failed" ) except BaseException as restore_exc: raise BoxError("in_doubt", "could not verify reversal") from restore_exc diff --git a/src/inferrsi/box/repos/vllm_common/worker_base.py b/src/inferrsi/box/repos/vllm_common/worker_base.py index b66727b54..aab31111d 100644 --- a/src/inferrsi/box/repos/vllm_common/worker_base.py +++ b/src/inferrsi/box/repos/vllm_common/worker_base.py @@ -108,6 +108,7 @@ def __init__( module_resolver=self._resolve_module, create_module_policy=self._create_module_path, allowed_target=config.is_target_allowed, + allowed_import=config.is_module_allowed, observe_check=self._observed, ) @@ -488,7 +489,7 @@ def group_commit(self, data: Command | bytes, cache_cleared: bool) -> bytes: def _jit_mutation_bindings(self): bindings = {} for change in self.plan[0]: - for target in dict.fromkeys((*change.codes, *change.plan.additions)): + for target in dict.fromkeys((*change.plan.codes, *change.plan.additions)): binding = change.module.bindings.get(target) if binding is not None and binding.kernel is not None: bindings[binding.witness_key] = ( @@ -525,7 +526,7 @@ def _commit_graphs(self, command, details): targets = tuple( f"{change.module.module.__name__}:{target}" for change in self.plan[0] - for target in (*change.codes, *change.plan.additions) + for target in (*change.plan.codes, *change.plan.additions) ) native = self._jit_mutation_bindings() site_keys = tuple( diff --git a/tests/box/conformance/test_structural_transactions.py b/tests/box/conformance/test_structural_transactions.py index 44943b383..0c76f2484 100644 --- a/tests/box/conformance/test_structural_transactions.py +++ b/tests/box/conformance/test_structural_transactions.py @@ -16,7 +16,7 @@ from inferrsi.box.kernel.swap import ManagedModule, discover_targets from inferrsi.box.patch import CompoundPatchSpec, PatchSpec from inferrsi.box.protocol import BoxError, Command, Identity, decode -from tests.box.vllm_common.fake_jit import FakeJit +from tests.box.vllm_common.fake_jit import FakeJit, FakeTuner class State: @@ -146,6 +146,9 @@ def test_stacked_globals_and_exact_reverse(setup): state.requests = 9 assert box.install(patch(box, module.__name__, source_b, name="B"))["code"] == "rolled_back" assert state.requests == 9 and module.helper is helper and helper() == 2 + failed = patch(box, module.__name__, source_b + "\nBROKEN = 1 / 0\n", name="B") + assert box.install(failed)["code"] == "rolled_back" + assert module.helper is helper and helper() == 2 and "BROKEN" not in vars(module) assert box.install(patch(box, module.__name__, source_b, name="B"))["code"] == "ok" assert box.uninstall("A")["details"]["removed_patch_ids"] == ["B", "A"] assert box.source(module.__name__)["details"]["structure_hash"] == baseline["structure_hash"] @@ -206,7 +209,6 @@ def test_signature_docstring_and_super_use_live_class(setup): BASE + "\nPENDING.append('leak')\n", BASE + "\nif G:\n PENDING.append('leak')\n", BASE + "\nimport structural_cold_unknown\n", - BASE + "\nclass Invalid:\n @PENDING.append\n def leak(self):\n pass\n", BASE.replace("DEFAULT = 3", "DEFAULT = 5"), BASE.replace("def old(self):", "def __init__(self):"), BASE.replace("return x + G", "global G\n G = x\n return G"), @@ -532,7 +534,7 @@ def test_regrouped_declarations_preserve_the_live_bindings(setup): assert "__annotations__" not in vars(module) -def test_static_import_never_calls_module_descriptor(setup, monkeypatch): +def test_native_import_calls_module_descriptor_only_at_commit(setup, monkeypatch): module, _, endpoint, box = setup calls = [] @@ -549,7 +551,7 @@ def __getattribute__(self, name): endpoint.preflight_mutation(command(box, "install", candidate.payload())) assert calls == [] and "VALUE" not in vars(module) assert box.install(candidate)["code"] == "ok" - assert module.VALUE == 4 and calls == [] + assert module.VALUE == 4 and calls == ["VALUE"] assert box.uninstall()["code"] == "ok" @@ -558,9 +560,13 @@ def test_structural_preflight_detects_active_original_frame(setup): source = BASE + "\ndef active(callback):\n return callback()\n" assert box.install(patch(box, module.__name__, source, name="add"))["code"] == "ok" code = module.active.__code__ - candidate = patch(box, module.__name__, source.replace("callback()", "(callback(),)"), name="B") + probes = [] + module.probe = lambda: probes.append("exec") + changed = source.replace("callback()", "(callback(),)") + "\nPROBED = probe()\n" + candidate = patch(box, module.__name__, changed, name="B") outcome = module.active(lambda: box.install(candidate)) assert outcome["code"] == "unsafe_point" + assert probes == [] and "PROBED" not in vars(module) assert module.active.__code__ is code assert box.uninstall()["code"] == "ok" @@ -607,8 +613,10 @@ def test_live_nested_function_default_changes_are_refused_until_recreated(setup) "restart_required" ) assert retained() == 7 - assert box.uninstall("patch")["code"] == "ok" + assert box.uninstall("body")["code"] == "ok" assert retained() == 6 + assert box.uninstall("patch")["code"] == "in_doubt" + assert box.isolated def test_enrolled_cold_module_with_effects_is_not_imported(setup): @@ -1038,8 +1046,13 @@ def test_removed_method_can_be_replaced_by_data_after_the_read_is_rewritten(setu assert box.uninstall("rewrite")["code"] == "ok" and instance.report()() == 17 -def test_new_property_is_not_a_callable_fallback_for_a_removed_method(setup): +@pytest.mark.parametrize("decorator", ["property", "cached_property", "opaque"]) +def test_new_descriptor_is_not_a_callable_fallback_for_a_removed_method(setup, decorator): + from functools import cached_property + module, _, _, box = setup + module.cached_property = cached_property + module.opaque = lambda function: property(function) score = "\n def score(self):\n return 17\n" source = BASE + score + "\n def report(self):\n return self.score()\n" assert box.install(patch(box, module.__name__, source))["code"] == "ok" @@ -1047,14 +1060,14 @@ def test_new_property_is_not_a_callable_fallback_for_a_removed_method(setup): old = module.Model.score candidate = source.replace(score, "").replace( "class Model(Parent):", - " @property\n def score(self):\n return 29\n\nclass Model(Parent):", + f" @{decorator}\n def score(self):\n return 29\n\nclass Model(Parent):", ) assert box.install(patch(box, module.__name__, candidate, name="invalid"))["code"] == ( "restart_required" ) assert "score" not in vars(module.Parent) and module.Model.score is old assert instance.report() == 17 - safe = candidate.replace(" @property\n", "") + safe = candidate.replace(f" @{decorator}\n", "") assert box.install(patch(box, module.__name__, safe, name="valid"))["code"] == "ok" assert instance.report() == 29 @@ -1204,3 +1217,618 @@ def test_same_line_non_call_read_does_not_inherit_an_unrelated_call_shape(setup, after, value = instance.report(other) assert after(29) == 29 and value == 9 assert box.uninstall("remove")["code"] == "ok" and instance.report(other)[0](17) == 18 + + +@pytest.mark.parametrize("create", [False, True]) +def test_native_dataclass_annotations_and_constants(setup, create): + module, _, endpoint, box = setup + source = """\ +from dataclasses import dataclass, field +from typing import Optional +import math + +ROWS = tuple(range(8)) +ALIGNMENT = len(ROWS) // math.gcd(4, 6) + +@dataclass +class Helper: + counts: dict[str, list[int]] | None = field(default_factory=dict) + entries: list[int] = field(default_factory=list) + + def length(self, value: Optional[int] = None) -> int | None: + return value or ALIGNMENT + +class Values(list): + def __init__(self): + super().__init__(ROWS) +""" + name = module.__package__ + ".helpers" if create else module.__name__ + if not create: + source += BASE.replace("def value(x=1):", "def value(x: int | None = ALIGNMENT):") + spec = patch(box, name, source, create=create) + before = sys.modules.copy(), vars(module).copy() + endpoint.preflight_mutation(command(box, "install", spec.payload())) + assert before == (sys.modules, vars(module)) + assert box.install(spec)["code"] == "ok" + active = sys.modules[name] + first, second = active.Helper(), active.Helper() + assert first.counts == second.counts == {} and first.counts is not second.counts + assert first.entries == second.entries == [] and first.entries is not second.entries + assert first.length() == 4 and active.Values() == list(range(8)) + assert active.Helper.__annotations__["counts"] == dict[str, list[int]] | None + assert active.Helper.length.__annotations__ == {"value": int | None, "return": int | None} + if not create: + assert active.value.__annotations__ == {"x": int | None} + assert active.value() == 6 + assert box.uninstall()["code"] == "ok" + assert before == (sys.modules, vars(module)) + assert module.value.__annotations__ == {} + + +def test_native_wrappers_abc_super_and_witness_only_execute_at_commit(setup): + module, _, endpoint, box = setup + source = ("from abc import ABC\n" + BASE).replace( + "class Model(Parent):", "class Model(Parent, ABC):" + ) + # This class shape is the already loaded source before the structural method edit. + peer_name = module.__package__ + ".abstract_model" + Path(module.__file__).with_name("abstract_model.py").write_text(source, encoding="utf-8") + peer = importlib.import_module(peer_name) + endpoint.log.register_module( + ManagedModule( + Path(module.__file__).parent, peer, discover_targets(Path(module.__file__).parent, peer) + ) + ) + calls = [] + + def wrap(): + calls.append("constructed") + + def decorate(fn): + def wrapper(*args, **kwargs): + return fn(*args, **kwargs) + + return wrapper + + return decorate + + peer.wrap = wrap + endpoint.workloads["abstract"] = lambda _: peer.Model().with_super() + peer.helper() + methods = """\ + + @wrap() + def with_super(self, scale=DEFAULT) -> int | None: + return scale + super().measure() + + @classmethod + def type_name(cls): + return cls.__name__ + + @staticmethod + def static(): + return 2 + + @property + def property_value(self): + return super().measure() +""" + updated = source + methods + "\n@wrap()\ndef helper():\n return G\n" + spec = patch(box, peer_name, updated) + endpoint.preflight_mutation(command(box, "install", spec.payload())) + assert calls == [] and "with_super" not in vars(peer.Model) + assert box.install(spec)["code"] == "ok" + assert calls == ["constructed", "constructed"] + model = peer.Model() + assert (model.type_name(), model.static(), model.property_value) == ("Model", 2, 10) + result = box.check("abstract")["details"] + assert result["output"] == 15 + assert result["witnesses"][peer_name + ":Model.with_super"] == {"hit": True, "calls": 1} + assert result["witnesses"][peer_name + ":helper"] == {"hit": True, "calls": 1} + assert box.uninstall()["code"] == "ok" + assert "with_super" not in vars(peer.Model) and "helper" not in vars(peer) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_compound_native_imports_added_export_from_an_edit(setup, reverse): + module, _, endpoint, box = setup + root = module.__package__ + peer_source = "def peer():\n return 3\n" + Path(module.__file__).with_name("peer.py").write_text(peer_source, encoding="utf-8") + peer = importlib.import_module(root + ".peer") + directory = Path(module.__file__).parent + endpoint.log.register_module(ManagedModule(directory, peer, discover_targets(directory, peer))) + edits = ( + patch(box, peer.__name__, peer_source + "\ndef new_export():\n return 7\n"), + patch( + box, + module.__name__, + "from .peer import new_export\n" + + BASE.replace("return x + G", "return new_export() + x"), + ), + ) + assert ( + box.install(CompoundPatchSpec("edits", edits[::-1] if reverse else edits))["code"] == "ok" + ) + assert module.new_export is peer.new_export and module.value() == 8 + assert box.uninstall("edits")["code"] == "ok" + assert module.value() == 3 and not hasattr(peer, "new_export") + cycle = ( + patch(box, peer.__name__, "from .model import value\n" + peer_source), + patch(box, module.__name__, "from .peer import peer\n" + BASE), + ) + assert box.install(CompoundPatchSpec("cycle", cycle))["code"] == "invalid_request" + assert "value" not in vars(peer) and "peer" not in vars(module) + + +def test_local_import_admission_and_cold_import_undo(setup): + module, _, endpoint, box = setup + new = module.__package__ + ".helpers" + candidate = CompoundPatchSpec( + "imports", + ( + patch( + box, + module.__name__, + BASE.replace( + "return x + G", + "from .helpers import EXTRA\n import math\n" + " import ipaddress\n" + " return EXTRA + math.gcd(x, 6) + ipaddress.IPv4Address(0).version", + ), + ), + patch(box, new, "EXTRA = 9\n", create=True), + ), + ) + endpoint.preflight_mutation(command(box, "install", candidate.payload())) + assert new not in sys.modules + assert box.install(candidate)["code"] == "ok" and module.value() == 14 + assert box.uninstall()["code"] == "ok" and new not in sys.modules + invalid = patch( + box, + module.__name__, + BASE.replace("return x + G", "import denied_cold_import\n return x + G"), + ) + assert box.install(invalid)["code"] == "restart_required" + assert "denied_cold_import" not in sys.modules + + cold_name = module.__package__ + ".cold" + Path(module.__file__).with_name("cold.py").write_text("OFFSET = 4\n", encoding="utf-8") + endpoint.log.allowed_import = {cold_name}.__contains__ + spec = patch(box, module.__name__, "from .cold import OFFSET\n" + BASE) + assert box.install(spec)["code"] == "ok" and module.OFFSET == 4 + assert box.uninstall()["code"] == "ok" + assert cold_name not in sys.modules and "cold" not in vars(sys.modules[module.__package__]) + + +@pytest.mark.parametrize("pollution", [None, "module", "binding", "registry"]) +def test_native_exec_exception_settles_only_if_reversal_is_clean(setup, monkeypatch, pollution): + module, _, endpoint, box = setup + probes = [] + registry = {} + runtime = ModuleType("triton.runtime.jit") + runtime._triton_jit_function_registry = registry + monkeypatch.setitem(sys.modules, runtime.__name__, runtime) + leaked_name = module.__package__ + ".residue" + + def fail(): + probes.append("exec") + if pollution == "module": + sys.modules[leaked_name] = ModuleType(leaked_name) + elif pollution == "binding": + module.LEAK = True + elif pollution == "registry": + registry["stray"] = object() + raise RuntimeError("constructor failed") + + module.fail = fail + source = BASE + "\nTRANSIENT = tuple(range(8))\n\n@fail()\ndef added():\n return 1\n" + rejected = source.replace("def old(self):", "def __init__(self):") + assert box.install(patch(box, module.__name__, rejected))["code"] == "restart_required" + spec = patch(box, module.__name__, source) + endpoint.preflight_mutation(command(box, "install", spec.payload())) + assert probes == [] and "TRANSIENT" not in vars(module) + result = box.install(spec) + assert probes == ["exec"] and "TRANSIENT" not in vars(module) and "added" not in vars(module) + if pollution: + assert result["code"] == "in_doubt" and box.isolated + assert box.source(module.__name__)["code"] == "in_doubt" + else: + assert result["code"] == "rolled_back" and not box.isolated + assert ( + box.install(patch(box, module.__name__, BASE.replace("G = 2", "G = 5")))["code"] == "ok" + ) + + +@pytest.mark.parametrize("fallback", [False, True]) +def test_undo_checks_nested_functions_created_during_the_patch(setup, fallback): + module, _, _, box = setup + baseline = ( + BASE + "\ndef factory(base):\n def inner():\n return base\n return inner\n" + ) + assert box.install(patch(box, module.__name__, baseline, name="baseline"))["code"] == "ok" + body = "inner" if fallback else "replacement" + candidate = baseline.replace("inner", body).replace("return base", "return 2 * base") + assert box.install(patch(box, module.__name__, candidate, name="candidate"))["code"] == "ok" + escaped = module.factory(7) + assert escaped() == 14 + result = box.uninstall("candidate") + if fallback: + assert result["code"] == "ok" and escaped() == 7 + else: + assert result["code"] == "in_doubt" and box.isolated + + +def test_native_parameterized_jit_registration_deletion_and_restore(setup, monkeypatch): + module, _, _, box = setup + registry = {} + runtime = ModuleType("triton.runtime.jit") + runtime._triton_jit_function_registry = registry + monkeypatch.setitem(sys.modules, runtime.__name__, runtime) + + def construct(*, debug): + assert debug + + def decorator(fn): + assert "__inferrsi_box_hit__" not in fn.__code__.co_names + kernel = FakeJit(fn) + registry[f"{fn.__module__}:{fn.__qualname__}"] = kernel + return FakeTuner(kernel) + + return decorator + + def abort(_): + raise RuntimeError("outer decorator failed") + + module.construct = construct + module.abort = abort + definition = "\n@construct(debug=True)\ndef fast(x):\n return x + 10\n" + caller = BASE.replace("return x + G", "return fast.run(x)") + partial = definition.replace("@construct", "@abort\n@construct") + assert box.install(patch(box, module.__name__, caller + partial))["code"] == "rolled_back" + assert not registry and "fast" not in vars(module) + failed = patch(box, module.__name__, caller + definition + "\nBROKEN = 1 / 0\n") + assert box.install(failed)["code"] == "rolled_back" + assert not registry and "fast" not in vars(module) + assert box.install(patch(box, module.__name__, caller + definition))["code"] == "ok" + wrapped = module.fast + key = f"{module.__name__}:fast" + assert registry[key] is wrapped.fn + proof = box.check("value", 4)["details"] + assert proof["output"] == 14 and proof["witnesses"][key]["triton_launches"] == 1 + assert proof["witnesses"][key]["compiled_cache_entries"] == 1 + + assert ( + box.install(patch(box, module.__name__, caller, name="live"))["code"] == "restart_required" + ) + module.alias = wrapped + assert ( + box.install(patch(box, module.__name__, BASE, name="alias"))["code"] == "restart_required" + ) + del module.alias + assert box.install(patch(box, module.__name__, BASE, name="delete"))["code"] == "ok" + assert key not in registry and not wrapped.fn.pre_run_hooks and not wrapped.cache + assert not wrapped.fn.device_caches + assert box.uninstall("delete")["code"] == "ok" + assert module.fast is wrapped and registry[key] is wrapped.fn + assert box.check("value", 4)["details"]["output"] == 14 + assert box.uninstall()["code"] == "ok" + assert not registry and not wrapped.fn.pre_run_hooks and not wrapped.cache + + +@pytest.mark.parametrize("raises", [False, True]) +@pytest.mark.parametrize("nested", [False, True]) +def test_construction_with_an_in_place_global_change_requires_respawn(setup, raises, nested): + module, _, endpoint, box = setup + pending = module.PENDING + target = [] if nested else pending + if nested: + pending.append({"target": target, "cycle": pending}) + + def mutate(): + target.append("side effect") + if raises: + raise RuntimeError("construction failed") + return None + + module.mutate = mutate + candidate = patch(box, module.__name__, BASE + "\nCANDIDATE = mutate()\n") + endpoint.preflight_mutation(command(box, "install", candidate.payload())) + assert target == [] and "CANDIDATE" not in vars(module) + assert box.install(candidate)["code"] == "in_doubt" + assert module.PENDING is pending and target == ["side effect"] and box.isolated + assert box.uninstall()["code"] == "in_doubt" + + +@pytest.mark.parametrize("presorted", [False, True]) +def test_failed_construction_that_reorders_a_live_dict_requires_respawn(setup, presorted): + module, _, _, box = setup + columns = {"height": 2, "width": 1} if presorted else {"width": 1, "height": 2} + module.COLUMNS = columns + before = list(columns) + + def sort_then_fail(): + ordered = dict(sorted(columns.items())) + columns.clear() + columns.update(ordered) + return 1 // 0 + + module.sort_then_fail = sort_then_fail + result = box.install(patch(box, module.__name__, BASE + "\nCANDIDATE = sort_then_fail()\n")) + assert module.COLUMNS is columns and "CANDIDATE" not in vars(module) + if presorted: + assert result["code"] == "rolled_back" and not box.isolated and list(columns) == before + else: + assert result["code"] == "in_doubt" and box.isolated + assert list(columns) == ["height", "width"] + + +@pytest.mark.parametrize("held", ["global", "container", "attribute"]) +def test_failed_construction_that_mutates_a_live_object_requires_respawn(setup, held): + module, _, _, box = setup + + class Opaque: + def __init__(self): + self.value = 0 + + opaque = Opaque() + if held == "global": + module.opaque = opaque + elif held == "container": + module.HOLDERS = {"opaque": [opaque]} + else: + module.holder = Opaque() + module.holder.inner = opaque + + def mutate_then_fail(): + opaque.value = 42 + raise RuntimeError("construction failed") + + module.mutate_then_fail = mutate_then_fail + result = box.install(patch(box, module.__name__, BASE + "\nCANDIDATE = mutate_then_fail()\n")) + assert result["code"] == "in_doubt" and box.isolated and opaque.value == 42 + + +def test_failed_construction_that_replaces_a_live_object_dict_requires_respawn(setup): + module, _, _, box = setup + + class Opaque: + def __init__(self): + self.value = 0 + + module.opaque = opaque = Opaque() + + def replace_then_fail(): + opaque.__dict__ = {"value": 0} + raise RuntimeError("construction failed") + + module.replace_then_fail = replace_then_fail + result = box.install(patch(box, module.__name__, BASE + "\nCANDIDATE = replace_then_fail()\n")) + assert result["code"] == "in_doubt" and box.isolated and opaque.value == 0 + + +def test_checkpoint_sampling_runs_no_metaclass_hooks(setup): + module, _, _, box = setup + reads = [] + + class Recording(type): + def __getattribute__(cls, name): + if name in ("__mro__", "__dict__"): + reads.append(name) + return super().__getattribute__(name) + + class Config(metaclass=Recording): + def __init__(self): + self.size = 1 + + module.CONFIG = Config() + reads.clear() + result = box.install(patch(box, module.__name__, BASE + "\nUNRELATED = 7\n")) + assert result["code"] == "ok" and module.UNRELATED == 7 and reads == [] + + +def test_failed_construction_that_leaves_a_live_object_unchanged_rolls_back(setup): + module, _, _, box = setup + + class Opaque: + def __init__(self): + self.value = 0 + + module.opaque = opaque = Opaque() + + def touch_then_fail(): + opaque.value = 42 + opaque.value = 0 + raise RuntimeError("construction failed") + + module.touch_then_fail = touch_then_fail + result = box.install(patch(box, module.__name__, BASE + "\nCANDIDATE = touch_then_fail()\n")) + assert result["code"] == "rolled_back" and not box.isolated and opaque.value == 0 + assert box.install(patch(box, module.__name__, BASE.replace("G = 2", "G = 5")))["code"] == "ok" + + +def test_failed_cold_import_reverses_loaded_parent_package(setup): + module, _, endpoint, box = setup + package = Path(module.__file__).parent / "cold_package" + package.mkdir() + (package / "__init__.py").write_text("LOADED = True\n", encoding="utf-8") + expected = module.__package__ + ".cold_package" + endpoint.log.allowed_import = {expected + ".absent"}.__contains__ + + candidate = patch(box, module.__name__, "from .cold_package.absent import VALUE\n" + BASE) + endpoint.preflight_mutation(command(box, "install", candidate.payload())) + assert expected not in sys.modules + assert box.install(candidate)["code"] == "rolled_back" + assert expected not in sys.modules and "cold_package" not in vars( + sys.modules[module.__package__] + ) + + +def test_native_declarations_see_earlier_function_updates(setup): + module, _, _, box = setup + original = module.value + original_code = original.__code__ + original_method_defaults = module.Model.measure.__defaults__ + source = BASE.replace("return x + G", "return x + G + 10").replace( + "scale=DEFAULT", "scale=value()" + ) + source += ( + "\nSNAPSHOT = value()\nMETHOD_SNAPSHOT = Model().measure()\n" + "\ndef snapshot(x=value()):\n return x\n" + ) + cold = {} + exec(compile(source, "", "exec"), cold) + + failed = patch(box, module.__name__, source + "\nBROKEN = 1 / 0\n") + assert box.install(failed)["code"] == "rolled_back" + assert original() == 3 and original.__code__ is original_code + assert module.Model.measure.__defaults__ is original_method_defaults + assert {"SNAPSHOT", "METHOD_SNAPSHOT", "snapshot"}.isdisjoint(vars(module)) + + assert box.install(patch(box, module.__name__, source))["code"] == "ok" + assert module.value is original and module.value() == cold["value"]() == 13 + assert module.SNAPSHOT == cold["SNAPSHOT"] == 13 + assert module.snapshot() == cold["snapshot"]() == 13 + assert module.Model().measure() == module.METHOD_SNAPSHOT == cold["METHOD_SNAPSHOT"] == 15 + assert module.Model.measure.__doc__ is cold["Model"].measure.__doc__ is None + + assert box.uninstall()["code"] == "ok" + assert original() == 3 and original.__code__ is original_code + assert module.Model.measure.__defaults__ is original_method_defaults + assert {"SNAPSHOT", "METHOD_SNAPSHOT", "snapshot"}.isdisjoint(vars(module)) + + +@pytest.mark.parametrize(("fallback", "escape"), [(True, True), (False, False), (False, True)]) +@pytest.mark.parametrize("binding", ["constant", "default"]) +def test_undo_checks_nested_functions_created_by_declarations(setup, fallback, escape, binding): + module, _, _, box = setup + baseline = ( + BASE + "\ndef factory(base):\n def inner():\n return base\n return inner\n" + ) + assert box.install(patch(box, module.__name__, baseline, name="baseline"))["code"] == "ok" + declaration = ( + "CALLBACK = factory(7)\n" + if binding == "constant" + else "def CALLBACK(callback=factory(7)):\n return callback()\n" + ) + candidate = baseline.replace("return base", "return 2 * base") + "\n" + declaration + if not fallback: + candidate = candidate.replace("inner", "replacement") + failed = patch(box, module.__name__, candidate + "\nBROKEN = 1 / 0\n") + assert box.install(failed)["code"] == "rolled_back" + assert "CALLBACK" not in vars(module) + assert box.install(patch(box, module.__name__, candidate, name="candidate"))["code"] == "ok" + assert module.CALLBACK() == 14 + escaped = None + if escape: + escaped = module.CALLBACK if binding == "constant" else module.CALLBACK.__defaults__ + + result = box.uninstall("candidate") + if escape and not fallback: + assert result["code"] == "in_doubt" and box.isolated + else: + assert result["code"] == "ok" and "CALLBACK" not in vars(module) + if escaped is not None: + callback = escaped if binding == "constant" else escaped[0] + assert callback() == 7 + + +@pytest.mark.parametrize("later", ["delete", "rebind", "alias", "wrap", "migrate"]) +@pytest.mark.parametrize("escape", [False, True]) +def test_stacked_uninstall_checks_declaration_callback_escape(setup, later, escape): + module, _, _, box = setup + baseline = ( + BASE + "\ndef factory(base):\n def inner():\n return base\n return inner\n" + ) + assert box.install(patch(box, module.__name__, baseline, name="baseline"))["code"] == "ok" + candidate = baseline.replace("inner", "replacement") + "\nCALLBACK = factory(7)\n" + assert box.install(patch(box, module.__name__, candidate, name="candidate"))["code"] == "ok" + + class Holder: + pass + + retained = Holder() + if escape and later != "wrap": + retained.callback = module.CALLBACK + if later == "delete": + updated = candidate.replace("CALLBACK = factory(7)\n", "") + elif later == "rebind": + updated = candidate.replace("CALLBACK = factory(7)", "CALLBACK = 42") + elif later == "alias": + updated = candidate + "ALIAS = CALLBACK\n" + elif later == "wrap": + updated = candidate + "ALIAS = ((CALLBACK,),)\n" + else: + updated = candidate.replace("return base", "return 2 * base") + assert box.install(patch(box, module.__name__, updated, name="later"))["code"] == "ok" + + if escape and later == "wrap": + retained.callback = module.ALIAS + result = box.uninstall("candidate") + if escape: + assert retained.callback is not None and result["code"] == "in_doubt" and box.isolated + else: + assert result["code"] == "ok" + assert "CALLBACK" not in vars(module) and "ALIAS" not in vars(module) + assert module.factory(7)() == 7 + + +def test_failed_construction_requires_verified_profile_state_restore(setup): + module, state, _, box = setup + state.restore = lambda _: None + + def mutate(): + state.requests = 37 + raise RuntimeError("construction failed") + + module.mutate = mutate + candidate = patch(box, module.__name__, BASE + "\nCANDIDATE = mutate()\n") + assert box.install(candidate)["code"] == "in_doubt" + assert state.requests == 37 and "CANDIDATE" not in vars(module) and box.isolated + + +def test_uninstall_isolates_on_an_in_place_mutation_after_a_successful_install(setup): + module, _, _, box = setup + nested = [] + container = module.PENDING + container.append({"nested": nested}) + + class Watched(type): + def __delattr__(cls, name): + if name == "added": + nested.append("untracked teardown effect") + super().__delattr__(name) + + module.Watched = Watched + baseline = BASE + "\nclass Target(metaclass=Watched):\n pass\n" + assert box.install(patch(box, module.__name__, baseline, name="baseline"))["code"] == "ok" + source = baseline + "\n def added(self):\n return 7\n" + assert box.install(patch(box, module.__name__, source, name="candidate"))["code"] == "ok" + assert module.Target().added() == 7 and nested == [] + + assert box.uninstall("candidate")["code"] == "in_doubt" + assert module.PENDING is container and nested == ["untracked teardown effect"] + assert box.isolated + + +@pytest.mark.parametrize(("fallback", "escape"), [(True, True), (False, False), (False, True)]) +def test_uninstall_checks_closure_held_through_a_declaration_container(setup, fallback, escape): + module, _, _, box = setup + baseline = ( + BASE + "\ndef factory(base):\n def inner():\n return base\n return inner\n" + ) + assert box.install(patch(box, module.__name__, baseline, name="baseline"))["code"] == "ok" + candidate = baseline.replace("return base", "return 2 * base") + candidate += "\nCALLBACKS = (factory(7),)\n\ndef call_snapshot():\n return CALLBACKS[0]()\n" + if not fallback: + candidate = candidate.replace("inner", "replacement") + assert box.install(patch(box, module.__name__, candidate, name="candidate"))["code"] == "ok" + assert module.call_snapshot() == 14 + kept = module.CALLBACKS if escape else None + + result = box.uninstall("candidate") + if escape and not fallback: + assert result["code"] == "in_doubt" and box.isolated + else: + assert result["code"] == "ok" and "CALLBACKS" not in vars(module) + if kept is not None: + assert kept[0]() == 7 diff --git a/tests/box/vllm_common/test_multi_rank_and_core.py b/tests/box/vllm_common/test_multi_rank_and_core.py index bab34e81d..10f34db95 100644 --- a/tests/box/vllm_common/test_multi_rank_and_core.py +++ b/tests/box/vllm_common/test_multi_rank_and_core.py @@ -154,7 +154,7 @@ def patch(name): source = ( body + """\n -STRUCTURAL_TABLE = dict({("z", 1), ("b", 2), ("k", 3)}) +STRUCTURAL_TABLE = dict(zip(("z", "b", "k"), range(3))) def structural_helper(value, choices=STRUCTURAL_TABLE): return value + len(choices)