From 5a15dbe4a5505ea3a9d0ff3ba85a2a459cb545d1 Mon Sep 17 00:00:00 2001 From: yanhuojiyusheng <2398249916@qq.com> Date: Sun, 25 Oct 2026 10:40:06 +0800 Subject: [PATCH 1/4] fix(hermes): bootstrap the proxy off the host's load deadline register() no longer waits on discovery/spawn/manifest inside the host's 10s load budget; a daemon thread bootstraps under one 90s deadline, the first model request is held for readiness (falling back to proxy mode, never a silent direct turn), /acp reports starting/failed/unloaded, and unload can no longer be raced by a late registration or env write. --- hermes-plugin/__init__.py | 438 ++++++++++++++++++++++++++++++------ tests/hermes-native.test.ts | 306 ++++++++++++++++++++++++- 2 files changed, 668 insertions(+), 76 deletions(-) diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index 75099f0a7c..d4c923d0a6 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -55,6 +55,22 @@ SPAWN_WAIT_S = 10.0 SPAWN_POLL_S = 0.1 STARTING_MARKER_TTL_S = 90.0 +# The host caps a plugin's import + register() at `plugins.load_timeout_seconds` (default 10s) and +# abandons the load on timeout (later registrations are ignored). register() blocks at most this +# long for a fast bootstrap and hands a slow one to the background thread. +REGISTER_WAIT_S = 4.0 +# ONE total budget for a background bootstrap, from thread start to the last side effect. Attach, +# discovery, spawn and the manifest all poll this same deadline; no stage adds a budget of its own. +BOOTSTRAP_BUDGET_S = 90.0 +# The explicit-attach poll is capped inside that budget; a local spawn gets whatever remains. +ATTACH_WAIT_S = 30.0 +# A first model request racing the bootstrap waits for it; the wait must OUTLAST the budget, or a +# slow-but-healthy start would still let turn 1 slip out uncompressed — the defect this gate exists +# for. Derived, not hand-tuned: the two can never drift apart. +FIRST_REQUEST_WAIT_S = BOOTSTRAP_BUDGET_S + 15.0 +# Core ACP tools whose absence from the OUTGOING request proves this session's tool snapshot was +# built before the background registration landed — plugin-mode headers must not be stamped then. +CORE_TOOL_NAMES = ("compress", "decompress", "acp_status") MAX_TRACKED_SESSIONS = 256 # Host-resolution memo: (model, base_url, output) -> (limit|None, monotonic_ts). # The window lookup runs on the request path, so a repeat must be free; a positive answer is @@ -73,6 +89,10 @@ # max_output: OrderedDict[session_id -> int(max_tokens)]; runtime_info_sent: (model, max_output) pairs; # refused: origins refused by the #1338 attach gate (log dedup per process); # instance_id: the registry id discover_instance picked (None until an attach is chosen). +# loaded: register() installed the cheap surfaces and started a bootstrap; +# bootstrap: {"state": "starting"|"ready"|"failed"|"stopped", "started_at", "deadline", "error"} — +# /acp reports it while the proxy is cold; tool_names: the manifest's tools (the visibility gate +# in on_llm_request compares them against the outgoing request). _state: Dict[str, Any] = { "origin": None, "mode": None, @@ -83,19 +103,42 @@ "runtime_info_sent": set(), "refused": set(), "instance_id": None, + "loaded": False, + "bootstrap": None, + "tool_names": (), + "thread": None, + "ready_event": threading.Event(), + "stop_event": threading.Event(), + "warned_direct": False, + "snapshot_warned": False, } +# Serializes load/unload against bootstrap side effects (tool registration, env routing, child +# spawn). _shutdown sets the stop event first, then takes this lock: when unload returns, no side +# effect is in flight, and every bootstrap critical section re-checks its stop event under it. +_lifecycle_lock = threading.RLock() + def _reset_for_test() -> None: - _state["origin"] = None - _state["mode"] = None - _state["child"] = None - _state["tools_ready"] = False - _state["env_applied"] = False - _state["max_output"].clear() - _state["runtime_info_sent"].clear() - _state["refused"].clear() - _state["instance_id"] = None + _shutdown() + with _lifecycle_lock: + _state["origin"] = None + _state["mode"] = None + _state["child"] = None + _state["tools_ready"] = False + _state["env_applied"] = False + _state["max_output"].clear() + _state["runtime_info_sent"].clear() + _state["refused"].clear() + _state["instance_id"] = None + _state["loaded"] = False + _state["bootstrap"] = None + _state["tool_names"] = () + _state["thread"] = None + _state["ready_event"] = threading.Event() + _state["stop_event"] = threading.Event() + _state["warned_direct"] = False + _state["snapshot_warned"] = False # — paths --------------------------------------------------------------------- @@ -419,7 +462,8 @@ def _refuse(origin: str, message: str) -> None: logger.warning("billion-context: refusing to attach to %s — %s.", origin, message) -def discover_instance(script: str) -> Optional[str]: +def discover_instance(script: str, deadline: Optional[float] = None, + stop: Optional[threading.Event] = None) -> Optional[str]: """#2905: lane-aware attach discovery — the Python twin of probeLiveInstances + pickAttachable (src/launcher.ts). Candidates come from EVERY live registry marker plus the single proxy-origin file (registry wins id collisions, mirroring probeLiveInstances). @@ -444,6 +488,8 @@ def discover_instance(script: str) -> Optional[str]: best_key: Optional[Tuple[int, int]] = None best: Optional[Dict[str, Any]] = None for inst in candidates.values(): + if _stopped() or (stop is not None and stop.is_set()) or (deadline is not None and time.monotonic() >= deadline): + return None origin = inst["origin"] if inst["pid"] is not None and not pid_alive(inst["pid"]): continue @@ -948,16 +994,60 @@ def _attach(origin: str) -> str: return origin -def ensure_origin(sidecar: Dict[str, str]) -> Optional[str]: +def _stopped() -> bool: + """True once the host unloaded the plugin: the bootstrap must not touch the proxy or the + registration surface any more (a late register_* after unload would leak an orphan entry).""" + event = _state.get("stop_event") + return bool(event is not None and event.is_set()) + + +def _reap_unready_child() -> None: + """Terminate a proxy we spawned but never became healthy with: it has no watchdog owner yet + (the plugin never registered as one), so nothing else would reap it. Once the process env + routes through an origin, killing it would break traffic — such a child is left to the + watcher/watchdog protocol (it carries BILI_PARENT_PID and exits with the host).""" + if _state.get("tools_ready") or _state.get("env_applied"): + return + child = _state.get("child") + _state["child"] = None + if child is None or child.poll() is not None: + return + try: + child.terminate() + except Exception: + pass + + +def ensure_origin(sidecar: Dict[str, str], deadline: Optional[float] = None) -> Optional[str]: """Return a healthy proxy origin. Attach when possible (explicit target, then any recorded - instance); otherwise spawn our own behind the starting-marker arbiter.""" + instance); otherwise spawn our own behind the starting-marker arbiter. + + `deadline` is ONE monotonic instant shared by every wait below (attach poll, marker + arbitration, spawn poll) — the caller's total budget, never a per-stage one: stages that each + take a fresh timeout turn one cold start into a three-minute one and make the first-request + wait impossible to size. Defaults to the historical single SPAWN_WAIT_S slice.""" + if deadline is None: + deadline = time.monotonic() + SPAWN_WAIT_S attach = (os.environ.get(ATTACH_ENV) or "").strip().rstrip("/") if attach: - if probe_proxy(attach): - return _attach(attach) - logger.warning("billion-context: %s %s is not healthy — falling back to local bootstrap", ATTACH_ENV, attach) + # An explicit target may be a launcher-owned proxy that is still BOOTING (the launcher + # starts the proxy and hermes concurrently; a cold store takes far longer than one TCP + # probe). Poll it for the shared budget instead of declaring it dead and spawning a + # second proxy that would compete for the same session store. + attach_wait = min(max(0.0, deadline - time.monotonic()), ATTACH_WAIT_S) + attach_deadline = time.monotonic() + attach_wait + while True: + if _stopped(): + return None + if probe_proxy(attach): + return _attach(attach) + if time.monotonic() >= attach_deadline: + break + time.sleep(SPAWN_POLL_S) + logger.warning("billion-context: %s %s is not healthy after %.0fs — falling back to local bootstrap", + ATTACH_ENV, attach, attach_wait) - found = discover_instance(sidecar["script"]) + found = discover_instance(sidecar["script"], deadline=deadline, stop=_state.get("stop_event")) if found: return _attach(found) @@ -967,16 +1057,17 @@ def ensure_origin(sidecar: Dict[str, str]) -> Optional[str]: token = uuid.uuid4().hex claimed = claim_starting_marker(token, port) if not claimed: - deadline = time.monotonic() + SPAWN_WAIT_S while time.monotonic() < deadline: - found = discover_instance(sidecar["script"]) + if _stopped(): + return None + found = discover_instance(sidecar["script"], deadline=deadline, stop=_state.get("stop_event")) if found: return _attach(found) marker = _read_marker() if marker is None or _marker_is_stale(marker): break time.sleep(SPAWN_POLL_S) - if not claim_starting_marker(token, port): + if _stopped() or not claim_starting_marker(token, port): return None claimed = True try: @@ -984,8 +1075,9 @@ def ensure_origin(sidecar: Dict[str, str]) -> Optional[str]: if child is None: return None _state["child"] = child - deadline = time.monotonic() + SPAWN_WAIT_S while time.monotonic() < deadline: + if _stopped(): + return None inst = read_instance_file() if inst and inst.get("launch_token") == token and probe_proxy(inst["origin"]): _state.update(origin=inst["origin"], mode="spawn") @@ -996,7 +1088,7 @@ def ensure_origin(sidecar: Dict[str, str]) -> Optional[str]: os.path.join(tempfile.gettempdir(), f"bili-proxy-{port}.log")) return None time.sleep(SPAWN_POLL_S) - logger.warning("billion-context: proxy did not become healthy within %ss", SPAWN_WAIT_S) + logger.warning("billion-context: proxy did not become healthy within its startup budget") try: child.terminate() except Exception: @@ -1009,23 +1101,29 @@ def ensure_origin(sidecar: Dict[str, str]) -> Optional[str]: # — runtime effects ------------------------------------------------------------- -def apply_env(origin: str) -> None: +def apply_env(origin: str) -> bool: """Route hermes's model traffic through the proxy. Only called once the proxy is healthy — - the same pair `bili hermes` sets for the launched process.""" - os.environ["HTTPS_PROXY"] = origin - os.environ["https_proxy"] = origin - ca_dir = data_dir() / "ca" - root = ca_dir / "root-ca.pem" - if root.is_file(): - os.environ["HERMES_CA_BUNDLE"] = str(root) - combined = ca_dir / "combined-ca.pem" - if combined.is_file(): - # Current hermes' main client ignores HERMES_CA_BUNDLE (agent/ssl_verify.py: platform - # store + per-provider ssl_ca_cert); ambient trust rides SSL_CERT_FILE — OpenSSL - # REPLACE semantics, so it must be the COMBINED bundle (MITM root + public roots) to - # keep blind-tunnelled hosts validating (#1375). - os.environ["SSL_CERT_FILE"] = str(combined) - _state["env_applied"] = True + the same pair `bili hermes` sets for the launched process. Returns False when the host unloaded + the plugin first: routing a torn-down process's traffic would outlive the unload (checked and + applied under the lifecycle lock, so an unload cannot slip between the two).""" + with _lifecycle_lock: + if _stopped(): + return False + os.environ["HTTPS_PROXY"] = origin + os.environ["https_proxy"] = origin + ca_dir = data_dir() / "ca" + root = ca_dir / "root-ca.pem" + if root.is_file(): + os.environ["HERMES_CA_BUNDLE"] = str(root) + combined = ca_dir / "combined-ca.pem" + if combined.is_file(): + # Current hermes' main client ignores HERMES_CA_BUNDLE (agent/ssl_verify.py: platform + # store + per-provider ssl_ca_cert); ambient trust rides SSL_CERT_FILE — OpenSSL + # REPLACE semantics, so it must be the COMBINED bundle (MITM root + public roots) to + # keep blind-tunnelled hosts validating (#1375). + os.environ["SSL_CERT_FILE"] = str(combined) + _state["env_applied"] = True + return True def make_tool_handler(tool_name: str) -> Callable[..., str]: @@ -1056,6 +1154,129 @@ def handler(args: Dict[str, Any], **kwargs: Any) -> str: return handler +# — startup bootstrap ------------------------------------------------------------ + +def _bootstrap_record() -> Dict[str, Any]: + rec = _state.get("bootstrap") + if not isinstance(rec, dict): + rec = {"state": "starting", "started_at": time.monotonic(), "error": None} + _state["bootstrap"] = rec + return rec + + +def _register_tools(ctx: Any, tools: List[Any]) -> List[str]: + """Register the manifest's tools and commit the readiness flag under the lifecycle lock, so an + unload lands either entirely before (nothing registered, tools stay unavailable) or entirely + after (the host disposes them) — never between check and registration.""" + names: List[str] = [] + with _lifecycle_lock: + if _stopped(): + return names + for tool in tools: + if not isinstance(tool, dict) or not tool.get("name"): + continue + name = str(tool["name"]) + ctx.register_tool( + name=name, + toolset=PLUGIN_ID, + schema=tool.get("input_schema") or {}, + handler=make_tool_handler(name), + description=str(tool.get("description") or ""), + ) + names.append(name) + _state["tool_names"] = tuple(names) + _state["tools_ready"] = True + return names + + +def _bootstrap(sidecar: Dict[str, str], ctx: Any) -> None: + """The slow half of register(): find/spawn a healthy proxy, route the process env through it, + and install the native tools. It runs on a daemon thread so the host's load deadline only + bounds the cheap registrations (REGISTER_WAIT_S). Every side effect re-checks the stop event: + an unload mid-bootstrap must leave neither a registration nor a child behind.""" + rec = _bootstrap_record() + deadline = time.monotonic() + BOOTSTRAP_BUDGET_S + try: + origin = ensure_origin(sidecar, deadline=deadline) + if _stopped(): + _reap_unready_child() + return + if not origin: + rec.update(state="failed", error="could not reach or start a bili proxy") + logger.warning("billion-context: could not reach or start a bili proxy — model traffic " + "goes direct (uncompressed) in this process") + return + if not apply_env(origin): + _reap_unready_child() + return + manifest = http_get_json(origin.rstrip("/") + "/__bili/plugin/manifest", MANIFEST_TIMEOUT_S) + tools = manifest.get("tools", {}).get("anthropic") if isinstance(manifest, dict) else None + if not isinstance(tools, list) or not tools: + rec.update(state="failed", error="proxy manifest had no tool definitions") + logger.warning("billion-context: proxy manifest had no tool definitions — compression " + "stays server-side (proxy mode)") + return + names = _register_tools(ctx, tools) + if not _state.get("tools_ready"): + _reap_unready_child() + return + with _lifecycle_lock: + if _stopped(): + _reap_unready_child() + return + rec.update(state="ready", error=None) + logger.info("billion-context: hermes native mode ready (%s, tools: %s)", + _state.get("mode"), ", ".join(names)) + except Exception as exc: + if not _stopped(): + rec.update(state="failed", error=f"{type(exc).__name__}: {exc}") + if _state.get("origin") and _state.get("env_applied"): + logger.warning("billion-context: background bootstrap failed (%s) — traffic is routed " + "through %s in proxy mode; native tools are unavailable this session", + exc, _state.get("origin")) + else: + logger.warning("billion-context: background bootstrap failed (%s) — model traffic goes " + "direct (uncompressed) in this process", exc) + finally: + event = _state.get("ready_event") + if event is not None: + event.set() + + +def _start_bootstrap(sidecar: Dict[str, str], ctx: Any) -> None: + rec = _bootstrap_record() + rec.update(state="starting", started_at=time.monotonic(), error=None) + thread = threading.Thread(target=_bootstrap, args=(sidecar, ctx), + name="bili-bootstrap", daemon=True) + _state["thread"] = thread + thread.start() + + +def _shutdown() -> None: + """on_unload: stop the bootstrap, release anything waiting on it, and reap a child that never + became healthy. The stop event and the state flags move under the lifecycle lock, so a + registration/env commit either finished before this call (the host disposes of it) or is + refused by it; the join runs outside the lock, since the bootstrap needs it to observe the + stop.""" + with _lifecycle_lock: + stop = _state.get("stop_event") + if stop is not None: + stop.set() + ready = _state.get("ready_event") + if ready is not None: + ready.set() + _state["loaded"] = False + _state["tools_ready"] = False + _state["tool_names"] = () + rec = _state.get("bootstrap") + if isinstance(rec, dict) and rec.get("state") != "ready": + rec.update(state="stopped", error=None) + thread = _state.get("thread") + if thread is not None and thread.is_alive() and thread is not threading.current_thread(): + thread.join(timeout=1.0) + _reap_unready_child() + + def _stampable_header_value(value: Any) -> Optional[str]: """#2455: HTTP header values are ByteStrings — a char above U+00FF (e.g. a Chinese provider/model id) makes the host HTTP stack throw when it BUILDS the request, so @@ -1068,15 +1289,63 @@ def _stampable_header_value(value: Any) -> Optional[str]: return None +def _request_tool_names(request: Dict[str, Any]) -> set: + """Tool names carried by the OUTGOING request (OpenAI chat, Anthropic messages and Responses + shapes all covered).""" + tools = request.get("tools") + if not isinstance(tools, list): + return set() + names = set() + for tool in tools: + if not isinstance(tool, dict): + continue + fn = tool.get("function") + name = fn.get("name") if isinstance(fn, dict) else tool.get("name") + if isinstance(name, str) and name: + names.add(name) + return names + + +def _plugin_tools_visible(request: Dict[str, Any]) -> bool: + """Plugin mode is only safe when THIS request carries the ACP tools — the agent can then call + compress/decompress itself. Hermes snapshots agent.tools once per session, so a tool registered + after that snapshot is absent here; stamping plugin headers anyway would suppress the proxy's + own tool+nudge injection while the model has no way to compress (silent context growth).""" + required = [name for name in CORE_TOOL_NAMES if name in _state.get("tool_names", ())] + if not required: + return False + names = _request_tool_names(request) + return all(name in names for name in required) + + def on_llm_request(request: Optional[Dict[str, Any]] = None, **context: Any) -> Optional[Dict[str, Any]]: - """llm_request middleware: stamp plugin-mode headers once the native tools are registered. - Round 1 (before tools are ready) deliberately returns None — it rides wire mode.""" + """llm_request middleware. Two jobs: + 1) readiness gate — a cold bootstrap must not let turn 1 slip out direct (that silent + uncompressed turn is exactly the defect this design fixes); hold it, bounded. + 2) plugin-mode headers — only when the outgoing request itself proves this session's tool + snapshot has the native tools.""" try: - if not _state.get("tools_ready") or request is None or not isinstance(request, dict): + if request is None or not isinstance(request, dict) or not _state.get("loaded"): return None - origin = _state.get("origin") session_id = context.get("session_id") - if not origin or not session_id: + if not session_id: + return None + if not _state.get("tools_ready"): + event = _state.get("ready_event") + if event is not None: + event.wait(FIRST_REQUEST_WAIT_S) + origin = _state.get("origin") + if not origin or not _state.get("env_applied"): + if not _state.get("warned_direct"): + _state["warned_direct"] = True + logger.warning("billion-context: proxy not ready — this process's model traffic goes " + "direct (uncompressed); see the bootstrap warning above") + return None + if not _plugin_tools_visible(request): + if not _state.get("snapshot_warned"): + _state["snapshot_warned"] = True + logger.info("billion-context: native tools are not in this session's tool list — " + "compressing in proxy mode until a new session") return None headers = request.get("extra_headers") merged = dict(headers) if isinstance(headers, dict) else {} @@ -1193,6 +1462,27 @@ def acp_command(raw_args: str = "", *, session_id: str = "") -> Optional[str]: proxy's HTTP endpoints.""" try: origin = _command_origin() + boot: Dict[str, Any] = _state.get("bootstrap") if isinstance(_state.get("bootstrap"), dict) else {} + boot_state = boot.get("state") + # Before the bootstrap settles there is no honest panel to show; report the STARTUP state + # instead of the installer hint (the plugin IS installed, it is just still cold). + if not _state.get("tools_ready") and boot_state in ("starting", "failed", "stopped"): + where = f" at {origin}" if origin else "" + if boot_state == "stopped": + return "bili: plugin unloaded — model traffic goes direct (uncompressed) in this process." + if boot_state == "starting": + started = boot.get("started_at") + elapsed = max(0.0, time.monotonic() - float(started)) if isinstance(started, (int, float)) else 0.0 + return (f"bili: proxy is starting in the background{where} ({elapsed:.0f}s elapsed, " + f"budget {BOOTSTRAP_BUDGET_S:.0f}s) — model traffic is held until it is " + "ready; run /acp again in a moment.") + detail = str(boot.get("error") or "unknown error") + if origin and _state.get("env_applied"): + return (f"bili: proxy at {origin} is up but the native tool manifest is unavailable " + f"({detail}) — traffic is compressed in proxy mode until a new session. " + "Check the hermes log for the proxy's own output.") + return (f"bili: proxy failed to start{where} ({detail}) — model traffic is going direct " + "(uncompressed). Check the hermes log for the proxy's own output.") if not origin: return ("bili: no proxy detected — install the plugin (`bili plugin install hermes`) " "and start a new hermes session so /acp can read context status.") @@ -1258,36 +1548,16 @@ def register(ctx: Any) -> None: try: if gated_off(os.environ): return - if _state.get("tools_ready"): + if _state.get("loaded"): return sidecar = load_sidecar() if not sidecar: logger.warning("billion-context: no usable bili.json sidecar next to the hermes plugin " "(run `bili plugin install hermes`) — staying inert") return - origin = ensure_origin(sidecar) - if not origin: - logger.warning("billion-context: could not reach or start a bili proxy — staying inert " - "(hermes talks to the upstream directly)") - return - apply_env(origin) - manifest = http_get_json(origin.rstrip("/") + "/__bili/plugin/manifest", MANIFEST_TIMEOUT_S) - tools = manifest.get("tools", {}).get("anthropic") if isinstance(manifest, dict) else None - if not isinstance(tools, list) or not tools: - logger.warning("billion-context: proxy manifest had no tool definitions — staying inert") - return - names: List[str] = [] - for tool in tools: - if not isinstance(tool, dict) or not tool.get("name"): - continue - ctx.register_tool( - name=str(tool["name"]), - toolset=PLUGIN_ID, - schema=tool.get("input_schema") or {}, - handler=make_tool_handler(str(tool["name"])), - description=str(tool.get("description") or ""), - ) - names.append(str(tool["name"])) + # 1) Everything cheap and blocking-free goes in FIRST. The host caps import+register() at + # its load deadline (10s) and ABANDONS the load on timeout — every registration made + # after that is ignored, so a slow proxy bootstrap must never sit in this path. ctx.register_middleware("llm_request", on_llm_request) ctx.register_hook("pre_api_request", on_pre_api_request) # In-session slash commands; hosts without PluginContext.register_command @@ -1301,8 +1571,38 @@ def register(ctx: Any) -> None: "acp-cache", acp_cache_command, description="Prompt-cache reconciliation (same report as the acp_cache tool)", ) - _state["tools_ready"] = True - logger.info("billion-context: hermes native mode active (%s, tools: %s)", - _state.get("mode"), ", ".join(names)) + if hasattr(ctx, "on_unload"): + ctx.on_unload(_shutdown) + # 2) The slow half — discover/attach/spawn, manifest, tool registration — on its own thread + # (see _bootstrap). Warm/attach finishes inside REGISTER_WAIT_S, so a normal start still + # registers the native tools before this session's tool snapshot is built (the host calls + # discover_plugins() before model_tools.get_tool_definitions()). A cold start lets + # register() return instead of being abandoned; the first model request then waits for + # readiness (on_llm_request) and compresses in proxy mode until the next session. + # "loaded" both guards against a double register() and gates the middleware's readiness + # wait; the failure path below clears it (and releases the event) so a bootstrap that never + # started can never park the first turn on an event nothing will set. + with _lifecycle_lock: + if _stopped(): + # The host can reuse this module after an unload (re-enable without a re-import): + # a stale stop event would kill the new bootstrap on its first check, so this + # generation gets fresh events and a clean record. + _state["stop_event"] = threading.Event() + _state["ready_event"] = threading.Event() + _state["bootstrap"] = None + _state["loaded"] = True + _start_bootstrap(sidecar, ctx) + event = _state.get("ready_event") + if event is not None: + event.wait(REGISTER_WAIT_S) + rec: Dict[str, Any] = _state.get("bootstrap") if isinstance(_state.get("bootstrap"), dict) else {} + if rec.get("state") == "starting": + logger.info("billion-context: proxy bootstrap still running after %.0fs — returning from " + "register() (host load deadline); the first model request waits up to %.0fs", + REGISTER_WAIT_S, FIRST_REQUEST_WAIT_S) except Exception as exc: + _state["loaded"] = False + event = _state.get("ready_event") + if event is not None: + event.set() logger.warning("billion-context: plugin registration failed (%s) — staying inert", exc) diff --git a/tests/hermes-native.test.ts b/tests/hermes-native.test.ts index 0ff8532d7d..c5d04d6ffd 100644 --- a/tests/hermes-native.test.ts +++ b/tests/hermes-native.test.ts @@ -129,6 +129,11 @@ describe("installer lane (bili plugin install hermes)", () => { const home = track(makeTmp("nocli")); const emptyBin = track(makeTmp("emptybin")); const restore = setHermesEnv(home, emptyBin); + // setHermesEnv PREPENDS, so a real hermes on the developer's PATH would still resolve and + // the lane would take the "enabled it" branch (passing/failing by machine, not by code). + // This case needs an actually CLI-less PATH. + const prevPath = process.env.PATH; + process.env.PATH = emptyBin; try { const msg = pluginInstall("hermes"); // The exact head differs by platform: a POSIX ENOENT prints "the @@ -138,6 +143,7 @@ describe("installer lane (bili plugin install hermes)", () => { assert.match(msg, /enable it manually: hermes plugins enable billion-context/); assert.equal(hermesStatus(), "installed"); } finally { + process.env.PATH = prevPath ?? ""; restore(); } }); @@ -225,6 +231,10 @@ for k in ("BILLION_CONTEXT_ATTACH", "BILLION_CONTEXT_PROXY", "BILI_NATIVE_HERMES os.environ.pop(k, None) RECORDED = {"tool": [], "runtime_info": [], "watcher": [], "health": [], "status": []} +# Deterministic cold-start control: while enabled and unreleased, the stub answers the manifest +# and health probes with 503 (a proxy that is listening but not ready yet — the same distinction +# the plugin's manifest-based readiness makes). No timers: the scenario sets/clears the event. +SLOW = {"enabled": False, "release": threading.Event()} # --- hermetic YAML backend stubs for the MITM-domain discovery tests (#2838) --- # A minimal parser for the restricted config shape under test; lets each scenario pin exactly @@ -285,7 +295,10 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write(body) def do_GET(self): - if self.path == "/__bili/health": + if SLOW["enabled"] and not SLOW["release"].is_set() and ( + self.path == "/__bili/health" or self.path == "/__bili/plugin/manifest"): + self._send({"error": "proxy still booting"}, 503) + elif self.path == "/__bili/health": RECORDED["health"].append(1) mode = os.environ.get("BC_HEALTH_WATCHDOG", "armed") if mode == "absent": @@ -390,6 +403,7 @@ class FakeCtx: self.middlewares = {} self.hooks = {} self.commands = {} + self.unload = [] def register_tool(self, name=None, toolset=None, schema=None, handler=None, description="", **kw): self.tools[name] = {"toolset": toolset, "schema": schema, "handler": handler, "description": description} @@ -404,6 +418,29 @@ class FakeCtx: self.commands[name] = {"handler": handler, "description": description} return object() + def on_unload(self, cb): + self.unload.append(cb) + + def run_unload(self): + for cb in reversed(self.unload): + cb() + +CORE_TOOLS = ("compress", "decompress", "acp_status") + +def tool_defs(names=CORE_TOOLS): + """The native tools as Hermes' per-session snapshot would carry them (OpenAI chat shape).""" + return [{"type": "function", "function": {"name": n, "parameters": {"type": "object"}}} for n in names] + +def tool_defs_anthropic(names=CORE_TOOLS): + return [{"name": n, "input_schema": {"type": "object"}} for n in names] + +def mw_request(model, with_tools=True, names=CORE_TOOLS, **extra): + req = {"model": model} + if with_tools: + req["tools"] = tool_defs(names) + req.update(extra) + return req + mod = load_module() mod._reset_for_test() ctx = FakeCtx() @@ -460,6 +497,113 @@ elif SCENARIO == "no-sidecar": elif SCENARIO == "spawn-fail": install_sidecar(True) mod.register(ctx) +elif SCENARIO == "slow-boot-ready": + # Cold start: the host's load deadline only bounds register(); the proxy keeps booting on the + # background thread. Readiness is the MANIFEST (not a TCP connect), and the release is + # event-driven — no sleeps, no wall-clock assumptions. + install_sidecar(False) + os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN + mod.REGISTER_WAIT_S = 0.2 + mod.BOOTSTRAP_BUDGET_S = 10.0 + mod.FIRST_REQUEST_WAIT_S = 10.0 + SLOW["enabled"] = True + started = __import__("time").monotonic() + mod.register(ctx) + out["register_elapsed"] = __import__("time").monotonic() - started + out["state_after_register"] = (mod._state.get("bootstrap") or {}).get("state") + out["tools_after_register"] = sorted(ctx.tools.keys()) + out["commands_after_register"] = sorted(ctx.commands.keys()) + out["unload_hooked"] = len(ctx.unload) + out["acp_while_starting"] = mod.acp_command("", session_id="sess-slow") + out["env_before_ready"] = os.environ.get("HTTPS_PROXY") + # Release from another thread while the first model request is parked in the middleware: + # proves the gate WAITS for readiness instead of letting turn 1 go out direct. + def release_later(): + __import__("time").sleep(0.3) + SLOW["release"].set() + threading.Thread(target=release_later, daemon=True).start() + mw = ctx.middlewares["llm_request"] + t0 = __import__("time").monotonic() + first = mw(request=mw_request("slow-model"), session_id="sess-slow", model="slow-model") + out["gate_wait_s"] = __import__("time").monotonic() - t0 + out["first_headers"] = first["request"]["extra_headers"] if isinstance(first, dict) else None + out["tools_after_ready"] = sorted(ctx.tools.keys()) + out["state_after_ready"] = (mod._state.get("bootstrap") or {}).get("state") + out["acp_after_ready"] = mod.acp_command("", session_id="sess-slow") + out["env_after_ready"] = os.environ.get("HTTPS_PROXY") + # A session whose snapshot predates the registration: readiness alone must not stamp headers. + out["stale_request_none"] = mw(request=mw_request("slow-model", with_tools=False), + session_id="sess-slow", model="slow-model") is None + out["ready_event_set"] = mod._state["ready_event"].is_set() +elif SCENARIO == "slow-boot-fail": + install_sidecar(True) # spawn path: the child exits at once, so the bootstrap fails fast + os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN + mod.REGISTER_WAIT_S = 0.2 + mod.BOOTSTRAP_BUDGET_S = 0.4 + mod.FIRST_REQUEST_WAIT_S = 2.0 + SLOW["enabled"] = True + mod.register(ctx) + out["state_after_register"] = (mod._state.get("bootstrap") or {}).get("state") + out["acp_while_starting"] = mod.acp_command("", session_id="sess-fail") + thread = mod._state.get("thread") + if thread is not None: + thread.join(10) + out["state_after_fail"] = (mod._state.get("bootstrap") or {}).get("state") + out["tools_after_fail"] = sorted(ctx.tools.keys()) + out["env_after_fail"] = os.environ.get("HTTPS_PROXY") + out["acp_after_fail"] = mod.acp_command("", session_id="sess-fail") + mw = ctx.middlewares["llm_request"] + t0 = __import__("time").monotonic() + first = mw(request=mw_request("m"), session_id="sess-fail", model="m") + out["mw_after_fail_none"] = first is None + out["mw_after_fail_elapsed"] = __import__("time").monotonic() - t0 + out["ready_event_set"] = mod._state["ready_event"].is_set() +elif SCENARIO == "slow-boot-unload": + install_sidecar(False) + os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN + mod.REGISTER_WAIT_S = 0.2 + mod.BOOTSTRAP_BUDGET_S = 5.0 + SLOW["enabled"] = True + mod.register(ctx) + out["state_before_unload"] = (mod._state.get("bootstrap") or {}).get("state") + ctx.run_unload() # host tears the plugin down mid-bootstrap + SLOW["release"].set() # the proxy would come up right after the unload — it must not matter + thread = mod._state.get("thread") + deadline = __import__("time").monotonic() + 3.0 + while thread is not None and thread.is_alive() and __import__("time").monotonic() < deadline: + __import__("time").sleep(0.02) + out["tools_after_unload"] = sorted(ctx.tools.keys()) + out["unload_thread_alive"] = bool(thread is not None and thread.is_alive()) + out["state_after_unload"] = (mod._state.get("bootstrap") or {}).get("state") + out["env_after_unload"] = os.environ.get("HTTPS_PROXY") + out["mw_after_unload_none"] = ctx.middlewares["llm_request"]( + request=mw_request("m"), session_id="s") is None + out["acp_after_unload"] = mod.acp_command("", session_id="s") +elif SCENARIO == "slow-boot-restart": + # Re-enable without a re-import (the host keeps the module): the second register() must get a + # fresh generation — a stale stop event would abort its bootstrap on the first check. + install_sidecar(False) + os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN + mod.REGISTER_WAIT_S = 0.2 + mod.BOOTSTRAP_BUDGET_S = 10.0 + mod.FIRST_REQUEST_WAIT_S = 10.0 + SLOW["enabled"] = True + mod.register(ctx) + ctx.run_unload() + ctx.tools.clear() # the host disposes what the unloaded plugin registered + SLOW["release"].set() # the proxy becomes healthy while the plugin is off + thread = mod._state.get("thread") + deadline = __import__("time").monotonic() + 3.0 + while thread is not None and thread.is_alive() and __import__("time").monotonic() < deadline: + __import__("time").sleep(0.02) + mod.register(ctx) + ready = mod._state.get("ready_event") + if ready is not None: + ready.wait(10) + out["tools_after_reenable"] = sorted(ctx.tools.keys()) + out["state_after_reenable"] = (mod._state.get("bootstrap") or {}).get("state") + out["env_after_reenable"] = os.environ.get("HTTPS_PROXY") + out["origin_after_reenable"] = mod._state.get("origin") elif SCENARIO.startswith("attach-window"): # #3261: the host knows the model window (context_length_cache.yaml) — verify it now # rides both report channels; the ambiguous leg pins "no guess" on conflicting entries. @@ -504,9 +648,12 @@ elif SCENARIO.startswith("attach-window"): mod.register(ctx) mw = ctx.middlewares.get("llm_request") hook = ctx.hooks.get("pre_api_request") - req = {"model": win_model, "max_tokens": 100} + req = mw_request(win_model, max_tokens=100) frozen = json.loads(json.dumps(req)) first = mw(request=req, original_request=frozen, session_id="sess-w", model=win_model, provider=win_provider, api_mode="chat") + # a request whose tool snapshot predates the registration must NOT get plugin headers + stale = mw(request=mw_request(win_model, with_tools=False), session_id="sess-w", model=win_model, + provider=win_provider, api_mode="chat") hook(session_id="sess-w", model=win_model, max_tokens=4096) deadline = __import__("time").monotonic() + 3.0 while not RECORDED["runtime_info"] and __import__("time").monotonic() < deadline: @@ -514,6 +661,7 @@ elif SCENARIO.startswith("attach-window"): out.update({ "req_unmutated": req == frozen, "win_headers": first["request"]["extra_headers"] if isinstance(first, dict) else None, + "stale_headers": stale["request"]["extra_headers"] if isinstance(stale, dict) else None, }) elif SCENARIO == "output-limits": import types @@ -524,7 +672,8 @@ elif SCENARIO == "output-limits": "group/no-cap": {"context_length": 500000}} mod._host_import = lambda name: types.SimpleNamespace(fetch_endpoint_model_metadata=fetch) mod._host_resolve = lambda name, base: 500000 - mod._state.update(origin=ORIGIN, tools_ready=True) + mod._state.update(origin=ORIGIN, tools_ready=True, env_applied=True, loaded=True, + tool_names=CORE_TOOLS, mode="attach") out["limits"] = [] for model, base, explicit in [ ("group/sol", "http://upstream.example/v1", None), @@ -536,7 +685,7 @@ elif SCENARIO == "output-limits": ("group/sol", "http://upstream.example/v1", 4096), ]: session = "limit-" + str(len(out["limits"])) - req = {"model": model, "messages": []} + req = mw_request(model) context = dict(session_id=session, model=model, base_url=base) mod.on_llm_request(request=req, **context) for thread in threading.enumerate(): @@ -563,17 +712,25 @@ elif SCENARIO.startswith("attach"): if ctx.middlewares.get("llm_request"): mw = ctx.middlewares["llm_request"] hook = ctx.hooks.get("pre_api_request") - req = {"model": "test-model", "max_tokens": 100, "extra_headers": {"X-Custom": "keep"}} + req = mw_request("test-model", max_tokens=100, extra_headers={"X-Custom": "keep"}) frozen = json.loads(json.dumps(req)) first = mw(request=req, original_request=frozen, session_id="sess-1", model="test-model", provider="p", api_mode="chat") - second_req = {"model": "test-model", "messages": []} + second_req = mw_request("test-model") hook(session_id="sess-1", model="test-model", max_tokens=4096) deadline = __import__("time").monotonic() + 3.0 while not RECORDED["runtime_info"] and __import__("time").monotonic() < deadline: __import__("time").sleep(0.05) second = mw(request=second_req, original_request=second_req, session_id="sess-1", model="test-model", provider="p", api_mode="chat") - cjk_req = {"model": "m-cjk", "messages": []} + cjk_req = mw_request("m-cjk") cjk = mw(request=cjk_req, original_request=cjk_req, session_id="sess-1", model="浮生云算/gpt-6.1-sol", provider="p", api_mode="chat") + # The tools-visibility gate: the same session can be served by a request whose snapshot + # does NOT carry the tools (built before the registration) — it must ride proxy mode. + no_tools = mw(request=mw_request("test-model", with_tools=False), session_id="sess-1", + model="test-model", provider="p", api_mode="chat") + partial_tools = mw(request=mw_request("test-model", names=("compress", "decompress")), + session_id="sess-1", model="test-model", provider="p", api_mode="chat") + anthropic_req = {"model": "test-model", "tools": tool_defs_anthropic()} + anthropic = mw(request=anthropic_req, session_id="sess-1", model="test-model", provider="p", api_mode="anthropic") tool_result = ctx.tools.get("compress", {}).get("handler")({}, session_id="sess-1", task_id="t1") no_session_result = ctx.tools.get("compress", {}).get("handler")({}, task_id="t1") # #2072 negative leg: the model-transcribed conversation_id channel stays UNFLAGGED @@ -585,6 +742,9 @@ elif SCENARIO.startswith("attach"): "second_headers": second["request"]["extra_headers"] if isinstance(second, dict) else None, "second_model_kept": second["request"].get("model") if isinstance(second, dict) else None, "cjk_headers": cjk["request"]["extra_headers"] if isinstance(cjk, dict) else None, + "no_tools_none": no_tools is None, + "partial_tools_none": partial_tools is None, + "anthropic_headers": anthropic["request"]["extra_headers"] if isinstance(anthropic, dict) else None, "tool_result": tool_result, "no_session_result": no_session_result, "transcribed_result": transcribed_result, @@ -595,6 +755,12 @@ elif SCENARIO.startswith("cmd-acp"): install_sidecar(False) os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN mod.register(ctx) + if SCENARIO == "cmd-acp-manifest-fail": + # Attach succeeded and the env is routed, but the manifest GET failed afterwards. The panel + # must say "proxy mode" — NOT the direct/uncompressed wording (traffic IS compressed). + mod._state["bootstrap"].update(state="failed", error="HTTP 500 from manifest") + mod._state["tools_ready"] = False + mod._state["tool_names"] = () import inspect import types route = types.ModuleType("hermes_cli.plugin_session") @@ -672,6 +838,7 @@ out.update({ "refused": sorted(mod._state.get("refused") or []), "instance_id": mod._state.get("instance_id"), "commands": {k: v["description"] for k, v in ctx.commands.items()}, + "unload_callbacks": len(ctx.unload), "status_calls": RECORDED["status"], }) server.shutdown() @@ -714,10 +881,46 @@ interface DriverOut { mitm_domains?: string[]; mitm_warnings?: string[]; commands?: Record; + tools_after_reenable?: string[]; + state_after_reenable?: string; + env_after_reenable?: string | null; + origin_after_reenable?: string | null; status_calls?: Array>; cmd_acp?: string | null; cmd_acp_cache?: string | null; command_results?: Array<{ session: string; panel: string; cache: string }>; + unload_callbacks?: number; + stale_headers?: Record | null; + no_tools_none?: boolean; + partial_tools_none?: boolean; + anthropic_headers?: Record | null; + register_elapsed?: number; + state_after_register?: string; + tools_after_register?: string[]; + commands_after_register?: string[]; + unload_hooked?: number; + acp_while_starting?: string | null; + env_before_ready?: string | null; + gate_wait_s?: number; + tools_after_ready?: string[]; + state_after_ready?: string; + acp_after_ready?: string | null; + env_after_ready?: string | null; + stale_request_none?: boolean; + ready_event_set?: boolean; + state_after_fail?: string; + tools_after_fail?: string[]; + env_after_fail?: string | null; + acp_after_fail?: string | null; + mw_after_fail_none?: boolean; + mw_after_fail_elapsed?: number; + state_before_unload?: string; + tools_after_unload?: string[]; + unload_thread_alive?: boolean; + state_after_unload?: string; + env_after_unload?: string | null; + mw_after_unload_none?: boolean; + acp_after_unload?: string | null; } function runDriver(scenario: string, extraEnv: Record = {}): { out: DriverOut | null; err: string } { @@ -767,6 +970,15 @@ describe("python plugin runtime (subprocess)", () => { assert.equal(h1["X-Custom"], "keep"); assert.equal(h1["x-bili-plugin-max-output"], undefined); assert.equal(h1["x-bili-plugin-context-window"], undefined, "#3261 fail-open: no host cache file -> no window header"); + // Cold-start gate: only a request that actually carries the registered native tools is + // stamped plugin-mode. A session snapshot taken before the background bootstrap (no tools + // key, or a partial surface) must fall back to proxy mode — otherwise the plugin-mode + // header makes the proxy suppress tool+nudge injection and the session silently stops + // compressing with no way for the model to call compress/decompress. + assert.equal(out!.no_tools_none, true, "no tools array -> no plugin-mode stamp"); + assert.equal(out!.partial_tools_none, true, "snapshot raced registration (partial surface) -> no stamp"); + assert.equal(out!.anthropic_headers!["x-bili-plugin"], "hermes", "Anthropic tool shape still counts as visible"); + assert.equal(out!.unload_callbacks, 1, "on_unload registered so teardown can stop a late bootstrap"); const h2 = out!.second_headers!; assert.equal(h2["x-bili-plugin-max-output"], "4096"); assert.equal(out!.second_model_kept, "test-model"); @@ -814,6 +1026,7 @@ describe("python plugin runtime (subprocess)", () => { assert.equal(h["x-bili-plugin-model"], "group/sol"); assert.equal(h["x-bili-plugin-context-window"], "500000", "header channel: the host's own window value"); assert.equal(out!.req_unmutated, true); + assert.equal(out!.stale_headers, null, "request without the registered tools is never stamped plugin-mode"); assert.deepEqual(out!.runtime_info, [ { agent: "hermes", model: "group/sol", maxOutput: 4096, contextWindow: 500000, source: "hermes-native" }, ]); @@ -1055,6 +1268,76 @@ describe("python plugin runtime (subprocess)", () => { assert.equal(out!.env_https_proxy, null); assert.equal(out!.marker_left, false); }); + + // Cold start: Hermes abandons the plugin context after its 10s load deadline and drops every + // registration made later, so register() must return fast and let the slow half finish on a + // background thread. The stub proxy answers 503 until the test releases it — readiness is the + // MANIFEST, and every wait is event-driven (no sleep standing in for a boot). + test("cold start: register returns before the proxy is ready; the first request waits instead of going direct", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("slow-boot-ready"); + assert.ok(out, err); + assert.ok(out!.register_elapsed! < 2, `register must fit the host's load deadline (took ${out!.register_elapsed}s)`); + assert.equal(out!.state_after_register, "starting"); + assert.deepEqual(out!.tools_after_register, [], "tools wait for the manifest — never guessed"); + assert.deepEqual(out!.commands_after_register, ["acp", "acp-cache"], "slash commands are cheap and registered synchronously"); + assert.equal(out!.unload_hooked, 1); + assert.match(out!.acp_while_starting!, /starting in the background/); + assert.match(out!.acp_while_starting!, /budget 10s/); + assert.equal(out!.env_before_ready, null, "no env routing before the proxy answers its manifest"); + assert.ok(out!.gate_wait_s! >= 0.1, "the first model request parked until readiness instead of going out direct"); + assert.equal(out!.first_headers!["x-bili-plugin"], "hermes"); + assert.equal(out!.first_headers!["x-bili-plugin-conversation"], "sess-slow"); + assert.deepEqual(out!.tools_after_ready, ["acp_status", "compress", "decompress"]); + assert.equal(out!.state_after_ready, "ready"); + assert.equal(out!.env_after_ready, out!.origin); + assert.equal(out!.stale_request_none, true, "readiness alone never stamps a session whose snapshot predates the tools"); + assert.equal(out!.ready_event_set, true); + assert.doesNotMatch(out!.acp_after_ready!, /starting in the background/); + }); + + test("cold start failure: /acp reports the failure and model traffic goes direct — never silently stalls", () => { + if (!PY) return; + const { out, err } = runDriver("slow-boot-fail"); + assert.ok(out, err); + assert.equal(out!.state_after_register, "starting"); + assert.match(out!.acp_while_starting!, /starting in the background/); + assert.equal(out!.state_after_fail, "failed"); + assert.deepEqual(out!.tools_after_fail, [], "a failed bootstrap registers nothing"); + assert.equal(out!.env_after_fail, null, "env is not routed through an unreachable proxy"); + assert.match(out!.acp_after_fail!, /failed to start/); + assert.match(out!.acp_after_fail!, /going direct/); + assert.equal(out!.mw_after_fail_none, true); + assert.ok(out!.mw_after_fail_elapsed! < 1, "a settled failure is not re-waited on every turn"); + assert.equal(out!.ready_event_set, true); + }); + + test("unload mid-bootstrap: no late tool registration, the thread stops, and the middleware goes inert", () => { + if (!PY) return; + const { out, err } = runDriver("slow-boot-unload"); + assert.ok(out, err); + assert.equal(out!.state_before_unload, "starting"); + assert.deepEqual(out!.tools_after_unload, [], "no register_tool after unload — the host would drop it anyway"); + assert.equal(out!.unload_thread_alive, false, "the bootstrap thread exits on the stop event"); + assert.equal(out!.state_after_unload, "stopped"); + assert.equal(out!.env_after_unload, null); + assert.equal(out!.mw_after_unload_none, true); + assert.match(out!.acp_after_unload!, /plugin unloaded/); + }); + + test("re-enable after unload: the second register() bootstraps again instead of inheriting the stop", () => { + if (!PY) return; + const { out, err } = runDriver("slow-boot-restart"); + assert.ok(out, err); + assert.deepEqual(out!.tools_after_reenable, ["acp_status", "compress", "decompress"], + "the new generation repopulates the host's tool surface"); + assert.equal(out!.state_after_reenable, "ready"); + assert.equal(out!.env_after_reenable, out!.origin, "traffic is routed again"); + assert.equal(out!.origin_after_reenable, out!.origin); + }); }); describe("in-session slash commands (#3697)", () => { @@ -1121,6 +1404,15 @@ describe("in-session slash commands (#3697)", () => { ); }); + test("cmd-acp: a manifest failure after attach reports proxy mode, never claims direct traffic", () => { + if (!PY) return; + const { out, err } = runDriver("cmd-acp-manifest-fail"); + assert.ok(out, err); + assert.match(out!.cmd_acp!, /native tool manifest is unavailable/); + assert.match(out!.cmd_acp!, /proxy mode/); + assert.doesNotMatch(out!.cmd_acp!, /going direct/); + }); + test("cmd-acp-no-proxy: error text without any HTTP traffic", () => { if (!PY) { console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); From d8afbdbbb4fb38808d9c9ea7e00ee9f816f6cdf8 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 12:38:41 +0800 Subject: [PATCH 2/4] fix(hermes): self-heal after bootstrap failure and routed-origin death (#4644) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed hermes bootstrap was terminal until host restart: one transient hiccup settled state 'failed' forever, and a routed proxy that died later left the process env pointing at a dead port for the whole host lifetime (silent direct connection, connect-refused storms). - bootstrap retries failed stages with backoff (10/30/60s, 4 attempts total), each attempt on a fresh 90s budget; already-succeeded stages are not re-run; an unload mid-backoff still settles 'stopped', never clobbered by a late 'failed' - origin watchdog: 30s probe x 3 consecutive misses (or our own child exiting) unroutes the process env — restoring the values present before routing — and re-bootstraps inline, re-arming the registered tools without re-registering them - starting marker gains the lane field (#1225 alignment, additive): our claims declare lane 'hermes'; undeclared lanes wildcard both sides; a same-lane starter is honored (wait + attach), a live foreign-lane starter is neither waited on nor removed, stale markers are removed and re-claimed Tests: 5 new hermes-native scenarios (retry-land, retry-exhaust, origin-death, marker-foreign, marker-same-lane); local targeted suite 48/48 green, typecheck clean. --- hermes-plugin/__init__.py | 371 +++++++++++++++++++++++++++++------- tests/hermes-native.test.ts | 251 ++++++++++++++++++++++++ 2 files changed, 551 insertions(+), 71 deletions(-) diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index d4c923d0a6..772ba5acdb 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -68,6 +68,18 @@ # slow-but-healthy start would still let turn 1 slip out uncompressed — the defect this gate exists # for. Derived, not hand-tuned: the two can never drift apart. FIRST_REQUEST_WAIT_S = BOOTSTRAP_BUDGET_S + 15.0 +# #4644: a failed bootstrap stage is retried with backoff instead of settling "failed" until the +# host restarts — one transient hiccup (busy disk, momentarily unavailable port) must not cost the +# whole host lifetime. Each attempt gets a FRESH BOOTSTRAP_BUDGET_S; the tuple is the sleep before +# attempts 2..N, so total attempts = len(tuple) + 1. +BOOTSTRAP_RETRY_BACKOFF_S = (10.0, 30.0, 60.0) +# #4644: a ROUTED origin that dies takes the process env with it — the proxy vars were written once +# at bootstrap and nothing would ever clear them, so every later model request hits a dead port +# (connect-refused storms, silent direct connection). Poll the routed origin; N consecutive misses +# (or our own child exiting) unroute it and re-bootstrap. Cadence mirrors the claude lane's proven +# self-heal (30 s tick x 3 failures = recovery within ~90 s, README "Self-healing"). +ORIGIN_WATCH_INTERVAL_S = 30.0 +ORIGIN_WATCH_FAIL_LIMIT = 3 # Core ACP tools whose absence from the OUTGOING request proves this session's tool snapshot was # built before the background registration landed — plugin-mode headers must not be stamped then. CORE_TOOL_NAMES = ("compress", "decompress", "acp_status") @@ -111,6 +123,13 @@ "stop_event": threading.Event(), "warned_direct": False, "snapshot_warned": False, + # #4644 self-healing: watchdog_gen invalidates a previous generation's watchdog thread on + # load/unload; recovering marks an origin-death recovery in flight (single-flight guard); + # env_backup holds what apply_env overwrote so _unroute_env RESTORES it instead of deleting it. + "watchdog_gen": 0, + "watchdog_thread": None, + "recovering": False, + "env_backup": {}, } # Serializes load/unload against bootstrap side effects (tool registration, env routing, child @@ -139,6 +158,10 @@ def _reset_for_test() -> None: _state["stop_event"] = threading.Event() _state["warned_direct"] = False _state["snapshot_warned"] = False + _state["watchdog_gen"] = 0 + _state["watchdog_thread"] = None + _state["recovering"] = False + _state["env_backup"] = {} # — paths --------------------------------------------------------------------- @@ -557,29 +580,49 @@ def _read_marker() -> Optional[Dict[str, Any]]: return None -def claim_starting_marker(token: str, port: int) -> bool: +def claim_starting_marker(token: str, port: int, lane: Optional[str] = None) -> bool: + """Pure O_EXCL claim (#707). A live holder — of ANY lane — wins; the caller inspects the + marker and decides between waiting, removing a stale one, or spawning without coordinating + (#1225 lane semantics).""" path = _marker_path() - marker = {"token": token, "pid": os.getpid(), "host": "127.0.0.1", "port": port, - "startedAt": int(time.time() * 1000)} - while True: - try: - path.parent.mkdir(parents=True, exist_ok=True) - fd = os.open(str(path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(json.dumps(marker)) - return True - except FileExistsError: - cur = _read_marker() - if cur is not None and not _marker_is_stale(cur): - return False - try: - path.unlink() - except FileNotFoundError: - pass - except Exception: - return False - except Exception: - return False + marker: Dict[str, Any] = {"token": token, "pid": os.getpid(), "host": "127.0.0.1", "port": port, + "startedAt": int(time.time() * 1000)} + if lane: + # #1225: declare our lane so OTHER lanes' launchers can tell our bring-up from theirs + # instead of stalling behind it for the whole TTL. + marker["lane"] = lane + try: + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(str(path), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(json.dumps(marker)) + return True + except FileExistsError: + return False + except Exception: + return False + + +def remove_stale_marker() -> bool: + """Unlink ONLY when the holder is verified dead/TTL-expired or unreadable. While any marker + file exists, O_EXCL bars a newer claimant, so this can never clobber a live coordinator.""" + cur = _read_marker() + if cur is not None and not _marker_is_stale(cur): + return False + try: + _marker_path().unlink() + return True + except FileNotFoundError: + return True + except Exception: + return False + + +def _marker_lane_matches(marker: Dict[str, Any]) -> bool: + """#1225: an undeclared lane wildcards on both sides — only two DIFFERENT declared lanes are + mutually invisible to each other's starting markers.""" + lane = marker.get("lane") + return not isinstance(lane, str) or lane == "" or lane == AGENT_NAME def clear_starting_marker(token: str) -> None: @@ -1055,21 +1098,33 @@ def ensure_origin(sidecar: Dict[str, str], deadline: Optional[float] = None) -> if port is None: return None token = uuid.uuid4().hex - claimed = claim_starting_marker(token, port) + claimed = claim_starting_marker(token, port, AGENT_NAME) if not claimed: - while time.monotonic() < deadline: - if _stopped(): - return None - found = discover_instance(sidecar["script"], deadline=deadline, stop=_state.get("stop_event")) - if found: - return _attach(found) - marker = _read_marker() - if marker is None or _marker_is_stale(marker): - break - time.sleep(SPAWN_POLL_S) - if _stopped() or not claim_starting_marker(token, port): - return None - claimed = True + holder = _read_marker() + if holder is not None and not _marker_is_stale(holder): + if _marker_lane_matches(holder): + # A same-lane starter may produce an instance we can attach to: honor its + # bring-up instead of double-spawning over the same session store (#707). + while time.monotonic() < deadline: + if _stopped(): + return None + found = discover_instance(sidecar["script"], deadline=deadline, + stop=_state.get("stop_event")) + if found: + return _attach(found) + marker = _read_marker() + if marker is None or _marker_is_stale(marker) or not _marker_lane_matches(marker): + break + time.sleep(SPAWN_POLL_S) + claimed = claim_starting_marker(token, port, AGENT_NAME) + # A live DIFFERENT-lane holder can never produce an instance this lane may attach to + # (#1225): spawn without coordinating, and leave its marker ALONE — removing it would + # break THAT starter's coordination with its own same-lane launches. + elif remove_stale_marker(): + # Stale or unreadable (crash mid-write): safe to remove — retry once to take the slot. + claimed = claim_starting_marker(token, port, AGENT_NAME) + # Still unclaimed (unwritable state dir, or lost the retry race): degrade to pre-#707 + # behavior — spawn without coordinating; the token-guarded clear below becomes a no-op. try: child = _spawn_child(sidecar, port, token) if child is None: @@ -1101,7 +1156,11 @@ def ensure_origin(sidecar: Dict[str, str], deadline: Optional[float] = None) -> # — runtime effects ------------------------------------------------------------- -def apply_env(origin: str) -> bool: +# The exact keys apply_env routes; _unroute_env restores them one-for-one on origin death (#4644). +_ENV_ROUTED_KEYS = ("HTTPS_PROXY", "https_proxy", "HERMES_CA_BUNDLE", "SSL_CERT_FILE") + + +def apply_env(origin: str, sidecar: Optional[Dict[str, str]] = None, ctx: Any = None) -> bool: """Route hermes's model traffic through the proxy. Only called once the proxy is healthy — the same pair `bili hermes` sets for the launched process. Returns False when the host unloaded the plugin first: routing a torn-down process's traffic would outlive the unload (checked and @@ -1109,6 +1168,13 @@ def apply_env(origin: str) -> bool: with _lifecycle_lock: if _stopped(): return False + if not _state.get("env_applied"): + # Remember what we are about to overwrite so _unroute_env can put it BACK when the + # origin dies mid-session — restoring (not deleting) keeps a user's pre-existing + # proxy configuration intact. + backup = _state.get("env_backup") + if not isinstance(backup, dict) or not backup: + _state["env_backup"] = {key: os.environ.get(key) for key in _ENV_ROUTED_KEYS} os.environ["HTTPS_PROXY"] = origin os.environ["https_proxy"] = origin ca_dir = data_dir() / "ca" @@ -1123,7 +1189,110 @@ def apply_env(origin: str) -> bool: # keep blind-tunnelled hosts validating (#1375). os.environ["SSL_CERT_FILE"] = str(combined) _state["env_applied"] = True - return True + _ensure_watchdog(sidecar, ctx) + return True + + +def _unroute_env() -> None: + """Undo apply_env after the routed origin died (#4644): restore whatever was there before we + routed (or drop the key entirely). Caller holds _lifecycle_lock.""" + backup = _state.get("env_backup") + for key in _ENV_ROUTED_KEYS: + original = backup.get(key) if isinstance(backup, dict) else None + if original is None: + os.environ.pop(key, None) + else: + os.environ[key] = original + _state["env_applied"] = False + _state["env_backup"] = {} + + +def _ensure_watchdog(sidecar: Optional[Dict[str, str]], ctx: Any) -> None: + """Start the origin-health watchdog once per generation (#4644). A live thread means nothing + to do; register()/unload bump watchdog_gen so a previous generation's thread exits on its next + tick instead of double-driving recovery.""" + if sidecar is None or ctx is None or _stopped(): + return + thread = _state.get("watchdog_thread") + if thread is not None and thread.is_alive(): + return + gen = int(_state.get("watchdog_gen") or 0) + watcher = threading.Thread(target=_watchdog_loop, args=(sidecar, ctx, gen), + name="bili-origin-watchdog", daemon=True) + _state["watchdog_thread"] = watcher + watcher.start() + + +def _watchdog_loop(sidecar: Dict[str, str], ctx: Any, gen: int) -> None: + """#4644: poll the ROUTED origin; N consecutive probe failures (or our own child exiting) + mean it is gone — unroute the process env and re-bootstrap inline, watching the new origin. + Without this, the env written once at bootstrap keeps pointing at a dead port for the whole + host lifetime (silent direct connection). The death verdict is re-validated against the + CURRENT origin under the lifecycle lock, so a concurrent re-route/unload wins over a stale + probe result.""" + fails = 0 + while True: + if _stopped() or int(_state.get("watchdog_gen") or 0) != gen: + return + event = _state.get("stop_event") + if event is not None and event.wait(ORIGIN_WATCH_INTERVAL_S): + return + if _stopped() or int(_state.get("watchdog_gen") or 0) != gen: + return + with _lifecycle_lock: + origin = _state.get("origin") + env_applied = bool(_state.get("env_applied")) + child = _state.get("child") + if not origin or not env_applied: + fails = 0 + continue + reason: Optional[str] = None + if child is not None and child.poll() is not None: + reason = f"proxy child exited (code {child.returncode})" + elif probe_proxy(str(origin)): + fails = 0 + continue + else: + fails += 1 + if fails >= ORIGIN_WATCH_FAIL_LIMIT: + reason = f"unreachable {fails}\u00d7 in a row" + if reason is None: + continue + with _lifecycle_lock: + if _stopped() or int(_state.get("watchdog_gen") or 0) != gen: + return + if (_state.get("origin") != origin or not _state.get("env_applied") + or _state.get("recovering")): + fails = 0 + continue + had_tools = bool(_state.get("tools_ready")) + dead_child = _state.get("child") + _unroute_env() + # tool_names stays intact on purpose: the host session snapshot permanently carries + # the registered tools, and their handlers follow _state["origin"] dynamically — so + # the recovered origin serves this session in plugin mode from a fresh fold state. + _state.update(tools_ready=False, origin=None, mode=None, instance_id=None, + child=None, warned_direct=False, recovering=True) + ready = _state.get("ready_event") + if ready is not None: + ready.clear() + rec = _bootstrap_record() + rec.update(state="starting", started_at=time.monotonic(), error=None, attempt=1) + if dead_child is not None: + try: + dead_child.terminate() + except Exception: + pass + logger.warning("billion-context: routed proxy %s is gone (%s) — unrouting and re-bootstrapping; " + "model traffic goes direct until a new origin is healthy", origin, reason) + try: + _bootstrap(sidecar, ctx, skip_register=had_tools) + except Exception as exc: + logger.warning("billion-context: recovery bootstrap failed (%s)", exc) + finally: + with _lifecycle_lock: + _state["recovering"] = False + fails = 0 def make_tool_handler(tool_name: str) -> Callable[..., str]: @@ -1189,44 +1358,93 @@ def _register_tools(ctx: Any, tools: List[Any]) -> List[str]: return names -def _bootstrap(sidecar: Dict[str, str], ctx: Any) -> None: +def _sleep_backoff(attempt: int) -> bool: + """Sleep before bootstrap retry #(attempt+1); False when the plugin was unloaded meanwhile.""" + delays = BOOTSTRAP_RETRY_BACKOFF_S + delay = delays[min(attempt, len(delays)) - 1] + event = _state.get("stop_event") + if event is not None: + return not event.wait(delay) + time.sleep(delay) + return not _stopped() + + +def _bootstrap(sidecar: Dict[str, str], ctx: Any, skip_register: bool = False) -> None: """The slow half of register(): find/spawn a healthy proxy, route the process env through it, and install the native tools. It runs on a daemon thread so the host's load deadline only bounds the cheap registrations (REGISTER_WAIT_S). Every side effect re-checks the stop event: - an unload mid-bootstrap must leave neither a registration nor a child behind.""" + an unload mid-bootstrap must leave neither a registration nor a child behind. + + #4644: failed stages are retried with backoff (BOOTSTRAP_RETRY_BACKOFF_S), each attempt on a + FRESH BOOTSTRAP_BUDGET_S, and a stage that already succeeded is not re-run (a healthy origin + is not re-probed, a registered tool set is not re-fetched). skip_register marks the recovery + path: the host session snapshot already carries the tools from the previous generation and + their handlers follow _state["origin"] dynamically, so registration is re-armed, not repeated.""" rec = _bootstrap_record() - deadline = time.monotonic() + BOOTSTRAP_BUDGET_S + max_attempts = len(BOOTSTRAP_RETRY_BACKOFF_S) + 1 + origin: Optional[str] = None + env_ok = False try: - origin = ensure_origin(sidecar, deadline=deadline) - if _stopped(): - _reap_unready_child() - return - if not origin: - rec.update(state="failed", error="could not reach or start a bili proxy") - logger.warning("billion-context: could not reach or start a bili proxy — model traffic " - "goes direct (uncompressed) in this process") - return - if not apply_env(origin): - _reap_unready_child() - return - manifest = http_get_json(origin.rstrip("/") + "/__bili/plugin/manifest", MANIFEST_TIMEOUT_S) - tools = manifest.get("tools", {}).get("anthropic") if isinstance(manifest, dict) else None - if not isinstance(tools, list) or not tools: - rec.update(state="failed", error="proxy manifest had no tool definitions") - logger.warning("billion-context: proxy manifest had no tool definitions — compression " - "stays server-side (proxy mode)") - return - names = _register_tools(ctx, tools) - if not _state.get("tools_ready"): - _reap_unready_child() - return - with _lifecycle_lock: + for attempt in range(1, max_attempts + 1): + rec.update(attempt=attempt) if _stopped(): _reap_unready_child() return - rec.update(state="ready", error=None) - logger.info("billion-context: hermes native mode ready (%s, tools: %s)", - _state.get("mode"), ", ".join(names)) + if origin is None: + deadline = time.monotonic() + BOOTSTRAP_BUDGET_S + origin = ensure_origin(sidecar, deadline=deadline) + if _stopped(): + _reap_unready_child() + return + if not origin: + if attempt < max_attempts: + if not _sleep_backoff(attempt): + return # unloaded during the backoff — _shutdown owns the record + logger.warning("billion-context: could not reach or start a bili proxy " + "(attempt %d/%d) — retrying", attempt, max_attempts) + continue + rec.update(state="failed", error=f"could not reach or start a bili proxy " + f"(after {attempt} attempt{'s' if attempt > 1 else ''})") + logger.warning("billion-context: could not reach or start a bili proxy after " + "%d attempt%s — model traffic goes direct (uncompressed) in " + "this process", attempt, "s" if attempt > 1 else "") + return + if not env_ok: + if not apply_env(origin, sidecar, ctx): + _reap_unready_child() + return + env_ok = True + if skip_register and _state.get("tool_names"): + names = list(_state["tool_names"]) + with _lifecycle_lock: + if _stopped(): + _reap_unready_child() + return + _state["tools_ready"] = True + else: + manifest = http_get_json(origin.rstrip("/") + "/__bili/plugin/manifest", MANIFEST_TIMEOUT_S) + tools = manifest.get("tools", {}).get("anthropic") if isinstance(manifest, dict) else None + if not isinstance(tools, list) or not tools: + if attempt < max_attempts and _sleep_backoff(attempt): + logger.warning("billion-context: proxy manifest had no tool definitions " + "(attempt %d/%d) — retrying", attempt, max_attempts) + continue + rec.update(state="failed", error="proxy manifest had no tool definitions") + logger.warning("billion-context: proxy manifest had no tool definitions — " + "compression stays server-side (proxy mode)") + return + names = _register_tools(ctx, tools) + if not _state.get("tools_ready"): + _reap_unready_child() + return + with _lifecycle_lock: + if _stopped(): + _reap_unready_child() + return + rec.update(state="ready", error=None) + logger.info("billion-context: hermes native mode ready (%s, attempt %d, tools: %s)", + _state.get("mode"), attempt, ", ".join(names)) + return except Exception as exc: if not _stopped(): rec.update(state="failed", error=f"{type(exc).__name__}: {exc}") @@ -1268,12 +1486,18 @@ def _shutdown() -> None: _state["loaded"] = False _state["tools_ready"] = False _state["tool_names"] = () + # Invalidate any watchdog of this generation: it must not drive recovery for an + # unloaded plugin (the stop event above wakes it from its tick wait anyway). + _state["watchdog_gen"] = int(_state.get("watchdog_gen") or 0) + 1 rec = _state.get("bootstrap") if isinstance(rec, dict) and rec.get("state") != "ready": rec.update(state="stopped", error=None) thread = _state.get("thread") if thread is not None and thread.is_alive() and thread is not threading.current_thread(): thread.join(timeout=1.0) + watcher = _state.get("watchdog_thread") + if watcher is not None and watcher.is_alive() and watcher is not threading.current_thread(): + watcher.join(timeout=1.0) _reap_unready_child() @@ -1473,9 +1697,11 @@ def acp_command(raw_args: str = "", *, session_id: str = "") -> Optional[str]: if boot_state == "starting": started = boot.get("started_at") elapsed = max(0.0, time.monotonic() - float(started)) if isinstance(started, (int, float)) else 0.0 - return (f"bili: proxy is starting in the background{where} ({elapsed:.0f}s elapsed, " - f"budget {BOOTSTRAP_BUDGET_S:.0f}s) — model traffic is held until it is " - "ready; run /acp again in a moment.") + attempt = boot.get("attempt") + attempt_note = f", attempt {attempt}" if isinstance(attempt, int) and attempt > 1 else "" + return (f"bili: proxy is starting in the background{where}{attempt_note} " + f"({elapsed:.0f}s elapsed, budget {BOOTSTRAP_BUDGET_S:.0f}s per attempt) — " + "model traffic is held until it is ready; run /acp again in a moment.") detail = str(boot.get("error") or "unknown error") if origin and _state.get("env_applied"): return (f"bili: proxy at {origin} is up but the native tool manifest is unavailable " @@ -1588,6 +1814,9 @@ def register(ctx: Any) -> None: # a stale stop event would kill the new bootstrap on its first check, so this # generation gets fresh events and a clean record. _state["stop_event"] = threading.Event() + # New generation: a previous generation's watchdog (if any) exits on its next tick + # instead of racing this bootstrap for recovery. + _state["watchdog_gen"] = int(_state.get("watchdog_gen") or 0) + 1 _state["ready_event"] = threading.Event() _state["bootstrap"] = None _state["loaded"] = True diff --git a/tests/hermes-native.test.ts b/tests/hermes-native.test.ts index c5d04d6ffd..0c573b0168 100644 --- a/tests/hermes-native.test.ts +++ b/tests/hermes-native.test.ts @@ -404,8 +404,10 @@ class FakeCtx: self.hooks = {} self.commands = {} self.unload = [] + self.reg_counts = {} def register_tool(self, name=None, toolset=None, schema=None, handler=None, description="", **kw): + self.reg_counts[name] = self.reg_counts.get(name, 0) + 1 self.tools[name] = {"toolset": toolset, "schema": schema, "handler": handler, "description": description} def register_middleware(self, kind, cb): @@ -540,6 +542,7 @@ elif SCENARIO == "slow-boot-fail": os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN mod.REGISTER_WAIT_S = 0.2 mod.BOOTSTRAP_BUDGET_S = 0.4 + mod.BOOTSTRAP_RETRY_BACKOFF_S = (0.1, 0.2, 0.3) mod.FIRST_REQUEST_WAIT_S = 2.0 SLOW["enabled"] = True mod.register(ctx) @@ -817,6 +820,162 @@ elif SCENARIO.startswith("mitm-"): out["mitm_kind"] = kind out["mitm_domains"] = mod.mitm_domains_from_config() out["mitm_warnings"] = list(WARNINGS) +elif SCENARIO == "retry-recover": + # #4644: attempt 1 hits a still-booting proxy; the backoff retry lands when it comes up. + install_sidecar(False) + os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN + mod.REGISTER_WAIT_S = 0.2 + mod.BOOTSTRAP_BUDGET_S = 1.0 + mod.BOOTSTRAP_RETRY_BACKOFF_S = (0.5, 1.0, 2.0) + mod.FIRST_REQUEST_WAIT_S = 3.0 + SLOW["enabled"] = True + def release_later(): + __import__("time").sleep(1.8) + SLOW["release"].set() + threading.Thread(target=release_later, daemon=True).start() + mod.register(ctx) + ready = mod._state.get("ready_event") + if ready is not None: + ready.wait(30) + rec = mod._state.get("bootstrap") or {} + out["retry_state"] = rec.get("state") + out["retry_attempt"] = rec.get("attempt") + out["retry_env"] = os.environ.get("HTTPS_PROXY") + out["retry_tools"] = sorted(ctx.tools.keys()) + out["retry_warnings"] = [w for w in WARNINGS if "retrying" in w] +elif SCENARIO == "retry-exhaust": + # #4644: a proxy that never comes up exhausts all attempts and settles failed (loudly). + install_sidecar(True) + os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN + mod.REGISTER_WAIT_S = 0.2 + mod.BOOTSTRAP_BUDGET_S = 0.3 + mod.BOOTSTRAP_RETRY_BACKOFF_S = (0.1, 0.1, 0.1) + mod.FIRST_REQUEST_WAIT_S = 1.0 + SLOW["enabled"] = True + mod.register(ctx) + thread = mod._state.get("thread") + if thread is not None: + thread.join(15) + rec = mod._state.get("bootstrap") or {} + out["exhaust_state"] = rec.get("state") + out["exhaust_error"] = rec.get("error") + out["exhaust_attempt"] = rec.get("attempt") + out["exhaust_env"] = os.environ.get("HTTPS_PROXY") + out["exhaust_acp"] = mod.acp_command("", session_id="sess-ex") + out["exhaust_warnings_retries"] = len([w for w in WARNINGS if "retrying" in w]) +elif SCENARIO == "origin-death": + # #4644: the routed origin dies after readiness; the watchdog unroutes (RESTORING the + # user's pre-existing proxy) and re-bootstraps without re-registering the tools. + install_sidecar(False) + os.environ["BILLION_CONTEXT_ATTACH"] = ORIGIN + os.environ["HTTPS_PROXY"] = "http://user-proxy.example:9999" + mod.REGISTER_WAIT_S = 0.2 + mod.BOOTSTRAP_BUDGET_S = 8.0 + mod.FIRST_REQUEST_WAIT_S = 8.0 + mod.ORIGIN_WATCH_INTERVAL_S = 0.2 + mod.ORIGIN_WATCH_FAIL_LIMIT = 2 + mod.register(ctx) + ready = mod._state.get("ready_event") + if ready is not None: + ready.wait(10) + out["death_initial_ready"] = (mod._state.get("bootstrap") or {}).get("state") + out["death_env_routed"] = os.environ.get("HTTPS_PROXY") + SLOW["enabled"] = True + def release_later(): + __import__("time").sleep(1.5) + SLOW["release"].set() + threading.Thread(target=release_later, daemon=True).start() + gap_values = [] + saw_gap = False + end = __import__("time").monotonic() + 20 + while __import__("time").monotonic() < end: + v = os.environ.get("HTTPS_PROXY") + gap_values.append(v) + if v != ORIGIN: + saw_gap = True + rec = mod._state.get("bootstrap") or {} + if saw_gap and rec.get("state") == "ready" and v == ORIGIN: + break + __import__("time").sleep(0.05) + out["death_gap_values"] = list(dict.fromkeys(gap_values)) + rec = mod._state.get("bootstrap") or {} + out["death_final_state"] = rec.get("state") + out["death_final_env"] = os.environ.get("HTTPS_PROXY") + out["death_tools"] = sorted(ctx.tools.keys()) + out["death_register_calls"] = sum(ctx.reg_counts.values()) + out["death_warnings"] = [w for w in WARNINGS if "is gone" in w] +elif SCENARIO == "marker-foreign": + # #1225/#4644: our own claims declare the lane; a live FOREIGN-lane starter neither blocks us + # nor gets its marker removed (we spawn our own proxy beside it). + ok = mod.claim_starting_marker("lane-check", 1, "hermes") + m = mod._read_marker() + out["own_claim_lane"] = (m or {}).get("lane") if ok else None + mod.clear_starting_marker("lane-check") + # .cjs on purpose: BASE sits inside this ESM repo ("type": "module"), where a .js fixture + # using require() would die before writing anything. + proof_bytes = (b'require("fs").writeFileSync(require("path").join(process.env.XDG_STATE_HOME, ' + b'"billion-context", "spawn-proof.json"), JSON.stringify({started: true, ' + b'lane: process.env.BILI_LAUNCHER_LANE}));\n') + script = os.path.join(BASE, "proxy.cjs") + with open(script, "wb") as f: + f.write(proof_bytes) + with open(os.path.join(PLUGIN_DIR, "bili.json"), "w") as f: + json.dump({"proxyScript": script, "nodePath": os.environ["BC_NODE"]}, f) + sd = os.path.join(os.environ["XDG_STATE_HOME"], "billion-context") + os.makedirs(sd, exist_ok=True) + with open(os.path.join(sd, "proxy-starting"), "w") as f: + json.dump({"token": "foreign-token", "pid": os.getpid(), "host": "127.0.0.1", "port": 4321, + "startedAt": int(__import__("time").time() * 1000), "lane": "dsh"}, f) + mod.BOOTSTRAP_BUDGET_S = 0.5 + mod.BOOTSTRAP_RETRY_BACKOFF_S = (0.1, 0.1, 0.1) + mod.FIRST_REQUEST_WAIT_S = 1.0 + mod.register(ctx) + thread = mod._state.get("thread") + if thread is not None: + thread.join(20) + out["state_after_foreign"] = (mod._state.get("bootstrap") or {}).get("state") + try: + with open(os.path.join(os.environ["XDG_STATE_HOME"], "billion-context", "spawn-proof.json")) as f: + out["spawn_proof"] = json.load(f) + except Exception: + out["spawn_proof"] = None + m = mod._read_marker() + out["foreign_marker_kept"] = bool(m and m.get("token") == "foreign-token" and m.get("lane") == "dsh") +elif SCENARIO == "marker-same-lane": + # #1225/#4644: a SAME-lane starter is honored — we wait for its instance instead of + # double-spawning, and its marker stays untouched. The instance appears mid-wait + # (discovery runs once up front, so pre-writing it would bypass the marker path). + proof_bytes = (b'require("fs").writeFileSync(require("path").join(process.env.XDG_STATE_HOME, ' + b'"billion-context", "spawn-proof.json"), "1");\n') + script = os.path.join(BASE, "proxy.js") + with open(script, "wb") as f: + f.write(proof_bytes) + with open(os.path.join(PLUGIN_DIR, "bili.json"), "w") as f: + json.dump({"proxyScript": script, "nodePath": os.environ["BC_NODE"]}, f) + sd = os.path.join(os.environ["XDG_STATE_HOME"], "billion-context") + os.makedirs(sd, exist_ok=True) + with open(os.path.join(sd, "proxy-starting"), "w") as f: + json.dump({"token": "starter-token", "pid": os.getpid(), "host": "127.0.0.1", "port": 4321, + "startedAt": int(__import__("time").time() * 1000), "lane": "hermes"}, f) + def publish_later(): + __import__("time").sleep(0.6) + rec = {"origin": ORIGIN, "pid": os.getpid(), "instanceId": "drv-starter", + "codeFingerprint": hashlib.sha256(proof_bytes).hexdigest(), "host": "127.0.0.1", + "passthrough": False, "mitmDomains": [], "modelWindows": {}, "startedAt": 1, + "lane": "hermes", "launchToken": "tok"} + with open(os.path.join(sd, "proxy-origin"), "w") as f: + json.dump(rec, f) + threading.Thread(target=publish_later, daemon=True).start() + mod.BOOTSTRAP_BUDGET_S = 8.0 + mod.register(ctx) + ready = mod._state.get("ready_event") + if ready is not None: + ready.wait(10) + out["mode_same_lane"] = mod._state.get("mode") + out["env_same_lane"] = os.environ.get("HTTPS_PROXY") + m = mod._read_marker() + out["starter_marker_kept"] = bool(m and m.get("token") == "starter-token") + out["same_lane_spawned"] = os.path.exists(os.path.join(sd, "spawn-proof.json")) else: raise SystemExit("unknown scenario: " + SCENARIO) @@ -840,6 +999,7 @@ out.update({ "commands": {k: v["description"] for k, v in ctx.commands.items()}, "unload_callbacks": len(ctx.unload), "status_calls": RECORDED["status"], + "register_calls": sum(ctx.reg_counts.values()), }) server.shutdown() print(json.dumps(out)) @@ -921,6 +1081,34 @@ interface DriverOut { env_after_unload?: string | null; mw_after_unload_none?: boolean; acp_after_unload?: string | null; + register_calls?: number; + retry_state?: string; + retry_attempt?: number; + retry_env?: string | null; + retry_tools?: string[]; + retry_warnings?: string[]; + exhaust_state?: string; + exhaust_error?: string | null; + exhaust_attempt?: number; + exhaust_env?: string | null; + exhaust_acp?: string | null; + exhaust_warnings_retries?: number; + death_initial_ready?: string; + death_env_routed?: string | null; + death_gap_values?: Array; + death_final_state?: string; + death_final_env?: string | null; + death_tools?: string[]; + death_register_calls?: number; + death_warnings?: string[]; + own_claim_lane?: string | null; + spawn_proof?: { started?: boolean; lane?: string } | null; + foreign_marker_kept?: boolean; + state_after_foreign?: string; + mode_same_lane?: string; + env_same_lane?: string | null; + starter_marker_kept?: boolean; + same_lane_spawned?: boolean; } function runDriver(scenario: string, extraEnv: Record = {}): { out: DriverOut | null; err: string } { @@ -1315,6 +1503,69 @@ describe("python plugin runtime (subprocess)", () => { assert.equal(out!.ready_event_set, true); }); + // #4644 self-healing: a failed bootstrap stage is retried with backoff instead of settling + // "failed" for the whole host lifetime, a routed origin that dies is unrouted and re-bootstrapped, + // and the starting marker carries the lane so cross-lane starters neither block nor are clobbered. + test("bootstrap retry: a failed start is retried with backoff and lands when the proxy comes up", () => { + if (!PY) return; + const { out, err } = runDriver("retry-recover"); + assert.ok(out, err); + assert.equal(out!.retry_state, "ready"); + assert.equal(out!.retry_attempt, 2, "the second attempt is the one that landed"); + assert.equal(out!.retry_env, out!.origin, "traffic is routed after the successful retry"); + assert.deepEqual(out!.retry_tools, ["acp_status", "compress", "decompress"]); + assert.equal(out!.retry_warnings!.length, 1, "each failed attempt logs one retry warning"); + }); + + test("bootstrap retry: persistent failure exhausts the attempts and settles failed loudly", () => { + if (!PY) return; + const { out, err } = runDriver("retry-exhaust"); + assert.ok(out, err); + assert.equal(out!.exhaust_state, "failed"); + assert.equal(out!.exhaust_attempt, 4, "all four attempts ran before giving up"); + assert.match(out!.exhaust_error!, /after 4 attempts/); + assert.equal(out!.exhaust_env, null, "env is not routed through an unreachable proxy"); + assert.match(out!.exhaust_acp!, /failed to start/); + assert.match(out!.exhaust_acp!, /going direct/); + assert.equal(out!.exhaust_warnings_retries, 3, "three retries between the four attempts"); + }); + + test("origin death: a dying routed proxy is unrouted (restoring prior env) and re-bootstrapped", () => { + if (!PY) return; + const { out, err } = runDriver("origin-death"); + assert.ok(out, err); + assert.equal(out!.death_initial_ready, "ready"); + assert.equal(out!.death_env_routed, out!.origin); + assert.ok(out!.death_gap_values!.includes("http://user-proxy.example:9999"), + "the unroute RESTORED the pre-existing user proxy instead of deleting the key"); + assert.equal(out!.death_final_state, "ready", "the watchdog re-bootstrapped a healthy origin"); + assert.equal(out!.death_final_env, out!.origin, "traffic is routed through the recovered origin again"); + assert.deepEqual(out!.death_tools, ["acp_status", "compress", "decompress"]); + assert.equal(out!.death_register_calls, 3, "recovery re-arms readiness without re-registering tools"); + assert.equal(out!.death_warnings!.length, 1, "one loud warning per death episode"); + }); + + test("starting marker: our claim declares the lane; a live foreign-lane starter blocks nothing and is untouched", () => { + if (!PY) return; + const { out, err } = runDriver("marker-foreign"); + assert.ok(out, err); + assert.equal(out!.own_claim_lane, "hermes", "our claims carry the lane for other lanes' launchers"); + assert.ok(out!.spawn_proof?.started, "we spawned our own proxy instead of stalling behind the foreign marker"); + assert.equal(out!.spawn_proof?.lane, "hermes"); + assert.equal(out!.foreign_marker_kept, true, "the foreign starter's marker stays intact"); + assert.equal(out!.state_after_foreign, "failed"); + }); + + test("starting marker: a same-lane starter is honored — wait + attach, no double-spawn, marker untouched", () => { + if (!PY) return; + const { out, err } = runDriver("marker-same-lane"); + assert.ok(out, err); + assert.equal(out!.mode_same_lane, "attach", "attached to the same-lane starter's instance"); + assert.equal(out!.env_same_lane, out!.origin, "traffic is routed through it"); + assert.equal(out!.same_lane_spawned, false, "no double-spawn over the starter's bring-up"); + assert.equal(out!.starter_marker_kept, true); + }); + test("unload mid-bootstrap: no late tool registration, the thread stops, and the middleware goes inert", () => { if (!PY) return; const { out, err } = runDriver("slow-boot-unload"); From ef1d2728161d1b29d5b64a7e6c659cd8de78dc56 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 13:01:15 +0800 Subject: [PATCH 3/4] fix(hermes): final discovery probe closes the same-lane wait deadline sliver (#4644) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fix on 2026-10-25_hermes-selfheal: the same-lane marker wait loop in ensure_origin exited at the shared deadline without a last discovery pass, while the reference implementation (waitForStarterInstance, src/launcher.ts) probes once more first — its success path clears the starting marker, so an attach landing right at the boundary is indistinguishable from a failure bail without that look, and we double-spawn over the starter's bring-up instead of attaching. Add the single-shot pass (no deadline arg = pure one-shot) before the post-wait claim, mirroring the TS lane. --- hermes-plugin/__init__.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index 772ba5acdb..c437a88c2a 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -1116,6 +1116,13 @@ def ensure_origin(sidecar: Dict[str, str], deadline: Optional[float] = None) -> if marker is None or _marker_is_stale(marker) or not _marker_lane_matches(marker): break time.sleep(SPAWN_POLL_S) + # Final discovery pass closes the deadline-boundary sliver (#707, mirrors + # waitForStarterInstance in src/launcher.ts): the starter's own poll window ends + # ~now and its success path clears the marker — without one last look, an attach + # landing right at the boundary looks like a failure bail and double-spawns. + found = discover_instance(sidecar["script"], stop=_state.get("stop_event")) + if found: + return _attach(found) claimed = claim_starting_marker(token, port, AGENT_NAME) # A live DIFFERENT-lane holder can never produce an instance this lane may attach to # (#1225): spawn without coordinating, and leave its marker ALONE — removing it would From f74c28d21eef797bc9ac76c029686f29fb6ee7b2 Mon Sep 17 00:00:00 2001 From: repo-owner-agent Date: Mon, 26 Oct 2026 10:05:41 +0800 Subject: [PATCH 4/4] fix(hermes): port the #4658 registry-pid adoption into the restructured spawn poll (#4646, #4656) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebase follow-up on #4646: the branch rewrote the spawn-poll loop inside the background _bootstrap and thereby dropped the #4656 fix that #4658 implements on master's structure. Port it into the new loop: - _find_spawned_in_registry(child_pid) (latest started_at among same-pid markers, #4658 review hardening) after the shared-pointer token check and before the child-exit check, with the manifest health probe before adoption - adoption now also records instance_id (the #4658 review nit — /acp panels show the adopted instance instead of a blank id) - tests ported under the new structure: spawn-clobber waits on the bootstrap readiness event (register() returns early now) and pins the instance_id; registry-find keeps rf_own/rf_foreign/rf_dead/rf_none plus the dup-pid aaa-stale vs zzz-own started_at tie-break --- hermes-plugin/__init__.py | 27 ++++++++++ tests/hermes-native.test.ts | 99 +++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index c437a88c2a..e99b0bb5ec 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -422,6 +422,28 @@ def read_registry_entries() -> List[Dict[str, Any]]: return entries +def _find_spawned_in_registry(child_pid: Optional[int]) -> Optional[Dict[str, Any]]: + """#4656 / Python twin of #2954 (src/launcher.ts): locate OUR spawned child among the + per-instance registry markers by pid. The single proxy-origin file is last-writer-wins + machine-wide, so a concurrent bring-up registering AFTER our child overwrites it with a + foreign launchToken and starves the shared-pointer match for the whole budget — but the + registry omits the launcher-private token and is keyed per instance, so it cannot be + clobbered that way; the pid WE spawned is the reliable identity proof (a concurrent writer + cannot fake it). If several markers carry that pid — a stale one from a previous run whose + dead pid the OS later reused for our child — the newest registration wins: our child's own + marker always postdates the stale one (the TS twin closes the same corner with a + responder-pid check, src/launcher.ts #2954). The caller still health-probes the returned + origin before trusting it.""" + if not isinstance(child_pid, int) or child_pid <= 1: + return None + best: Optional[Dict[str, Any]] = None + for entry in read_registry_entries(): + if entry.get("pid") == child_pid and entry.get("origin"): + if best is None or entry.get("started_at", 0) > best.get("started_at", 0): + best = entry + return best + + def pid_alive(pid: Optional[int]) -> bool: if not isinstance(pid, int) or pid <= 1: return False @@ -1144,6 +1166,11 @@ def ensure_origin(sidecar: Dict[str, str], deadline: Optional[float] = None) -> if inst and inst.get("launch_token") == token and probe_proxy(inst["origin"]): _state.update(origin=inst["origin"], mode="spawn") return inst["origin"] + mine = _find_spawned_in_registry(child.pid) + if mine and probe_proxy(mine["origin"]): + _state.update(origin=mine["origin"], mode="spawn", + instance_id=mine.get("instance_id") or None) + return mine["origin"] if child.poll() is not None: logger.warning("billion-context: proxy child exited before becoming healthy " "(code %s); log: %s", child.returncode, diff --git a/tests/hermes-native.test.ts b/tests/hermes-native.test.ts index 0c573b0168..08c7855a75 100644 --- a/tests/hermes-native.test.ts +++ b/tests/hermes-native.test.ts @@ -976,6 +976,61 @@ elif SCENARIO == "marker-same-lane": m = mod._read_marker() out["starter_marker_kept"] = bool(m and m.get("token") == "starter-token") out["same_lane_spawned"] = os.path.exists(os.path.join(sd, "spawn-proof.json")) +elif SCENARIO == "spawn-clobber": + # #4656: the global proxy-origin file is last-writer-wins machine-wide. A concurrent + # bring-up registering AFTER our child overwrites it with a foreign launchToken, starving + # the shared-pointer match for the whole budget -> old code SIGKILLed the healthy child at + # timeout and the host went inert (model traffic direct). Pre-seed the clobbered pointer + # (foreign lane + token, so discovery rejects it too); our spawned child self-registers by + # pid in the per-instance registry (no launcher-private token there), which cannot be + # clobbered that way. The fix must find OUR child there and adopt its origin. The bootstrap + # runs on the background thread (register() returns early): wait on its readiness event. + script = os.path.join(BASE, "proxy.cjs") + with open(script, "w") as f: + f.write( + 'const fs=require("fs"),path=require("path");' + 'const sd=path.join(process.env.XDG_STATE_HOME,"billion-context","instances");' + 'fs.mkdirSync(sd,{recursive:true});' + 'fs.writeFileSync(path.join(sd,"drv-spawn.json"),JSON.stringify({' + 'origin:process.env.BC_FAKE_ORIGIN,pid:process.pid,instanceId:"drv-spawn",' + 'host:"127.0.0.1",passthrough:false,mitmDomains:[],modelWindows:{},startedAt:Date.now()}));' + 'setTimeout(()=>{},3000);\n' + ) + with open(os.path.join(PLUGIN_DIR, "bili.json"), "w") as f: + json.dump({"proxyScript": script, "nodePath": os.environ["BC_NODE"]}, f) + os.environ["BC_FAKE_ORIGIN"] = ORIGIN + write_origin(inst_rec(False, lane="dsh", token="foreign-token")) + mod.BOOTSTRAP_BUDGET_S = 10.0 + mod.register(ctx) + ready = mod._state.get("ready_event") + if ready is not None: + ready.wait(10) + out["spawn_mode"] = mod._state.get("mode") + out["spawn_origin"] = mod._state.get("origin") +elif SCENARIO == "registry-find": + # #4656 acceptance criteria for _find_spawned_in_registry: accept ONLY our child's own pid + # with a live origin; never a live foreign instance (its own launchToken) nor a stale marker + # left by a dead pid from a previous run. Each sub-case seeds an isolated registry. + rd = os.path.join(os.environ["XDG_STATE_HOME"], "billion-context", "instances") + def seed(recs): + shutil.rmtree(rd, ignore_errors=True) + os.makedirs(rd, exist_ok=True) + for iid, rec in recs.items(): + with open(os.path.join(rd, iid + ".json"), "w") as f: + json.dump(rec, f) + seed({"own": {"origin": ORIGIN, "pid": 4242, "instanceId": "own"}}) + out["rf_own"] = (mod._find_spawned_in_registry(4242) or {}).get("instance_id") + seed({"foreign": {"origin": ORIGIN, "pid": 7777, "instanceId": "foreign", "launchToken": "other"}}) + out["rf_foreign"] = mod._find_spawned_in_registry(4242) + seed({"stale": {"origin": ORIGIN, "pid": 12345, "instanceId": "stale"}}) + out["rf_dead"] = mod._find_spawned_in_registry(4242) + # Two markers share OUR child's pid: a stale one from a previous run whose dead pid the OS + # reused (it sorts FIRST by filename) plus our child's own newer registration. The newest + # started_at must win — never the alphabetically-first stale marker (#4658 review). + seed({"aaa-stale": {"origin": ORIGIN, "pid": 4242, "instanceId": "aaa-stale", "startedAt": 1}, + "zzz-own": {"origin": ORIGIN, "pid": 4242, "instanceId": "zzz-own", "startedAt": 999}}) + out["rf_dup_pid"] = (mod._find_spawned_in_registry(4242) or {}).get("instance_id") + out["rf_none"] = mod._find_spawned_in_registry(None) else: raise SystemExit("unknown scenario: " + SCENARIO) @@ -1109,6 +1164,13 @@ interface DriverOut { env_same_lane?: string | null; starter_marker_kept?: boolean; same_lane_spawned?: boolean; + spawn_mode?: string | null; + spawn_origin?: string | null; + rf_own?: string | null; + rf_foreign?: unknown; + rf_dead?: unknown; + rf_dup_pid?: string | null; + rf_none?: unknown; } function runDriver(scenario: string, extraEnv: Record = {}): { out: DriverOut | null; err: string } { @@ -1413,6 +1475,43 @@ describe("python plugin runtime (subprocess)", () => { assert.equal(out!.env_https_proxy, null, "dummy sidecar never serves — inert"); }); + // #4656: the shared proxy-origin pointer is last-writer-wins machine-wide. When a concurrent + // bring-up clobbers it AFTER our child registers, a loop that only trusts that pointer's + // launchToken starves for the whole budget and SIGKILLs our healthy child -> the host goes + // inert (model traffic direct). The fix finds OUR child by pid in the per-instance registry + // (no launcher token there, cannot be clobbered) and adopts its origin. Positive regression: + // on the pre-fix code this scenario times out and stays inert (tools_registered empty). + test("spawn: survives a concurrent clobber of the shared proxy-origin; adopts own child via registry (#4656)", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("spawn-clobber"); + assert.ok(out, err); + assert.equal(out!.spawn_mode, "spawn", "own healthy child adopted despite the clobbered shared pointer"); + assert.equal(out!.spawn_origin, out!.origin, "adopted origin is the child's self-registered origin"); + assert.equal(out!.instance_id, "drv-spawn", "registry adoption records the child's instance id"); + assert.deepEqual(out!.tools_registered, ["acp_status", "compress", "decompress"], "plugin became active, not inert"); + assert.equal(out!.marker_left, false, "starting marker cleaned up"); + }); + + // #4656: _find_spawned_in_registry accepts ONLY our child's own pid with a live origin — never + // a live foreign instance carrying its own launchToken, nor a stale marker left by a dead pid + // from a previous run. Deterministic (no subprocess): each sub-case seeds an isolated registry. + test("_find_spawned_in_registry matches only our child's own pid (#4656)", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("registry-find"); + assert.ok(out, err); + assert.equal(out!.rf_own, "own", "our child's own pid resolves to its marker"); + assert.equal(out!.rf_foreign, null, "a live foreign instance (its own launchToken) is never mistaken for ours"); + assert.equal(out!.rf_dead, null, "a stale marker from a dead pid is not adopted"); + assert.equal(out!.rf_dup_pid, "zzz-own", "two markers sharing our child's pid (reused-pid corner): the newest registration wins, never the alphabetically-first stale one"); + assert.equal(out!.rf_none, null, "no child pid -> never match"); + }); + for (const [scenario, extraEnv] of [ ["gate-opt-out", { BILI_NATIVE_HERMES: "0" }], ["gate-plugin-0", { BILLION_CONTEXT_PLUGIN: "0" }],