The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e): gate the tenancy and C20 expected failures on merge-order-safe probes
teknium1b37b8089bfb2
diff --git a/tests/e2e/core/_pending_fixes.py b/tests/e2e/core/_pending_fixes.pynew file mode 100644index 00000000000..5d2241167b4--- /dev/null+++ b/tests/e2e/core/_pending_fixes.py@@ -0,0 +1,170 @@+"""Merge-order-safe expected failures for live gaps whose fix is an open PR.++A plain ``xfail(strict=True)`` turns main red the moment its fix merges (XPASS), and a+non-strict one guards nothing. Instead, each gap here has a PROBE: a few lines that reproduce+the defect's mechanism on the tree under test, in a throwaway interpreter with its own+``HOME``/``HERMES_HOME`` (no state leaks into the suite process). ``expect_gaps`` applies an+xfail only while a probe still reproduces its defect, and only for the bug-specific exception+that cell raises when it observes THAT leak (``raises=``): a timeout, a boot failure or any+other assertion still fails the cell. Once the fix is in the tree the cell runs as a plain+test, so it must pass. Whichever lands first, suite or fix, main stays green.++``strict=False`` is only for a gap the end-to-end cell reproduces probabilistically (a race);+the probe itself is deterministic, so the mark still disappears when the fix lands.++Same pattern as ``tests/e2e/core/delivery/_pending_fixes.py`` (PR #120344). When a fix has+landed, delete its probe and every ``Gap`` naming it.+"""++from __future__ import annotations++import functools+import json+import os+import subprocess+import sys+import tempfile+from dataclasses import dataclass+from pathlib import Path+from typing import Dict, Tuple, Type++import pytest++REPO_ROOT = Path(__file__).resolve().parents[3]++# ``verdict`` writes to a file, not stdout: importing tui_gateway.server repoints stdout (its JSON-RPC+# channel) at stderr.+_PRELUDE = ("import json, os, sys\nfrom pathlib import Path\nsys.path.insert(0, os.getcwd())\n"+ "HOME = Path(os.environ['HERMES_HOME'])\n"+ "def verdict(v):\n Path(os.environ['GAP_VERDICT']).write_text(v)\n")++# PR -> (extra env, script). A script records ``open`` while the defect reproduces, ``fixed`` once+# it no longer does; anything else (including a crash) fails the cell that asked.+PROBES: Dict[int, Tuple[Dict[str, str], str]] = {+ # Desktop backend: a secondary profile's session.create / lazy session info reported (and+ # stored) the LAUNCH profile's configured model.+ 120319: ({}, r'''+(HOME / "config.yaml").write_text("model:\n default: launch-model\n")+alpha = HOME / "profiles" / "alpha"+alpha.mkdir(parents=True)+(alpha / "config.yaml").write_text("model:\n default: alpha-model\n")+from tui_gateway import server+model = server._lazy_resume_info(str(HOME), profile="alpha")["model"]+verdict({"launch-model": "open", "alpha-model": "fixed"}.get(model, f"unexpected model {model!r}"))+'''),+ # Multiplexed host: (a) the first import of gateway.run under a routed profile's home override+ # loaded THAT profile's .env into the process env; (b) session-less work (cron) for a routed+ # profile reused the shared "default" terminal environment.+ 120307: ({}, r'''+alpha = HOME / "profiles" / "alpha"+alpha.mkdir(parents=True)+(alpha / ".env").write_text("C7_PROBE_ROUTED_CANARY=alpha\n")+from hermes_constants import set_hermes_home_override+set_hermes_home_override(str(alpha))+import gateway.run # noqa: F401+bridged = os.environ.get("C7_PROBE_ROUTED_CANARY") == "alpha"+from tools.terminal_tool import _resolve_container_task_id+shared = _resolve_container_task_id(None) == "default"+verdict("open" if bridged or shared else "fixed")+'''),+ # Credential routing: (a) with no OpenRouter key, the OpenRouter resolver fell back to an+ # OPENAI_API_KEY that OPENAI_BASE_URL binds to another host; (b) the pre-request Anthropic+ # credential refresh ran for provider 'anthropic' on a foreign (alias) host.+ 120299: ({"OPENAI_API_KEY": "sk-probe-bound-elsewhere", "OPENAI_BASE_URL": "http://127.0.0.1:9/v1"}, r'''+(HOME / "config.yaml").write_text("model:\n provider: custom\n default: m\n")+from hermes_cli.runtime_provider_backends import _resolve_openrouter_runtime+openrouter_leak = _resolve_openrouter_runtime(requested_provider="openrouter").get("api_key") == "sk-probe-bound-elsewhere"+from types import SimpleNamespace+from unittest.mock import MagicMock+import agent.anthropic_credentials as creds+from agent.client_lifecycle import ClientLifecycleMixin+creds.resolve_anthropic_token = lambda **_kw: "sk-ant-probe-refreshed"+agent = SimpleNamespace(api_mode="anthropic_messages", provider="anthropic", model="claude-probe",+ _anthropic_api_key="", _anthropic_base_url="http://127.0.0.1:9",+ _anthropic_client=MagicMock(), _build_direct_anthropic_client=lambda *a: MagicMock(),+ _anthropic_oauth_flag=lambda _t: False)+refresh_leak = ClientLifecycleMixin._try_refresh_anthropic_client_credentials(agent) is True+verdict("open" if openrouter_leak or refresh_leak else "fixed")+'''),+ # /model <id> --provider X adopted another provider's alias (its base_url and key) that+ # exposes the same model id.+ 120295: ({"PROVIDER_B_KEY": "sk-provider-b"}, r'''+(HOME / "config.yaml").write_text(+ "model:\n provider: provider-a\n default: old-model\n"+ "providers:\n"+ " provider-a:\n base_url: https://api-a.example.com/v1\n"+ " provider-b:\n base_url: https://api-b.example.com/v1\n key_env: PROVIDER_B_KEY\n")+import hermes_cli.model_switch as ms+import hermes_cli.models_validate as mv+from hermes_cli.config import load_config+ms.DIRECT_ALIASES = {"a-alias": ms.DirectAlias("shared-model", "custom", "https://alias-host.example.com/v1",+ api_key="sk-alias-host")}+mv.validate_requested_model = lambda *a, **kw: {"accepted": True, "persist": True, "recognized": True, "message": None}+r = ms.switch_model("shared-model", "provider-a", "old-model", current_base_url="https://api-a.example.com/v1",+ current_api_key="sk-provider-a", explicit_provider="provider-b",+ user_providers=load_config()["providers"])+assert r.success, r.error_message+verdict("fixed" if (r.base_url, r.api_key) == ("https://api-b.example.com/v1", "sk-provider-b") else "open")+'''),+ # tui_gateway: when the approval wait had already ended by the time the settle hook was+ # attached (answered by RPC, resolved on another surface), the sent request was never+ # withdrawn and stayed in open_requests.+ 120374: ({}, r'''+from tui_gateway import server, server_requests+settled = []+server_requests.send_async = lambda method, sid, params, on_result: settled.append+server._sessions["probe"] = {"session_key": "probe-key"}+server._emit_approval_request("probe", {"request_id": "already-resolved", "description": "probe"})+verdict("fixed" if settled else "open")+'''),+}++[email protected]_cache(maxsize=None)+def gap_open(pr: int) -> bool:+ """True while the defect PR ``pr`` fixes still reproduces on this tree."""+ extra_env, script = PROBES[pr]+ with tempfile.TemporaryDirectory(prefix=f"gap-{pr}-") as tmp:+ home = Path(tmp) / "home"+ (home / ".hermes").mkdir(parents=True)+ out = Path(tmp) / "verdict"+ env = {k: v for k, v in os.environ.items()+ if not k.startswith(("PYTEST_", "HERMES_")) and not k.endswith(("_API_KEY", "_BASE_URL"))}+ env.update({"HOME": str(home), "HERMES_HOME": str(home / ".hermes"), "GAP_VERDICT": str(out),+ "PYTHONPATH": str(REPO_ROOT), **extra_env})+ proc = subprocess.run([sys.executable, "-c", _PRELUDE + script], cwd=str(REPO_ROOT), env=env,+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120)+ verdict = out.read_text() if proc.returncode == 0 and out.exists() else ""+ if verdict not in ("open", "fixed"):+ raise AssertionError(f"probe for #{pr} is broken (rc={proc.returncode}, verdict={verdict!r}): "+ f"{json.dumps(proc.stdout[-800:])} {proc.stderr[-2000:]}")+ return verdict == "open"+++@dataclass(frozen=True)+class Gap:+ pr: int+ reason: str+ raises: Type[BaseException] | Tuple[Type[BaseException], ...]+ strict: bool = True++ def __post_init__(self) -> None:+ assert f"#{self.pr}" in self.reason, f"reason for a #{self.pr} gap must name the PR: {self.reason!r}"+ assert self.pr in PROBES, f"#{self.pr} has no probe"+++def expect_gaps(request: pytest.FixtureRequest, *gaps: Gap) -> None:+ """One xfail for this cell covering every gap whose probe still reproduces; a plain test once none does.++ pytest honours only the first matching xfail mark, so open gaps are merged: ``raises`` is the+ union of their bug-specific exceptions, and the mark is strict when any open gap is deterministic.+ """+ open_gaps = [g for g in gaps if gap_open(g.pr)]+ if not open_gaps:+ return+ raises: tuple = ()+ for g in open_gaps:+ raises += g.raises if isinstance(g.raises, tuple) else (g.raises,)+ request.applymarker(pytest.mark.xfail(+ strict=any(g.strict for g in open_gaps), raises=tuple(dict.fromkeys(raises)),+ reason=" | ".join(g.reason for g in open_gaps)))diff --git a/tests/e2e/core/tenancy/_helpers.py b/tests/e2e/core/tenancy/_helpers.pyindex 2808c7ded36..6e941f84e47 100644--- a/tests/e2e/core/tenancy/_helpers.py+++ b/tests/e2e/core/tenancy/_helpers.py@@ -33,6 +33,15 @@ REPO_ROOT = Path(__file__).resolve().parents[4]ENV_PROBE = "echo SNAPSHOT-BEGIN; env | sort; echo CWD=$(pwd); echo SNAPSHOT-END"PROVIDER_KEY_ENV = "TENANT_PROVIDER_KEY" # same NAME in every profile's .env, distinct VALUE+class TenantLeak(AssertionError):+ """A provider request, tool subprocess, file, RPC frame or log carried another tenant's canary."""+++class LaunchProfileBleed(AssertionError):+ """A secondary profile's session reported the launch profile's model, or a settings write+ addressed to one profile changed another profile's files."""++_STRIP_SUFFIXES = ("_API_KEY", "_TOKEN", "_BASE_URL", "_SECRET", "_ACCESS_KEY", "_KEY_ID", "_KEY")_STRIP_PREFIXES = ("HERMES_", "OPENAI", "ANTHROPIC", "OPENROUTER", "AWS_", "AZURE_", "GOOGLE_", "GEMINI","PYTEST_", "NOUS_", "XAI_", "LLM_", "CUSTOM_", "TERMINAL_", "TENANT_", "API_SERVER_")@@ -251,14 +260,18 @@ def env_snapshots(t: Tenant) -> list[tuple[str, str]]:return list(seen.values())-def snapshot_problems(tenants: dict[str, Tenant], min_per_tenant: int = 1) -> list[str]:+def snapshot_shortfall(tenants: dict[str, Tenant], min_per_tenant: int = 1) -> list[str]:+ """Tenants whose provider received fewer env snapshots than the scenario drove (a harness or+ liveness failure, not a leak)."""+ return [f"{t.name}: {n} env snapshot(s) reached its provider, expected >= {min_per_tenant}"+ for t in tenants.values() if (n := len(env_snapshots(t))) < min_per_tenant]+++def snapshot_problems(tenants: dict[str, Tenant]) -> list[str]:"""Inside a tool subprocess: cwd is the tenant's own, and no other tenant's canary is visible."""problems: list[str] = []for t in tenants.values():- snaps = env_snapshots(t)- if len(snaps) < min_per_tenant:- problems.append(f"{t.name}: {len(snaps)} env snapshot(s) reached its provider, expected >= {min_per_tenant}")- for origin, s in snaps:+ for origin, s in env_snapshots(t):text = s.encode().decode("unicode_escape", errors="ignore") if "\\n" in s else sown_dirs = [str(t.workdir), *(v for k, v in t.extra.items() if k.startswith("workdir"))]if not any(f"CWD={d}\n" in text + "\n" for d in own_dirs):@@ -293,9 +306,16 @@ def file_leaks(tenants: dict[str, Tenant], launch: str = "default") -> list[str]def check_isolation(tenants: dict[str, Tenant], *, launch: str = "default", min_snapshots: int = 1,extra: Iterable[str] = ()) -> None:- problems = [*request_leaks(tenants), *snapshot_problems(tenants, min_snapshots), *file_leaks(tenants, launch),- *extra]- assert not problems, "cross-tenant leak(s):\n " + "\n ".join(dict.fromkeys(problems))+ problems = [*request_leaks(tenants), *snapshot_problems(tenants), *file_leaks(tenants, launch), *extra]+ if problems:+ raise TenantLeak("cross-tenant leak(s):\n " + "\n ".join(dict.fromkeys(problems)))+ shortfall = snapshot_shortfall(tenants, min_snapshots)+ assert not shortfall, "\n".join(shortfall)+++def assert_no_text_leaks(label: str, text: str, tenants: dict[str, Tenant], owner: str | None = None) -> None:+ if leaks := text_leaks(label, text, tenants, owner):+ raise TenantLeak("\n".join(leaks))def text_leaks(label: str, text: str, tenants: dict[str, Tenant], owner: str | None = None) -> list[str]:diff --git a/tests/e2e/core/tenancy/_routing_helpers.py b/tests/e2e/core/tenancy/_routing_helpers.pyindex 87f23ae9ba3..438bd94a161 100644--- a/tests/e2e/core/tenancy/_routing_helpers.py+++ b/tests/e2e/core/tenancy/_routing_helpers.py@@ -33,6 +33,18 @@ from tests.fakes.fake_llm_provider import Error, FakeLLMServer, TextREPO_ROOT = Path(__file__).resolve().parents[4]+class RoutingLeak(AssertionError):+ """A prompt or credential reached a host it must not: an unselected fleet host, a selected host+ with another identity's key, or a real inference API (egress trap)."""+++def assert_routing(problems: list[str], ctx: str) -> None:+ """Leaks raise ``RoutingLeak``; a host that was merely not reached is a plain failure."""+ if any(p.startswith("LEAK") for p in problems):+ raise RoutingLeak("\n".join(problems) + "\n" + ctx)+ assert not problems, "\n".join(problems) + "\n" + ctx++# Env that could route or authenticate a child Hermes outside the fake fleet._STRIP_SUFFIXES = ("_API_KEY", "_TOKEN", "_BASE_URL", "_SECRET", "_ACCESS_KEY", "_KEY_ID")_STRIP_PREFIXES = ("HERMES_", "OPENAI", "ANTHROPIC", "OPENROUTER", "AWS_", "AZURE_", "GOOGLE_",diff --git a/tests/e2e/core/tenancy/test_routing_truth_table.py b/tests/e2e/core/tenancy/test_routing_truth_table.pyindex 7d23cb36592..bae4423bc60 100644--- a/tests/e2e/core/tenancy/test_routing_truth_table.py+++ b/tests/e2e/core/tenancy/test_routing_truth_table.py@@ -32,14 +32,17 @@ from urllib.parse import urlparseimport pytest+from tests.e2e.core._pending_fixes import Gap, expect_gapsfrom tests.fakes.fake_llm_provider import MODEL_ID, Error, ToolCallfrom ._routing_helpers import (EgressTrap,Fleet,+ RoutingLeak,RunResult,TuiGateway,always,+ assert_routing,check_routing,describe,inference_hosts,@@ -102,6 +105,8 @@ class Leg:answer_from: str | None = None # host whose answer the user must see (rc 0)rc: str = "ok" # ok | fail | anyprofile: str | None = None # run with HERMES_HOME = profiles/<name>+ fail_text: str | None = None # rc="fail": the error the user must see+ timeout: float = 240.0@dataclass@@ -216,7 +221,9 @@ def _profile_work(f: Fleet) -> dict[str, tuple[dict[str, Any], dict[str, str]]]:CASES: list[Case] = [Case("custom_base_url_key_env", [Leg(Q, ("main",), {"main": 1}, "main")]),Case("custom_base_url_api_key_literal", [Leg(Q, ("main",), {"main": 1}, "main")], _main_api_key_literal),- Case("bare_custom_without_base_url_fails_fast", [Leg(Q, (), rc="fail")], _bare_custom),+ # Fails fast with the no-key error: a hang to the harness kill (rc -9) is not a fail-fast.+ Case("bare_custom_without_base_url_fails_fast",+ [Leg(Q, (), rc="fail", fail_text="No LLM provider configured", timeout=90)], _bare_custom),Case("named_providers_entry_key_env",[Leg(Q, ("named",), {"named": 1}, "named")], _model(provider="named-host", default="model-named")),Case("legacy_custom_providers_entry_api_key",@@ -275,7 +282,7 @@ def _run_case(case: Case, root: Path) -> tuple[Fleet, list[LegOutcome]]:for leg in case.legs:marks, egress_mark = fleet.marks(), len(trap.attempts)hermes_home = home / ".hermes" / "profiles" / leg.profile if leg.profile else None- run = run_hermes(leg.argv, home, hermes_home=hermes_home, proxy=trap.url)+ run = run_hermes(leg.argv, home, hermes_home=hermes_home, proxy=trap.url, timeout=leg.timeout)outcomes.append(LegOutcome(leg, run, fleet.since(marks), trap.attempts[egress_mark:]))return fleet, outcomesfinally:@@ -292,35 +299,34 @@ def cli_outcomes(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Any]:return {cid: fut for cid, fut in futures.items()}-# Real production bugs on base, fixed on test/core-tenancy and landing as their own PRs.-# strict: each cell flips red (XPASS) once its fix is in, so the mark comes off with it.-KNOWN_BUGS = {- "bare_custom_without_base_url_fails_fast": pytest.mark.xfail(- strict=True, raises=AssertionError,- reason="bare `provider: custom` with no endpoint falls through to OpenRouter and ships the "- "OPENAI_BASE_URL-bound OPENAI_API_KEY there (fix: #120299)"),-}+# Live gaps, applied only while their probe reproduces them (see _pending_fixes).+GAP_120299 = Gap(120299, "#120299: bare `provider: custom` with no endpoint falls through to OpenRouter and ships the "+ "OPENAI_BASE_URL-bound OPENAI_API_KEY there; the pre-request Anthropic credential refresh "+ "puts ANTHROPIC_API_KEY on an alias's foreign host", raises=RoutingLeak)+GAP_120295 = Gap(120295, "#120295: `/model <id> --provider X` adopts another provider's alias (endpoint + key) "+ "for the same model id", raises=RoutingLeak)+KNOWN_GAPS = {"bare_custom_without_base_url_fails_fast": (GAP_120299,)}[email protected]("case", [- pytest.param(c, id=c.id, marks=[KNOWN_BUGS[c.id]] if c.id in KNOWN_BUGS else [])- for c in CASES])-def test_cli_routing_truth_table(case: Case, cli_outcomes: dict[str, Any]) -> None:[email protected]("case", [pytest.param(c, id=c.id) for c in CASES])+def test_cli_routing_truth_table(case: Case, cli_outcomes: dict[str, Any], request: pytest.FixtureRequest) -> None:+ expect_gaps(request, *KNOWN_GAPS.get(case.id, ()))fleet, outcomes = cli_outcomes[case.id].result(timeout=900)for i, out in enumerate(outcomes):leg, run = out.leg, out.runctx = (f"[{case.id} leg {i}: hermes {' '.join(leg.argv)}] rc={run.rc} ({run.seconds:.1f}s)\n"f"requests:\n{describe(out.log)}\nstdout tail:\n{run.stdout[-1500:]}\nstderr tail:\n{run.stderr[-1500:]}")- problems = check_routing(fleet, out.log, {h: fleet.keys[h] for h in leg.hosts}, leg.must_hit)- assert not problems, "\n".join(problems) + "\n" + ctx+ assert_routing(check_routing(fleet, out.log, {h: fleet.keys[h] for h in leg.hosts}, leg.must_hit), ctx)+ leaked = [t for _m, t in out.egress if urlparse(t).hostname in inference_hosts()]+ if leaked:+ raise RoutingLeak(f"prompt egress to a real inference API: {leaked}\n{ctx}")if leg.rc == "ok":assert run.rc == 0, ctxelif leg.rc == "fail":- assert run.rc != 0, "expected a fail-fast exit\n" + ctx+ assert run.rc not in (0, None, -9), "expected a fail-fast exit, not success or the harness kill\n" + ctx+ assert leg.fail_text in run.stdout + run.stderr, f"expected {leg.fail_text!r}\n" + ctxif leg.answer_from:assert f"answer-from-{leg.answer_from}" in run.stdout, ctx- leaked = [t for _m, t in out.egress if urlparse(t).hostname in inference_hosts()]- assert not leaked, f"prompt egress to a real inference API: {leaked}\n{ctx}"if case.key_order:host, order = case.key_orderseen: list[str] = []@@ -342,15 +348,11 @@ class Switch:keyless: bool = False # the host may also see NO credential (withholding a key is not a leak)- strict=True, raises=AssertionError,- reason="leg 5: `/model <id> --provider X` adopts an alias's endpoint+key for the same model "- "(fix: #120295); leg 6: the pre-request Anthropic "- "credential refresh puts ANTHROPIC_API_KEY on an alias's foreign host "- "(fix: #120299). Flips once both land.")-def test_tui_gateway_model_switch_routing(tmp_path: Path) -> None:+def test_tui_gateway_model_switch_routing(tmp_path: Path, request: pytest.FixtureRequest) -> None:"""One live session walks the switch matrix; after every switch the next turn lands on- exactly the selected host with exactly its key, and nothing reaches any other host."""+ exactly the selected host with exactly its key, and nothing reaches any other host.+ Leg 5 is #120295's cell, leg 6 #120299's."""+ expect_gaps(request, GAP_120295, GAP_120299)fleet = Fleet(ROLES).start()trap = EgressTrap()home = tmp_path / "home"@@ -392,8 +394,7 @@ def test_tui_gateway_model_switch_routing(tmp_path: Path) -> None:ctx = f"leg {i} ({leg.value!r} -> {leg.host}): {done.get('params', {}).get('type')} {str(payload)[:300]}\n{describe(log)}"print(ctx)allowed = {*fleet.keys[leg.host], *(("", "no-key-required") if leg.keyless else ())}- problems = check_routing(fleet, log, {leg.host: allowed}, {leg.host: 1})- assert not problems, "\n".join(problems) + "\n" + ctx+ assert_routing(check_routing(fleet, log, {leg.host: allowed}, {leg.host: 1}), ctx)if leg.ok:assert payload.get("text") == f"answer-from-{leg.host}", ctxfinally:diff --git a/tests/e2e/core/tenancy/test_two_tenant_desktop_backend.py b/tests/e2e/core/tenancy/test_two_tenant_desktop_backend.pyindex d4ed78d9b0d..0c4a7fe85dd 100644--- a/tests/e2e/core/tenancy/test_two_tenant_desktop_backend.py+++ b/tests/e2e/core/tenancy/test_two_tenant_desktop_backend.py@@ -28,6 +28,8 @@ from typing import Anyimport pytest+from tests.e2e.core._pending_fixes import Gap, expect_gaps+from . import _helpers as HNAMES = ("default", "alpha", "beta")@@ -69,6 +71,11 @@ def _changed(before: dict[str, bytes], after: dict[str, bytes]) -> set[str]:return {k for k in after if before.get(k) != after[k]}+def _expect_only(before: dict[str, bytes], after: dict[str, bytes], expected: set[str], what: str) -> None:+ if (changed := _changed(before, after)) != expected:+ raise H.LaunchProfileBleed(f"{what} changed {sorted(changed)}, expected only {sorted(expected)}")++def _rpc_leaks(b: H.ServeBackend, owners: dict[str, str], tenants: dict[str, H.Tenant]) -> list[str]:"""Replies/events bound to a session must carry no other tenant's canary."""out: list[str] = []@@ -93,13 +100,18 @@ def _await_cron(tenants: dict[str, H.Tenant], fires: int) -> None:f"cron fire #{fires} in every profile")- strict=True, raises=AssertionError,- reason="session.create / the first state.db row use the launch profile's model and "- "model.save_key writes the launch profile's .env (fix: #120319); "- "gateway.run's import-time config bridge writes a secondary session's terminal.* into the "- "process env, red ~6/7 runs (fix: #120307). Flips once all land.")-def test_desktop_backend_never_crosses_tenants(fleet) -> None:+# Live gaps, applied only while their probe reproduces them (see _pending_fixes).+GAPS = (+ Gap(120319, "#120319: session.create / the first state.db row use the launch profile's model and "+ "model.save_key writes the launch profile's .env", raises=H.LaunchProfileBleed),+ # A race in this cell (which session first imports gateway.run), red in ~6 of 7 runs: not strict.+ Gap(120307, "#120307: gateway.run's import-time config bridge writes a secondary session's .env / "+ "terminal.* into the process env", raises=H.TenantLeak, strict=False),+)+++def test_desktop_backend_never_crosses_tenants(fleet, request: pytest.FixtureRequest) -> None:+ expect_gaps(request, *GAPS)root, tenants, backends = fleet# Phase 1: one backend, three profile sessions, interleaved turns, one cron fire per profile.@@ -110,8 +122,8 @@ def test_desktop_backend_never_crosses_tenants(fleet) -> None:for name in ("alpha", "default", "beta"):res = b.ok("session.create", _profile_param(name))sids[name], stored[name] = res["session_id"], res["stored_session_id"]- assert res["info"]["model"] == tenants[name].model, (- f"session.create for {name} reports model {res['info']['model']!r}")+ if res["info"]["model"] != tenants[name].model:+ raise H.LaunchProfileBleed(f"session.create for {name} reports model {res['info']['model']!r}")owners = {sid: name for name, sid in sids.items()}for name in ("alpha", "default", "beta", "alpha", "beta"):b.turn(sids[name], f"turn for {name}")@@ -125,17 +137,17 @@ def test_desktop_backend_never_crosses_tenants(fleet) -> None:t.extra["workdir2"] = str(new_cwd) # the live session may keep its cwd; both dirs are t's ownbefore = _files(tenants)b.ok("config.set", {"session_id": sids[name], "key": "cwd", "value": str(new_cwd)})- assert _changed(before, _files(tenants)) == {f"{name}/config.yaml"}, f"cwd write for {name}"+ _expect_only(before, _files(tenants), {f"{name}/config.yaml"}, f"cwd write for {name}")beta = tenants["beta"]beta.extra["custom_prompt"] = f"prompt-canary-beta-{beta.tag}"before = _files(tenants)b.ok("config.set", {"profile": "beta", "key": "prompt", "value": beta.extra["custom_prompt"]})- assert _changed(before, _files(tenants)) == {"beta/config.yaml"}, "profile-bound prompt write"+ _expect_only(before, _files(tenants), {"beta/config.yaml"}, "profile-bound prompt write")alpha = tenants["alpha"]alpha.extra["saved_key"] = f"sk-savekey-alpha-{alpha.tag}"before = _files(tenants)b.ok("model.save_key", {"session_id": sids["alpha"], "slug": "deepseek", "api_key": alpha.extra["saved_key"]})- assert _changed(before, _files(tenants)) == {"alpha/.env"}, "session-bound model.save_key write"+ _expect_only(before, _files(tenants), {"alpha/.env"}, "session-bound model.save_key write")for name in ("default", "beta", "alpha"):b.turn(sids[name], f"after settings for {name}")H.check_isolation(tenants, min_snapshots=3, extra=_rpc_leaks(b, owners, tenants))@@ -163,5 +175,4 @@ def test_desktop_backend_never_crosses_tenants(fleet) -> None:b.close()log = (root / "serve.log").read_text(encoding="utf-8", errors="replace")- leaks = H.text_leaks("serve output", log, tenants)- assert not leaks, "\n".join(leaks)+ H.assert_no_text_leaks("serve output", log, tenants)diff --git a/tests/e2e/core/tenancy/test_two_tenant_gateway.py b/tests/e2e/core/tenancy/test_two_tenant_gateway.pyindex 2e25b0e84d9..7ba77cc3d4f 100644--- a/tests/e2e/core/tenancy/test_two_tenant_gateway.py+++ b/tests/e2e/core/tenancy/test_two_tenant_gateway.py@@ -36,6 +36,8 @@ from typing import Anyimport pytest+from tests.e2e.core._pending_fixes import Gap, expect_gaps+from . import _helpers as H# The gateway child is spawned and reaped by this module (fake HOME, no systemd bus in its env).@@ -151,12 +153,14 @@ def _await_cron(tenants: dict[str, H.Tenant], at_least: int) -> None:f"cron fire #{at_least} in every profile")- strict=True, raises=AssertionError,- reason="phase 1: session-less work (cron) for a routed profile keys the shared 'default' "- "terminal env, so alpha/beta cron tool calls inherit default's .env, cwd and shell "- "state (fix: #120307)")-def test_multiplexed_gateway_never_crosses_tenants(fleet) -> None:+# Applied only while the probe reproduces it (see _pending_fixes).+GAP_120307 = Gap(120307, "#120307: session-less work (cron) for a routed profile keys the shared 'default' "+ "terminal env, so alpha/beta cron tool calls inherit default's .env, cwd and shell state",+ raises=H.TenantLeak)+++def test_multiplexed_gateway_never_crosses_tenants(fleet, request: pytest.FixtureRequest) -> None:+ expect_gaps(request, GAP_120307)root, tenants, gw = fleethome = root / "home"@@ -202,5 +206,4 @@ def test_multiplexed_gateway_never_crosses_tenants(fleet) -> None:H.check_isolation(tenants, min_snapshots=5)gw.stop()- leaks = H.text_leaks("gateway output", gw.tail(10**9), tenants)- assert not leaks, "\n".join(leaks)+ H.assert_no_text_leaks("gateway output", gw.tail(10**9), tenants)diff --git a/tests/e2e/core/terminal/test_interactive_roundtrip.py b/tests/e2e/core/terminal/test_interactive_roundtrip.pyindex 1915ea66305..72dbbe4fbf0 100644--- a/tests/e2e/core/terminal/test_interactive_roundtrip.py+++ b/tests/e2e/core/terminal/test_interactive_roundtrip.py@@ -29,6 +29,7 @@ import threadingimport pytest+from tests.e2e.core._pending_fixes import Gap, expect_gapsfrom tests.e2e.core.terminal._gateway_client import Backend, WSClient, etype, poll_untilfrom tests.fakes.fake_llm_provider import Text, ToolCall@@ -40,6 +41,10 @@ TAG_RE = re.compile(r"\b(CLARIFY|RMRF)-([a-z0-9_]+)\b")PROMPT_TIMEOUT = 90.0+class PromptLeftPending(AssertionError):+ """The turn finished but a clarify/approval request is still in ``open_requests``."""++class Script:"""Tool call for the newest user tag; after the tool ran, record its result and reply ``DONE <tag>``."""@@ -184,7 +189,8 @@ def _drive(backend: Backend, script: Script, kind: str, how: str, tag: str) -> N# Nothing left waiting on a human, from any surface.final = poll_until(lambda: _resume_ok(responder, key), timeout=PROMPT_TIMEOUT, what="final resume")- assert not final.get("open_requests"), f"prompt left pending after the turn: {final.get('open_requests')}"+ if final.get("open_requests"):+ raise PromptLeftPending(f"prompt left pending after the turn: {final.get('open_requests')}")assert not final.get("pending_approval"), final.get("pending_approval")assert _pending(responder, sid) == []for conn in (a, responder):@@ -208,19 +214,22 @@ CASES = []-# A race, so it cannot be strict: the RPC answer can end the approval wait before the gateway attaches the-# hook that withdraws the sent request, which then stays in ``open_requests`` (red in about 1 in 4 loaded runs;-# deterministic with the gap widened). Drop the mark when #120374 lands.-_RACY = {("approval_deny", "rpc"): pytest.mark.xfail(- strict=False, raises=AssertionError,- reason="#120374: an approval answered by RPC before the settle hook attaches stays in open_requests")}+# Applied only while the probe reproduces it (see _pending_fixes). A race in this cell, so not strict: the RPC+# answer can end the approval wait before the gateway attaches the hook that withdraws the sent request, which+# then stays in ``open_requests`` (red in about 1 in 4 loaded runs). Only ``PromptLeftPending`` is excused.+GAPS = {("approval_deny", "rpc"): Gap(+ 120374, "#120374: an approval answered by RPC before the settle hook attaches stays in open_requests",+ raises=PromptLeftPending, strict=False)}[email protected](("kind", "how"), [pytest.param(k, h, id=f"{k}-{h}", marks=_RACY.get((k, h), ()))- for k, h in CASES])-def test_interactive_roundtrip(backend: Backend, script: Script, kind: str, how: str) -> None:[email protected](("kind", "how"), [pytest.param(k, h, id=f"{k}-{h}") for k, h in CASES])+def test_interactive_roundtrip(backend: Backend, script: Script, kind: str, how: str,+ request: pytest.FixtureRequest) -> None:+ if gap := GAPS.get((kind, how)):+ expect_gaps(request, gap)tag = f"{kind}_{how}".lower()try:_drive(backend, script, kind, how, tag)except AssertionError as exc:- raise AssertionError(f"{kind}/{how}: {exc}\n{backend.logs(25)}") from None+ # Keep the class: the gap's xfail excuses only PromptLeftPending.+ raise type(exc)(f"{kind}/{how}: {exc}\n{backend.logs(25)}") from None