Skip to content
46 changes: 30 additions & 16 deletions src/inferrsi/box/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/inferrsi/box/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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]] = {}
Expand Down
68 changes: 52 additions & 16 deletions src/inferrsi/box/kernel/jit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from types import FunctionType, ModuleType

from ..protocol import BoxError
from .journal import MISSING
from .witness import record_hit

_REQUIRED = (
Expand Down Expand Up @@ -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)}"

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 (
Expand All @@ -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),
Expand Down Expand Up @@ -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)


Expand All @@ -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)
Loading
Loading