Repository navigation
Preload SciPy in NEMAR's browser runtime, imported before the seal - #504
Merged
Merged
Conversation
Contributor
Preview Deployment
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.
3 tasks
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
force-pushed
the
feature/nemar-scipy-preload
branch
from
September 25, 2026 01:33
b7be87f to
63a39e8
Compare
This was referenced Sep 25, 2026
Merged
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.
6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #495.
NEMAR's chat runtime now preloads SciPy and SciPy works under the runtime's seal. The prompt now calls
scipy.signalinstead 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 ontodevelop(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) refusesctypesto executed code through asys.meta_pathfinder and the__import__guard, and it evictsctypesfromsys.modules. SciPy importsctypeswhile it loads:import scipygoes throughscipy._lib._ccallbackand its compiled_ccallback_c.scipy.statsgoes through_continuous_distns.scipy.iogoes througharff.scipy/__init__.pyturns the refusal into "Thescipyinstall you are using seems to be broken, (extension modules cannot be imported)". The chained cause isImportError: '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.PythonRuntimeConfig,src/core/config/community.py):preloadnames, written as its import name (eegprep-leanbecomeseegprep_lean);SEALED_IMPORT_ROOTSmirrors the seal's_BLOCKED_ROOTS, and a pytest readsosa-egress.jsand compares the two.test-data-lane.jsalso checks each root against its lock entry'simports.osa-worker-core.js,boot()):preloadandallow_install, before the helpers and the namespace seal;pyodide.pyimport(name)per module, so nothing is bound into the user namespace;phase: "importing",module) inside the boot's fixed step budget;kind: "import_before_seal", the module's name and its own exception.PythonRuntimeConfig, and throughbuildWorkerConfig. The runtime bundle and its integrity pin are rebuilt, and--checkpasses.[scipy, scipy.stats, scipy.io], measured rather than guessed:scipyalone,scipy.stats,scipy.ioandscipy.signal(which importsscipy.stats) still fail under the seal;test-data-lane.jswalks SciPy's package tree and imports all 153 in the sealed runtime.scipy.signalandscipy.fftto 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.
ctypesis still a blocked root and the finder is not weakened. After boot, executed code still gets a refusal forimport ctypes(the import gate'sdenied_import),importlib.import_module("ctypes"),__import__("ctypes")andctypes.util. Noctypesmodule is left insys.modules.What this change costs: a module imported before the seal keeps the
ctypesit imported, as an ordinary attribute.scipy._lib._ccallback.ctypes, or throughscipy.stats._continuous_distnsorscipy.io.arff._arffread.ctypesinnumpy._core._internal. A sealed import would have leftNonethere.test-data-lane.jsandtest-worker-core.jsassert 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: nativefetchis 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 thanctypesgives. I measured two routes against the base branch's seal under Bun: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 guardedfetch.import _ctypes. The C extension that does ctypes' foreign calls is not a blocked root, and it imports after the seal ondeveloptoday. 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.
[scipy, scipy.stats, scipy.io]before the sealscipy0.18 s,scipy.stats0.96 s,scipy.io0.06 s, out of a 3.6 to 3.7 s NEMAR boot.from scipy import signalwould claim anyway. After a first spectrum and filter the heap is 149 MB in every configuration where SciPy works.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
welchis refused, per channel works, andfirwin+filtfiltandbutter+sosfiltfiltwork on 2-D arrays.The cause is more specific than 2-D input.
welchmakes 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 // npersegsamples to each call, and tells the model to say how many seconds the spectrum covers when that cut the read short.test-data-lane.jsruns 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,periodogramone segment at a time, which has no length limit. I keptwelchbecause the issue asks for it.What changed
src/core/config/community.py: theimport_before_sealfield, its validators, andSEALED_IMPORT_ROOTS.frontend/osa-worker-core.jsandfrontend/osa-runtime.js: the boot step and the pass-through. The bundle is rebuilt.frontend/osa-chat-widget.jschanges 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-runbun scripts/build-runtime-bundle.jsafter rebasing. The widget does not label the newimportingphase 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;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 thewelchrule.%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.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.mdand thechrome.jscomment;test.ymlandtests.yml, identical in both so the parity test passes.CHANGELOG.md's 0.8.14 entry ("the chat runtime has no SciPy") is released history, so I left it.CHANGELOG.mdunder[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.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 importsctypesat its top level the way_ccallbackdoes. It checks:ctypesworks;ctypesfrom executed code is still refused;bun frontend/test-data-lane.js: 106 passed. It covers:ctypesis still refused, and the documented reference exists;welchrefusals, and a check that twice the bound is refused, so the bound is not needlessly short;import_before_sealis checked against the lock.bun frontend/browser-harness/chrome.js(Chrome 153.0.8010.53, productionnemarlikepolicy): nemarlike passed 45 of 45 checks, including SciPy imports and per-channelwelchplussosfiltfilt, andimport ctypesdenied. The control boot failed as required, and the workspace, warm and lock-change checks passed.bun notebook/e2e-check.js, with--environment productionand--environment develop: all checks passed.--serveChrome checks,build-runtime-bundle.js --checkandnode --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 intests/test_knowledge/test_papers_sync.py. They are not markednetwork, and locally they hang on an OpenAlex connection; this is unrelated to this change.test_version_shows_versionfails only whenFORCE_COLOR=1is set in the shell.uv run ruff check .anduv run ruff format --check src testsare clean.Mutations, each confirmed to fail the tests:
ctypesfrom the seal's blocked roots: worker-core 8 fail, data-lane 3 fail, and the drift pytest fails;ctypes: worker-core 4 fail;welchlength bound: data-lane 8 fail;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-packageswas keyed onpackage.jsonalone. 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.ymlandtests.yml, identically:actions/cache/restorerestores the newest cache for thispackage.jsonby prefix. The prefix also matches the old key.actions/cache/savesaves 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.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:
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:
preload"would not be installed when the imports run". That is false forallow_install. It now states the rule, the docstring says whyallow_installcannot vouch for a module (it names requirements and URLs, not imports), and a test pins that boundary.welchbound's tightness is now pinned.%piparguments instead of matching one exact string, and I dropped an assertion that already held before this change.Left open
_ctypesis importable after the seal. This was already true before this PR; it is tracked in Sealed code reaches the worker's global scope: block _pyodide, and cover storage and postMessage #506, and I left it out of this PR.importingphase. That goes to Widget: say what the assistant is doing while it writes and runs code #494.