Skip to main content

kernel

one running kernel: execute and complete over the shell channel, variables over its in-kernel

Run one local or gateway kernel. Execution returns nbformat outputs. Inspection uses the Dhrishti HTTP API.

KERNELS lists supported Python launchers. Unknown launcher names use ipykernel.


source

give_up_after

async def give_up_after(
    coro, timeout:float=5.0
):

Await coro, then stop waiting rather than hold the caller open. Failing to close is not news.

give_up_after stops waiting for shutdown after the timeout. A host that closes several kernels at once wraps the close in it, so one kernel that never answers cannot hold the rest up.

t = time.time()
await give_up_after(asyncio.sleep(30), timeout=.05)      # the deadline ends this, not the sleep
async def never_answers(): raise RuntimeError('the kernel never answered')
await give_up_after(never_answers()), time.time() - t < 1
(None, True)

never_answers

async def never_answers():

source

ipymini_available

def ipymini_available():

True when the ipymini package can be imported in this interpreter.

ipymini_available checks whether the package can be imported without importing it.

ipymini_available()
True

source

comm_content

def comm_content(
    comm_id, # the comm both ends agreed on
    data:NoneType=None, # JSON-able payload
    msg_type:str='comm_msg', # one of `COMM_MSGS`
    target_name:NoneType=None, # the kernel-side target; only a `comm_open` names one
):

The content of one comm message to a kernel, checked before it is sent.


source

CommsUnsupported

def CommsUnsupported(
    *args, **kwargs
):

This kernel has no comm manager to relay widgets to: ipymini, and kernels for other languages.

comm_content builds what a host sends to relay a widget comm. A comm_open names the kernel-side target the comm attaches to, so one without target_name fails here rather than being closed silently by the kernel.

with ExceptionExpected(ValueError, 'target_name'): comm_content('c1', msg_type='comm_open')
comm_content('c1', {'method': 'update', 'state': {'value': 3}}), comm_content('c2', msg_type='comm_open', target_name='jupyter.widget')
({'comm_id': 'c1', 'data': {'method': 'update', 'state': {'value': 3}}},
 {'comm_id': 'c2', 'data': {}, 'target_name': 'jupyter.widget'})

source

Feed

def Feed(
    maxsize:int=1000
):

Hand messages to subscribers from a bounded queue, so whatever produces them never waits on whoever reads them.

Feed is how a kernel tells its host about traffic no request asked for: widget comms, output from a comm handler, and {'type': 'kernel_restart'} or {'type': 'kernel_gone'}. The router puts and returns at once. One task delivers to each subscriber in turn, and a subscriber that falls maxsize messages behind loses the oldest, counted in dropped, so a stalled browser tab can neither block the kernel’s reader nor grow memory without bound.

f, seen = Feed(maxsize=2), []
f.put('before anyone listened')
f.subscribe(seen.append)
for i in range(4): f.put(i)
await f.flush()
seen, f.dropped
([2, 3], 2)

source

InspectorClient

def InspectorClient(
    *args, **kwargs
):

The inspector-client half shared by Kernel and GatewayKernel.

InspectorClient holds state and Dhrishti client methods shared by local and gateway kernels. A host’s own runner subclasses it to get the same inspector calls, idle clock and stop behaviour. Every kernel also has a feed: subscribe registers a callback and emit announces a lifecycle event. A kernel without comms raises CommsUnsupported from comm_send and comm_info.

p = Probe('http://127.0.0.1:8123')
p.token, p._headers(), Probe().token
('S3CRET', {'X-Dhrishti-Token': 'S3CRET'}, None)
p.touch()
p.busy, p.idle_for < 1, p.kernel_kind
(False, True, 'ipykernel')

names returns top-level names from Dhrishti’s grouped response.

class Rows(Probe):
    "The inspector's answer, without the inspector."
    async def api(self, path, params=None, timeout=15):
        self.asked = path
        return {'groups': [{'name': 'data', 'nodes': [{'name': 'df'}, {'name': 'raw'}]}, {'name': 'other', 'nodes': [{'name': 'x'}]}]}
r = Rows('http://127.0.0.1:8123')
await r.names(), r.asked
(['df', 'raw', 'x'], '/api/rows')

Rows

def Rows(
    base:NoneType=None, name:str='nb'
):

The inspector’s answer, without the inspector.

stop interrupts the active execution. It restarts the kernel when the execution does not stop before the timeout.

async def one_cell(obeys):
    k = Running(obeys)
    return (await k.stop(timeout=.05))['note'], k.restarted
print(await Probe().stop())
for obeys in (True, False): print(await one_cell(obeys))
{'ok': False, 'forced': False, 'note': 'nothing is running'}
('cell interrupted', False)
('kernel restarted after interrupt was ignored', True)

one_cell

async def one_cell(
    obeys
):

source

MessageRouter

def MessageRouter(
    *args, **kwargs
):

The one reader of a kernel’s iopub and shell replies, sending each message to its run, its waiter or the subscribers.

MessageRouter is what Kernel and GatewayKernel share: each transport feeds every inbound message to _route, and nothing else reads the kernel. A shell reply resolves the request that is waiting for it, so complete, inspect_obj, comm_info and execute overlap without stealing each other’s replies. Output parented to the running execute joins its outputs. Comm traffic, and output whose request is not a running execute, such as a print inside a comm’s on_msg handler, go whole to the subscribers, buffers included.

An Output widget changes where output belongs. While its msg_id state names a request, the frontend shows that request’s output inside the widget, so the router tags it with the widget’s output_comm_id and gives it to the subscribers instead of the cell. Here a router with no kernel under it is fed the messages ipywidgets sends for with out: print(...) inside a cell:

class Wire(MessageRouter):
    "A router fed by hand."
    comms = True
    def __init__(self): self._init_router()

def msg(t, content, parent='cell-1'): return {'header': {'msg_type': t}, 'parent_header': {'msg_id': parent}, 'content': content, 'channel': 'iopub'}
state = lambda msg_id: {'comm_id': 'out-1', 'data': {'method': 'update', 'state': {'msg_id': msg_id}}}
w, got, run = Wire(), [], _Run()
w.subscribe(got.append)
w._runs['cell-1'] = run
for m in [msg('comm_open', {'comm_id': 'out-1', 'target_name': 'jupyter.widget', 'data': {'state': {'_model_name': 'OutputModel', 'msg_id': ''}}}),
          msg('comm_msg', state('cell-1')), msg('stream', {'name': 'stdout', 'text': 'inside the widget\n'}),
          msg('comm_msg', state('')), msg('stream', {'name': 'stdout', 'text': 'in the cell\n'})]: w._route(m)
await w.feed.flush()
run.outs, [(m['msg_type'], m.get('output_comm_id')) for m in got]
([{'output_type': 'stream', 'name': 'stdout', 'text': 'in the cell\n'}],
 [('comm_open', None),
  ('comm_msg', None),
  ('stream', 'out-1'),
  ('comm_msg', None)])

msg

def msg(
    t, content, parent:str='cell-1'
):

Wire

def Wire():

A router fed by hand.

A clear_output message also sends on_output the event {'output_type': 'clear_output'}. A consumer that builds the output list resets it on this event. With wait=False the event comes at once. With wait=True the event comes immediately before the event of the next output. A wait=True clear with no later output sends no event. Here a run is fed print('a'), clear_output() and print('b'):

def fed(*msgs):
    "The `on_output` events and the final outputs of one run fed `msgs` by hand."
    w, events = Wire(), []
    w._runs['cell-1'] = r = _Run(events.append)
    for m in msgs: w._route(m)
    return events, r.outs

out = lambda text: msg('stream', {'name': 'stdout', 'text': text})
fed(out('a\n'), msg('clear_output', {'wait': False}), out('b\n'))
([{'output_type': 'stream', 'name': 'stdout', 'text': 'a\n'},
  {'output_type': 'clear_output'},
  {'output_type': 'stream', 'name': 'stdout', 'text': 'b\n'}],
 [{'output_type': 'stream', 'name': 'stdout', 'text': 'b\n'}])

fed

def fed(
    *msgs
):

The on_output events and the final outputs of one run fed msgs by hand.


source

DebugClient

def DebugClient(
    *args, **kwargs
):

Cell debugging over the Jupyter Debug Protocol, shared by Kernel and GatewayKernel; each transport supplies debug_request.

DebugClient is the cell debugger both kernels share. A transport supplies debug_request, which sends one Debug Adapter Protocol request on the control channel and returns its reply’s content. Requests go one at a time under a lock, each with the next seq number, and a reply without success raises. debug_start dumps every notebook cell to the file ipykernel runs it from, so _debug_sources maps a paused frame’s source path back to its cell, then sets the breakpoints of the cell about to run. The stopped event arrives on iopub, where the router records its thread for debug_state, debug_evaluate and debug_control. A GatewayKernel restart or shutdown forgets the session and settles a request still waiting, so no caller waits on a kernel that is gone.


source

Kernel

def Kernel(
    cwd:NoneType=None, name:NoneType=None, python:NoneType=None, inspect:bool=True, agent:str='restricted',
    port:int=0, # 0: the OS gives the inspector a free port
    kernel:str='ipykernel', lang:str='python',
    known:NoneType=None, # the host's `{language: kernelspec}`, handed down by the pool
    install:str='', # what would install a kernel for `lang`, for the error when none is
):

One ipykernel process: execute/complete over jupyter_client, live variables over its in-kernel.

Kernel owns one local kernel process and its Jupyter client. start waits for the kernel and then starts Dhrishti when inspection is enabled.

k = Kernel(kernel='not-a-kernel', inspect=False)
j = Kernel(cwd='/proj', lang='julia', inspect=True)
k.kernel, (j.kernel, j.inspect, await j.chdir('/proj'))
('ipykernel', ('ipykernel', False, False))

Execution on a stopped kernel returns a failed ExecOutcome. One reader per channel feeds the router from start until shutdown, and restart replaces it, so a request never reads the kernel itself. A timeout bounds the whole run, and a run that outlives it comes back failed with the outputs it had.

k.alive, k.pid, (await k.execute('1+1')).error, await k.complete('1+', 2), await k.inspect_obj('1+', 2)
(False, None, 'kernel is not running', {'from': 2, 'matches': []}, '')

Registered language kernels use their installed kernelspec. A missing kernelspec raises KernelStartError.

_as_output converts one IOPub message to an nbformat output. Messages without output return None.

[Kernel._as_output('stream', {'name': 'stdout', 'text': 'hello\n'}),
 Kernel._as_output('execute_result', {'data': {'text/plain': '42'}, 'execution_count': 1}),
 Kernel._as_output('update_display_data', {'data': {'text/plain': 'second'}}),
 Kernel._as_output('status', {'execution_state': 'idle'})]
[{'output_type': 'stream', 'name': 'stdout', 'text': 'hello\n'},
 {'output_type': 'execute_result',
  'data': {'text/plain': '42'},
  'metadata': {},
  'execution_count': 1},
 {'output_type': 'display_data',
  'data': {'text/plain': 'second'},
  'metadata': {}},
 None]

source

check_gateway_deps

def check_gateway_deps():

Check the gateway dependencies and versions.

check_gateway_deps reports a missing or incompatible gateway package. jupyasyncclient before 0.2.12 is refused: older clients route messages differently, and GatewayKernel relies on every message no request claims reaching on_jmsg.

try: check_gateway_deps()
except RuntimeError as e: print(e)

source

GatewayService

def GatewayService(
    port:int=8787, token:NoneType=None
):

One supervised jupygate for all workspace kernels in this host process.

GatewayService starts one Jupyter gateway for this process and returns its connection details.

g = GatewayService(port='8899', token='shared-secret')
g.url, g.server
('http://127.0.0.1:8899', None)

source

GatewayKernel

def GatewayKernel(
    gateway, cwd:NoneType=None, name:NoneType=None, python:NoneType=None, inspect:bool=True, agent:str='restricted',
    port:int=0, kernel:str='ipykernel'
):

The Kernel interface over jupygate + jupyasyncclient, so a kernel outlives a client reconnect.

GatewayKernel implements the Kernel interface over a gateway WebSocket. The gateway owns the kernel process. The client’s reply futures answer complete, inspect_obj and comm_info, and everything else reaches the router through on_jmsg, which outlives a websocket reconnect. jupygate drops the frames in flight when that websocket dies, so a run that has heard nothing for QUIET seconds asks the kernel for kernel_info on shell. That request queues behind the execute, so an answer while the run still waits means its reply was lost, and the run comes back with lost=True rather than waiting forever.

gk = GatewayKernel(None, name='nb', inspect=False)
gk.alive, gk.pid, gk.lang, gk._boot_name.startswith('nb:'), (await gk.execute('1+1')).error
(False, None, 'python', True, 'kernel is not running')