Skip to content

Python in cells: engine, sandboxed worker processes, CPython and built-in backends - #469

Closed
prxnvt wants to merge 12 commits into
storytold:mainfrom
prxnvt:pr/python-engine
Closed

prxnvt wants to merge 12 commits into
storytold:mainfrom
prxnvt:pr/python-engine

Conversation

@prxnvt

@prxnvt prxnvt commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This pull request adds Python in cells to the engine, without any user interface. A Python cell holds Python code instead of a formula; its result is the cell's value, so formulas, display and files read it like any other cell. Cells run on the user's own CPython 3.11 or newer when one is installed, so pandas and numpy work, and otherwise on a built-in, sandboxed Python (Monty). Code never runs in the GridCraft process: every workbook has its own worker process, which is killed when a cell exceeds its time limit or its memory limit, and replaced when it crashes.

Everything is reachable through commands (python.insert, python.set, python.clear, python.output, python.reset, python.diagnostics, python.initialization, python.options, python.enable), and therefore through the CLI, MCP and the control channel. None of them opens a dialog. Workbooks opened from a file run no Python until python.enable. Python cells are saved to xlsx as PY("…",0|1) formulas with their cached values, so other applications show the results.

The editing interface (Python mode in the formula bar, the Diagnostics pane, the Enable bar, Python Options) is left for a later pull request, as are an application-managed Python environment with package installation, richer object output and import-aware time limits.

Design

Worker process

Python code runs in a separate process because no in-process harness can stop all hostile code: 'x' * 10**12 makes an interpreter allocate until the process aborts, and 10**10**8 never checks an interpreter's time limit; catch_unwind can stop neither. The worker is either

  • the application binary started again with --python-worker, which runs Monty (the built-in Python), or
  • the user's CPython, started as <python> -P -X utf8 -u -c <shim>, where the shim (crates/python/src/shim.py, embedded with include_str!) implements the same protocol.

The parent (crates/python/src/client.rs) reads the worker's output on a thread, so polling never blocks longer than asked. It kills a worker one second after its cell's time limit (5 s by default, python.options {timeoutSeconds}), kills it when its resident set size passes 512 MB (sampled every 50 ms), and replaces a worker that exits. Workers start in a process group of their own (a job object on Windows), so a kill also stops processes the user's code started. A cell that took its worker down is not run again until its code or its inputs change, or python.reset runs every cell (a guard against crash loops). Both applications check for --python-worker first thing in main, before the logger, panic hook or window.

Protocol

One JSON object per line (crates/python/src/protocol.rs). The parent sends Init {limits, init_code}, Run {id, code}, XlValue {id, reply} and Reset; the worker answers Ready {init_error}, Xl {id, reference, headers} (a request for cell values made by xl() in the code) and Done {id, output, stdout, stderr, error {line, message}, elapsed_ms}. Worker frames begin with a marker, so other text that reaches the worker's standard output is never taken for a frame. Values travel as gridcraft_core::Value. Limits: 1 MB of printed output per run, 10,000 xl() calls per run and 1,000,000 output cells.

Engine runtime

After every top-level command that changed a workbook, Session::execute hands the workbook before and after to the runtime (crates/engine/src/python.rs). It runs the Python cells whose code changed, whose xl() literals read cells that changed (references resolve like a formula's, so names, tables and other sheets work), or whose reference is only known at run time; and, because all cells of a workbook share one namespace, every Python cell after the first of those, in row-major order, sheet by sheet. Each cell's result is written into the workbook (arrays spill, or show #SPILL! when blocked), and calc recalculates its dependents before the next cell runs. Results have no undo step of their own: one undo takes back the edit and the results it caused, as for data tables. A Python cell that depends, through formulas, on a later Python cell in the same refresh gets #CALC!. xl() literals follow reference-moving edits (row and column insert and delete, cut-move, sheet rename and delete) as formula references do.

Headless callers run Python inside the command, so python.set answers with the cell's value. A host with a frame loop can call set_python_background(true) and step_python(); waiting cells then show #BUSY!. In manual calculation, affected cells are marked stale until Calculate Now. Runs are recorded in a ring buffer of 500 entries (python.diagnostics).

Trust gate

This builds on the document trust added in the engine-seams pull request (Local for workbooks made in the session, FromFile for workbooks opened from a file). It adds a third state, Trusted, for a file whose active content the person allowed to run. A FromFile workbook runs no Python: opening it shows the cached values, edits run nothing, and new code there shows #BLOCKED!. python.enable makes the workbook Trusted and runs its Python cells. Python never runs merely because a workbook was opened, whatever its trust.

CPython and the built-in Python

CPython (preferred) Built-in (Monty)
When Python 3.11 or newer is found No suitable CPython
Packages Whatever the interpreter has (pandas, numpy) None; most of the standard library is absent
Access That of the person's account: files, network, processes None: file, environment and network access are refused
xl("A1:B3") A pandas DataFrame when pandas is installed, else a list of rows A list of rows
Recursion limit At least 1000 200

The interpreter search (crates/python/src/interp.rs) tries the path from python.options {interpreter}, VIRTUAL_ENV, CONDA_PREFIX, python3 and python on PATH, and on Windows the py -3 launcher and the usual install folders; Microsoft Store shortcuts are skipped. Each candidate is probed under a 5 s deadline for its version, sys.executable, the pandas and numpy versions (from package metadata, without importing them) and whether it is externally managed (PEP 668). The search runs on a thread of its own, only in the applications (interp::enable_search()); tests and library users keep the built-in Python or the launcher they set. GridCraft never installs an interpreter or packages. On CPython, a missing module names the pip install command for that interpreter, or suggests a virtual environment when the interpreter is externally managed.

Monty refuses, before running anything, a cell that imports a module it does not have or that uses a construct its compiler does not support, with a message that asks for CPython. RustPython was considered for the built-in Python first and rejected because every recent release depends on the LGPL-3.0 malachite crates, which would be linked into the application binary.

shim.py is the one piece of the application that is not Rust; it is data that the user's interpreter runs. AGENTS.md and CLAUDE.md now say so.

Changes

  • New crate gridcraft-python (layer 1, on core; registered in xtask layers): protocol, worker (Monty, behind the python feature and compiled out on wasm32), client, client_web (the wasm32 stand-in), run, interp, imports (the import scanner used to refuse cells on Monty) and shim.py.
  • Model: Cell::py: Option<Arc<PyCode>> (serde default, not written for ordinary cells, so older native files load unchanged); PyCode holds the code, the output mode, the last result and a stale flag; Cell::has_content and Cell::clear_content; the PY(…) file form and the xl("…") literal scanner in model/python.rs. Every Cell { … } literal in the tree gains py: None.
  • Core: CellError::{Python, Busy, Timeout, Blocked}.
  • Calc: lay_python_spill; Python spills are kept through recalculation, and malformed arrays never spill.
  • Engine: the runtime (python.rs), the commands (cmd/python.rs), Trust::Trusted, Prefs::{python_timeout_seconds, python_interpreter}, DocState::py_log; edits that clear, paste, fill, sort, merge or move cells handle the code; cell.set with =PY( is refused with a pointer to python.set; the protection check compares code; Python cells refuse a table's header row; io::adopt_python and io::enforce_python_limits on open; four catalog entries under Formulas › Python.
  • XLSX: Python cells are written as PY("chunk"&"chunk",0|1) with cached values (spills as dynamic arrays) and read back; the four Python errors are cached as #VALUE!, as #SPILL! and #CALC! already are.
  • Apps: --python-worker in apps/gridcraft and apps/gridcraft-cli, the default launcher, and the CPython search.
  • Docs: architecture (new section and layer row), file-format parity, function parity, CLI, ROADMAP, target-app parity, gaps, parity checklist (278 / 294), AGENTS.md and CLAUDE.md.

Commits:

  1. Python: gridcraft-python crate, a sandboxed Monty worker process and its JSON-lines protocol
  2. Model: Python cells, and the #PYTHON!, #BUSY!, #TIMEOUT! and #BLOCKED! errors
  3. Engine: run Python cells after each edit, in row-major order, in a worker per workbook
  4. Engine: python.* commands, and the trust gate for workbooks opened from files
  5. XLSX: Python cells as PY() formulas with cached values; opening limits for Python content
  6. Python: run cells on the user's CPython 3.11 or newer through a shim
  7. Python: the built-in interpreter refuses code it cannot run; a guard against crash loops
  8. Docs: Python in cells (architecture, file formats, functions, CLI, roadmap)

Error codes

Four error values are added: #PYTHON! (the code raised an error, or Python stopped), #BUSY! (waiting to run), #TIMEOUT! (the time limit was reached) and #BLOCKED! (Python may not or cannot run here).

ERROR.TYPE returns 11 for #BLOCKED!, the number Excel returns. Microsoft documents no ERROR.TYPE number for #PYTHON!, #BUSY! or #TIMEOUT!. This pull request gives them 19, 20 and 21, after the numbers Excel is known to use; these are GridCraft's own choice and may need to change. The choice is stated in a comment on CellError::code (crates/core/src/value.rs) and in docs/function-parity.md. Reviewers may prefer another convention, for example returning #N/A for these three until Excel's numbers are known.

The xlsx writer caches all four as #VALUE!, because they are not error codes of the file format.

Dependencies and licences

Direct dependencies of gridcraft-python:

Crate Version Licence Use
monty, monty-types 1.1.0 (pinned exactly) MIT The built-in Python interpreter (only with the python feature, which only the application binaries enable; not on wasm32)
sysinfo 0.39 MIT The memory watchdog reads the worker's resident set size
process-wrap 10.0.1 (pinned exactly) MIT OR Apache-2.0 Starts workers in a process group or job object
windows 0.62 (Windows only; already in the tree) MIT OR Apache-2.0 CREATE_NO_WINDOW

New crates in Cargo.lock, with their licences as declared in each crate's manifest:

  • MIT: attribute-derive-macro, bitvec, castaway, char_str, collection_literals, compact_str, fancy-regex, funty, generic-array, jiter, monty, monty-macros, monty-types, nix, phf, phf_codegen, phf_generator, phf_shared, quote-use, quote-use-macros, radium, ruff_python_ast, ruff_python_codegen, ruff_python_literal, ruff_python_parser, ruff_python_stdlib, ruff_python_trivia, ruff_source_file, ruff_text_size, speedate, spin, strum, strum_macros, synstructure, sysinfo, tap, wyz
  • MIT OR Apache-2.0 (or Apache-2.0 OR MIT, MIT/Apache-2.0): atomic-polyfill, attribute-derive, bit-set, bit-vec, block-buffer, bstr, chrono, cobs, cpufeatures, critical-section, crypto-common, defmt, defmt-macros, defmt-parser, digest, displaydoc, drop_bomb, embedded-io (0.4, 0.6), get-size2, get-size-derive2, getrandom 0.2, hash32, heapless, heck, iana-time-zone, iana-time-zone-haiku, interpolator, itertools 0.14, lexical-parse-float, lexical-parse-integer, lexical-util, manyhow, manyhow-macros, ntapi, num-bigint, num-integer, object, ordermap, postcard, ppv-lite86, proc-macro-utils, process-wrap, psm, pyo3, pyo3-build-config, pyo3-ffi, pyo3-macros, pyo3-macros-backend, rand 0.8, rand_chacha, rand_core 0.6, serde_bytes, sha2, stable_deref_trait, stacker, thin-vec, unicode-normalization, unicode_names2_generator, utf8_iter, winapi, winapi-i686-pc-windows-gnu, winapi-x86_64-pc-windows-gnu
  • Apache-2.0: is-macro
  • Apache-2.0 WITH LLVM-exception: ar_archive_writer, target-lexicon; wasi 0.11 (Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT)
  • Zlib OR Apache-2.0 OR MIT: objc2-io-kit, tinyvec
  • Unlicense OR MIT: byteorder, jiff, jiff-core, jiff-static
  • Apache-2.0 OR BSL-1.0: ryu
  • (MIT OR Apache-2.0) AND Unicode-DFS-2016: unicode_names2
  • Unicode-3.0: icu_collections, icu_locale_core, icu_properties, icu_properties_data, icu_provider, litemap, potential_utf, tinystr, writeable, yoke, yoke-derive, zerofrom, zerofrom-derive, zerotrie, zerovec, zerovec-derive
  • BlueOak-1.0.0: minicbor, minicbor-serde

No GPL, AGPL or LGPL licence appears. pyo3 and its sub-crates (an optional dependency of jiter) and defmt (an optional dependency of jiff) are listed in Cargo.lock, but those features are not enabled and they are not built (cargo tree --workspace --target all does not show them). Monty and its tree are compiled only into the two application binaries (feature python); the engine depends on gridcraft-python without it and only drives a worker through the protocol. The engine's tests enable the feature to run an in-process worker.

Platform notes

  • Web (wasm32). There are no worker processes or threads in the browser. On wasm32 the crate compiles client_web.rs in place of the client, with the same API: every run fails as unavailable, and Python cells show #BLOCKED! with the message "Python isn't available in the web version". Monty, sysinfo, process-wrap and the interpreter search are compiled out, and the engine has no cfg of its own for Python. cargo xtask wasm passes, and gridcraft-python is among the crates it checks.
  • Windows. Workers run in a job object and start with CREATE_NO_WINDOW; the interpreter search skips Microsoft Store shortcuts and tries py -3 and the install folders. These paths are covered by tests against a fake Windows host; they have not been run on a Windows machine for this pull request.
  • macOS and Linux. Workers run in their own process group. The CPython shim installs its own SIGINT handler, since a parent started with SIGINT ignored passes that on and would otherwise disable the time limit.
  • Rust version. Monty 1.1 declares rust-version = "1.96", so gridcraft-python declares the same; CI uses the stable toolchain.

Testing

  • cargo xtask ci steps on every commit: fmt, clippy with -D warnings, cargo test --workspace --no-fail-fast, assets, layers, wasm, parity and keytips. The only test failures are the three that already fail on main (i18n::tests::translations_are_unique_and_preserve_unknown_text and the two CSV separator tests), fixed by other open pull requests.
  • tests::every_command_survives_empty_params covers the nine python.* commands.
  • New tests:
    • gridcraft-python: protocol round trips, conversions in both directions, refused host access, output caps, a shared namespace, initialization code and reset; on real worker processes, while True: pass and 10**10**9 time out, 'x' * 10**12 is stopped by the memory watchdog, a killed worker is replaced, and a worker that dies before it is ready is started once more; the interpreter search against fake machines (including Windows) and this machine; shim tests (protocol, conversions, time limits, SIGINT ignored, child processes killed with the group, pandas when installed) that are skipped with a message when no Python 3.11 or newer is present; the Monty refusals and the import scanner on hostile input.
    • engine: edits on Python cells (python_cells.rs), the runtime (python_run.rs: order, dependencies, spills, cycles, errors, time limits, the trust gate, manual calculation, undo, background runs, a killed worker, the crash-loop guard, cells on the detected CPython), the commands (python_commands.rs) and files (python_files.rs: xlsx and JSON round trips, hostile content, the code limit on open).
    • gridcraft-cli: the binary serves as a worker and survives hostile code; python.set through the CLI on a real worker process.
  • Exercised by hand with gridcraft-cli run: cells on the built-in worker (with no Python 3.11 or newer on PATH), including a refused import statistics and a formula fed by a Python cell; cells on Homebrew's CPython 3.14 found on PATH, and on a temporary virtual environment found through VIRTUAL_ENV; a workbook saved to xlsx with a spilling Python cell and initialization code, reopened (trust fromFile, cached values shown, an edit of an input runs nothing, new code shows #BLOCKED!), then python.enable (the cells run again with the edited input and the initialization code) and formulas.calculateNow.

Depends on

This pull request is stacked on #462 (engine building blocks: undo groups, the recording buffer, document trust and workbook data in hidden names). It uses the document trust and the hidden-name storage from that pull request; its own commits start after it.


Generative AI use: The code and descriptions in this pull request were written with the assistance of Claude Opus 5.5 (Claude Code). I directed the work, chose its scope, and reviewed and tested the changes.

prxnvt added 12 commits October 11, 2026 21:03
Session::grouped(label, f) runs f as one undo step on the active
document. On success the group leaves exactly one undo entry holding the
workbook from before the group; on error it restores the workbook,
selection, undo and redo stacks as they were and returns the error.
group_begin, group_end and group_rollback do the same across separate
calls, for an action that runs one step per call.

While a group is open on a document, undoable commands on it add no
undo steps of their own, so a long group neither grows the history nor
pushes older entries past the undo limit, and Undo and Redo are
disabled there. Groups nest: the outermost one makes the step, and a
failing inner group rolls back only its own changes. Closing a document
drops its groups, and a command that panics drops the groups it opened.
history.list reports whether a group is open.

Insert Copied Cells folds its nested steps into one undo step by
counting revisions; inside a group the nested steps push no entries, so
it now leaves the history alone there instead of removing entries from
before the group.
A macro recorder needs more than a journal index: the journal is
trimmed past 10,000 entries, it also holds the commands that other
commands run (so playback would run them twice), and it keeps no
selection, which relative references need.

Session now tracks how deeply execute calls are nested. While recording,
a buffer (record.rs) keeps each successful, journaled top-level call with
the document uid, the active sheet (index and name) and the selection it
ran in, then its id and parameters without secrets, as the journal
stores them. Queries, failed commands and the command that starts
recording are not kept. The buffer holds up to 100,000 steps and counts
any it drops. Session::start_recording, stop_recording, is_recording and
depth are the interface.

Automate › Record Actions keeps recording through the journal as before.
Active content such as macros must not run only because a workbook was
opened. DocState gets a trust state: Local for workbooks made in the
session (new workbooks and samples) and FromFile for anything opened
with file.open. Active content in a FromFile workbook asks before it
runs. A second window on a workbook shares its trust.

The clipboard carries the trust of its source document. Pasting
formulas, formats (conditional formats hold formulas) or validation
from a FromFile workbook into another workbook makes that workbook
FromFile too; pasting values, column widths or notes carries nothing
active and changes nothing. Sheet moves and copies stay inside one
workbook, so its trust is unchanged. document.inspect reports the trust.
GridCraft keeps workbook data in hidden defined names so it travels
inside the xlsx file. The existing items write one name holding one
string literal, which past Excel's 255-character literal and
8,192-character formula limits gives a file Excel does not accept.

cmd/stash.rs stores an item `key` as hidden workbook-scope names
_gc_<key>_0, _gc_<key>_1, ..., each a formula of string literals of at
most 255 characters (UTF-16 units, as Excel counts them) joined with &,
at most 8,192 characters per name. Reading concatenates the chunks in
order and stops at a gap; it also accepts the older single _sc_<key>
name. Names are matched case-insensitively and only at workbook scope.
Keys are limited to letters, digits, _ and ., items to 4,194,304
characters, and junk around or inside the literals, duplicate or
out-of-order chunks, non-JSON and over-deep JSON all read safely.
keys(prefix) lists the stored items that start with a prefix.

Custom views, scripts, the watch list and scenarios keep their current
storage; nothing reads or writes the new names yet.

docs/architecture.md describes the engine building blocks added in this
series: undo groups, the recording buffer, document trust and this
storage.
…its JSON-lines protocol

Python code for cells runs in Monty 1.1.0 (MIT), a Python interpreter
written in Rust for sandboxed code, inside a separate worker process:
the app binary started again with --python-worker. Code such as
'x' * 10**12 makes an interpreter allocate until the process aborts, and
10**10**8 never checks the interpreter's time limit; catch_unwind can
stop neither, so only a separate process that the app can kill is a
reliable harness. RustPython was considered first, but every recent
release depends on the LGPL-3.0 malachite crates, which would be linked
into the app binary.

The new crate gridcraft-python (layer 1, on core) holds:

- protocol: one JSON object per line. The parent sends Init {limits,
  init_code}, Run {id, code}, XlValue {id, reply} and Reset; the worker
  answers Ready {init_error}, Xl {id, reference, headers} and Done {id,
  output, stdout, stderr, error {line, message}, elapsed_ms}. Worker
  frames start with a marker, so other text that reaches its standard
  output is never taken for a frame. Values travel as
  gridcraft_core::Value.
- worker (feature `python`, not on wasm32): one Monty REPL whose
  namespace is shared by every cell, with the initialization code run at
  start and on Reset. print output is collected per run (1 MB, then cut
  off). xl() asks the parent and waits for the reply; file, environment
  and network access are refused with PermissionError. Limits: the time
  limit, recursion depth 200, 10,000 xl() calls per run and 1,000,000
  output cells. A closed input pipe ends the worker even while code
  runs.
- conversions: None to empty, bool, int and float to numbers (NaN,
  infinities and integers too large for a double give #NUM!), str to
  text, a list to a column, a list of lists to a table padded with #N/A,
  a dict to a key/value table, and any other object to its repr. xl()
  gives a scalar for one cell, a list of rows for a range, and a list of
  dicts keyed by the first row with headers=True.
- client: PyWorker starts the worker and reads its frames on a thread,
  so poll() never blocks longer than asked. A run past its time limit
  plus one second is killed (#TIMEOUT!), a watchdog reads the worker's
  resident set size every 50 ms and kills it above 512 MB, and a worker
  that exits fails its runs; the next run starts a fresh worker. An
  in-process transport runs the worker on a thread for tests.

apps/gridcraft and apps/gridcraft-cli check for --python-worker first
thing in main, before the logger, panic hook or window.

Tests: protocol round trips, conversions in both directions, error
lines, refused host access and the output cap; in-process runs with a
shared namespace, xl(), initialization code, reset and initialization
errors; and, on a real process, `while True: pass` and 10**10**9 time
out, 'x' * 10**12 is stopped by the memory watchdog, a killed worker is
replaced, and the host keeps running throughout.
…! errors

Cell gains `py: Option<Arc<PyCode>>`, read with a serde default and not
written for ordinary cells, so older native files load and ordinary
cells serialize as before. PyCode holds the code, the output mode
(Python object or cell values), the last result (value, type name,
preview, whether it converted to cells) and a stale flag for manual
calculation. The cell's `value` stays the cached result, so formulas,
display and saving read a Python cell like any other. is_blank,
CellStore::has and input_text (which returns the code) take the code
into account; Cell::has_content and clear_content cover value, formula
and code together. The model also reads and writes the file form,
PY("chunk"&"chunk",0|1) with string literals of at most 255 characters,
and finds the xl("...") literals in code, skipping comments and other
strings. Code is limited to 7,000 characters so that the formula stays
under the 8,192-character formula limit.

Edits: cell.set over a Python cell, Clear Contents, Clear All and the
cells a merge empties remove the code; Clear Formats keeps it. Copy and
paste (All, Formulas), Fill, sort, cut-move, sheet copy and undo carry
it unchanged; Paste Values and Paste Link do not, and paste operations
do not combine numbers with a Python cell. Fill copies Python cells
instead of extending them as a series. cell.set with =PY(...) is
refused with a message that points to python.set. The sheet-protection
check compares the code, so a locked Python cell cannot be changed.
cell.get reports {python: code, output, typeName, preview, stale}.

The xl() literals follow reference-moving edits: rewrite_all_formulas
(row and column insert and delete, cell insert and delete, cut-move),
sheet rename and sheet delete adjust each literal like a formula
reference, and replace it only when it changed.

Errors: CellError gains Python, Busy, Timeout and Blocked, and ALL has
14 entries, so the lexer reads them as literals. ERROR.TYPE gives 11 for
#BLOCKED!, the number Excel returns. Microsoft documents no ERROR.TYPE
number for #PYTHON!, #BUSY! or #TIMEOUT!; they take 19, 20 and 21, after
the numbers Excel is known to use. The xlsx writer caches the four as
#VALUE!, as it already does #SPILL! and #CALC!, because they are not
error codes of the file format.

Tests cover the =PY refusal, removal by entry and clearing, undo, copy,
paste values, fill and sort, xl() rewrites through row insert, sheet
rename, cut-move and column delete, native JSON round trips, and the
new errors.
…rker per workbook

After every top-level command that changed a workbook, Session::execute
hands the workbook before and after to the Python runtime
(engine/src/python.rs), which finds the cells to run: Python cells
whose code changed, whose xl() literals read cells that changed (cell
store and spill differences, sheet by sheet; references resolve like a
formula's, so names, tables and Sheet! references work), or whose
literal names something only known at run time; every Python cell after
the first of those, in row-major order sheet by sheet, because they
share one namespace; all of them when a call is xl(<non-literal>) or a
sheet with Python cells disappeared; and the cells after a removed
Python cell. Python cell positions are cached per sheet version and
patched from the edit's band differences, so a workbook without Python
pays only for the bands an edit touched. Nothing runs when a workbook is
opened.

Each cell runs once per refresh: run, write the value (an array spills
through calc::lay_python_spill, or shows #SPILL! when blocked), let calc
recalculate its formula dependents, then the next cell. Results go
straight into the workbook and are not undoable, as for data tables: one
undo takes back the edit and the results it caused. A Python cell fed,
through formulas or directly, by a later Python cell in the same refresh
gets #CALC!. xl() is answered from the current workbook and refused for
non-references, missing sheets and names, deleted (#REF!) cells and
ranges over the output cap.

Calc keeps a Python cell's spill: cells_changed no longer drops it as it
does a replaced formula's, recalc_all lays Python spills out again from
the kept results, and after each edit the runtime lays out again the
spills of Python cells showing #SPILL! or whose area the edit touched,
so clearing a blocker spills again without running the code.

Runs happen inside the command for headless callers (CLI, MCP, tests).
With set_python_background(true) a host steps them with step_python();
waiting cells show #BUSY!, and an edit, undo or reset during a refresh
restarts it from the earlier of its next cell and the new first cell,
discarding the result in flight. Undo, redo and the panic restore mark
the namespace dirty: the next refresh resets it and runs every cell. A
failure that took the worker down (time limit, memory, crash) starts a
fresh worker, which runs the earlier cells again once before the queue
continues. In manual and automatic-except-tables calculation, affected
cells are only marked stale until Calculate Now or Calculate Sheet runs
them. Workbooks opened from a file (Trust::FromFile) run nothing, and
new or edited code there shows #BLOCKED!. Without a worker launcher (the
web build, or a host that set none) cells show #BLOCKED!.

Limits: Prefs.python_timeout_seconds (5 s) per cell, 512 MB per worker,
recursion depth 200, 1 MB of output kept, 1,000,000 output cells. Every
run is recorded in DocState.py_log, a ring buffer of 500 entries with
the cell, status, duration, output and error line.

gridcraft-python gains run.rs (the launcher, run outcomes, and the
default launcher that apps set at start-up) and a web stand-in for the
client with the same API, so the engine needs no cfg of its own. Both
apps set the default launcher to their own binary.

Tests: order and the shared namespace, xl() dependencies with formula
dependents, the Python to formula to Python chain, the cycle error,
spills blocked, unblocked and kept through a structural edit, errors
with their line and output, time limits, ranges, names and other
sheets, the trust gate, manual calculation, undo resetting the
namespace, background runs with #BUSY! and restart, and a real worker
process killed mid-refresh with the earlier cell run again.
…om files

cmd/python.rs registers the Python commands, all reachable from the
control channel, the CLI and MCP:

- python.insert {cell?} (Formulas > Python, Ctrl+Alt+Shift+P) makes the
  cell a Python cell with no code yet;
- python.set {cell?, code, output?} sets the code (at most 7,000
  characters) and runs it, answering with the cell's value; the same
  code again keeps its result without running;
- python.clear {cell?} (Convert to Normal Cell) turns Python off,
  clearing the code and value, undoably; the cells after it run again;
- python.output {cell?, mode: object|value} shows the result as a
  Python object (its type name, with no spill) or converts it to values;
- python.reset {clearDiagnostics?} starts Python afresh and runs every
  Python cell again;
- python.diagnostics {sheet?, errorsOnly?} returns the last 500 runs;
- python.initialization {code?} returns, or sets and then runs again
  with, the workbook's initialization code, kept in the hidden workbook
  data item py_init;
- python.options {timeoutSeconds?} reads or sets the per-cell time
  limit (0.1 to 3600 s, default 5);
- python.enable lets Python run in a workbook opened from a file
  (FromFile becomes Trusted) and runs its Python cells.

None of them opens a dialog. With empty parameters they act on the
active cell or report state, or return an error.

Trust gate: a workbook opened from a file runs no Python; code set
there shows #BLOCKED!, and python.reset does not change that;
python.enable does, by making the workbook Trusted, a new Trust state
for a file whose active content the person allowed to run.
document.inspect reports it as `trusted`. A locked cell on a protected sheet refuses
python.set through the existing protection check, which compares
Python code.

python.set, insert, output and clear refresh inside the command so they
can report the result, and tell Session::execute that the refresh is
done (only as the top-level command; inside another command, that
command's refresh covers them).

Tests: set, rerun avoidance, clear and undo, insert, output modes, the
code limit, parameter errors, protection, reset and diagnostics
filters, initialization code (first, on change, its errors), the trust
gate and enabling, a missing worker, the time-limit setting, and a CLI
test that drives python.set through gridcraft-cli with Python in a real
worker process: `while True: pass` gives #TIMEOUT!, 'x' * 10**12 gives
#PYTHON!, and the next cell still runs.
…s for Python content

A Python cell is written to xlsx as an ordinary formula,
PY("chunk"&"chunk",0|1), with string literals of at most 255
characters, 1 for a Python object result and 0 for values, and no
_xlfn. prefix, together with its cached value. A spilling result is
written like a dynamic array (cm="1", t="array" ref=...) with the
spilled values cached, so other spreadsheet applications show the
values (and #NAME? if they recalculate). The reader turns a formula
that is PY( followed by string literals, and optionally ,0 or ,1, back
into a Python cell, reading the formula's own text so that line breaks
in the code survive, and keeps the cached spilled values as the cell's
result, so a reopened workbook shows its arrays without running
anything. Python errors are cached as #VALUE!, as #SPILL! and #CALC!
already are. The initialization code travels in the hidden workbook
data names. Native JSON keeps Cell.py whole: code, output mode, the
last result and the exact error.

Opening any file adopts PY(...) formulas from every format
(io::adopt_python) and then applies limits to Python content
(io::enforce_python_limits): a cell with more than 7,000 characters of
code keeps only its cached value, with a warning, and a kept result
that is not a well-formed array of at most 1,000,000 cells is dropped.
calc::lay_python_spill refuses such an array too (#SPILL!), so a
crafted file cannot make it loop over a claimed size. Opening a file
still runs nothing: the workbook is FromFile, shows its cached values,
and runs Python only after python.enable.

python.set and python.insert refuse a table's header row, which holds
the column's name, as Excel keeps formulas out of headers.

Catalog: Formulas > Python gains Insert Python, Reset, Diagnostics and
Initialization; `cargo xtask parity` gives 278 / 294 (94.6%).

Tests: xlsx round trip of values, a formula over a Python cell, a
spilling table, an object-mode cell, 7,000 characters of code with
quotes and line breaks, an error and initialization code, checking the
written PY() formulas; the native JSON round trip; hostile content (code
over the limit in JSON and xlsx, a result claiming far more cells than
it holds); and a malformed result that never spills.
When the person has Python 3.11 or newer, Python cells run on it, so
pandas and numpy work; otherwise they run on the built-in Monty worker.
GridCraft never installs an interpreter or packages.

Finding the interpreter (gridcraft-python `interp`): the search order
is the path from python.options (a bare name is looked up on PATH),
VIRTUAL_ENV, CONDA_PREFIX, python3 then python on PATH, and on Windows
the `py -3` launcher and the usual install folders, newest first. The
Microsoft Store shortcuts under %LOCALAPPDATA%\Microsoft\WindowsApps
are skipped with a reason, since they open the Store instead of running
Python. Each candidate is probed under a 5 s deadline: first with -I
for its version (anything older than 3.11 is rejected with the version
it reported), then with -P -X utf8 for sys.executable, the pandas and
numpy versions (from package metadata, without importing pandas) and
whether it is externally managed (PEP 668). Cells run with
sys.executable, so a virtual environment and the program behind
`py -3` are used directly. The search takes a Host trait, so tests run
it against fake machines, including a fake Windows one. It runs on its
own thread and never on the web build. The engine caches the result per
session and searches again when the interpreter option changes, on
python.reset and on python.options {detect: true}. Apps opt in with
interp::enable_search(); tests and library users keep the built-in
Python or the launcher they set. Prefs.python_interpreter keeps the
path.

Running on it: the parent's process handling is unchanged (the deadline
kill, the memory watchdog, the restart after a crash and the JSON-lines
protocol, including the xl() round trip). Only the child differs:
`<python> -P -X utf8 -u -c <shim>` instead of the app binary with
--python-worker. -P keeps the current folder off sys.path; -I and -s
are not used because they hide user site-packages, where
`pip install --user` puts pandas.

- crates/python/src/shim.py, embedded with include_str!, is the worker
  for CPython. It is data that the user's interpreter runs, not app
  code. It keeps frames on a private copy of standard output and points
  file descriptor 1 at standard error, so output from C code or child
  processes cannot break a frame; reads input on a thread and exits
  when GridCraft goes away; collects print output per run up to the
  limit; stops a run at the time limit with a timer and interrupt_main
  (the parent's kill covers C calls that cannot be interrupted), and
  installs the SIGINT handler itself, since a parent started with SIGINT
  ignored passes that on; and returns the last expression's value.
  SystemExit is a cell error, not an exit.
- Conversions: xl() gives a pandas DataFrame when pandas is installed
  (imported on first use; the first row is the header with
  headers=True) and lists otherwise, as the built-in Python does.
  Results: DataFrame (with the index only when it is not the default
  RangeIndex), Series, one- and two-dimensional ndarrays, lists and
  dicts spill; numpy scalars become numbers or booleans; datetime, date
  and Timestamp become date serials; NaN and infinities become #NUM!;
  None, NaT and NA become empty; anything else is an object with its
  repr. The limits on output cells and xl() calls apply.
- The recursion limit on CPython is at least 1000, since pandas calls
  deeper than the built-in Python's 200 allows.
- Workers start in a process group of their own (a job object on
  Windows) through process-wrap (MIT OR Apache-2.0), so a kill also
  stops processes the user's code started; CREATE_NO_WINDOW keeps a
  console window from appearing on Windows. The worker's standard error
  is drained on a thread, keeping its last 8 KB.
- A worker that exits or times out before its Ready message is started
  once more and its waiting runs are sent again.
- The engine picks the launcher per run: one set for the session, else
  the detected CPython, else the built-in worker. In the background,
  cells wait as #BUSY! while the search finishes; headless callers wait
  for it. A new search stops the workers so that they start again on
  what it finds, from a fresh namespace, and an options change runs the
  cells again.

python.options takes `interpreter` and `detect` and reports the
backend; python.diagnostics reports it too: kind, summary line, path,
version, pandas, numpy, source and every rejected candidate with its
reason.

The user's CPython has the access of the person's own account: files,
network and processes. The trust gate is what keeps a workbook opened
from a file from running code on it before python.enable.

Tests: the search against fake machines and this machine; shim protocol
tests that run when this machine has Python 3.11 or newer and are
skipped with a message otherwise (xl() round trip, conversions, print
capture, errors with lines, the time limit, the shim's own and the
parent's kill, a loop stopped with SIGINT ignored, reset, and a child
process killed with the worker's group); pandas tests that run only
when pandas imports; the retry before Ready; and an engine run of cells
on the detected CPython.
…against crash loops

The built-in Python (Monty) is the fallback when no CPython is found. It
now refuses code it cannot run before any of it runs, instead of
running part of it, and no failure can hang the application or make
the worker restart in a loop.

- Imports: a small tokenizer (crates/python/src/imports.rs) reads the
  import statements of a cell, with strings and comments blanked,
  bracketed and backslash-continued lines joined, and statements split
  on `;` and `:`. A module Monty does not have (pandas, numpy, scipy,
  statistics and others) refuses the cell with #PYTHON! and "This cell
  needs CPython: `<module>` isn't available in the built-in Python.
  Install Python 3.11 or newer and set it in Python Options.", at the
  import's line. The scan is bounded and never fails.
- Constructs: the cell is first compiled on its own; a
  NotImplementedError from Monty's compiler (match, del, yield, type
  aliases, wildcard imports and others) refuses it with "This cell
  needs CPython: the built-in Python doesn't support <what>." Other
  compile errors still come from the run, as before.
- Messages, on both backends: a time limit gives #TIMEOUT! "Stopped
  after N s (an endless loop?)", whether the interpreter stopped itself
  or the parent killed it; RecursionError gives #PYTHON! "Too much
  recursion", as does a worker that died of a stack overflow (read from
  the end of its standard error); the memory watchdog gives "Used more
  than N MB".
- Crash-loop guard: when the worker dies while running a cell (a kill
  at the deadline, the memory limit, a crash), the cell is remembered
  with a fingerprint of its code and of what its xl() calls read. It
  does not run again (#PYTHON!, "Not run: this cell stopped Python the
  last time it ran", status `refused` in the diagnostics) until one of
  those changes or python.reset runs everything again. A call whose
  reference is only known at run time counts any edit as a change.
- On CPython, ModuleNotFoundError names the command for that
  interpreter, `"<sys.executable>" -m pip install <package>` (with the
  pip names of sklearn, cv2, PIL, yaml and a few others). When the
  interpreter is externally managed (PEP 668), it says to make a
  virtual environment instead and choose its python in python.options.
  GridCraft never runs pip.

Tests: Monty refusals (pandas, statistics, from numpy, match, wildcard
imports; nothing of a refused cell prints), the scanner on strings,
comments, multi-line statements and hostile input, the exact time
limit, recursion and memory messages, a worker dying of a stack
overflow, the guard (refused after a kill, run again when its input
changes, on reset and on a code change), and the pip hint on this
machine's CPython.
…admap)

- architecture.md: the python crate in the layer table, and a Python in
  cells section: worker processes, the protocol, the built-in and
  CPython backends, the engine runtime, the trust gate (with the
  Trusted state), files and the web build.
- file-format-parity.md: Python cells in xlsx, other imports and native
  JSON, the initialization code and the limits on open.
- function-parity.md: Python in cells, and #PYTHON!, #BUSY!, #TIMEOUT!
  and #BLOCKED! with their ERROR.TYPE numbers (19, 20 and 21 are
  GridCraft's own; Microsoft documents none for them).
- cli.md: running Python cells headless, which Python runs them, and
  the trust gate for files opened with --in.
- ROADMAP.md, target-app-parity.md and gaps.md: progress log, catalog
  278 / 294, and the UI that is still to come.
- AGENTS.md and CLAUDE.md: python in the layering list, and the CPython
  shim as the one exception to the Rust-only rule.
@faysou

faysou commented Oct 16, 2026

Copy link
Copy Markdown

#1566 related, using uv or pyodide, ie. some modern package and python distribution managers could be interesting solutions.

@aiongg

aiongg commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Security points from reading 39a89a6:

  • Full user access after enable: with a system CPython 3.11+ found (PATH, VIRTUAL_ENV, CONDA_PREFIX, py -3), one python.enable lets a downloaded workbook run code with the user's file, network and process access, like an enabled VBA macro. The process group and job object limit resources only; setsid escapes the group.
  • Agents: MCP execute_command (mcp/tools.rs:564) accepts python.set and python.enable, and python.options {interpreter} (cmd/python.rs:260 → interp.rs:422) runs any path it is given, so a prompt injection in a workbook can become code execution. Python commands and python.options should be refused from programmatic callers unless the user opted in.
  • Unbounded output: the parent reads worker lines with no length cap into an unbounded channel (client.rs:367); the 1M-cell cap is enforced only in the worker.
  • Monty: it refuses file, env and network access itself, but has no OS sandbox behind it.
  • Toolchain: monty 1.1.0 needs Rust 1.96, while the workspace declares 1.90.

Opening a file running nothing until the document is enabled (engine/python.rs:772, trust carried through paste) looks right.

@prxnvt

prxnvt commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

The Python work is being restructured according to the guidance above: off by default and enabled only in the user interface, sandboxed, with data passing only through the cells, strict limits, and a small core.

The first pull requests of the new series store and edit Python cells and run no code:

  1. Python cells as data. Cells of the form _xlfn._xlws.PY("…",0 or 1) are read from and written to .xlsx as Excel writes them, with their cached values and spilled results. Code is stored with python.set. Opening a file limits code size, result size and spill ranges. A workbook saved by Excel opens with its Python results.
  2. Editing. The formula bar has a Python mode; Python cells carry a PY tag; a card shows the cached result; the return type switches between Python Object and Excel Value; Formulas › Python has Insert Python.
  3. A Python editor window.

Running the code depends on the sandbox, and the design of that layer is the open question. The proposed design is as follows. The application starts itself as a small launcher, which restricts itself and then starts the user's own Python interpreter. On Linux the restrictions are Landlock (read-only access to the interpreter, its standard library and its site-packages, and no write access) and a seccomp filter (no sockets and no new processes). On macOS the launcher runs the interpreter under sandbox-exec with a deny-by-default profile. A worker is refused when the operating system does not confirm that the restrictions are enforced. Windows, FreeBSD and the web build show #BLOCKED!. The design adds two Linux-only crates, landlock and seccompiler.

The questions for the maintainers are the following:

  1. Is this sandbox design acceptable, including the two crates?
  2. Do the maintainers prefer to write the confinement layer themselves, or to use an external tool such as bubblewrap on Linux?
  3. Is a first step that stores and edits Python cells without running them acceptable?

@prxnvt

prxnvt commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Closed in favour of #2637, the first part of the restructured series described in the comment above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants