Skip to main content

support

probe and install what a kernel needs into the environment it will run in

Check and install kernel support in a selected Python environment.

KERNEL_PACKAGES lists the required distributions. kernel_requirements turns them into what an install asks for. IPYKERNEL_FLOOR is the first ipykernel without the shell stall, and MIN_PY the oldest Python kunda installs into.

HOST_PY, INSPECTOR, KERNEL_PACKAGES, IPYKERNEL_FLOOR, MIN_PY
((3, 11),
 ('dhrishti',),
 ('ipykernel', 'ipymini', 'kernmini', 'fastcore', 'microio'))

source

work_dir

def work_dir(
    cwd:NoneType=None
):

cwd as a string, falling back to a writable directory when the process inherited / or a read-only bundle.

work_dir returns a supplied directory as text. A missing directory uses the current working directory.

work_dir(Path('/repo/notebooks'))
'/repo/notebooks'

source

support_paths

def support_paths():

The host’s absolute, existing sys.path entries: where the inspector’s finder looks for its own dependencies.

support_paths returns the existing absolute import paths of the host. Relative and missing paths are excluded. A kernel does not get these paths on its sys.path. Only the finder in INSPECTOR_LOADER searches them.

Each interpreter path has one shared probe lock.

test_is(_lock_for('/a/.venv/bin/python'), _lock_for('/a/.venv/bin/python'))
assert _lock_for('/a/.venv/bin/python') is not _lock_for('/b/.venv/bin/python')

_run always returns returncode, stdout, and stderr. Process-start failures become a non-zero result. Its stdin is /dev/null, so a probe never shares the host’s terminal.

p = _run(['/definitely/not/a/python', '-c', 'pass'])
p.returncode, p.stderr
(127, "[Errno 2] No such file or directory: '/definitely/not/a/python'")
import os, pty, sys
m, s = pty.openpty(); os.write(m, b'x\n')   # a line waiting on the terminal, which only the parent may read
probe = "import os, select, sys; from kunda.support import _run; print(_run([sys.executable, '-c', 'import os; print(os.isatty(0))']).stdout.strip(), os.read(0, 9) if select.select([0], [], [], 1)[0] else b'')"
got = subprocess.run([sys.executable, '-c', probe], stdin=s, capture_output=True, text=True, timeout=60).stdout.split()
os.close(s); os.close(m)
test_eq(got, ['False', "b'x\\n'"])

_last_line returns the last non-empty line, or an empty string.

_last_line('Traceback (most recent call last):\n  File "<string>", line 1\nImportError: numpy ABI\n\n')
'ImportError: numpy ABI'

source

inspector_modules

def inspector_modules(
    root:str='dhrishti', skip:tuple=('numpy', 'pandas')
):

The top-level modules of root’s runtime dependencies, which a kernel may load from the host for root alone.

inspector_modules follows the runtime requirements of Dhrishti through the host’s package metadata. It returns the import names of those packages. Dhrishti itself is not in the list, because the loader loads it by file path. VALUE_TYPES are not in the list. Dhrishti only checks whether a value is an ndarray or a DataFrame, and it reads numpy and pandas from sys.modules for that.

inspector_modules()[:6]

source

inspector_loader

def inspector_loader():

Source that loads the host’s Dhrishti into a kernel of the host’s Python; ’’ when the host has no Dhrishti.

INSPECTOR_LOADER loads the host’s Dhrishti by file path. The kernel’s sys.path does not change, so user code imports only what the kernel’s own environment has. Dhrishti still needs its dependencies, for example fasthtml and safepyrun, and the environment often does not have them. The loader adds a finder at the end of sys.meta_path for these. The finder answers only when all of these are true:

  1. The name is a top-level module in inspector_modules.
  2. The environment does not have that module. The finder is last, so the environment’s own copy is used first.
  3. The import comes from Dhrishti, or from a module that the finder itself gave.

An import from user code goes to the finder too, and the finder refuses it. A module that Dhrishti already loaded stays in sys.modules, as every loaded module does. After the bootstrap, import fasthtml in user code can find Dhrishti’s copy. A package that Dhrishti does not use, such as vishalakshi, is never found.

In a kernel of another Python minor version the loader does nothing. Then the bootstrap imports the environment’s own Dhrishti, as before.

import venv

The test makes an empty venv of the host’s Python. The loader loads Dhrishti there, and Dhrishti answers. User code cannot import jupygate, which the host has and Dhrishti does not use. It cannot import numpy either, because Dhrishti did not load it. safepyrun is refused too: Dhrishti imports it only when an agent runs, so it is not loaded yet.

A module probe returns available, version, and error. pre runs first, in the same process: inspector_support passes inspector_loader there.

tmp = TemporaryDirectory(); d = Path(tmp.name)
(d/'borrowed.py').write_text('__version__ = "1.2"')
_probe(sys.executable, 'borrowed', pre=f'import sys; sys.path.append({str(d)!r})')
{'available': True, 'version': '1.2', 'error': ''}

source

ipykernel_notice

def ipykernel_notice(
    python:NoneType=None, version:NoneType=None
):

What a host shows for an ipykernel whose shell can stop answering, or None. version skips the read.


source

ipykernel_version

def ipykernel_version(
    python:NoneType=None
):

The ipykernel version python launches, read from its metadata without importing it; ’’ when it has none.

ipykernel_version reads the version from a venv’s dist-info folder on disk, and starts the interpreter only when that folder cannot say. ipykernel_notice turns a version from 7.0 to 7.3 into a message a host can show.

tmp_v = TemporaryDirectory(); venv = Path(tmp_v.name)
(venv/'pyvenv.cfg').write_text('home = /nowhere\n')
(venv/'lib/python3.12/site-packages/ipykernel-7.2.0.dist-info').mkdir(parents=True)
ipykernel_version(venv/'bin/python'), ipykernel_notice(version='7.2.0')['message']

source

kernel_support

def kernel_support(
    python
):

Importability of both supported kernel launchers in python; the ipykernel entry carries ipykernel_notice.

kernel_support probes both kernel launchers in the selected interpreter. Its ipykernel entry also holds notice, which is None unless that ipykernel can stall.

ok = kernel_support(sys.executable)['ipymini']
gone = kernel_support('/definitely/not/a/python')['ipymini']
ok, gone
assert kernel_support(sys.executable)['ipykernel']['notice'] is None
({'available': True, 'version': '0.1.21', 'error': ''},
 {'available': False,
  'version': '',
  'error': "[Errno 2] No such file or directory: '/definitely/not/a/python'"})

source

import_failure

def import_failure(
    err
):

Whether bootstrap failed on an inspector import.


source

inspector_support

def inspector_support(
    python, refresh:bool=False
):

Check whether python can import the live-variable inspector, returning what blocked it if not.

inspector_support caches one result per interpreter for INSPECTOR_TTL seconds. import_failure recognizes a missing or broken inspector import.

inspector_support(sys.executable), import_failure("ModuleNotFoundError: No module named 'dhrishti'")
{'available': False,
 'version': '',
 'error': "ModuleNotFoundError: No module named 'dhrishti'"}

source

installable

def installable(
    python
):

Whether anything may install into python. Never this one, and never inside a signed bundle.

installable rejects a missing path, the current interpreter, and interpreters inside a macOS application bundle.

installable(sys.executable), installable('/repo/.venv/bin/python')
(False, True)

source

as_installed

def as_installed(
    names:tuple=('ipykernel', 'ipymini', 'kernmini', 'fastcore', 'microio')
):

Pin names to the versions this process runs; leave unpinned what it doesn’t have, so installs stay compatible with the host.

as_installed pins names to versions installed in the host process.

as_installed(['fastcore', 'ipymini', 'not_a_real_package'])
['fastcore==2.2.19', 'ipymini==0.1.21', 'not_a_real_package']

source

kernel_requirements

def kernel_requirements(
    names:tuple=('ipykernel', 'ipymini', 'kernmini', 'fastcore', 'microio')
):

What an install asks for: ipykernel at IPYKERNEL_FLOOR or later, the rest pinned by as_installed.

kernel_requirements asks for ipykernel by its floor rather than the host’s exact version, so a project that pins a later ipykernel still installs, and one on 7.0 to 7.3 is raised past the stall.

kernel_requirements(['ipykernel', 'fastcore'])

_attempts tries uv when available and always includes python -m pip install.

_attempts('/nowhere/bin/python', ['ipymini==0.1.21'])[-1]
['/nowhere/bin/python', '-m', 'pip', 'install', 'ipymini==0.1.21']

_log records the command, return code, and bounded output.


source

install_kernel_support

def install_kernel_support(
    python, packages:NoneType=None
):

Install kernel packages via uv or pip; verify the import works after, so failures name the package not the installer.

install_kernel_support installs kernel_requirements and succeeds only when both launchers import. It refuses a Python older than MIN_PY before it installs anything.


source

make_venv

def make_venv(
    root, python:NoneType=None
):

Make root/.venv on python (this Python’s minor by default) with kernel support; its interpreter. An existing venv is kept; a half-made one is removed.

make_venv gives a project its own .venv, so the project never borrows an environment from a parent folder or from the host. It uses uv venv on the host’s Python minor when uv is on PATH, and the standard venv module when it is not. Then it installs kernel support. A venv that exists already is kept. A .venv folder with no interpreter is refused, because it may hold something the person wants. When a step fails, the new folder is removed, so the next try starts clean. One lock per folder stops two callers from making the same venv at once.


source

install_inspector_support

def install_inspector_support(
    python, packages:tuple=('dhrishti',)
):

Give python its own copy of what the inspector imports, then ask it again.

install_inspector_support installs Dhrishti and probes it again.