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); + }); +});