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.
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.
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.
(None, True)
True when the ipymini package can be imported in this interpreter.
ipymini_available checks whether the package can be imported without importing it.
The content of one comm message to a kernel, checked before it is sent.
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.
({'comm_id': 'c1', 'data': {'method': 'update', 'state': {'value': 3}}},
{'comm_id': 'c2', 'data': {}, 'target_name': 'jupyter.widget'})
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.
([2, 3], 2)
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.
('S3CRET', {'X-Dhrishti-Token': 'S3CRET'}, None)
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')
stop interrupts the active execution. It restarts the kernel when the execution does not stop before the timeout.
{'ok': False, 'forced': False, 'note': 'nothing is running'}
('cell interrupted', False)
('kernel restarted after interrupt was ignored', True)
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)])
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'}])
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.
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.
('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.
(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.
[{'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]
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.
One supervised jupygate for all workspace kernels in this host process.
GatewayService starts one Jupyter gateway for this process and returns its connection details.
('http://127.0.0.1:8899', None)
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.