Skip to content

Phase 5: Browser ICLabel via ONNX Runtime Web with an await-able entry point #378

Open

Description

@neuromechanist

Phase 5 of #324.
Base: epic/324-pyodide-browser.
Depends on: phase 4 for the artifact, phase 2 for the Pyodide harness.
Parallel with: phase 6.

Why

onnxruntime has no WebAssembly build, so the browser path has to go through ONNX Runtime Web, which is JavaScript and asynchronous.
That asynchrony is the real design problem in this phase, and it is why it is separated from phase 4.
Everything in eegprep that reaches ICLabel today is synchronous.

The actual design question

Under Pyodide, calling into ONNX Runtime Web returns a JavaScript promise that must be awaited.
iclabel() is synchronous, pop_iclabel() is synchronous, and both are reachable from the GUI menus and from eegprep-console.

So this phase has to decide and document how the await-able entry point reaches users without forking the API:

  • what the async entry point is called and where it lives,
  • whether the synchronous pop_iclabel raises a clear error under Emscripten rather than silently blocking,
  • how the console and the GUI menu action reach the async path, given the EEGPrepSession contract in AGENTS.md that GUI and console must stay synchronized,
  • whether return_com=True history still produces a command a user can replay.

Present the options on the issue before implementing.
Do not invent a parallel async copy of the whole pop_* surface; AGENTS.md rules out parallel implementations of existing helpers.

Grounding, verified against the current tree

pop_iclabel at src/eegprep/plugins/ICLabel/pop_iclabel.py:16 already supports return_com and a GUI path through inputgui, and it recurses over lists of datasets at :38.
Any async seam has to preserve all three behaviors.
iclabel.py is the single place the network is actually invoked, which is the natural seam.

Scope

  • ONNX Runtime Web backend selected when sys.platform == "emscripten", resolved once, consistent with phase 3's helper pattern.
  • An await-able entry point, designed per the decision above.
  • Clear, early failure if the synchronous path is called under Emscripten, naming the async entry point.
  • Parity test under the phase 2 Pyodide harness: browser backend against the native onnxruntime backend on the same input.

Non-goals

No quantization; phase 6.
No server-side execution, per the epic.
No async variants of pop_* functions other than what ICLabel strictly needs.

Acceptance criteria

  • Design options for the async entry point posted on this issue and resolved before implementation.
  • Backend resolved once from the platform, not per call, and not via an environment variable.
  • ONNX Runtime Web path classifies correctly under the phase 2 Pyodide harness.
  • Browser and native backends agree on the same input to a stated, justified tolerance.
  • Synchronous entry under Emscripten fails immediately with a message naming the async entry point.
  • return_com=True still yields a replayable history command.
  • List-of-datasets recursion at pop_iclabel.py:38 still works on the async path.
  • GUI plus eegprep-console synchronization preserved; add or update tests/test_console_workspace.py coverage, per AGENTS.md.
  • CI runs the browser ICLabel parity test under Pyodide.
  • docs/source/ workflow docs explain the browser path and how a user invokes it from both the GUI and the console.
  • src/eegprep/resources/help/pop_iclabel.md updated if user-facing behavior changed.
  • Pre-commit, ruff, ruff format, ty clean.

/goal prompt

/goal Make ICLabel run in the browser through ONNX Runtime Web, with an await-able entry point that does not fork eegprep's public API.

Source of truth: src/eegprep/plugins/ICLabel/iclabel.py and pop_iclabel.py, phase 4's ONNX artifact, phase 2's Pyodide harness, and the EEGPrepSession GUI-plus-console contract in AGENTS.md. Read AGENTS.md first.

Constraints: no server-side execution; no parallel async copy of the pop_* surface; resolve the backend once from the platform rather than from an environment variable; preserve return_com, the GUI path, and list-of-datasets recursion.

Start by posting the async entry point design options on the issue and getting an answer. Do not implement before that is resolved.

Finish line: the browser backend classifies under the Pyodide harness and agrees with native onnxruntime at a justified tolerance; the synchronous path fails fast under Emscripten with a message naming the async entry point; console and GUI stay synchronized with tests/test_console_workspace.py coverage; CI runs the browser parity test; workflow docs and pop_iclabel.md updated.

Report any review finding you chose not to fix, with the reason.

Activity

  1. added
    phase
    on Sep 17, 2026
  2. neuromechanist commented on Sep 17, 2026

    @neuromechanist
    MemberAuthor

    🤖 Phase 5 async-seam design gate — proposal for approval before implementation

    I inspected the current ICLabel, GUI, console, session, Pyodide, test, and help contracts on feature/issue-378-phase5-iclabel-web at 9057bd0e. The load-bearing facts are:

    • iclabel() prepares the four-way augmented feature batch, transposes to the three NCHW inputs, makes one synchronous network call, then performs the existing output reshape/mean and attaches the seven-class result (src/eegprep/plugins/ICLabel/iclabel.py:58-98). That is the natural inference seam.
    • pop_iclabel() owns the GUI dialog, version normalization, list-of-datasets recursion, ICA validation, and return_com history command (src/eegprep/plugins/ICLabel/pop_iclabel.py:15-44, :47-69, :72-79).
    • The native ONNX session is already lazy and module-cached (src/eegprep/plugins/ICLabel/iclabel_net_onnx.py:16-34); the actual call is synchronous at :50-57.
    • The console wrapper is synchronous today: it injects return_com=True, calls the function, and passes the result to the session bridge (src/eegprep/functions/adminfunc/console.py:197-259). The bridge stores EEG/history once and suppresses duplicate post-cell history (:383-397, :462-520).
    • The GUI dispatch currently keeps gui_action around a synchronous dispatch (src/eegprep/functions/guifunc/menu_actions.py:278-287); pop_iclabel is a normal multi-dataset pop action (:164-175, :233-255, :1082-1085, :1147-1150). The existing long-task helper runs a callable in a Qt worker thread (src/eegprep/functions/guifunc/long_task.py:35-45, :57-74), so it should not be assumed to be the ONNX Runtime Web Promise scheduler.
    • One EEGPrepSession is the source of truth for GUI and console state; CURRENTSET is an ordered 1-based selection, and store_current(..., index=...) supports committing a result back to explicit one-based slots (src/eegprep/functions/guifunc/session.py:129-140, :218-220, :222-260). The current docs require one shared session, one history append, and replayable commands (docs/source/user_guide/gui_console_session.rst:95-124).
    • The Phase 2 harness installs a local wheel through emfs: and runs the target script with await pyodide.runPythonAsync(...) (tools/pyodide/run_pyodide.mjs:123-141, :148-166). It does not yet provide an ONNX Runtime Web bridge. Existing ICLabel parity uses measured rtol=1e-4, atol=1e-5 (tests/test_iclabel.py:113-129).

    Option A — paired pure async APIs (recommended)

    Public entry points, in the existing modules:

    • async def iclabel_async(EEG, algorithm="default", engine=None) in src/eegprep/plugins/ICLabel/iclabel.py.
    • async def pop_iclabel_async(EEG, icversion=None, *, gui=None, renderer=None, engine=None, return_com=False) in src/eegprep/plugins/ICLabel/pop_iclabel.py.
    • Export both through the normal eegprep lazy API. Keep the existing native synchronous APIs unchanged except for the Emscripten guard below.

    Synchronous Emscripten contract:

    RuntimeError(
        "ICLabel synchronous entry points are unavailable under Emscripten; "
        "use await iclabel_async(...) or await pop_iclabel_async(...)."
    )
    

    Put the guard at the first executable line of both synchronous functions, before GUI display, EEG is None handling, deepcopy, ICA validation, or engine dispatch. This is intentionally an immediate, deterministic failure; MATLAB/Octave engine arguments do not bypass a browser execution boundary. The owner still needs to approve whether the EEG is None no-op should be the one exception, but the acceptance wording favors the strict guard.

    Behavior and session flow:

    • Share feature preparation, backend invocation, output post-processing, and metadata attachment between the sync and async low-level functions. pop_iclabel_async keeps the current dialog/version behavior and awaits iclabel_async; for a list it awaits each dataset sequentially, preserving input order and one return_com command.
    • Its async history result is explicit and replayable in an async-capable context: EEG = await pop_iclabel_async(EEG, 'default');. The native sync wrapper continues to emit its current EEG = pop_iclabel(EEG, 'default');. This means history is entry-point/context specific rather than one byte-for-byte command across native and browser runtimes.
    • Keep the plugin wrapper pure: do not pass EEGPrepSession into it. The browser GUI dispatcher captures session.selected_dataset_indices() before the await, begins the GUI action, schedules the coroutine on the browser/GUI event loop, and ends the action only in success/error/finally. On success it calls the existing session storage path with the captured explicit index list, then echo_command, store_current, add_history, notify_changed, and refresh. No session mutation or history append occurs before inference completes. Native GUI dispatch remains synchronous.
    • Add a narrow async console wrapper for pop_iclabel_async (not an async fork of every pop_*). It awaits the function, feeds the resolved (EEG, command) to the existing accept_pop_result path, and returns the same compact unpackable console result. Thus bare await pop_iclabel_async(EEG) auto-stores once, preserves scalar/list CURRENTSET, updates EEG/ALLEEG/LASTCOM/ALLCOM, and the existing post-cell hook does not append history twice. Because the emitted command contains await, execute_history_command() must gain an async-capable replay branch; its current raw exec implementation is synchronous (src/eegprep/functions/adminfunc/console.py:588-592). IPython top-level await can be the console-facing execution boundary.
    • The async GUI/console code must choose a stale-selection policy. Recommendation: capture the ordered 1-based slots at action start and commit back to those slots; abort-on-selection-change is safer but changes the existing multi-dataset workflow and needs a user-facing conflict policy.

    Backend and Promise boundary:

    Test plan:

    • Native unit coverage for iclabel_async and pop_iclabel_async; exact Emscripten fast-fail tests for both sync APIs; GUI dialog/list/return-com tests; async console tests covering one shared session, ordered list selection, one history append, and failed inference with no mutation.
    • Extend the Phase 2 harness with an async ICLabel script. First prove the Python await seam with a Promise-shaped bridge; then run the real onnxruntime-web bridge in the Node/browser harness, compare the same input/model against native, and report measured output differences using the existing tolerance rather than assuming parity. Add docs and src/eegprep/resources/help/pop_iclabel.md examples for the async command.

    Tradeoffs: this adds two narrowly scoped public names and one async-aware console/replay path, but preserves the current pure pop_*/session boundary and minimizes GUI/console drift. It has the clearest test seam for the existing one-network-call implementation.

    Option B — only expose iclabel_async; adapters own pop orchestration

    Public entry point: async def iclabel_async(...) in src/eegprep/plugins/ICLabel/iclabel.py; no public pop_iclabel_async. Both synchronous functions use this exact contract:

    RuntimeError(
        "ICLabel synchronous entry points are unavailable under Emscripten; "
        "use await iclabel_async(...) from the browser integration."
    )
    

    The GUI and console each call a shared private async coordinator in pop_iclabel.py, but the dialog, ICA check, list recursion, async history string, explicit CURRENTSET slot commit, and return_com handling are assembled outside the public pop wrapper. The console needs a special awaitable adapter; the GUI needs a main-loop completion callback and a long-lived begin_gui_action/end_gui_action pair. Backend selection and Promise handling are otherwise the same one-time sys.platform == "emscripten" design as Option A. The harness tests the private coordinator through GUI/console integration and tests iclabel_async directly at the Promise boundary.

    Tradeoff: only one new public symbol, but it moves the user-facing pop contract into two callers and makes it easier for GUI, console, and normal scripts to disagree about list order, return_com, or history replay. This is the smallest API but the highest drift risk.

    Option C — session-aware async pop coordinator

    Public entry point: async def pop_iclabel_async(EEG, icversion=None, *, session: EEGPrepSession, gui=None, renderer=None, engine=None, return_com=False) in src/eegprep/plugins/ICLabel/pop_iclabel.py. The low-level async model runner remains private in iclabel.py. The existing sync functions fail immediately with:

    RuntimeError(
        "ICLabel synchronous entry points are unavailable under Emscripten; "
        "use await pop_iclabel_async(..., session=session)."
    )
    

    The coordinator captures session.CURRENTSET, awaits sequential list inference, and commits through session.store_current(..., index=...) plus one history/notification transaction. GUI and console both pass their one shared session, so CURRENTSET, list recursion, and failure atomicity are centralized. The async command remains EEG = await pop_iclabel_async(EEG, 'default', session=session);; the console must avoid applying the returned EEG a second time.

    Backend resolution is still a one-time sys.platform == "emscripten" choice and the harness tests the session coordinator plus the real ORT Web Promise bridge. The tradeoff is architectural coupling: an EEGLAB-style processing wrapper currently returns a dataset and command without knowing the GUI/session, while this option imports and mutates the interactive session from the plugin layer and requires a special console path. It is attractive only if atomic session commit is more important than keeping processing and interactive state separated.

    Recommendation and decisions needed

    Recommend Option A. It follows the current separation: iclabel.py owns the single inference seam, pop_iclabel.py owns GUI/list/history semantics, EEGPrepSession remains the single state boundary, and the console bridge remains the single auto-store boundary. It also lets native callers keep today's synchronous API while browser callers use an explicitly awaitable API.

    Before implementation, please choose/approve:

    1. Option A, B, or C.
    2. The exact public names/modules and the exact RuntimeError message.
    3. The recommended browser history policy: async return_com commands containing await, with an async history-replay branch, versus a different platform-aware replay design.
    4. The stale-selection policy while inference is pending (recommend captured 1-based slots).
    5. The JS bridge/model transport and GUI event-loop integration contract; MATLAB/Octave and non-default model behavior under Emscripten should also be explicitly bounded.

    @arnodelorme please choose the option and approve the contract before Phase 5 implementation begins.

  3. neuromechanist commented on Sep 17, 2026

    @neuromechanist
    MemberAuthor

    🤖 Phase 5 is implemented in PR #384. It adds iclabel_async/pop_iclabel_async, fail-fast synchronous Emscripten entry points, the ONNX Runtime Web bridge, async GUI/console synchronization with stale-selection protection, and CI parity coverage. Local native-vs-Pyodide float32 parity is allclose: true for shape [32, 7] with max absolute difference 4.3213e-06 at rtol=1e-4/atol=1e-5. The corrected CI run has browser parity green and is finishing the existing one-thread ICA/platform jobs.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    phase

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions