Skip to content

Host a JupyterLite notebook site at notebook.osc.earth/osa - #465

Merged
neuromechanist merged 32 commits into
developfrom
feature/issue-453-notebook-site
Sep 24, 2026
Merged

neuromechanist merged 32 commits into
developfrom
feature/issue-453-notebook-site

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Hosts a JupyterLite notebook site at notebook.osc.earth/osa/, from this repository, so a reader can open a dataset in a real Python notebook in their browser. This is the follow-up ADR 0010 deferred to #453, decided by the maintainer on 2026-09-23; ADR 0011 records it. The widget button that opens it is the capsule launcher (#436), in a separate PR.

How it works

  • https://notebook.osc.earth/osa/open.html?community=nemar&dataset=nm000103 validates both parameters against the site's starters, writes a starter notebook into JupyterLite's own browser storage (localforage over IndexedDB, the same database and store JupyterLite uses, JupyterLite Storage - /osa/), and redirects into it. It never overwrites a notebook the reader already has, so opening the same dataset again keeps their edits. JupyterLite 0.8.4 has no ?fromURL=, which is why the bootstrap is a same-origin page.
  • Pyodide 0.29.5 loads from jsDelivr through the kernel's pyodideUrl, rather than self-hosted: --pyodide=<tarball> copies the whole 464 MB distribution into the site. The deployed site is 501 files and 19.9 MB (sourcemaps stripped).
  • Each notebook community's lock overlay is merged into Pyodide 0.29.5's own lock (the stock lock's sha256 is pinned and checked at build), with the community's wheels bundled on the site under absolute URLs, so %pip install eegprep-lean resolves eegprep-lean and zarr from the site and everything else from the distribution, each sha256-checked by Pyodide. An overlay may add a package, never replace one; two communities adding the same package must agree byte for byte.
  • A community opts in with a notebook: block (starter, an .ipynb template with {{dataset_id}}, and an anchored dataset_pattern), and must run the site's Pyodide version. NEMAR's starter lists the dataset's recordings with a Zarr copy, reads two seconds of four channels in physical units and plots them.
  • PyPI fallback stays on: a notebook runs the reader's own code, unlike the widget's sealed runtime, which runs code the model wrote.
  • deploy-notebook.yml builds and deploys on pushes to develop (develop-notebook.osc.earth/osa/) and main (notebook.osc.earth/osa/), creating the osa-notebook Pages project and the two custom domains idempotently. Not on pull requests. cleanup-preview-dns.yml only touches *-demo.osc.earth names.
  • Out of scope, stated in the docs: handing the widget's workspace to the notebook (Hosted JupyterLite notebook surface (follow-up to ADR 0010) #453's fourth prerequisite).

Tests

  • pytest: the notebook config (21 in test_notebook_lock.py, 10 in test_community.py, 3 in test_shipped_runtimes.py) and the build (20 offline, plus one network test that builds the real site end to end).
  • Bun: notebook/test-open.js, the bootstrap's validation, token filling and no-overwrite logic; added to both workflow suites.
  • Chrome, real (bun notebook/e2e-check.js, live zarr.nemar.org, served under /osa/): the index line, the exact read (4, 500) uV 250.0 ('E1', 'E2', 'E3', 'E4'), one rendered figure, no errors or page exceptions; an edit survives reopening; an unknown community and a malformed dataset each show a sentence and write nothing. Cold 7.6 to 10.1 s over seven runs, warm rerun 4.0 s. The Chrome check and the full build now also run in CI on pull requests touching the site (notebook-site-check.yml).
  • Eight mutations, each caught (the no-overwrite rule by the Chrome check).
  • Full suite: 2,802 passed; the one failure is the pre-existing color-terminal test (test_version_shows_version fails locally and passes in CI, because rich colorizes on a TTY #434).

PR review findings: config.yaml's comment omitted /osa; notebook_lock.py's
module docstring omitted it too; test_shipped_runtimes.py's docstring cited
the build script by its old hyphenated name (build-notebook-site.py, the
real file uses underscores); the changelog's code span for
deploy-notebook.yml was split across a line wrap; browser-execution-tool-
design.md still said the hosted JupyterLite surface was deferred to #453
with no mention that ADR 0011 has since built and hosted it.
Two PR review findings, both defense in depth for the same bootstrap page:

- A dataset id now must match a generic safe shape
  (^[A-Za-z0-9._-]{1,64}$) BEFORE it is even checked against the
  community's own dataset_pattern. The value is substituted unescaped into
  the starter's Python source, so a community pattern that is accidentally
  too loose must not become a code-injection hole on its own.
- The storage write (the community's directory entry, then the notebook
  itself, never overwriting an existing one) is now raced against a five-
  second timeout (raceStorage/STORAGE_TIMEOUT). Some private-browsing and
  storage-blocked modes never settle a storage call at all, which used to
  leave the reader stuck on "Opening your notebook..." forever; this page
  now shows a plain sentence instead. writeToStorage is pulled out of
  main() specifically so the race wraps only the storage section, not the
  network fetches above it.
Adds, all against real stand-ins for localforage at the boundary (a real
in-memory store, and a real never-settling Promise), never a mock of this
module's own logic:

- datasetProblem refuses a hostile probe (a quote, a backslash, a newline,
  a space) even under a deliberately wide-open community pattern.
- writeToStorage never overwrites a path that already holds content, proven
  by seeding one and confirming a second write leaves it untouched.
- raceStorage resolves to STORAGE_TIMEOUT against a storage call that never
  settles, and passes through a call that settles normally.
- A composed assertion at the production shape: storageDatabaseName(
  resolveBaseUrl(config, '/osa/')) is exactly 'JupyterLite Storage - /osa/'.

Each new guard was mutation-tested by hand (removed, confirmed the relevant
assertions turn red -- the timeout guard's removal was confirmed by an
actual hang under a 15s wall clock, not just a failed assertion --
restored, confirmed green again).
PR review finding: NotebookConfig.dataset_pattern was checked for anchoring
and compilation, but nothing stopped a pattern loose enough to accept a
quote, a backslash, a newline, or a space -- exactly what open.js's own
generic shape guard exists to keep out, and a dataset id is substituted
unescaped into the starter's Python source. A new field validator
(_dataset_pattern_refuses_hostile_probes) refuses any dataset_pattern that
matches one of HOSTILE_DATASET_PROBES, independent of open.js's client-side
guard, so a community's pattern can never rely on that guard alone. Also
fixes this file's own /osa omission in two docstrings, found by the same
review pass that flagged the config.yaml comment.
Four patterns that would each let through one hostile probe (a match-all,
and three narrower ones each reaching a quote, a backslash, or whitespace
directly), plus a check that NEMAR's own shipped pattern still passes.
Mutation-tested: emptied the validator's hostile-probe list by hand,
confirmed all four rejection cases fail, restored, confirmed green.
PR review finding: the reviewer demonstrated that writing _headers/
_redirects into the site subdirectory instead of the true Cloudflare Pages
publish root passes every existing offline test, because build()'s own
wiring of write_headers/write_root_redirect is only exercised by the
network-marked full build. Pulling that wiring into its own function
(finalize_publish_root) makes it callable against a synthetic output tree,
with no jupyterlite build and no network. Also fixes this file's own /osa
omission in its module docstring.
Builds a fake output tree (a site subdirectory with a placeholder file,
standing in for a real jupyterlite build) and asserts finalize_publish_root
writes _headers/_redirects at the publish root, never inside the site
subdirectory, plus the bare-host case where no _redirects file is written
at all. Mutation-tested: pointed both writes at the site subdirectory
instead of the publish root, confirmed the new test fails, restored,
confirmed green.
paths: named the build script and the assistant-side notebook/runtime/
config files, but not src/core/config/notebook_lock.py, community.py, or
runtime_lock.py -- so a Pyodide pin bump or a lock-merge fix there would
never trigger a redeploy.
PR review finding: TestFullBuildEndToEnd only runs in test.yml's post-merge
Integration Tests job, with continue-on-error, and notebook/e2e-check.js
runs in no workflow at all -- the reviewer demonstrated concretely that a
regression in either the _headers/_redirects placement or the no-overwrite
rule passes every check that gates a PR today.

notebook-site-check.yml runs both for real, with no continue-on-error, on a
pull request touching the notebook site's own paths (the same list
deploy-notebook.yml deploys on), a weekly schedule, and workflow_dispatch.
A scheduled failure opens or updates a tracking issue through the existing
.github/actions/track-issue, the same convention widget-route-health.yml
uses; a pull_request failure does not, since it already surfaces as a
failing PR check.
PR review finding. Fixes a pre-existing shellcheck SC2129 in deploy-
notebook.yml's site-URL step (individual >> "$GITHUB_OUTPUT" redirects
collapsed into one { ...; } block) so actionlint on this file is clean, then
adds an actionlint step to both lint jobs (test.yml, tests.yml), pinned to
1.7.12 and scoped to deploy-notebook.yml and notebook-site-check.yml only --
not every workflow in .github/workflows/, which would surface pre-existing,
unrelated findings (confirmed locally: test.yml itself has one at line 225)
that are out of scope for this change.
PR review findings: CORS, CDN, CSP, and API each appeared before being
spelled out in ADR 0011, community-notebook.md, or notebook/README.md.
Also applies semantic line breaks (one sentence per line, split further at
a colon or em-dash for a long sentence) to the two paragraphs the review
named: ADR 0011's /osa naming-rule paragraph and notebook/README.md's
--site-url subdirectory paragraph.
PR review finding: the timing table recorded four cold runs (7.6-8.6 s),
but the handback report separately cited a 9.1 s run that never made it
into the table. Adds that run (row 5) plus two more real runs from this
review pass (rows 6-7, 10.1 s and 8.6 s, after this PR's own review-driven
code changes), and updates the prose range (7.6-10.1 s across seven runs on
two separate days) so it matches the table exactly. The warm figures have
not moved in any run measured so far.
@neuromechanist
neuromechanist force-pushed the feature/issue-453-notebook-site branch from 56a5525 to 310f401 Compare September 24, 2026 05:36
@neuromechanist

Copy link
Copy Markdown
Member Author

Review response

Three Sonnet reviewers ran (code and security, tests, docs). Every finding is addressed in the commits after the rebase onto develop.

Code and security

  • The deploy workflow now also redeploys on changes to the build's own logic (notebook_lock.py, community.py, runtime_lock.py) (ea12e0d).
  • open.js races its storage write against a 5-second timeout and shows a plain sentence when a private-browsing or blocked-storage mode never answers (702d3ac).
  • Defense in depth for the dataset value, which is substituted into Python source: open.js refuses anything outside ^[A-Za-z0-9._-]{1,64}$ before the community's own pattern, and NotebookConfig refuses a dataset_pattern that accepts a quote, a backslash, a newline or a space (702d3ac, db4eab8; both mutation-checked).
  • Kept, deliberately: the DNS step's warn-and-continue (the same self-healing convention as deploy-pages.yml), and Pyodide from jsDelivr pinned by version (the widget runtime's existing trust model; the stock lock and the community wheels are sha256-pinned).

Tests

  • The two checks that catch real regressions now gate: .github/workflows/notebook-site-check.yml runs the full network build test and the real Chrome check on pull requests touching the site, weekly, and on dispatch, with no continue-on-error; a scheduled failure files a tracking issue the way widget-route-health.yml does (c94456c). It is running on this PR as "Build and open the notebook site".
  • Offline coverage for both mutations the reviewer proved invisible: _headers/_redirects placement through an extracted finalize_publish_root against a synthetic tree, and the no-overwrite rule through writeToStorage (31e5b6c, 2a077e1, c594d07).
  • The composed storage name under /osa/ (c594d07), and actionlint on the two notebook workflows in the lint job (9fd5aa8).

Docs: /osa restored in every host-root mention, build_notebook_site.py spelled right, the changelog's split code span joined, abbreviations spelled out, one sentence per line, the design note updated where it still said the site was deferred, and the measurements table now records every run (cold 7.6 to 10.1 s over seven runs on two days) (a86dd96, d817a35, 722cedd).

Gates: offline pytest 2,802 passed (the one failure is #434); the network build test passed; every Bun suite, notebook/test-open.js (52) and chrome.js passed; notebook/e2e-check.js passed twice in Chrome (cold 10.1 and 8.6 s, warm rerun 4.0 s).

PR #465's CI run showed only 'timed out after 120000ms ... last value:
false' with no way to tell whether the notebook was stuck, a request
failed, or the page threw. Wraps the whole flow (open, run, edit/save,
warm reopen, refusals) in a try/catch that, on any failure, prints bounded
diagnostics for whichever page was active before rethrowing: the page's
URL, every cell's prompt and output text (a traceback renders as plain
visible text, so it is captured the same way as any other output), every
console error/warning and uncaught exception seen so far, and every
network request that failed or returned 4xx/5xx -- across the page's own
session AND every worker it spawned, via chrome.js's existing
NetworkRecorder/attachWithNetwork (Pyodide's own fetches happen inside a
worker the page's Network domain never sees). Everything is capped (20
list items, 1000 chars per item) so a real failure cannot flood the log.

Verified against a real forced timeout (a bogus sentinel string, a
shortened poll deadline): the diagnostics printed the page URL, all four
cells with their live prompt state, the one benign favicon 404, and 27
bounded console warnings, then the process still exited 1 with the
original timeout error, exactly as before. Verified the unmodified happy
path is unaffected (two full local runs, both ALL CHECKS PASSED).
Cheap, always printed: the GitHub-hosted runner and a laptop are rarely on
the exact same Chrome release, and this was worth knowing directly rather
than cross-referencing the runner image manifest by hand while
investigating PR #465's CI-only timeout.
The diagnostics from PR #465's CI run (35962090521) showed the exact race:
at timeout, every code cell's prompt was still '[ ]:' (never executed, not
'[*]:' queued), with no failed requests and no exceptions -- notebook:run-
all-cells fired before the notebook's kernel session was ready, so it
queued nothing. This Mac's kernel comes up sooner, so the race never showed
locally.

waitForKernelIdle polls the same thing a person reads off the notebook's
own kernel indicator: window.jupyterapp's current panel's sessionContext,
a session whose kernel.status is 'idle'. Given its own 90s deadline, called
before every Run All (cold run and the warm re-run both fire it). Cold time
is still measured from opening the link, unchanged.

runAllCellsAndConfirmQueued replaces the bare fire-and-forget call: after
firing, it confirms within 20s that at least one prompt left '[ ]:' before
falling through to the existing full-run wait. Deliberately not a retry --
a blind re-fire would hide a real 'Run All does nothing' bug behind an
apparent pass on a second try -- so a genuine no-op fails immediately with
that stated, rather than only after the full 120s timeout.

diagnose() now also reports the kernel's session/name/status and whether a
Pyodide worker target has even been seen, via the same KERNEL_INFO_EXPR
waitForKernelIdle itself polls, and openPage() tracks worker target URLs
(Target.attachedToTarget, type 'worker') for that.

Verified: two normal local runs, both ALL CHECKS PASSED (cold 7.3s/10.3s).
Verified against the actual race, not just a fast machine: with a temporary
CPU-throttle test hook (Emulation.setCPUThrottlingRate, removed before this
commit) at 4x, the full flow passed end to end; at 6x, the cold run's Run
All still passed correctly with the fix in place. With the fix temporarily
disabled and 6x throttling applied, the original bug reproduced exactly --
'did not queue any cell within 20s', with the kernel's own status caught
mid-transition to idle in the diagnostics -- confirming the throttle is a
meaningful stand-in for the race and that this fix is what prevents it.

Two unrelated, pre-existing timing assumptions surfaced only under heavy
throttling and are NOT touched here (out of scope for this fix): the
refusal-check's first page read can run before open.html's own script has
set up #app, and the edit-and-save-then-reopen step can race under 6x.
Both passed at normal speed and under 4x; flagging for a separate look.
Two more timing assumptions the throttled runs exposed, on top of 17ba233.

(1) The refusal check read document.getElementById('app').textContent
once. Right after Page.navigate, the target can still be showing
about:blank (no #app at all) before open.html's own document has loaded,
so #app is null and .textContent throws -- a page exception that crashed
the whole poll on its first iteration under load, rather than letting
pollUntil retry. Fixed with optional chaining
(getElementById('app')?.textContent ?? null): a page not yet loaded is now
just "condition not yet true," the same as everywhere else in this file.

(2) The save-then-reopen step polled only the document model's own dirty
flag before opening a second page. That flag is a UI-level convenience and,
under CPU throttling, testing showed it is not sufficient proof the
underlying write is visible to a DIFFERENT page's read. Added a second,
authoritative confirmation: window.jupyterapp.serviceManager.contents.get()
-- the SAME Contents drive a fresh page's notebook load reads through --
polled until its last_modified actually moves from its pre-edit value.

Testing also found a third, related gap needed to fully close this under
throttle: the edit-survived check itself read document.body.innerText once,
right after waitForNotebookReady, which only confirms the notebook widget
object exists, not that its cell views have finished mounting their editor
DOM. Wrapped in the same pollUntil pattern (up to 15s); a genuine failure
still reports FAIL, it is not swallowed or loosened.

No blind sleeps or retries anywhere in this change; every wait is a
condition on real state (an element's content, a last_modified timestamp,
rendered DOM text).

Verified with a temporary CPU-throttle test hook (Emulation.
setCPUThrottlingRate, removed before this commit, not shipped): two runs at
6x, both ALL CHECKS PASSED (previously this reproduced 'FAIL: the edit
survived...' consistently at 6x even with 17ba233 applied). Two further
runs at normal speed, both ALL CHECKS PASSED (cold 8.8s, 13.3s).
The wheel-copy loop re-read runtime.python.lockfile through two
Optionals the first loop had already narrowed; ty flagged all three
reads. Tested: build script unit tests pass, ty clean on the file.
The develop notebook site is embedded by test.nemar.org, whose dataset
pages read zarr-test.nemar.org, but the starter always read
zarr.nemar.org and the pattern refused xx ids, so a staging fixture
such as xx099903 could never open.

A community's notebook block now declares zarr_base and
dataset_page_base per environment (production, develop), and
build_notebook_site.py takes a required --environment that fills them
into the starter at build time. The deploy workflow passes develop or
production by branch, e2e-check.js takes the same flag with one fixture
per environment, and the scheduled check runs both. NEMAR's pattern
admits xx ids.

Tested: offline suite passes (2,836; the one failure is the version
test under FORCE_COLOR=1, unrelated). e2e-check.js in Chrome, both
environments: develop opens xx099903 from zarr-test.nemar.org, cold
8.3 s; production opens nm000103, cold 11.3 s; ALL CHECKS PASSED.
Review of #465 found the per-environment build guarded only by build()
calls with valid values. New tests: the CLI refuses a missing or
unknown --environment, build() fails before the JupyterLite build,
a missing dataset_page_base is refused, the shipped NEMAR starter
carries exactly its own hosts per environment, and the deploy
workflow's branch script is run for main and develop.

Tested: each guard mutated in the dangerous direction (nine
mutations, including a swapped workflow mapping and a typo'd NEMAR
develop host); every one fails a test.
--environment=develop, or a typo'd flag, used to be taken as the
screenshot path while the check ran against production. It now
accepts both --environment forms and throws on any other option or
extra argument.

Tested: a typo, an unknown environment, a missing value and an extra
argument each exit with the usage; --environment=develop builds.
From review: the NotebookConfig docstring named a staging key the
code refuses, the CommunityConfig.notebook example lacked the two
now-required maps, three new comments used a double-hyphen dash, and
the per-environment rationale was repeated in four places; it now
lives in ADR 0011 and the others point there.

Tested: ruff, ty and the config and build tests pass.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review response: per-environment Zarr host (b68a28c..4862aa1)

Four Sonnet reviewers (code, tests, silent failures, docs) reviewed b68a28c and 522a34c. Every finding is addressed below; none was skipped.

Tests (6482dbc)

  • --environment's guards were exercised only through build() with valid values. The CLI is now tested with no environment and with an unknown one (both exit 2), and build() with an unknown one.
  • The dataset_page_base-missing branch of environment_bases was untested; it now has its own refusal test.
  • Nothing proved the pre-flight check fires before the JupyterLite build. A test now asserts the output directory is never created.
  • The deploy workflow's branch-to-environment mapping was checked by nothing. The "Pick the site URL" step's real script is now run under bash for main and develop, and its outputs are asserted, along with the build step's arguments and the site check's two environments.
  • Nothing asserted the shipped NEMAR config's develop hosts, so a typo there would have built, deployed and passed e2e-check.js. The real NEMAR starter is now filled for both environments offline, and its exact index_url and dataset link are asserted, plus the absence of the other environment's hosts.
  • Mutation check: nine mutations in the dangerous direction (optional --environment, swapped workflow mapping, dropped develop check run, typo'd NEMAR develop Zarr and page hosts, trailing slash accepted, string sources left unfilled, the dataset_page_base check removed, the pre-flight check removed). Every one fails a test.

Silent failure (4d49b32)

  • e2e-check.js took --environment=develop or a typo'd flag as the screenshot path and ran against production. It now accepts both --environment forms and throws on any other option or extra argument.

Docs (4862aa1)

  • The NotebookConfig docstring named staging, a key the code refuses; it now says production and develop.
  • The CommunityConfig.notebook example lacked the two required maps.
  • Three new double-hyphen dashes removed, plus one in a rewrapped line.
  • The per-environment rationale appeared in four places; it now lives in ADR 0011 and the others point there.
  • config.yaml named xx099901 while the check and docs use xx099903. Both are staging-only fixtures; the comment now names the one the check opens.

Code: no issues found.

Verification

  • e2e-check.js in Chrome 153, both environments: develop opens xx099903 from zarr-test.nemar.org (cold 8.3 s, reopen 0.9 s, re-run 4.1 s; window (4, 2000) mV 1000.0); production opens nm000103 (cold 11.3 s, reopen 1.5 s, re-run 3.8 s). ALL CHECKS PASSED on each.
  • Offline suite: 2,836 passed. The one local failure is test_version_shows_version under FORCE_COLOR=1 in my shell; it passes without it and is unrelated.
  • Measured while checking cross-origin access: the nemar and nemar-dev buckets do not allow the notebook origins, but eegprep-lean reads everything through contract_base, and both Zarr hosts serve array files directly with the notebook origin allowed. Recorded in ADR 0011.

@neuromechanist
neuromechanist merged commit ba3777d into develop Sep 24, 2026
17 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-453-notebook-site branch September 24, 2026 08:03
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