Skip to content

Preload SciPy in NEMAR's browser runtime, imported before the seal - #504

Merged
neuromechanist merged 15 commits into
developfrom
feature/nemar-scipy-preload
Sep 25, 2026
Merged

neuromechanist merged 15 commits into
developfrom
feature/nemar-scipy-preload

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Closes #495.

NEMAR's chat runtime now preloads SciPy and SciPy works under the runtime's seal. The prompt now calls scipy.signal instead of asking the model to write Welch's method and a windowed-sinc filter by hand. Stacked on #489 while it was open; #489 is merged, so this is rebased onto develop (now including #502, #503, #505, #508, #509 and #510) and targets it.

Why SciPy did not import under the seal

Confirmed, not assumed. buildNamespaceSealSource (frontend/osa-egress.js) refuses ctypes to executed code through a sys.meta_path finder and the __import__ guard, and it evicts ctypes from sys.modules. SciPy imports ctypes while it loads:

  • import scipy goes through scipy._lib._ccallback and its compiled _ccallback_c.
  • scipy.stats goes through _continuous_distns.
  • scipy.io goes through arff.

scipy/__init__.py turns the refusal into "The scipy install you are using seems to be broken, (extension modules cannot be imported)". The chained cause is ImportError: 'ctypes' is not available to executed code.

The design

A new optional key, runtime.python.import_before_seal: [module, ...]. It is empty by default, so every other community boots exactly as before.

  • Validation (PythonRuntimeConfig, src/core/config/community.py):
    • each entry is a dotted module name, at most 16 entries, each named once;
    • each top-level package is one that preload names, written as its import name (eegprep-lean becomes eegprep_lean);
    • no entry may be a root the seal removes. SEALED_IMPORT_ROOTS mirrors the seal's _BLOCKED_ROOTS, and a pytest reads osa-egress.js and compares the two.
    • test-data-lane.js also checks each root against its lock entry's imports.
  • Boot (osa-worker-core.js, boot()):
    • runs after preload and allow_install, before the helpers and the namespace seal;
    • uses one pyodide.pyimport(name) per module, so nothing is bound into the user namespace;
    • each module is its own progress step (phase: "importing", module) inside the boot's fixed step budget;
    • a failed import stops the boot before the seal and the prelude, with kind: "import_before_seal", the module's name and its own exception.
  • Passed through the public config response, which serializes PythonRuntimeConfig, and through buildWorkerConfig. The runtime bundle and its integrity pin are rebuilt, and --check passes.
  • NEMAR sets [scipy, scipy.stats, scipy.io], measured rather than guessed:
    • with scipy alone, scipy.stats, scipy.io and scipy.signal (which imports scipy.stats) still fail under the seal;
    • with all three, every public SciPy module imports. test-data-lane.js walks SciPy's package tree and imports all 153 in the sealed runtime.
    • Adding scipy.signal and scipy.fft to the list added up to 0.1 s of boot and saved about 0.06 s on the first spectrum, so I left them out. This is shorter than the brief's "at least scipy, scipy.signal, scipy.stats, scipy.fft", because the measurement allowed it.

Security analysis, for the maintainer to judge

The seal is unchanged. ctypes is still a blocked root and the finder is not weakened. After boot, executed code still gets a refusal for import ctypes (the import gate's denied_import), importlib.import_module("ctypes"), __import__("ctypes") and ctypes.util. No ctypes module is left in sys.modules.

What this change costs: a module imported before the seal keeps the ctypes it imported, as an ordinary attribute.

  • Executed code can reach it as scipy._lib._ccallback.ctypes, or through scipy.stats._continuous_distns or scipy.io.arff._arffread.
  • numpy is imported before the seal as SciPy's dependency, so it keeps a real ctypes in numpy._core._internal. A sealed import would have left None there.
  • test-data-lane.js and test-worker-core.js assert that the reference exists, so the documentation of it stays true.

I think this fits the seal's documented purpose (osa-egress.js, "WHAT THIS IS AND IS NOT A BOUNDARY AGAINST"). The namespace seal removes the obvious routes so a model does not stumble onto one. The boundary is the fetch shim: native fetch is deleted from the prototype chain, the shim is non-writable and non-configurable, and nested workers are blocked. Before this change, executed code could already reach further than ctypes gives. I measured two routes against the base branch's seal under Bun:

  • Arbitrary JavaScript. osa.fetch.__closure__ holds a JsProxy, and .constructor.constructor("...")() runs JavaScript. This is the route the module docs describe. That code still finds only the guarded fetch.
  • import _ctypes. The C extension that does ctypes' foreign calls is not a blocked root, and it imports after the seal on develop today. I have not changed this; it is out of scope. Sealed code reaches the worker's global scope: block _pyodide, and cover storage and postMessage #506 tracks it, together with _pyodide.

The pre-seal imports run with boot's reach, so the docs say to name only modules from packages the community trusts as much as the rest of its preload. The config validator rejects anything that is not rooted in a preloaded package.

Measurements

Pyodide 0.29.5, SciPy 1.14.1, 2026-09-24.

NEMAR's runtime, under Bun (three runs each) interpreter, preload and seal wasm heap after boot
without SciPy (before this PR) 1.0 s 35 MB
SciPy preloaded, nothing imported before the seal (SciPy broken) 1.6 s 72 MB
SciPy preloaded, [scipy, scipy.stats, scipy.io] before the seal 2.7 to 2.8 s 104 MB
  • The three imports take about 1.1 s under Bun. In Chrome 153 under the production policy they take about 1.2 s: scipy 0.18 s, scipy.stats 0.96 s, scipy.io 0.06 s, out of a 3.6 to 3.7 s NEMAR boot.
  • Their 32 MB of heap is what the first from scipy import signal would claim anyway. After a first spectrum and filter the heap is 149 MB in every configuration where SciPy works.
  • First load, from a cold Chrome 153 profile: 35.4 MB over the network with SciPy and 19.1 MB without (42.9 MB and 26.5 MB decoded). SciPy is 16.3 MB of that.
  • The docs' old figures (5.3, 18.9 and 35.2 MB) match the over-the-network numbers to within 0.2 MB, but were labeled "uncompressed". The docs are corrected.

Something the brief did not anticipate: welch fails per channel too, on a long read

I measured the issue's table again and it holds: whole-array welch is refused, per channel works, and firwin + filtfilt and butter + sosfiltfilt work on 2-D arrays.

The cause is more specific than 2-D input. welch makes a view of every window at once, and 32-bit WebAssembly refuses a view of 2 GiB or more, which is channels × samples × nperseg × 8 bytes. So one channel also fails on a long high-rate read. With 2-second segments that means past about 36 minutes at 250 Hz, 9 minutes at 500 Hz, and 2.3 minutes at 1000 Hz (measured at each edge).

The prompt says "a minute or more, or the whole recording", so a per-channel rule alone would still fail at 1000 Hz. The prompt's block now also passes at most most = 2**28 // nperseg samples to each call, and tells the model to say how many seconds the spectrum covers when that cut the read short. test-data-lane.js runs the block on 33 × 30,000 at 250 Hz and on 4 × 200,000 at 1000 Hz. Its controls check that the whole array, and one unbounded 1000 Hz channel, are both refused. Dropping the bound fails the suite. An alternative is the notebook starter's approach, periodogram one segment at a time, which has no length limit. I kept welch because the issue asks for it.

What changed

  • src/core/config/community.py: the import_before_seal field, its validators, and SEALED_IMPORT_ROOTS.
  • frontend/osa-worker-core.js and frontend/osa-runtime.js: the boot step and the pass-through. The bundle is rebuilt. frontend/osa-chat-widget.js changes only in its generated integrity line. Another branch is editing that file for Widget: a larger capsule at rest that shrinks when the panel opens #490 to Widget: say what the assistant is doing while it writes and runs code #494; if both land, re-run bun scripts/build-runtime-bundle.js after rebasing. The widget does not label the new importing phase yet, so during those steps it keeps showing the last "Loading" line. That label goes to Widget: say what the assistant is doing while it writes and runs code #494.
  • src/assistants/nemar/config.yaml:
    • import_before_seal;
    • the prompt's spectrum block, now bounded, and its filter block, from 89e7d98;
    • the comment above dataset_suggested_questions, from 89e7d98;
    • execute_code's description, which the model reads on every call. It said "numpy, matplotlib, zarr and eegprep_lean are installed and nothing else can be". It now names SciPy and the welch rule.
  • The notebook starter's setup cell runs %pip install eegprep-lean scipy. The spectrum cell no longer runs its own %pip install scipy, and the intro's example package is now pandas.
  • Statements that said NEMAR has no SciPy, found with grep:
    • docs/community-widget.md ("not scipy", "belongs in the notebook"): corrected;
    • docs/community-browser-runtime.md: the new key, "Importing before the seal", "What it costs", "SciPy in 32-bit WebAssembly", first-load cost and progress steps;
    • .context/browser-execution-tool-design.md: dated "As built (NEMAR: preload SciPy in the chat runtime and teach scipy.signal #495)" notes;
    • frontend/browser-harness/README.md and the chrome.js comment;
    • the Pyodide cache comment in test.yml and tests.yml, identical in both so the parity test passes.
    • No ADR mentions SciPy. CHANGELOG.md's 0.8.14 entry ("the chat runtime has no SciPy") is released history, so I left it.
  • CHANGELOG.md under [Unreleased]. Ask NEMAR's model for one condition per events call #489's unreleased entry says the prompt tells the model to keep "the filter's slice as written". That filter is gone now, and my entry says it retires that note. I did not edit Ask NEMAR's model for one condition per events call #489's line.
  • Commit 89e7d98 (originally 122199d) says "Tested: NOT passing yet". The commits after it make those tests pass; I did not rewrite it.

Tests

  • bun frontend/test-worker-core.js: 213 passed. A new section uses a real wheel, built by hand and installed by micropip from a local server, whose module imports ctypes at its top level the way _ccallback does. It checks:
    • the control without the key fails the way SciPy did;
    • with the key, the module imports and its ctypes works;
    • progress steps come in order, before the seal;
    • nothing is bound into the user namespace;
    • every route to ctypes from executed code is still refused;
    • a missing module, and a module that raises, each fail the boot, named, before the seal and the prelude.
  • bun frontend/test-data-lane.js: 106 passed. It covers:
    • NEMAR's import steps;
    • every public SciPy module imports under the seal;
    • ctypes is still refused, and the documented reference exists;
    • a control boot without the key, where SciPy is broken;
    • the prompt's ERP low-pass and spectrum blocks run as written;
    • controls for the 2-D and the over-long welch refusals, and a check that twice the bound is refused, so the bound is not needlessly short;
    • every community's import_before_seal is checked against the lock.
  • bun frontend/browser-harness/chrome.js (Chrome 153.0.8010.53, production nemarlike policy): nemarlike passed 45 of 45 checks, including SciPy imports and per-channel welch plus sosfiltfilt, and import ctypes denied. The control boot failed as required, and the workspace, warm and lock-change checks passed.
  • bun notebook/e2e-check.js, with --environment production and --environment develop: all checks passed.
  • Every other Bun suite both workflows run passed, as did the three --serve Chrome checks, build-runtime-bundle.js --check and node --check.
  • uv run pytest --ignore=tests/test_integration -m "not network", which is the gating job's command: 2951 passed, 21 skipped. I deselected the two live OpenAlex classes in tests/test_knowledge/test_papers_sync.py. They are not marked network, and locally they hang on an OpenAlex connection; this is unrelated to this change. test_version_shows_version fails only when FORCE_COLOR=1 is set in the shell. uv run ruff check . and uv run ruff format --check src tests are clean.

Mutations, each confirmed to fail the tests:

  • remove ctypes from the seal's blocked roots: worker-core 8 fail, data-lane 3 fail, and the drift pytest fails;
  • let only the finder pass ctypes: worker-core 4 fail;
  • skip the pre-seal import: worker-core 9 fail, data-lane 8 fail;
  • move the imports after the seal: both suites fail;
  • drop the preload-root rule in Python: 5 pytest fail;
  • drop SciPy from the tool description's installed list: the new pin fails;
  • drop the welch length bound: data-lane 8 fail;
  • set the bound 16 times too short (2**24): the tightness check fails.

The CI Pyodide cache

This PR is what made a cache miss expensive, so it also fixes the cache. .cache/pyodide-packages was keyed on package.json alone. Run 1 of this PR restored a 13 MB cache that had no SciPy wheel, fetched SciPy (16 MB), and then logged "Cache hit occurred on the primary key ..., not saving cache". The cache is never overwritten, so every later run would have fetched SciPy again.

In both test.yml and tests.yml, identically:

  • actions/cache/restore restores the newest cache for this package.json by prefix. The prefix also matches the old key.
  • After the three suites that load Pyodide, actions/cache/save saves under the hash of the wheels the directory holds. It saves only when that hash differs from what was restored, so a run that fetched nothing saves nothing.
  • A step between the two prints the restored key, the current key and the wheel count.
  • Stays compatible with fix: stop a failed request from hanging Python in Safari #502's notebook bridge step, which runs between the restore and the save.

I keyed it on the contents rather than on the configs because which wheels get fetched depends on every preload list, every overlay's depends, and whatever a suite loads itself.

What CI showed:

  • First run (3b0b7b7): restored the old 13 MB cache and saved a new 29.6 MB one holding SciPy, under the hash of its 23 wheels.
  • A rerun of that job: restored the old cache again. When a restore key matches a cache exactly, that match wins over a newer prefix match, and the only restore key was exactly the old key.
  • First attempted fix: the dash-terminated prefix came first and the old key second, as a fallback. That still restored the old cache, because an exact match of any restore key beats every prefix match, whatever the order.
  • Final version: the restore key is the dash-terminated prefix alone.
  • Second run with the final version (at b7be87f): the cache hit. The log shows "Cache hit for restore-key: pyodide-packages-…-92afdc…" (the 29.6 MB cache holding SciPy); "now holds" equals "restored" with 23 wheels, so nothing was fetched; and "Save Pyodide packages" was skipped.

A scope with no cache under the new scheme yet downloads every wheel once and saves one.

Review

Two Sonnet reviewers checked the diff: a code review and a test-coverage review. I fixed every finding:

  • The preload-only refusal said a package outside preload "would not be installed when the imports run". That is false for allow_install. It now states the rule, the docstring says why allow_install cannot vouch for a module (it names requirements and URLs, not imports), and a test pins that boundary.
  • The welch bound's tightness is now pinned.
  • The starter test reads the setup cell's %pip arguments instead of matching one exact string, and I dropped an assertion that already held before this change.
  • The drift test's regex now documents the source convention it relies on.
  • I left the tool-description extraction as it is. Its only failure mode is a loud false failure, never a false pass.

Left open

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-nemar-scipy-preload-demo.osc.earth
Branch feature/nemar-scipy-preload
Commit d04de01

This preview will be updated automatically when you push new commits.

neuromechanist added a commit that referenced this pull request Sep 25, 2026
Refs #495. The cache was keyed on package.json alone, so a wheel preloaded
after it was saved (SciPy, 16 MB) was fetched on every run: PR #504's first
Frontend Tests run restored a 13 MB cache without SciPy and logged 'Cache hit
occurred on the primary key, not saving cache'. It is now restored by prefix
(which also matches the old key) and saved after the suites that load
Pyodide under the hash of the wheels it holds, only when that differs from
what was restored. Identical in test.yml and tests.yml.

Tested: actionlint on both workflows (only the pre-existing SC2086 in the
integration job remains); uv run pytest tests/test_frontend_job_parity.py
(1 passed). A second CI run is what shows the hit.
Refs #495. Adds scipy to NEMAR's preload, and has the prompt use signal.welch one channel at a time (a 2-D array raises 'array is too big' in 32-bit WebAssembly, measured) and butter + sosfiltfilt for the ERP low-pass. test-data-lane.js runs both prompt blocks in the sealed runtime.

Tested: NOT passing yet. In the sealed runtime 'from scipy import signal' fails ('extension modules cannot be imported') because the namespace seal blocks ctypes, which scipy._lib._ccallback and scipy.stats._continuous_distns import at top level; the runtime needs to import them before the seal.
Refs #495. A new optional key: modules the browser runtime imports after its
installs and before the namespace seal, for a package that imports a sealed
module at its own top level (SciPy imports ctypes). Module names only, at most
16, each once, none a root the seal removes, and each rooted in a package
preload names. The public config response carries it as configured.

Tested: uv run pytest tests/test_core/test_config/test_community.py
tests/test_api/test_community_router.py (405 passed).
Refs #495. boot() imports each import_before_seal module after the installs
and before the namespace seal, one progress step each (phase 'importing'), and
fails the boot as kind 'import_before_seal', naming the module, if one does not
import. buildWorkerConfig passes the key through; default empty. The seal is
unchanged: it still evicts ctypes and refuses it to executed code. Runtime
bundle and its integrity pin rebuilt; the widget change is that generated line.

Tested: bun frontend/test-worker-core.js (213 passed), test-runtime-lifecycle
(184), test-egress (80), test-runtime-bundle (25), build-runtime-bundle --check.
Refs #495. NEMAR's import_before_seal is scipy, scipy.stats and scipy.io, the
three whose loading imports ctypes, measured: with only scipy, scipy.stats,
scipy.io and scipy.signal fail under the seal; with all three, every public
SciPy module imports. This makes the prompt's scipy.signal blocks from the
previous commit run.

test-data-lane.js walks every public SciPy module in the sealed runtime,
checks import ctypes is still refused, pins the documented ctypes reference
SciPy keeps, and keeps a control boot without the key where SciPy is broken.
Every community's import_before_seal root is checked against its lock entry.

Tested: bun frontend/test-data-lane.js (101 passed, including the prompt's
filter and per-channel welch blocks and the 2-D welch control); uv run pytest
tests/test_assistants (302 passed).
Refs #495. The browser harness's NEMAR boot now runs welch per channel and
butter + sosfiltfilt in the sealed runtime, and checks import ctypes is still
refused; its progress log is timed and names import_before_seal modules.

Tested: bun frontend/browser-harness/chrome.js, Chrome 153.0.8010.53 (nemarlike
45 of 45 checks, control failed as required, workspace, warm and lock-change
all passed); the three pre-seal imports took about 1.2 s of a 3.7 s boot.
Refs #495. The setup cell installs eegprep-lean and scipy; the spectrum cell
no longer runs its own %pip, and the intro's example package is pandas. A test
checks that only the setup cell installs anything.

Tested: uv run pytest tests/test_scripts/test_build_notebook_site.py (58
passed); bun notebook/e2e-check.js --environment production, all checks passed
(setup by itself 7.0 s, cold 10.5 s, both figures, no error output).
Refs #495. Measured in Pyodide 0.29.5: welch makes a view of every window at
once, and 32-bit WebAssembly refuses a view of 2 GiB or more (channels x
samples x nperseg x 8 bytes). One channel at a time is not enough for a long
high-rate read: with 2-second segments one channel fails past about 36 minutes
at 250 Hz, 9 at 500 Hz and 2.2 at 1000 Hz. The prompt's block now takes at
most 2**28 // nperseg samples per call and says so.

Tested: bun frontend/test-data-lane.js (105 passed): the block runs on 33 x
30,000 at 250 Hz and 4 x 200,000 at 1000 Hz, with controls that the whole
array and one unbounded 1000 Hz channel are refused; dropping the bound fails
the suite.
Refs #495. execute_code's description, which the model reads on every call,
said numpy, matplotlib, zarr and eegprep_lean are installed and nothing else
can be; it now names SciPy and the welch rule. docs/community-widget.md said
NEMAR preloads no SciPy and that SciPy work belongs in the notebook. A test
checks the description names every package the runtime preloads.

Tested: uv run pytest tests/test_assistants/test_nemar_runtime.py (38 passed);
with SciPy dropped from the description's installed list the new test fails.
Refs #495. docs/community-browser-runtime.md gains the key, the measured
reason NEMAR lists scipy, scipy.stats and scipy.io, the boot time and heap
with and without them, what the ctypes reference SciPy keeps costs and why
that fits the seal's purpose, and the welch limits in 32-bit WebAssembly.
The first-load figures are re-measured in Chrome (35.4 MB over the network,
42.9 MB decoded); the old ones were over-the-network sizes labeled
uncompressed. Package-list comments in the design note, the harness and both
workflows now include SciPy.

Tested: uv run pytest tests/test_frontend_job_parity.py (1 passed); figures
from bun measure scripts and a cold Chrome 153 boot.
Tested: not applicable (changelog only).
Review follow-up (#495). The refusal claimed a package outside preload would
not be installed when the imports run, which is false for allow_install; it now
states the rule, the docstring says why allow_install cannot vouch (it names
requirements and URLs, not imports), and a test pins that boundary.

Tested: uv run pytest tests/test_core/test_config/test_community.py -k
ImportBeforeSeal (28 passed).
Review follow-up (#495). test-data-lane.js reads 300 s at 1000 Hz and checks
one channel of twice the prompt's bound is refused, so a needlessly short bound
fails. The starter test reads the setup cell's %pip arguments rather than one
exact string, and drops an assertion that held before the change.

Tested: bun frontend/test-data-lane.js (106 passed; with the bound set to
2**24 the new check fails); uv run pytest
tests/test_scripts/test_build_notebook_site.py (58 passed).
Refs #495. The cache was keyed on package.json alone, so a wheel preloaded
after it was saved (SciPy, 16 MB) was fetched on every run: PR #504's first
Frontend Tests run restored a 13 MB cache without SciPy and logged 'Cache hit
occurred on the primary key, not saving cache'. It is now restored by prefix
(which also matches the old key) and saved after the suites that load
Pyodide under the hash of the wheels it holds, only when that differs from
what was restored. Identical in test.yml and tests.yml.

Tested: actionlint on both workflows (only the pre-existing SC2086 in the
integration job remains); uv run pytest tests/test_frontend_job_parity.py
(1 passed). A second CI run is what shows the hit.
Refs #495. A rerun of the previous commit's Frontend Tests restored the old
13 MB cache again, although the run before it had saved a 29.6 MB one with
SciPy: an exact match of a restore key wins over a newer prefix match, and the
only restore key was exactly the old key. The dash-terminated prefix now comes
first; the old key is the fallback. Identical in test.yml and tests.yml.

Tested: actionlint on both workflows (no new findings); uv run pytest
tests/test_frontend_job_parity.py (1 passed). CI shows the hit.
Refs #495. With the old package.json-only key listed after the prefix, the
run at 8edc26a still restored the old 13 MB cache over this PR's 29.6 MB one:
an exact match of any restore key beats every prefix match, whatever the
order. The old key is dropped, so a scope without a cache under the new
scheme downloads every wheel once and saves one.

Tested: actionlint on both workflows (no new findings); uv run pytest
tests/test_frontend_job_parity.py (1 passed).
@neuromechanist
neuromechanist force-pushed the feature/nemar-scipy-preload branch from b7be87f to 63a39e8 Compare September 25, 2026 01:33
@neuromechanist
neuromechanist merged commit d7c2404 into develop Sep 25, 2026
11 checks passed
@neuromechanist
neuromechanist deleted the feature/nemar-scipy-preload branch September 25, 2026 01:38
neuromechanist added a commit that referenced this pull request Sep 25, 2026
#504 replaced the windowed-sinc filter with sosfiltfilt, so the ERP
entry's note about keeping its slice no longer describes the prompt,
and the SciPy entry already says it was retired.

Tested: docs only; config.yaml on develop has no slice instruction.
neuromechanist added a commit that referenced this pull request Sep 25, 2026
* Changelog for 0.8.15

Moves the Unreleased entries under 0.8.15 and starts a new
Unreleased section, as each release does.

Tested: docs only; each entry already reviewed with its PR.

* Drop the retired filter-slice note from 0.8.15

#504 replaced the windowed-sinc filter with sosfiltfilt, so the ERP
entry's note about keeping its slice no longer describes the prompt,
and the SciPy entry already says it was retired.

Tested: docs only; config.yaml on develop has no slice instruction.
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.

1 participant