From 0a33001e3e62857b20c95214e1e37bfcddcf0586 Mon Sep 17 00:00:00 2001 From: autodev-bot Date: Tue, 30 Jun 2026 23:47:20 +0800 Subject: [PATCH] test(memos-local-plugin): pin bridge.cts startup ordering invariant (#1747) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue #1747 reported that the Hermes Python adapter's first `session.open` RPC times out (30s default) when MemOS bridge starts with dirty orphan episodes from a previous chat — `core.init()` was running orphan-episode recovery (LLM-driven reward grading, 10-60+ seconds) while the stdio JSON-RPC read loop was not yet attached, so the parent process's RPC frames sat unread in the pipe buffer until asyncio.TimeoutError fired. The structural fix (start stdio before `await core.init()`) already landed in commit 7c6bd250 (May 2026, "fix(memos-local-plugin): start stdio before host LLM fallback"), motivated by a different concern but structurally identical to what #1747 asks for. This change locks the fix in place so a future refactor cannot silently undo it. Three small additions, no runtime behavior change: - bridge.cts: expand the rationale comment at the ordering site (now documents BOTH host LLM fallback AND #1747's Python adapter timeout scenarios side-by-side, with an explicit link to the new test). - bridge/methods.ts: mark RPC_METHODS.CORE_INIT as deprecated in its docblock — no in-tree adapter sends it (#1747 correctly flagged this as dead code). Dispatch branch retained for wire-contract backward compatibility. - tests/unit/bridge/bridge-startup-ordering.test.ts: new source-level regression test (2 cases) asserting `stdio = startStdioServer({ core })` appears before `await core.init();` and stays inside the `if (!args.daemon)` guard. Verified red-on-bug / green-on-fix by programmatically swapping the call sites. All bridge unit tests pass (17/17). Environment-independent suites pass (82/82). The 2 pre-existing storage-layer failures on the base branch are unrelated (confirmed via `git stash`). `tsc --noEmit` clean. Refs: #1747 --- apps/memos-local-plugin/bridge.cts | 36 ++++++++-- apps/memos-local-plugin/bridge/methods.ts | 10 +++ .../bridge/bridge-startup-ordering.test.ts | 70 +++++++++++++++++++ 3 files changed, 110 insertions(+), 6 deletions(-) create mode 100644 apps/memos-local-plugin/tests/unit/bridge/bridge-startup-ordering.test.ts diff --git a/apps/memos-local-plugin/bridge.cts b/apps/memos-local-plugin/bridge.cts index 81848acf7..09f569fb5 100644 --- a/apps/memos-local-plugin/bridge.cts +++ b/apps/memos-local-plugin/bridge.cts @@ -318,12 +318,36 @@ async function main(): Promise { | ReturnType["startHeartbeat"]> | undefined; - // In stdio mode the host fallback path is a reverse JSON-RPC request - // over the same pipe as normal bridge traffic. `core.init()` may - // recover dirty episodes and run reflection/reward/L2/skill work; if - // that work hits a broken primary skill-evolver model, the LLM facade - // can fall back to host before init returns. Start stdio first so that - // fallback has a transport instead of tripping the lazy bridge guard. + // ─── Startup ordering invariant (issue #1747 + host LLM fallback) ─── + // + // `startStdioServer({ core })` MUST run before `await core.init()`. + // Two independent failure modes if this ordering is reversed: + // + // 1. Host LLM fallback (original motivation for this ordering): + // `core.init()` may recover dirty episodes and run + // reflection/reward/L2/skill work; if that work hits a broken + // primary skill-evolver model, the LLM facade can fall back to + // host before init returns. Starting stdio first gives the + // fallback a transport instead of tripping the lazy bridge guard. + // + // 2. Python adapter `session.open` timeout (issue #1747): + // `core.init()` synchronously scans `episodes WHERE status='open'` + // and recovers stale rows via `recoverOpenEpisodesAsSessionEnd` + // + `recoverDirtyClosedEpisodes` — both of which call the LLM + // and routinely take 10-60+ seconds when a previous chat left + // orphan episodes behind. The Hermes Python adapter's + // `_open_session()` default timeout is 30 s. If stdio starts + // after init, the parent writes `session.open` into the bridge's + // stdin and the Python side gets `asyncio.TimeoutError` before + // the read loop is attached. By starting stdio first, the read + // loop is alive immediately — `core.openSession()` is safe to + // serve pre-init because it depends only on the SQLite handle + // and event bus that `bootstrapMemoryCoreFull()` already + // provisioned. (`ensureLive()` only blocks on `shutDown`, not + // on `initialized`.) + // + // The invariant is pinned by + // `tests/unit/bridge/bridge-startup-ordering.test.ts`. if (!args.daemon) { stdio = startStdioServer({ core }); bridgeStatus?.markConnected(); diff --git a/apps/memos-local-plugin/bridge/methods.ts b/apps/memos-local-plugin/bridge/methods.ts index 3c61f75b3..1f3583746 100644 --- a/apps/memos-local-plugin/bridge/methods.ts +++ b/apps/memos-local-plugin/bridge/methods.ts @@ -104,6 +104,16 @@ export function makeDispatcher( switch (method) { // ── lifecycle ── + // CORE_INIT is retained for backward compatibility with any + // out-of-tree adapter that might still send it, but it is + // **deprecated** for in-tree use. The bridge always calls + // `core.init()` in-process during `bridge.cts::main()` — see + // the ordering invariant there (also enforced by + // `tests/unit/bridge/bridge-startup-ordering.test.ts`). No + // in-tree stdio adapter (OpenClaw, Hermes Python) sends this + // RPC. Issue #1747 flagged it as dead code; we keep the + // dispatch branch to avoid a wire-contract break and revisit + // removal once telemetry confirms zero callers. case RPC_METHODS.CORE_INIT: await core.init(); return { ok: true }; diff --git a/apps/memos-local-plugin/tests/unit/bridge/bridge-startup-ordering.test.ts b/apps/memos-local-plugin/tests/unit/bridge/bridge-startup-ordering.test.ts new file mode 100644 index 000000000..7f83255ec --- /dev/null +++ b/apps/memos-local-plugin/tests/unit/bridge/bridge-startup-ordering.test.ts @@ -0,0 +1,70 @@ +/** + * bridge.cts startup-ordering regression guard for issue #1747. + * + * Issue summary: when `core.init()` ran before `startStdioServer({ core })` + * in `bridge.cts`'s non-daemon (stdio) startup path, orphan-episode + * recovery (LLM-driven reward grading inside `core.init()`) could take + * 10-60+ seconds. While that ran, the stdio JSON-RPC read loop was not + * yet attached to `process.stdin`, so the Hermes Python adapter's + * `session.open` RPC sat unread in the pipe buffer until its 30 s + * `_open_session()` timeout fired with `asyncio.TimeoutError`. + * + * The fix landed in commit 7c6bd250 (May 2026) — `startStdioServer` now + * runs first. This test pins that invariant so a future refactor can't + * silently re-introduce the race. + * + * Why source-level (rather than runtime): `bridge.cts` is a top-level + * executable script — refactoring it into an injectable function just + * to runtime-test the ordering would be a much larger change than the + * invariant deserves. A source-level assertion catches the regression + * at the moment a developer rearranges the ordering, which is exactly + * what the issue asks us to prevent. + */ +import { describe, expect, it } from "vitest"; +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const BRIDGE_CTS_PATH = resolve(HERE, "..", "..", "..", "bridge.cts"); + +describe("bridge.cts startup ordering (regression guard for #1747)", () => { + const src = readFileSync(BRIDGE_CTS_PATH, "utf8"); + + it("starts the stdio JSON-RPC server before awaiting core.init() in non-daemon mode", () => { + // Match the assignment form `stdio = startStdioServer({ core })` + // and the call form `await core.init();` (with trailing semicolon). + // Both substrings appear *only* at the real call sites, never in + // the surrounding rationale comments (which use bare + // `startStdioServer({ core })` and `await core.init()` in prose). + const stdioIdx = src.indexOf("stdio = startStdioServer({ core })"); + const initIdx = src.indexOf("await core.init();"); + + expect(stdioIdx, "stdio = startStdioServer({ core }) call site not found").toBeGreaterThanOrEqual(0); + expect(initIdx, "await core.init(); call site not found").toBeGreaterThanOrEqual(0); + expect( + stdioIdx, + `bridge.cts: stdio = startStdioServer({ core }) must appear textually before await core.init(); ` + + `(stdioIdx=${stdioIdx} initIdx=${initIdx}). ` + + `Reordering reopens the issue #1747 race where the Python adapter's ` + + `session.open RPC times out while orphan recovery blocks the stdio reader.`, + ).toBeLessThan(initIdx); + }); + + it("keeps the stdio start guarded inside the !args.daemon branch", () => { + // Daemon mode (--daemon) intentionally skips stdio entirely and runs + // as a pure HTTP viewer. We want the regression guard to apply to + // the stdio (non-daemon) path only — moving the call outside the + // guard would re-enable stdio in daemon mode, which is a separate + // breaking change. This test pins the guard's presence. + const stdioIdx = src.indexOf("stdio = startStdioServer({ core })"); + expect(stdioIdx).toBeGreaterThanOrEqual(0); + + const before = src.slice(0, stdioIdx); + const lastDaemonGuard = before.lastIndexOf("if (!args.daemon)"); + expect( + lastDaemonGuard, + "bridge.cts: stdio = startStdioServer({ core }) must remain inside an `if (!args.daemon)` block", + ).toBeGreaterThanOrEqual(0); + }); +});