[PR #4727] [MERGED] fix(server): adaptive sandbox IPC polling instead of fixed 25ms intervals #6480

Closed
opened 2026-10-23 04:10:49 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/4727
Author: @kolacheee
Created: 8/7/2026
Status: ✅ Merged
Merged: 8/7/2026
Merged by: @kolacheee

Base: staging ← Head: fix/4706-extension-ipc-idle-wakeups


📝 Commits (10+)

  • 45294c2 fix(server): adaptive sandbox IPC polling instead of fixed 25ms intervals
  • b1d7a87 Merge branch 'staging' into fix/4706-extension-ipc-idle-wakeups
  • 144ad82 fix(server): cap the runner's residual input, await the output-handle close, and await runner exit in the IPC regression cleanup
  • 6b08e8d fix(server): mark expectedStop before every host-initiated sandbox kill so specific errors survive the close handler
  • c8874af fix(server): guard the close handler's active-map delete, tolerate cleanup races in the drain, and warn on failed stop writes
  • d056141 fix(server): serialize sandbox cleanup behind the close handler's finalization promise
  • 16087bd fix(server): route startup-failure teardown through stopExtension and contain cleanup rejections in the close finalizer
  • 1f36e03 fix(server): skip the dead close-event wait when stopping an already-exited sandbox
  • c8e60b4 fix(server): never dispatch storage during the final drain and contain storage-reply failures
  • 6fa406b fix(server): never race fallback cleanup against close finalization, and gate storage dispatch on expectedStop

📊 Changes

5 files changed (+599 additions, -44 deletions)

View changed files

📝 package.json (+1 -1)
📝 packages/server/src/assets/personal-extension-runner.mjs (+41 -4)
📝 packages/server/src/services/extensions/personal-server-extension-runtime.ts (+223 -39)
➕ packages/server/src/services/extensions/sandbox-protocol.ts (+95 -0)
➕ scripts/regressions/extension-ipc.regression.ts (+239 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Closes #4706

Why this change

  • Each running personal server extension cost ~80 timer wakeups per second plus one flash write per second, continuously from boot: the host polled the sandbox output file every 25 ms and ran a 250 ms double-stat watchdog, while the runner polled its input file every 25 ms and heartbeat-wrote every second. On a phone-hosted (Termux) install with a server extension enabled this was the largest remaining passive drain from the mobile-battery investigation (#4628–#4631, #4704/#4705, #4707).
  • The file transport itself is untouched — it is the sandbox security design. Only the polling discipline changes.

What changed

  • Adaptive cadence on both sides (new pure module sandbox-protocol.ts + personal-server-extension-runtime.ts + personal-extension-runner.mjs): the fixed intervals are now self-scheduling timeout chains that poll at the old 25 ms only while traffic is flowing (startup handshake unsettled, or bytes/messages moved within the last 3 s) and drop to 1 s (host) / 250 ms (runner) at idle. Each side's send() flips the other direction back to hot, since a reply is expected — storage round-trips and the stop handshake keep today's latency. Steady-state wakeups drop from ~80/s to ~5/s per extension.

  • Heartbeat 1 s → 5 s (5× fewer flash writes) with the host's unresponsive threshold rescaled 5 s → 25 s — the same five-missed-beats multiple as before — and the watchdog cadence 250 ms → 1 s. CLEANUP_TIMEOUT_MS gains headroom (3 s → 3.5 s) for the runner's idle stop pickup.

  • Per-message size cap (red-team amendment from the issue): the host's MAX_PROTOCOL_BYTES check previously applied to the whole buffered chunk — a fair approximation at 25 ms, but at an idle cadence the buffer batches everything that arrived across the silence, so several individually-legal messages bursting after a quiet spell would have been killed as one "oversized message". Extraction now caps each message individually (newline index per line, residual buffer after extraction) via the pure extractProtocolLines.

  • Final drain on close (red-team amendment): handleClose now waits out any in-flight poll and runs one last read before closing the file handle, before the expectedStop check (so a drained fatal message attributes the exit correctly instead of racing the generic fallback), and before sandbox.cleanup() removes the directory.

  • Timer-handle hygiene (red-team amendment): the stored poller handles are reassigned on every tick of the chains — clearing a stale handle from a previous tick can't leave a live timer running. The runner's heartbeat interval remains the process-liveness anchor.

  • The runner inlines its constants (it's a standalone sandbox asset that cannot import server modules) with a sync comment; the regression pins the pairing.
    An adversarial review pass on this diff (verifier ran an A/B harness driving the real runner against a faithful host transcription) caught and fixed two things:

  • The new close-time drain could resolve the startup handshake from a child that had already crashed right after ready (unhandled rejection → fatal → exit): load() would then insert the dead sandbox into the active set, report it as running, and a later stop-all would fail on its deleted input file — aborting shutdown of the healthy extensions (reproduced 6/6 pre-fix). load() now refuses to activate a sandbox whose child has exited or is marked stopped (surfacing the drained fatal's message instead), and a failed stop-write no longer aborts the kill/cleanup path.

  • Two of the regression's "no fixed 25 ms interval" source pins were regexes that could not match the code they forbid (a negated character class can't cross the ) in () => void …) — assertions that could never fail. Replaced with exact-substring forbids plus positive pins asserting the chains exist and their delay expressions actually consult the idle constants.

  • New regression (extension-ipc.regression.ts, wired into regression:issues): extraction semantics (a legal burst is not oversized; per-line and residual caps; split-message reassembly), cadence floors (no 25 ms idle timer or 250 ms watchdog can quietly return), the five-missed-beats multiple, host/runner constant sync via source scan — plus a live end-to-end of the real runner under plain node: start handshake, extension log delivery, a stop sent after the hot window lapses is picked up within the idle-cadence bound, clean exit 0.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

  • pnpm check and the full regression:issues lane pass locally, including the new IPC regression's live runner pass (real personal-extension-runner.mjs under plain node: handshake, log delivery, stop-after-silence within the idle bound, exit 0).
  • The built dist/assets/personal-extension-runner.mjs matches source byte-for-byte after pnpm build (the build copies assets).

Still to verify manually (contributor to-do — Windows cannot run the OS-sandboxed spawn, so the full host+sandbox pair needs a Linux/Termux pass):

  • Manually verify on Termux/Linux with a real server extension: it starts (Sandboxed … with … log), storage get/patch round-trips work, logs stream, disable/enable restarts it cleanly, and the sandbox dir shows the new cadences (heartbeat mtime every ~5 s; input/output stats quiet at idle).
  • Manually verify an unresponsive extension (e.g. busy-loop in extension code) is still killed by the watchdog within ~25 s.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

No user-facing docs impact — internal IPC cadence; no configuration surface changed.

Summary by CodeRabbit

  • Bug Fixes

    • Improved extension communication reliability when messages arrive together or are split across reads.
    • Prevented oversized messages from disrupting communication.
    • Improved startup and shutdown handling, including final output delivery and more tolerant cleanup.
    • Reduced unnecessary background activity while maintaining responsive input and output handling.
    • Improved heartbeat and watchdog behavior for more reliable process monitoring.
  • Tests

    • Added comprehensive regression coverage for communication, polling, message limits, and complete extension workflows.
    • Expanded the regression suite to include extension communication checks.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/4727 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/7/2026 **Status:** ✅ Merged **Merged:** 8/7/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/4706-extension-ipc-idle-wakeups` --- ### 📝 Commits (10+) - [`45294c2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/45294c2515383e9fe9cd80e8cf0f54af1b352488) fix(server): adaptive sandbox IPC polling instead of fixed 25ms intervals - [`b1d7a87`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b1d7a876a8f28aba7023f5d67d12ceefbd0529b5) Merge branch 'staging' into fix/4706-extension-ipc-idle-wakeups - [`144ad82`](https://github.com/Pasta-Devs/Marinara-Engine/commit/144ad8269d54b2363dacc5f36be8a30d4e157892) fix(server): cap the runner's residual input, await the output-handle close, and await runner exit in the IPC regression cleanup - [`6b08e8d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6b08e8dc2634b4122cc58d9bf296c68b3bde8935) fix(server): mark expectedStop before every host-initiated sandbox kill so specific errors survive the close handler - [`c8874af`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c8874af1024805e6b6dbb944af3471af6503acfc) fix(server): guard the close handler's active-map delete, tolerate cleanup races in the drain, and warn on failed stop writes - [`d056141`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d0561418501d03801f27157ba9f2ba4ef963f314) fix(server): serialize sandbox cleanup behind the close handler's finalization promise - [`16087bd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/16087bda0c038de288c60897093bdb9549886243) fix(server): route startup-failure teardown through stopExtension and contain cleanup rejections in the close finalizer - [`1f36e03`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1f36e030fa91a51a70ddc8f7708dba1a9debb46d) fix(server): skip the dead close-event wait when stopping an already-exited sandbox - [`c8e60b4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c8e60b43252d9bddb5e5e548d531e9c39b26a6a0) fix(server): never dispatch storage during the final drain and contain storage-reply failures - [`6fa406b`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6fa406bb2f4499b3f0a377cf229048bb32b21339) fix(server): never race fallback cleanup against close finalization, and gate storage dispatch on expectedStop ### 📊 Changes **5 files changed** (+599 additions, -44 deletions) <details> <summary>View changed files</summary> 📝 `package.json` (+1 -1) 📝 `packages/server/src/assets/personal-extension-runner.mjs` (+41 -4) 📝 `packages/server/src/services/extensions/personal-server-extension-runtime.ts` (+223 -39) ➕ `packages/server/src/services/extensions/sandbox-protocol.ts` (+95 -0) ➕ `scripts/regressions/extension-ipc.regression.ts` (+239 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. ## Linked issue Closes #4706 ## Why this change - Each running personal **server** extension cost ~**80 timer wakeups per second plus one flash write per second, continuously from boot**: the host polled the sandbox output file every 25 ms and ran a 250 ms double-stat watchdog, while the runner polled its input file every 25 ms and heartbeat-wrote every second. On a phone-hosted (Termux) install with a server extension enabled this was the largest remaining passive drain from the mobile-battery investigation (#4628–#4631, #4704/#4705, #4707). - The file transport itself is untouched — it *is* the sandbox security design. Only the polling discipline changes. ## What changed - **Adaptive cadence on both sides** (new pure module [`sandbox-protocol.ts`](packages/server/src/services/extensions/sandbox-protocol.ts) + [`personal-server-extension-runtime.ts`](packages/server/src/services/extensions/personal-server-extension-runtime.ts) + [`personal-extension-runner.mjs`](packages/server/src/assets/personal-extension-runner.mjs)): the fixed intervals are now self-scheduling timeout chains that poll at the old 25 ms only while traffic is flowing (startup handshake unsettled, or bytes/messages moved within the last 3 s) and drop to **1 s (host) / 250 ms (runner)** at idle. Each side's `send()` flips the other direction back to hot, since a reply is expected — storage round-trips and the stop handshake keep today's latency. Steady-state wakeups drop from ~80/s to ~5/s per extension. - **Heartbeat 1 s → 5 s** (5× fewer flash writes) with the host's unresponsive threshold rescaled 5 s → 25 s — the same five-missed-beats multiple as before — and the watchdog cadence 250 ms → 1 s. `CLEANUP_TIMEOUT_MS` gains headroom (3 s → 3.5 s) for the runner's idle stop pickup. - **Per-message size cap** (red-team amendment from the issue): the host's `MAX_PROTOCOL_BYTES` check previously applied to the whole buffered chunk — a fair approximation at 25 ms, but at an idle cadence the buffer batches everything that arrived across the silence, so several individually-legal messages bursting after a quiet spell would have been killed as one "oversized message". Extraction now caps each message individually (newline index per line, residual buffer after extraction) via the pure `extractProtocolLines`. - **Final drain on close** (red-team amendment): `handleClose` now waits out any in-flight poll and runs one last read **before** closing the file handle, before the `expectedStop` check (so a drained `fatal` message attributes the exit correctly instead of racing the generic fallback), and before `sandbox.cleanup()` removes the directory. - **Timer-handle hygiene** (red-team amendment): the stored poller handles are reassigned on every tick of the chains — clearing a stale handle from a previous tick can't leave a live timer running. The runner's heartbeat interval remains the process-liveness anchor. - The runner inlines its constants (it's a standalone sandbox asset that cannot import server modules) with a sync comment; the regression pins the pairing. An adversarial review pass on this diff (verifier ran an A/B harness driving the **real runner** against a faithful host transcription) caught and fixed two things: - The new close-time drain could resolve the startup handshake from a child that had already crashed right after `ready` (unhandled rejection → `fatal` → exit): `load()` would then insert the dead sandbox into the active set, report it as **running**, and a later stop-all would fail on its deleted input file — aborting shutdown of the *healthy* extensions (reproduced 6/6 pre-fix). `load()` now refuses to activate a sandbox whose child has exited or is marked stopped (surfacing the drained `fatal`'s message instead), and a failed stop-write no longer aborts the kill/cleanup path. - Two of the regression's "no fixed 25 ms interval" source pins were regexes that could not match the code they forbid (a negated character class can't cross the `)` in `() => void …`) — assertions that could never fail. Replaced with exact-substring forbids plus positive pins asserting the chains exist *and* their delay expressions actually consult the idle constants. - **New regression** ([`extension-ipc.regression.ts`](scripts/regressions/extension-ipc.regression.ts), wired into `regression:issues`): extraction semantics (a legal burst is not oversized; per-line and residual caps; split-message reassembly), cadence floors (no 25 ms idle timer or 250 ms watchdog can quietly return), the five-missed-beats multiple, host/runner constant sync via source scan — plus a **live end-to-end of the real runner under plain `node`**: start handshake, extension log delivery, a stop sent after the hot window lapses is picked up within the idle-cadence bound, clean exit 0. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes - `pnpm check` and the full `regression:issues` lane pass locally, including the new IPC regression's live runner pass (real `personal-extension-runner.mjs` under plain `node`: handshake, log delivery, stop-after-silence within the idle bound, exit 0). - The built `dist/assets/personal-extension-runner.mjs` matches source byte-for-byte after `pnpm build` (the build copies assets). Still to verify manually (contributor to-do — Windows cannot run the OS-sandboxed spawn, so the full host+sandbox pair needs a Linux/Termux pass): - Manually verify on Termux/Linux with a real server extension: it starts (`Sandboxed … with …` log), storage get/patch round-trips work, logs stream, disable/enable restarts it cleanly, and the sandbox dir shows the new cadences (heartbeat mtime every ~5 s; input/output stats quiet at idle). - Manually verify an unresponsive extension (e.g. busy-loop in extension code) is still killed by the watchdog within ~25 s. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) No user-facing docs impact — internal IPC cadence; no configuration surface changed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Improved extension communication reliability when messages arrive together or are split across reads. - Prevented oversized messages from disrupting communication. - Improved startup and shutdown handling, including final output delivery and more tolerant cleanup. - Reduced unnecessary background activity while maintaining responsive input and output handling. - Improved heartbeat and watchdog behavior for more reliable process monitoring. - **Tests** - Added comprehensive regression coverage for communication, polling, message limits, and complete extension workflows. - Expanded the regression suite to include extension communication checks. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:10:49 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#6480
No description provided.