Skip to content

setup

setup

Check and certify package-owned setup without knowing the dependency graph.

__all__ = ['SetupStatus', 'SetupCheck', 'SetupReceipt', 'SetupRequiredError', 'SetupDowngradeError', 'setup_status', 'setup_lock', 'require_no_downgrade', 'require_setup', 'python_identity'] module-attribute

SetupStatus

Bases: StrEnum

Whether installed setup can be used by the running package.

READY = 'ready' class-attribute instance-attribute

MISSING = 'missing' class-attribute instance-attribute

STALE = 'stale' class-attribute instance-attribute

DOWNGRADE = 'downgrade' class-attribute instance-attribute

INVALID = 'invalid' class-attribute instance-attribute

SetupCheck(owner, component, status, diagnostic='') dataclass

One owner's setup result, composable with checks from its dependencies.

owner instance-attribute

component instance-attribute

status instance-attribute

diagnostic = '' class-attribute instance-attribute

SetupReceipt(path, owner, version, inputs) dataclass

Certify one owner's version and setup inputs in an atomic JSON receipt.

Owners preflight their full dependency closure before changing artifacts, clear their receipt immediately before their own writes, and write it only after verification succeeds, holding setup_lock across the whole transition. A receipt never certifies child packages.

path instance-attribute

owner instance-attribute

version instance-attribute

inputs instance-attribute

check()

Compare the receipt with the current owner, version, and setup inputs.

Source code in src/terok_util/setup.py
def check(self) -> SetupCheck:
    """Compare the receipt with the current owner, version, and setup inputs."""
    try:
        stored = json.loads(self.path.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return self._result(SetupStatus.MISSING, "Setup receipt is missing")
    except (OSError, ValueError):
        return self._result(SetupStatus.INVALID, "Setup receipt cannot be read")
    if not _valid_receipt(stored) or stored["owner"] != self.owner:
        return self._result(SetupStatus.INVALID, "Setup receipt has an invalid owner or format")
    try:
        installed, current = Version(stored["version"]), Version(self.version)
    except InvalidVersion:
        return self._result(SetupStatus.INVALID, "Setup receipt version is invalid")
    if installed > current:
        return self._result(
            SetupStatus.DOWNGRADE,
            f"Setup belongs to newer {self.owner} {installed}; running {current}",
        )
    if installed != current or stored["inputs"] != self.inputs:
        return self._result(SetupStatus.STALE, "Setup version or inputs changed")
    return self._result(SetupStatus.READY)

clear()

Invalidate this owner's receipt, refusing an unsupported downgrade.

Source code in src/terok_util/setup.py
def clear(self) -> None:
    """Invalidate this owner's receipt, refusing an unsupported downgrade."""
    require_no_downgrade([self.check()])
    self.path.unlink(missing_ok=True)

write()

Atomically certify successful setup, refusing an unsupported downgrade.

Source code in src/terok_util/setup.py
def write(self) -> None:
    """Atomically certify successful setup, refusing an unsupported downgrade."""
    require_no_downgrade([self.check()])
    receipt = {"owner": self.owner, "version": self.version, "inputs": dict(self.inputs)}
    if not _valid_receipt(receipt):
        raise ValueError("Setup receipt requires a string owner, version, and inputs")
    Version(self.version)
    ensure_dir(self.path.parent)
    with tempfile.NamedTemporaryFile(
        mode="w", encoding="utf-8", dir=self.path.parent, delete=False
    ) as stream:
        temporary = Path(stream.name)
        try:
            json.dump(receipt, stream, sort_keys=True)
            stream.write("\n")
            stream.flush()
            os.replace(temporary, self.path)
        finally:
            temporary.unlink(missing_ok=True)

SetupRequiredError

Bases: RuntimeError

Setup must complete before an operation may change running tasks.

SetupDowngradeError

Bases: SetupRequiredError

Newer installed setup cannot be replaced by an older package.

setup_lock(*, allow_downgrade=False)

Serialize setup mutations across packages, processes, and threads.

Hold this around preflight, artifact changes, and receipt writes. Nested calls in the owning thread share the lock; competing callers fail with SetupRequiredError.

Parameters:

Name Type Description Default
allow_downgrade bool

Authorize setup to replace newer receipts in this scope. Nested setup calls inherit permission. Readiness checks still reject unrepaired setup; state compatibility is not guaranteed.

False
Source code in src/terok_util/setup.py
@contextmanager
def setup_lock(*, allow_downgrade: bool = False) -> Iterator[None]:
    """Serialize setup mutations across packages, processes, and threads.

    Hold this around preflight, artifact changes, and receipt writes. Nested
    calls in the owning thread share the lock; competing callers fail with
    [`SetupRequiredError`][terok_util.setup.SetupRequiredError].

    Args:
        allow_downgrade: Authorize setup to replace newer receipts in this
            scope. Nested setup calls inherit permission. Readiness checks
            still reject unrepaired setup; state compatibility is not guaranteed.
    """
    with _hold_setup_lock():
        owner = (os.getpid(), threading.get_ident())
        permit = _DowngradePermit(owner) if allow_downgrade or _downgrade_allowed() else None
        token = _downgrade_permit.set(permit)
        try:
            yield
        finally:
            if permit is not None:
                permit.active = False
            if os.getpid() == owner[0]:
                _downgrade_permit.reset(token)

setup_status(checks)

Summarize checks, prioritizing unsupported downgrades over repairable setup.

Source code in src/terok_util/setup.py
def setup_status(checks: Iterable[SetupCheck]) -> SetupStatus:
    """Summarize checks, prioritizing unsupported downgrades over repairable setup."""
    statuses = {check.status for check in checks}
    return next(
        (
            status
            for status in (
                SetupStatus.DOWNGRADE,
                SetupStatus.INVALID,
                SetupStatus.MISSING,
                SetupStatus.STALE,
            )
            if status in statuses
        ),
        SetupStatus.READY,
    )

require_no_downgrade(checks)

Reject newer setup unless the current setup scope explicitly permits it.

Source code in src/terok_util/setup.py
def require_no_downgrade(checks: Iterable[SetupCheck]) -> None:
    """Reject newer setup unless the current setup scope explicitly permits it."""
    if not _downgrade_allowed():
        _reject_downgrades(checks)

require_setup(checks)

Require all checks to be ready, using typed errors instead of process exits.

An owner whose receipt is missing has no setup at all — never run, or cleared by a run that did not complete — so its other components can say nothing a first-time user acts on. Such an owner is reported as that one fact, and the hint asks to run setup, not to run it again.

Source code in src/terok_util/setup.py
def require_setup(checks: Iterable[SetupCheck]) -> None:
    """Require all checks to be ready, using typed errors instead of process exits.

    An owner whose receipt is missing has no setup at all — never run, or
    cleared by a run that did not complete — so its other components can
    say nothing a first-time user acts on.  Such an owner is reported as
    that one fact, and the hint asks to run setup, not to run it *again*.
    """
    pending = [check for check in checks if check.status != SetupStatus.READY]
    _reject_downgrades(pending)
    if not pending:
        return
    unset = {
        check.owner
        for check in pending
        if check.component == _RECEIPT_COMPONENT and check.status == SetupStatus.MISSING
    }
    segments = dict.fromkeys(
        f"{check.owner}: {_NOT_SET_UP}" if check.owner in unset else _diagnostic(check)
        for check in pending
    )
    hint = "Run setup." if unset >= {check.owner for check in pending} else "Run setup again."
    raise SetupRequiredError("; ".join(segments) + f". {hint}")

python_identity()

Identify the running bootstrap Python and detect replacement or disappearance.

Source code in src/terok_util/setup.py
def python_identity() -> str:
    """Identify the running bootstrap Python and detect replacement or disappearance."""
    if not sys.executable:
        return json.dumps([sys.executable, sys.version, None])
    executable = Path(sys.executable)
    try:
        stat = executable.stat()
        identity = [stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns]
    except OSError:
        identity = None
    return json.dumps([str(executable), sys.version, identity])