Execution Pipeline#
The execution pipeline handles the complete flow from "run this cell" to "here are the outputs." It resolves which kernel or renderer handles the cell, processes magic commands, runs the code, collects outputs, and reports results.
Entry Points#
Execution starts from one of three methods on Scaffold:
| Method | Description |
|---|---|
ExecuteCellAsync(cellId, ct) |
Execute a single cell by ID |
ExecuteAllAsync(ct) |
Execute all cells in notebook order |
ExecuteCodeAsync(code, language?, ct) |
Execute arbitrary code in a transient cell (not added to the notebook) |
All three methods call EnsureParametersInjected() first, which pushes notebook parameter defaults into the variable store for any parameters not already present. Each call to ExecuteCellAsync creates a fresh ExecutionPipeline instance via Scaffold.BuildPipeline(). The pipeline is not reused across cells.
ExecuteAllAsync validates required parameters before executing. If any required parameter (marked required: true) has no default and no value in the variable store, the method executes only the parameters cell (to preserve its form output), appends the validation error, and returns a single failed result. Before running, ExecuteAllAsync resets every kernel so a "Run All" behaves as if the notebook is being executed from scratch: kernels are disposed and re-warmed lazily, and the variable store is cleared apart from parameter values.
Pipeline Construction#
Scaffold.BuildPipeline() creates an ExecutionPipeline by injecting all dependencies as constructor arguments:
IVariableStore-- the shared variable storeIThemeContext-- active theme for contextLayoutCapabilities-- active layout capabilitiesIExtensionHostContext-- for querying extensionsINotebookMetadata-- read-only notebook metadataINotebookOperations-- for notebook manipulation from magic commandsFunc<string, ILanguageKernel?>-- kernel resolution delegateFunc<ILanguageKernel, Task>-- kernel initialization delegateFunc<Guid, string?>-- language ID resolution for a cellFunc<Guid, int>-- execution count lookupFunc<string, IMagicCommand?>-- magic command resolution delegate- Optional
Action<Guid>-- notified when a running cell appends output - Optional input requester delegate -- asks the current host for interactive input
The pipeline has no direct reference to Scaffold. All access goes through these delegates and interfaces.
Cell Routing#
When ExecuteAsync(cell, ct) is called, the pipeline determines how to handle the cell through a priority-based dispatch:
Step 1: Check ICellType#
Query IExtensionHostContext.GetCellTypes() for a match on cell.Type (case-insensitive).
- If a matching
ICellTypeis found andcellType.Kernel is not null: route toExecuteWithKernelAsyncusing that kernel. - If a matching
ICellTypeis found andcellType.Kernel is null: route toRenderCellAsyncusingcellType.Renderer. This path is used by non-executable cells like parameters, which have a renderer but no kernel.
Step 2: Check Cell Language#
If no ICellType matched and cell.Language is set, look up the kernel via the resolution delegate. If found, route to ExecuteWithKernelAsync.
Step 3: Check Free-Standing Renderers#
Query IExtensionHostContext.GetRenderers() for a renderer whose CellTypeId matches cell.Type. If found, route to RenderCellAsync.
Step 4: Default Kernel#
As a last resort, resolve the notebook-level default language for this cell and look up that kernel. If found, route to ExecuteWithKernelAsync. If nothing matches at any step, the pipeline throws InvalidOperationException.
Kernel Execution Flow#
ExecuteWithKernelAsync handles cells that have a language kernel:
1. Initialize the Kernel#
Call the initialization delegate, which uses ConcurrentDictionary<string, Task> to ensure kernel.InitializeAsync() runs exactly once per session. Concurrent callers share the same task.
2. Clear Previous Outputs#
cell.Outputs.Clear() removes any outputs from the previous execution.
3. Set Up Output Collection#
A thread-safe AppendOutput delegate is created, backed by a lock. Outputs added via this delegate are tracked in a HashSet<CellOutput> (by reference) to avoid duplicates. This delegate is passed to both magic command contexts and execution contexts.
4. Process Magic Commands#
The pipeline runs a loop to process consecutive magic commands at the top of the cell:
while (true) {
parseResult = MagicCommandParser.Parse(currentSource);
if (!parseResult.IsMagicCommand) break;
// Resolve and execute the magic command
magicCommand.ExecuteAsync(arguments, magicContext);
if (magicContext.SuppressExecution) return Success;
currentSource = parseResult.RemainingCode;
}
See the Magic Commands section below for details.
5. Build Execution Context#
An ExecutionContext is constructed with the remaining code (after magic commands are stripped), the variable store, theme context, and all other shared services. This context implements IExecutionContext, which extends IVersoContext.
If the host supplied an input requester, the execution context exposes it through RequestInputAsync(prompt, isPassword, ct). Kernels can use this to pause execution until the front-end returns a value. Hosts that do not provide an input requester keep the default unsupported behavior.
6. Execute#
The kernel's ExecuteAsync(code, context) is called. The kernel can:
- Stream outputs during execution via
context.WriteOutputAsync(output), which calls theAppendOutputdelegate - Request interactive input during execution via
context.RequestInputAsync(...) - Return outputs from the method, which are appended after execution (skipping any already streamed)
7. Post-Processing#
If the #!time magic command was used, a wall-time output ("Wall time: X.Xms") is appended. The method returns ExecutionResult.Success with the cell ID, execution count, and elapsed time.
Error Handling#
OperationCanceledExceptionreturnsExecutionResult.Cancelled- Any other exception appends a
CellOutputwithIsError: true,ErrorName, andErrorStackTrace, then returnsExecutionResult.Failed
Background Faults#
Cell code can start work and return before that work finishes. When it then throws there is no result left to carry the failure, and .NET discards an unobserved task exception silently. BackgroundFaultMonitor hooks TaskScheduler.UnobservedTaskException and AppDomain.UnhandledException and holds what arrives until there is a cell to report it against, as a BackgroundFailure output on the next cell to run.
Neither runtime event says which notebook the work belonged to, so attribution is a heuristic. Each Scaffold registers a BackgroundFaultSink, and a fault goes to the single notebook that is inside a cell when it surfaces. When none or several are, it goes to all of them, on the grounds that a failure reported in more places than it happened is better than one nobody is told about. A host running one notebook, which includes the CLI and the VS Code extension, only ever has the one sink and is unaffected by the ambiguous case.
Each sink holds at most 100 faults. Past that the oldest are dropped and the report says how many, since a queue belonging to an idle or closed notebook is never drained.
Render-Only Flow#
RenderCellAsync handles cells that have a renderer but no kernel (like parameters and rich content cells):
- Clear
cell.Outputs - Build a
CellRenderContextwith the cell's metadata, variable store, and theme context - Call
renderer.RenderInputAsync(cell.Source, renderContext) - Append the
RenderResultas aCellOutput - Return
ExecutionResult.Success
Magic Commands#
Magic commands are #! directives at the top of a cell that modify execution behavior or perform side effects before the kernel runs.
Parsing#
MagicCommandParser.Parse(source) scans the first non-empty line. If it starts with #!, the parser extracts:
- CommandName: the first token after
#!(e.g.,nuget,time,import) - Arguments: everything after the command name on the same line
- RemainingCode: all lines after the magic command line
The parser returns a ParseResult record. The pipeline calls it in a loop to handle consecutive magic commands (e.g., two #!extension lines stacked at the top of a cell).
Resolution#
The pipeline resolves magic commands via the delegate from Scaffold, which queries ExtensionHost.GetMagicCommands() for a case-insensitive name match. If the command is not found, the pipeline checks whether it exists in a disabled extension (to distinguish "unknown command" from "disabled extension") and emits an appropriate error.
Context#
Each magic command receives a MagicCommandContext that provides:
RemainingCode-- the code after the magic command lineSuppressExecution-- settable by the command to prevent kernel execution- All
IVersoContextservices (variable store, theme, extension host, notebook operations)
Internally, the context also has ReportElapsedTime, which the #!time command sets so the pipeline appends timing information after kernel execution.
Built-In Magic Commands#
| Command | Effect |
|---|---|
#!about |
Outputs version, runtime, and extension info. Suppresses execution. |
#!time |
Enables elapsed time reporting after kernel execution. Does not suppress. |
#!nuget PackageId [Version] |
Resolves a NuGet package and stores assembly paths in the variable store for the kernel to pick up. |
#!extension PackageId\|path [Version] |
Loads an extension from NuGet or a local DLL. Requests consent for NuGet packages. Idempotent. |
#!import path [--param name=value ...] [--show-output] |
Imports another notebook or a raw source file. A notebook import deserializes and executes its code cells with optional parameter overrides; a raw source file (.cs, .fsx, .py, .sql, and similar) is routed to the kernel matched by its extension. Does not suppress: code written under the directive in the same cell still runs. Pass --show-output to surface the imported outputs in the importing cell. See Nested Imports. |
#!restart |
Restarts the current kernel. |
Language-specific magic commands are provided by their respective extensions:
| Command | Extension | Effect |
|---|---|---|
#!pip package |
Verso.Python | Installs a Python package |
#!python [path] |
Verso.Python | Inspects, lists, and selects the interpreter for the session |
#!bind widget name |
Verso.Python | Projects a widget's trait into the variable store under name, in both directions |
#!npm package |
Verso.JavaScript | Installs an npm package |
#!sql-connect |
Verso.Ado | Opens a named database connection |
Nested Imports#
An imported file may import another. Rather than reassembling the file into a single submission, each directive it carries runs on its own, in priority order: package directives first, then imports, then everything else. The file's own code runs last, as its own submission. A #!import written inside an imported file is therefore acted on rather than reaching a kernel as ordinary code.
A path in a nested #!import is read relative to the file that wrote it, falling back to the notebook's directory when nothing sits beside it. The importing directory travels with the import in an AsyncLocal that ResolveImportPath consults, rather than being rewritten into the directive text, because a resolved path can contain spaces and the parser that reads it back ends a path at the first one. ResolvePath is unchanged, since other commands share it and promise their users the notebook's directory.
Files part way through being imported are tracked in an AsyncLocal ImmutableHashSet. A file already in progress is passed over quietly, the way an include guard does, so two files that name each other terminate instead of recursing.
Output Model#
CellOutput is an immutable record:
record CellOutput(
string MimeType,
string Content,
bool IsError = false,
string? ErrorName = null,
string? ErrorStackTrace = null
);
Outputs are collected in cell.Outputs (a mutable List<CellOutput>). The pipeline clears this list at the start of each execution. Kernels can produce multiple outputs of different MIME types. Common patterns:
| MIME Type | Content |
|---|---|
text/plain |
Plain text output |
text/html |
Rich HTML (tables, formatted output) |
image/svg+xml |
SVG graphics |
image/png, image/jpeg |
Base64-encoded image data |
application/json |
JSON data (rendered as interactive tree in UI) |
text/csv |
CSV data (rendered as table in UI) |
text/x-verso-mermaid |
Mermaid diagram source (rendered by the UI) |
Error outputs set IsError = true and optionally include ErrorName (exception type) and ErrorStackTrace.
The Display API#
Kernels and user code can emit an output explicitly, without returning it, through the Display extension method in Verso.Abstractions:
myValue.Display(); // format and show a value mid-cell
htmlString.Display("text/html"); // force a MIME type
Display routes through the ambient display handler for the running cell, so a single execution can surface several values. It is the host-agnostic alternative to Console.WriteLine for rich output.
Live Output Notifications#
When a kernel calls WriteOutputAsync, the pipeline appends the output immediately and invokes the optional output-updated callback. Scaffold exposes this as OnCellOutputUpdated, and interactive hosts can forward it to their UI before the cell finishes executing. VS Code uses this path to send output/update and refresh the cell output cache while the execution/run request is still pending.
This mechanism streams outputs that are explicitly written through the execution context. Outputs that are only returned from ILanguageKernel.ExecuteAsync are still appended after the kernel method completes.
Interactive Input#
IExecutionContext.RequestInputAsync(prompt, isPassword, ct) asks the current host to collect a single line of input. It returns the entered value or null when the user cancels. The default interface implementation throws NotSupportedException, so kernels should treat this as an optional host capability.
The PowerShell kernel uses this capability through its internal host adapter around PowerShell's PSHost / PSHostUserInterface APIs. It maps host prompts such as Read-Host, credential prompts, and choice prompts onto RequestInputAsync. In VS Code, the request is delivered as an input/request notification and answered with input/response.
PowerShell host output (Write-Host, warnings, errors, verbose/debug output, and similar PSHostUserInterface writes) is converted to text/plain CellOutput values and written through WriteOutputAsync. ANSI escape sequences are currently stripped before display so host output stays readable in cell output. Future work may parse supported ANSI SGR sequences into safe rich output instead of discarding them.
Execution Result#
ExecutionResult is an immutable record returned by the pipeline:
enum ExecutionStatus { Success, Cancelled, Failed }
record ExecutionResult {
ExecutionStatus Status;
Guid CellId;
int ExecutionCount;
TimeSpan Elapsed;
Exception? Error;
}
Factory methods Success(...), Cancelled(...), and Failed(...) construct the appropriate result. The CellId and ExecutionCount allow the caller to correlate results with cells. Elapsed is the wall-clock time of the execution.
Cell Types and Renderers#
ICellType#
ICellType bundles a renderer with an optional kernel to define a complete cell type:
| Member | Description |
|---|---|
CellTypeId |
Matches CellModel.Type (e.g., "parameters", "html", "mermaid") |
Renderer |
The ICellRenderer that renders this cell type |
Kernel |
Optional ILanguageKernel; null for non-executable types |
IsEditable |
Whether the user can edit the cell source |
GetDefaultContent() |
Template content for newly created cells of this type |
ICellRenderer#
ICellRenderer transforms cell content into visual output:
| Member | Description |
|---|---|
CellTypeId |
Matches the cell type this renderer handles |
RenderInputAsync(source, context) |
Renders the cell source into HTML |
RenderOutputAsync(output, context) |
Re-renders a stored output |
GetEditorLanguage() |
Syntax highlighting language for the editor (null if no editor) |
CollapsesInputOnExecute |
If true, the source editor is hidden after execution (used by markdown) |
ICellInteractionHandler#
Renderers that produce interactive HTML (like the parameters form) can also implement ICellInteractionHandler to receive user interactions back from the browser:
Task<string?> OnCellInteractionAsync(CellInteractionContext context);
The CellInteractionContext carries the cell ID, extension ID, interaction type, and a JSON payload. The handler returns updated HTML (or null) which replaces the cell's output in the UI.
Data Formatters#
When a kernel produces a runtime object rather than a raw string output, the engine uses IDataFormatter extensions to convert it into a CellOutput. The engine probes CanFormat(value, context) in host MIME-preference order, using formatter Priority (higher values first) within each MIME type, and calls FormatAsync only for the winning representation.
Built-in formatters handle primitives, collections (as HTML tables), HTML strings, images, SVG, exceptions, Microsoft.Data.Analysis DataFrames, F# types, and SQL result sets.