Skip to content

feat: memory budget per step, run card heap report and whole-recording Welch recipe (E5.1, E5.2) - #699

Merged
neuromechanist merged 14 commits into
developfrom
feature/issue-668-memory-budget
Nov 11, 2026
Merged

neuromechanist merged 14 commits into
developfrom
feature/issue-668-memory-budget

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

E5.1 (browser memory budget) and E5.2 (whole-recording power spectrum) of the NEMAR AI experience plan, on top of the merged plan-first prompt (E2.2) and the plan card's est_peak_mb line (E2.3).

E5.1, widget and runtime

  • Settings has a Browser memory field (256 MB, 512 MB default, 1 GB, 2 GB; 44 px choices after the model fields; Cancel and Save unchanged), stored as memoryBudgetMb in the user settings. A stored value that is not one of the four reads as 512.
  • page_context.memory_budget_mb is sent on /chat and /chat/resume only from a page whose browser runtime has loaded. page_context is still absent when nothing else is set and there is no runtime. On /chat the page context is now built after the wait for the client tools, since that is when the runtime is known.
  • The worker reads Pyodide's heap (pyodide._module.HEAPU8.byteLength) after each run and sends it as heap_bytes beside the result. It is not a ClientToolResult field and never reaches the server (CLIENT_TOOL_RESULT_FIELDS is unchanged); PyodideRuntime#heapBytes(callId) hands it to the widget, which stores heapMb and the budgetMb the run was under on the run record and in the history normalizer.
  • The run card shows Heap N MB of B MB and, when N is more than B, a warning style and a line naming the step ("Step 2, Epoch the EEG, used more than the 512 MB budget. ..."; "This run" for a run no plan covers). Reload and History restore it.
  • The plan card keeps "Largest step needs about N MB" and warns, while the plan is a draft, when it is more than the budget.
  • New pure module frontend/osa-memory.js, exported as OSARuntime.memory; the runtime bundle and its integrity line are rebuilt.

E5.1, backend

  • PageContext (API) and the agent dataclass take memory_budget_mb, restricted to 256, 512, 1024 or 2048; any other value is a 422 on /chat and /chat/resume.
  • The prompt gets its own ## Browser memory budget paragraph, rendered for a budget-only request too. NEMAR's plan_first_instructions require est_peak_mb not to exceed it.

E5.2

  • NEMAR's Power spectrum recipe and the execute_code description now loop per channel over chunks of min(2**28 // nperseg, budget_mb * 2**20 // 160) samples, cut so that together they hold exactly the segments one welch call over the whole channel would, averaged weighted by segment count. The "cut short, say how many seconds" sentence is gone; the recipe asserts every channel averaged every segment and prints how many segments and seconds it covered.
  • frontend/test-data-lane.js runs the block under real Pyodide: (a) chunked equals one welch call per channel to 1e-9 (250, 128.5 and 1000 Hz, one chunk and many) and equals a by-hand numpy estimate; (b) a 50-minute signal at 250 Hz, which one call refuses, has all 2,999 segments counted on every channel and a tone carried only by its last tenth is found; (c) the old limits remain as controls.
  • docs/community-browser-runtime.md, docs/community-widget.md, CHANGELOG.md updated; tests/test_assistants/test_nemar_runtime.py no longer pins the old strings.

Recording used for E5.2

on002718 sub-002 FaceRecognition was read, for real, not a stand-in. zarr.nemar.org serves it (group eeg_250hz: 74 channels, 747,750 samples, 2,991 s). I read it through NEMAR's production runtime config and prelude on real Pyodide 0.29.5 under Bun, the same worker-core lane test-data-lane.js uses, with the recipe taken verbatim from the prompt:

  • read_window of the whole recording: 11.7 s (74 x 747,750 float64, 443 MB).
  • One welch call over a channel: refused ("array is too big"), as the controls say.
  • The recipe: 0.7 s, 2,990 segments on every channel in chunks of 2,146, 2,991 s covered of 2,991 s.
  • Against an independent numpy estimate that shares no code with SciPy (three channels): largest difference 1.3e-15 of the spectrum's peak.
  • The runtime's heap after the run was 1,155 MB, which is more than a 512 MB budget: the read alone is 443 MB. The recipe's last paragraph tells the model to read in pieces when the read does not fit the budget.

Caveat: this was Pyodide under Bun, not headless Chrome, and the one-off script that ran it is not committed (it reads a live host, so it cannot run in CI). The CI evidence is the synthetic 50-minute test above.

Closes

Closes #668
Closes #669

GitHub only closes these on the default branch, so they will not close on merge into develop; the project manager closes them after the squash merge with gh issue close N --reason completed .... #669's verification (a whole-recording spectrum on on002718 sub-002) was met as described above, with the caveat that it ran under Bun, not in a browser.

Commands run

  • uv sync --all-extras && bun install: ok
  • bun frontend/test-widget-memory-budget.js: 152 passed, 0 failed
  • bun frontend/test-widget-settings.js: 184 passed; test-widget-run-card.js: 261 passed; test-widget-plan-card.js: 264 passed
  • bun frontend/test-runtime-lifecycle.js: 192 passed; test-worker-core.js: 227 passed; test-data-lane.js: 152 passed
  • bun scripts/build-runtime-bundle.js && bun scripts/build-runtime-bundle.js --check: current (109484 bytes, sha384-0SZW+yBsJvcAmUfMq94z+uml6IwbQY2M1Hl9bxCcuNNqviHEhKJdIDLRjfPzhxsU); bun frontend/test-runtime-bundle.js: 39 passed
  • every other frontend/test-*.js suite: no failures
  • uv run pytest tests/test_agents/test_page_context.py tests/test_api/test_page_context.py tests/test_assistants/test_nemar_runtime.py tests/test_frontend -q: 351 passed
  • uv run pytest tests -m "not llm" (ignoring tests/test_core/test_llm_service.py, which fails to import under this Python 3.14 environment with a pydantic v1 error): 5,700 passed, 1 failed (tests/test_tools/test_hed_suggest.py::test_real_program_suggests_a_schema_tag, a HED tool call that needs a live service and touches nothing here)
  • uv run ruff check . && uv run ruff format --check .: clean

Deviations from the brief

  • The run record stores budgetMb as well as heapMb, so a card read later shows the budget the run had, not whatever Settings says now. Additive.
  • A chunk's span is (k - 1) * hop + nperseg samples with hop = nperseg - nperseg // 2, which is the brief's (m + 1) * hop and nperseg // 2 for even nperseg and exact for an odd one (128.5 Hz is tested).
  • The plan card warning shows on a draft only, where the reader can still edit the steps or raise the budget; a decided plan does not show it.
  • The Settings field also shows "Last step used N MB of B MB" with a bar, from the board's BROWSER MEMORY block.
  • The heap line and the plan warning need the runtime bundle, so a chat restored before it loads gets them when it does (the widget already redraws then). The four sizes and the heap limit are copied into the widget for reading saved settings, and the test holds the copies to osa-memory.js and to the server's list.
  • The diff is just under 1,500 lines inserted (about 1,450 without the minified bundle), so E5.2 stays in this PR rather than split into feature/issue-669-chunked-welch.
  • No Biome config exists in the repo, so no JS lint ran.

…the prompt (E5.1)

PageContext takes memory_budget_mb (256, 512, 1024 or 2048; anything else is a 422)
on /chat and /chat/resume, the agent dataclass carries it, and a budget-only request
renders its own '## Browser memory budget' section. NEMAR's plan-first text now
requires est_peak_mb to stay within it.

Tested: pytest on the page-context, plan-first and prompt tests, including the real
assistant factory and 422s over HTTP.
The worker measures Pyodide's memory after every run and sends heap_bytes beside the
result. PyodideRuntime keeps it by call id (heapBytes), outside ClientToolResult, so
the wire result is unchanged. New osa-memory.js holds the budget sizes, the heap
report and the warning text, exported as OSARuntime.memory; the bundle and its
integrity line are rebuilt.

Tested: test-worker-core.js (real Pyodide), test-runtime-lifecycle.js, bundle check.
…g (E5.1)

Settings gets a Browser memory field (256 MB, 512 MB default, 1 GB, 2 GB; 44 px
choices, Cancel and Save unchanged), stored as memoryBudgetMb with an invalid value
reading as 512. getPageContext sends memory_budget_mb on /chat and /chat/resume only
when the page has the browser runtime. Each run record keeps heapMb and the budget it
ran under; the run card shows 'Heap N MB of B MB' and, over budget, a warning naming
the step, restored by reload and History. The plan card warns while a draft's largest
step exceeds the budget.

Tested: new test-widget-memory-budget.js, registered in the frontend-tests job;
settings, plan-card, run-card and history suites still pass.
…ding (E5.2)

Replaces the capped one-channel recipe with a per-channel loop over chunks that start
every m * hop samples and span exactly their segments, averaged weighted by segment
count, so the result equals one welch call over the whole channel. The chunk is the
smaller of 2**28 // nperseg and what the reader's memory budget leaves room for; the
'cut short, say how many seconds' sentence is gone and the recipe prints the segments
and seconds it covered. The execute_code description follows.

Tested: test-data-lane.js on real Pyodide (chunked equals one welch call to 1e-9 at
250, 128.5 and 1000 Hz, a by-hand estimate, a 50-minute signal covered in full, the
old limits as controls) and the NEMAR config tests.
… (E5.1, E5.2)

Documents the Browser memory setting, the page_context field, the heap line and its
warning, and the chunked Welch recipe with the on002718 measurement and what was used
for it. CHANGELOG [Unreleased] updated.

Docs only; the suites they describe are run separately.
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-668-memory-bud-demo.osc.earth
Branch feature/issue-668-memory-budget
Commit 5885d74

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

…red sizes; budget tests use the scripted chat model (tested)
…olor token, page context captured at send time (tested)
…the recording; data lane runs it against one welch call (tested)
…asurement, real-recording script (not run in CI)
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 1: every finding has an outcome. Fix commits are on this branch (e6de8c9, bef22d1, 85564a9, 14884cf, 2ae78f4). Rerun: all bun suites the frontend-tests job runs (including test-data-lane.js, test-worker-core.js, test-widget-memory-budget.js, and build-runtime-bundle.js --check), ruff check and ruff format --check, and pytest tests/test_frontend tests/test_api tests/test_agents tests/test_assistants (all passed except test_documentation_urls_accessible[brainstorm], a live URL check unrelated to this change).

  • Over-budget warning blames a step for a high-water mark (important): fixed. heapReport now takes the previous run's heap (kept on the run record as heapBeforeMb). The run that took the heap past the budget, or grew it further, is named and styled as before; a run that reports the same figure as the run before it says "The runtime is still holding N MB from earlier steps; its memory does not shrink between runs." in the plain style. One deviation from the suggested rule: "grew" is heap !== previous rather than heap > previous, because a smaller figure than the previous one can only belong to a runtime started since (a reload), whose first over-budget run did grow it. The Settings row is now "Runtime memory after the last step". New widget tests run three and four consecutive runs, check the restore after a reload, and the pure-logic cases.
  • Piecewise read under-specified and untested (important): fixed. The recipe is now written out as code: it reads the recording in pieces (one read_window each, sized from the runtime's limit and the budget), calls welch on one channel of a piece at a time, carries the sums across pieces, and takes total from the group's n_samples, never from a piece; it asserts each read came back full and used == total. test-data-lane.js runs the block as written (its one read answered from an array in memory) against one welch call per channel to 1e-9 and a by-hand estimate, with a 1 MB budget forcing many pieces, checks that pieces start at multiples of m * hop, no read passes a quarter of the budget, and a 50-minute signal is covered whole. I also ran it on the real on002718 recording (committed script below).
  • PageContext.memory_budget_mb is a bare int (important): fixed. Typed as Literal[256, 512, 1024, 2048] | None, with a __post_init__ that raises ValueError for anything else, and a test that the sizes equal the API model's. create_assistant(page_context=PageContext(memory_budget_mb=300)) now raises.
  • Measurement misstated (important): fixed. The docs, CHANGELOG and recipe comment now say 45.6 MB for 536,870 samples (89 bytes per sample; 81 at 268,435), and that the 160-byte allowance is about 1.8 times that. The real-recording run also showed the recipe's share was too generous (heap came to about three times the read plus about 100 MB), so a piece now holds a quarter of the budget; the heap after the recipe on on002718 is 275, 452 and 805 MB for the 256 MB, 512 MB and 1 GB budgets, in the docs table (the 256 MB case is a little over, and the docs say why).
  • Stale docs (important): fixed. community-widget.md line 734 now says "when there is anything to send"; the request table has a memory_budget_mb row (sent regardless of the Share page URL toggle, only by a page with the runtime loaded and tools declared); the enable_page_context: false sentence covers the budget.
  • Contrast of the Settings bar (important): fixed. One token, --osa-warn (#b45309 light, #fbbf24 dark), on the widget root and its dark variant; the bar, the run card and the plan card all read it, and a test holds that no other rule writes the color. The Settings text also gets a screen-reader-only "(over budget)".
  • Inconsistent units (suggestion): fixed. Warnings and the Settings row use the same N MB helper as the heap line (mbLabel); only the four Settings choices read "1 GB" and "2 GB".
  • getPageContext() after the await (suggestion): fixed. The URL, dataset and carried move are captured when the question is sent; only the budget is added after the wait, and only when the request declares client tools, so a streaming-off request states none. New test for the streaming-off case.
  • MagicMock in TestMemoryBudgetInSystemPrompt (suggestion): fixed. Uses ScriptedChatModel from tests/helpers/chat_models.py. Older classes in that file that use the same MagicMock pattern are code this PR did not touch and were left alone.
  • One-off on002718 measurement not reproducible (suggestion): fixed. frontend/browser-harness/spectrum-real-recording.mjs extracts the block from NEMAR's prompt and runs it on the real recording over zarr.nemar.org under Bun (not a browser, and it says so), then checks it against a by-hand estimate; it needs the network, so CI does not run it. The docs give the command line and its output.
  • budget_mb term rarely binds (suggestion): fixed by keeping it and making it matter. The piece now counts every channel's read, so the budget binds at EEG rates with many channels (33 channels at 250 Hz and 256 MB: 158,282 samples against the limit's 536,870), and the data lane asserts that. The literal stays the one number the model edits besides GROUP; the prose says so and test_nemar_runtime.py and the swap check in the data lane hold it.

…ut; execute_code description teaches reading in pieces (tested)
…t comment, changelog capitalization (comment and docs only; tests rerun)
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 2 outcomes (fixes pushed to this branch; tests rerun: test-widget-memory-budget, test-data-lane, test-widget-plan-card, test-widget-history-panel, test-widget-notebook-entry, test-runtime-bundle, the bundle --check, and the assistants, frontend and page-context pytest suites; ruff check is clean).

  • Important: held-heap blame misattributed across chats - fixed. The previous heap now comes from the runtime (lastReportedHeapMb, kept beside browserRuntime), not from the chat on screen, so it survives New chat and History; a restarted runtime still reads as growth because its figure is smaller. New test: a 1155 MB step in chat A, a new chat, print(1), expects the held wording and no warning (it fails with the old chat-scoped lookup).
  • Suggestion: "plain style" claim for the held line - fixed in code, not docs. The held line is now a plain osa-run-card-note (osa-run-card-heap-held); the amber box is for the run that grew the heap only. Tests check the held line is not inside .osa-run-card-memory-warning. Docs and comment reworded.
  • Suggestion: stale execute_code description - fixed. The description now says to read the recording in pieces sized by the reader's budget and welch's limit, call welch on one channel of a piece at a time, and average by segment count. Docs line and test pins (which now also assert the old wording is gone) updated.
  • Suggestion: recipe block not self-contained - fixed. The block opens with import eegprep_lean, index = await eegprep_lean.read_index("DATASET_ID") and store = index.store("RECORDING_PATH"), listed beside GROUP in the replacement sentence, and prints the labels it left out. The data lane test checks the block opens its own read and swaps those three lines for the in-memory stand-in; the real-recording script fills the new placeholders.
  • Suggestion: small leftovers - fixed. Heap comment re-wrapped, getPageContext comment says the budget goes only with withBudget, and "They" is capitalized in the CHANGELOG.

No findings rejected or filed as new issues.

@neuromechanist

Copy link
Copy Markdown
Member Author

Project manager verdict: ready to merge. The branch conflicted with develop in CHANGELOG.md; resolved by keeping both entries (merge commit 1065e2c), bundle check, memory-budget, data-lane, bundle, run-card, plan-card and settings suites, metrics and page-context pytest and ruff all pass. Every check in gh pr checks is green (Lint, Test 3.11 and 3.12, Frontend Tests, Docker, notebook site). Every review finding from rounds 1 and 2 has an outcome. All six acceptance criteria are met per the diff and tests. Merge was not performed by this run (blocked by the permission classifier); #668 and #669 remain to be closed after the squash merge.

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