Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

test(e2e): bring the hermetic Model Hub E2E back to its owning contracts and run it nightly (#2670)

Call Whitec776951e4b54
diff --git a/.github/workflows/model-hub-e2e.yml b/.github/workflows/model-hub-e2e.yml
new file mode 100644
index 000000000..79bd8d693
--- /dev/null
+++ b/.github/workflows/model-hub-e2e.yml
@@ -0,0 +1,94 @@
+name: Model Hub release E2E
+
+# The hermetic Model Hub E2E (`-m e2e_model_hub`) runs the real gateway, the
+# pinned engine and real agent CLIs against a loopback mock upstream. It is too
+# slow for pull requests, so it runs nightly and on demand; a release needs a
+# green run at its SHA (docs/release.md).
+
+on:
+ schedule:
+ - cron: "23 3 * * *"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: model-hub-e2e-${{ github.ref }}
+ cancel-in-progress: false
+
+env:
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
+
+jobs:
+ model-hub-e2e:
+ name: model-hub-e2e
+ runs-on: ubuntu-latest
+ timeout-minutes: 120
+ steps:
+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
+
+ - name: Prepare hermetic UI asset placeholder
+ run: |
+ mkdir -p ui/dist
+ printf '%s\n' '<!doctype html><html><body></body></html>' > ui/dist/index.html
+
+ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6
+ with:
+ python-version: "3.12"
+
+ - name: Install pinned uv
+ run: |
+ python -m pip install --disable-pip-version-check --only-binary=:all: --no-deps uv==0.12.10
+
+ - name: Install package and test dependencies
+ run: uv pip install --system -e . --group dev
+
+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
+ with:
+ node-version: "22.14.0"
+
+ # The agent CLIs users install: the latest release of each, as Avibe installs them.
+ - name: Install agent CLIs
+ run: |
+ npm install -g @openai/codex opencode-ai
+ codex --version
+ opencode --version
+
+ # The packaged engine manifest, with this runner's asset downloaded and
+ # verified, so every scenario installs the pinned engine offline.
+ - name: Prepare the pinned engine offline
+ run: |
+ python - <<'EOF'
+ import hashlib, json, os, pathlib, urllib.request
+
+ manifest = json.loads(pathlib.Path("vibe/model_hub_runtime/cliproxyapi_manifest.json").read_text())
+ root = pathlib.Path(os.environ["RUNNER_TEMP"]) / "model-hub-engine"
+ root.mkdir(parents=True, exist_ok=True)
+ (asset,) = [item for item in manifest["assets"] if item["platform"] == "linux-amd64"]
+ archive = root / asset["url"].rsplit("/", 1)[1]
+ with urllib.request.urlopen(asset["url"], timeout=300) as response:
+ archive.write_bytes(response.read())
+ digest = hashlib.sha256(archive.read_bytes()).hexdigest()
+ if digest != asset["sha256"] or archive.stat().st_size != asset["size_bytes"]:
+ raise SystemExit(f"engine archive does not match the manifest: {digest}")
+ asset["url"] = archive.as_uri()
+ (root / "offline-manifest.json").write_text(json.dumps(manifest))
+ print(f"{manifest['asset_release_tag']} {asset['platform']} verified")
+ EOF
+ echo "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH=$RUNNER_TEMP/model-hub-engine/offline-manifest.json" >> "$GITHUB_ENV"
+
+ - name: Run the Model Hub E2E
+ run: |
+ python -m pytest -m e2e_model_hub tests/e2e -p no:cacheprovider -ra \
+ --basetemp="$RUNNER_TEMP/e2e" 2>&1 | tee model-hub-e2e.log
+ exit "${PIPESTATUS[0]}"
+
+ - name: Upload the run log
+ if: always()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
+ with:
+ name: model-hub-e2e-${{ github.run_id }}-${{ github.run_attempt }}
+ path: model-hub-e2e.log
+ if-no-files-found: ignore
+ retention-days: 14
diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.md
index 835940f03..3dc3673bc 100644
--- a/docs/plans/model-hub-contracts/opencode-overlay.md
+++ b/docs/plans/model-hub-contracts/opencode-overlay.md
@@ -85,7 +85,7 @@ contract (one OpenAI-compatible provider, `vendor/model` ids); nothing of that s
unchanged (measured on CLIProxyAPI v7.3.16, which otherwise sends `CLIProxyAPI/<version>`),
so an upstream sees the calling agent's identity. Upstream auth is the engine's Bearer form. A Responses-frontend body reaching a `codex-api-key` upstream
is rewritten by the engine's Codex executor regardless of flags (`max_output_tokens`
- dropped; `parallel_tool_calls: true`, `instructions: ""`) — a known engine limitation the implementation verifies against each real
+ dropped; `instructions: ""`, and `parallel_tool_calls: true` only when the body has tools) — a known engine limitation the implementation verifies against each real
`openai_responses` Source before enabling the route, and tracks as an engine follow-up.
The engine no longer adds its hosted `image_generation` tool: it runs with
`disable-image-generation: passthrough`, and nothing adds it back (`vibey-hosted-tools.md` §7.1).
@@ -130,6 +130,6 @@ conversion use documented safe degradation, never a blanket pre-release waiver.
| S1 | `@ai-sdk/openai` + custom `baseURL` calls `/v1/responses` | Yes: `options.baseURL = <gateway>/v1`; a prompt through `avibe-openai/gpt-5` hit the mock at `/v1/responses` with `model: gpt-5`. No option exists or is needed to force Responses; the custom-provider path calls the SDK's `languageModel()`, which is Responses. |
| S2 | `@ai-sdk/anthropic` + custom `baseURL` calls `/v1/messages`; client auth header | Yes: `/v1/messages`, sent with `X-Api-Key` and `Anthropic-Version: 2023-06-01`. The engine accepts its client key as `x-api-key` or `Authorization: Bearer` (200/200; wrong key 401). Toward a `claude-api-key` upstream it sends Bearer. |
| S3 | Same-protocol passthrough | Not by default: the engine added `metadata.user_id`, split `system` into billing/identity/Claude-Code-prompt segments and moved OpenCode's system text into a user `<system-reminder>`. With `disable-claude-cloak-mode: true` + credential `cloak.mode: never` + `rebuild-mid-system-message: false` the inbound and upstream bodies are JSON-identical. Headers stay fingerprinted (Claude-CLI `User-Agent`, `Anthropic-Beta`, `X-App`, `X-Claude-Code-Session-Id`, `X-Stainless-*`); `fingerprint-profile` does not exist in this version. Responses → `codex-api-key` is rewritten regardless of `codex.identity-confuse`/`optimize-multi-agent-v2` (see Menu projection). |
-| S4 | Variant shapes and cross-protocol survival | OpenAI `{ "reasoningEffort": "high" }` → `reasoning: {effort: high, summary: auto}`, preserved to a Codex upstream. Anthropic top-level `{ "effort": "high" }` → `output_config: {effort: high}`, preserved on a same-protocol hop. Anthropic `{ thinking: {type: enabled, budgetTokens: 4096} }` → engine folds to `thinking: adaptive` + `output_config.effort: medium`; `thinking: {type: enabled, effort: high}` → a 1024-token budget read back as `effort: low` (wrong). Cross-protocol: Responses effort `high` → `anthropic` upstream gets adaptive thinking + `effort: high`; Anthropic budget 4096 → `openai_chat` upstream gets `reasoning_effort: medium`; Anthropic top-level effort → `openai_chat` upstream gets nothing. |
+| S4 | Variant shapes and cross-protocol survival | OpenAI `{ "reasoningEffort": "high" }` → `reasoning.effort: high`, preserved to a Codex upstream (OpenCode 1.19 adds no `summary`; earlier releases added `summary: auto`). Anthropic top-level `{ "effort": "high" }` → `output_config: {effort: high}`, preserved on a same-protocol hop. Anthropic `{ thinking: {type: enabled, budgetTokens: 4096} }` → engine folds to `thinking: adaptive` + `output_config.effort: medium`; `thinking: {type: enabled, effort: high}` → a 1024-token budget read back as `effort: low` (wrong). Cross-protocol: Responses effort `high` → `anthropic` upstream gets adaptive thinking + `effort: high`; Anthropic budget 4096 → `openai_chat` upstream gets `reasoning_effort: medium`; Anthropic top-level effort → `openai_chat` upstream gets nothing. |
| S5 | `enabled_providers` hides user/env providers | Yes: with a scratch global config declaring `global-other` with an API key and the overlay's `enabled_providers: ["avibe-openai","avibe-anthropic"]`, `/config/providers` listed only the two Avibe providers. |
| S6 | Canonical reference and display | `/config/providers` shows each provider's overlay `name` and keys its models by the bare id; a prompt carries `providerID` and `modelID` separately, so the canonical reference string is `avibe-anthropic/claude-opus-5`. |
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.md
index 1b315cccf..a160e1f4b 100644
--- a/docs/plans/model-hub-e2e-test-plan.md
+++ b/docs/plans/model-hub-e2e-test-plan.md
@@ -66,12 +66,12 @@ Out of scope (documented, not dropped silently):
### D. Per-turn routing, fallback, capability behavior (C41–C50, C74–C81)
| ID | Steps | Expect | Status |
|---|---|---|---|
-| D1 | add api_key source first, subscription-class source second | **current**: appended at tail (key burns first). Baseline assert-current; expected value flips with decision D-1 | baseline |
+| D1 | add api_key source first, subscription-class source second | the subscription is placed ahead of the key (decision D-1, #2156); a contract test owns it, since adding a subscription hermetically is impossible (a takeover validates its grant with the provider) | contract |
| D2 | turn with hop0 healthy | served; provenance records hop; usage metered | assert |
| D3 | hop0 → 429 before first output | same-turn failover to hop1; `switch` event; hop0 initial local cooldown 60–72s; chat copy unchanged (silent) | assert |
| D4 | hop0 → quota (`insufficient_quota`) | fallback, cooldown 300s | assert |
| D5 | hop0 → 401 (api_key, non-refreshable) | `credential_revoked` needs_action; UI shows repair action; no mid-turn refresh attempt | assert |
-| D6 | hop0 → 5xx | source backoff with positive bounded jitter; later valid Retry-After survives the managed engine and takes precedence | assert |
+| D6 | hop0 → 5xx | source backoff with positive bounded jitter; later valid Retry-After survives the managed engine and takes precedence | xfail: the engine never forwards an upstream error's headers (its status errors carry none, with or without `passthrough-headers`), so upstream advice never arrives |
| D7 | stream interrupt after first output | terminal frame injected per protocol; **no replay/failover**; source still settles; next turn resolves hop1 (takeover pill visible) | assert |
| D8 | cooldown `retry_at` elapses | hop0 becomes eligible; only recognized output or valid empty completion clears its state and emits `recover` | unit/loopback covered; local Incus outstanding |
| D9 | all temporary hops keep failing | one closed recovery-exhausted result (Codex 400, Claude/OpenCode 424); localized final copy and original upstream provenance | gateway/scenario covered; local Incus outstanding |
@@ -160,7 +160,7 @@ Unit/contract suites already cover: config validation, guard structure, classifi
## 5. Owner decision ledger
-- **D-1 subscription-first placement.** Restore "subscription before API key" at placement time (surgical change in `_apply_source_placement`, reuse dead `recommended_source_order`), incl. one-time re-sort of existing configs? Current shipped contract says append-at-tail. Affects D1.
+- **D-1 subscription-first placement (decided, #2156).** A subscription is placed before API keys at placement time. Affects D1.
- **D-2 `count_tokens` 404.** Serve it (proxy to upstream tokenizers or estimate) or document Claude Code context-estimation degradation in hub mode? Affects D11.
- **D-3 missing `modelHub.*` browser i18n keys + absent Python-bundle codes.** Fix now (makes B11 pass) or baseline as expected-fail for this round?
- **D-4 Retry-After honoring (approved 2026-09-09).** Use the later of
@@ -257,7 +257,9 @@ lane-to-lane.
### Suite conventions
- pytest: files `tests/e2e/test_model_hub_*.py`, marker `e2e_model_hub`,
- NOT part of default CI in these PRs. Scenario IDs from §3 (A1…H3) appear in
+ not part of pull-request CI. `.github/workflows/model-hub-e2e.yml` runs it
+ nightly and on demand, and a stable release needs a green run at its SHA
+ (`docs/release.md`). Scenario IDs from §3 (A1…H3) appear in
test names or docstrings.
- Playwright: lives in `ui/e2e/`, config `ui/playwright.config.ts`, dependency
added explicitly to `ui/package.json` devDependencies, scripts
diff --git a/docs/release.md b/docs/release.md
index e1f8d97d9..099f65778 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -27,6 +27,14 @@ GitHub-only pre-releases use the `gh-vX.Y.ZrcN` format, such as
must include an installable wheel containing `ui/dist` and
`vibe/show_runtime/*.tgz`, plus the source distribution.
+## Release E2E
+
+Pull-request CI does not run the hermetic Model Hub E2E (`-m e2e_model_hub`).
+`Model Hub release E2E` runs it nightly and on demand on a clean runner, with
+the pinned engine and the latest agent CLIs. Before tagging a stable `v*`
+release, dispatch it on the release commit and require a green run at that
+exact SHA; a strict `xfail` names a known, tracked gap, not a pass to ignore.
+
## Managed-runtime manifests
Published managed-runtime manifests are availability contracts. Keep their
diff --git a/tests/e2e/drivers/controller_site/sitecustomize.py b/tests/e2e/drivers/controller_site/sitecustomize.py
new file mode 100644
index 000000000..25fb2bbad
--- /dev/null
+++ b/tests/e2e/drivers/controller_site/sitecustomize.py
@@ -0,0 +1,38 @@
+"""Scope the hermetic controller's native-CLI inventory to the processes its harness started.
+
+Native credential migration refuses while a native CLI of the same user runs
+(``core.backend_restart.native_cli_processes``). A developer's machine runs
+real Claude, Codex and OpenCode processes, so the unscoped scan would refuse
+every migration scenario there. Only that scan is scoped, to the descendants
+of the pytest process that launched this controller: Avibe-owned runtimes and
+anything a scenario starts itself stay visible, so "native busy" stays
+testable. Nothing else's view of the process table changes.
+
+This module runs before the controller's own directory is on ``sys.path``, so
+it must not import Avibe code.
+"""
+
+import os
+import sys
+
+_SCANNER = "core.backend_restart"
+
+
+def _scope_native_inventory_to_harness() -> None:
+ import psutil
+
+ harness = os.getppid()
+ process_iter = psutil.process_iter
+
+ def scoped(*args, **kwargs):
+ processes = process_iter(*args, **kwargs)
+ if sys._getframe(1).f_globals.get("__name__") != _SCANNER:
+ return processes
+ owned = {child.pid for child in psutil.Process(harness).children(recursive=True)}
+ return (process for process in processes if process.pid in owned)
+
+ scoped.cache_clear = process_iter.cache_clear
+ psutil.process_iter = scoped
+
+
+_scope_native_inventory_to_harness()
diff --git a/tests/e2e/drivers/mock_llm_upstream.py b/tests/e2e/drivers/mock_llm_upstream.py
index a97654275..9f3a839e3 100644
--- a/tests/e2e/drivers/mock_llm_upstream.py
+++ b/tests/e2e/drivers/mock_llm_upstream.py
@@ -102,18 +102,15 @@ OPENCODE_V4_S3_PASSTHROUGH_FIXTURES = {
],
"reasoning": {"effort": "high", "summary": "auto"},
"prompt_cache_key": "cache-fixture",
- "parallel_tool_calls": True,
"instructions": "",
- "tools": [{"type": "image_generation", "output_format": "png"}],
"include": ["reasoning.encrypted_content"],
"store": False,
"stream": True,
},
"expected_top_level_diff": {
+ # The engine adds no image tool (#2556), and drops parallel_tool_calls with no tools.
"added": {
"instructions": "",
- "parallel_tool_calls": True,
- "tools": [{"type": "image_generation", "output_format": "png"}],
},
"removed": ["max_output_tokens"],
"changed": {
@@ -129,7 +126,7 @@ OPENCODE_V4_S4_VARIANT_FIXTURES = {
"stored_model": "gpt-5",
"variant": {"reasoningEffort": "high"},
"upstream_fragment": {
- "reasoning": {"effort": "high", "summary": "auto"},
+ "reasoning": {"effort": "high"},
},
},
"anthropic_same_protocol": {
@@ -147,7 +144,7 @@ OPENCODE_V4_S4_VARIANT_FIXTURES = {
"stored_model": "claude-sonnet-4-5",
"variant": {"reasoningEffort": "high"},
"upstream_fragment": {
- "thinking": {"type": "adaptive", "display": "summarized"},
+ "thinking": {"type": "adaptive"},
"output_config": {"effort": "high"},
},
},
@@ -236,7 +233,7 @@ class MockUpstreamState:
not isinstance(required_key, str) or not required_key.strip()
):
raise ConfigurationError("required_api_key must be a non-empty string or null")
- if candidate["required_auth_scheme"] not in ("protocol", "bearer"):
+ if candidate["required_auth_scheme"] not in ("protocol", "bearer", "either"):
raise ConfigurationError("unsupported required_auth_scheme")
if candidate["stream"] not in STREAM_BEHAVIORS:
raise ConfigurationError("unsupported stream behavior")
@@ -390,21 +387,20 @@ class MockLLMUpstreamHandler(BaseHTTPRequestHandler):
"""Optional value check for synthetic credentials on data endpoints."""
required_key = config["required_api_key"]
if required_key is not None:
- use_api_key_header = (
- config["protocol"] == "anthropic"
- and config["required_auth_scheme"] == "protocol"
- )
- supplied = (
- self.headers.get("x-api-key")
- if use_api_key_header
- else self.headers.get("authorization")
+ scheme = config["required_auth_scheme"]
+ # ``either``: a relay that takes the key in either header, as most
+ # Anthropic-compatible relays do.
+ by_api_key = scheme == "either" or (
+ config["protocol"] == "anthropic" and scheme == "protocol"
)
- expected = (
- required_key
- if use_api_key_header
- else f"Bearer {required_key}"
- )
- if supplied != expected:
+ by_bearer = scheme == "either" or not by_api_key
+ if not (
+ (by_api_key and self.headers.get("x-api-key") == required_key)
+ or (
+ by_bearer
+ and self.headers.get("authorization") == f"Bearer {required_key}"
+ )
+ ):
self._write_behavior_error({**config, "auth": "401"})
return False
if config["auth"] != "ok":
diff --git a/tests/e2e/drivers/model_hub_app.py b/tests/e2e/drivers/model_hub_app.py
index 0460101cd..2728af129 100644
--- a/tests/e2e/drivers/model_hub_app.py
+++ b/tests/e2e/drivers/model_hub_app.py
@@ -31,6 +31,8 @@ import psutil
_MISSING = object()
+# The controller's ``sitecustomize``: its native-CLI scan sees only this harness's processes.
+_CONTROLLER_SITE = Path(__file__).resolve().parent / "controller_site"
_MUTATION_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
_ENGINE_MANIFEST_PATH_ENV = "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH"
_SAFE_INHERITED_ENV = (
@@ -247,6 +249,10 @@ class ModelHubTestApp:
self.runtime_root / "dispatch.sock"
),
"VIBE_SENTRY_DSN": "",
+ # OpenCode installs @opencode-ai/plugin from npm before its first
+ # request once a plugin is configured; offline, that install fails
+ # at once, and the Avibe plugin imports nothing from it.
+ "npm_config_offline": "true",
"NO_PROXY": "127.0.0.1,localhost",
"no_proxy": "127.0.0.1,localhost",
}
@@ -440,7 +446,7 @@ class ModelHubTestApp:
self._controller = subprocess.Popen(
[sys.executable, "main.py", str(self.avibe_home)],
cwd=self.repo_root,
- env=self.env,
+ env={**self.env, "PYTHONPATH": str(_CONTROLLER_SITE)},
stdout=self._controller_log,
stderr=subprocess.STDOUT,
start_new_session=True,
diff --git a/tests/e2e/test_codex_request_gateway.py b/tests/e2e/test_codex_request_gateway.py
index 8f8fc481e..3f367dbd1 100644
--- a/tests/e2e/test_codex_request_gateway.py
+++ b/tests/e2e/test_codex_request_gateway.py
@@ -10,8 +10,8 @@ from unittest.mock import Mock
import pytest
from core.handlers.model_hub.adapter import RawOutcomeKind
-from modules.agents.codex.agent import CodexAgent
from modules.agents.model_hub import bind_launch
+from tests.codex_generation_support import codex_agent_shell
from tests.e2e.drivers.mock_llm_upstream import _responses_stream_frames
from tests.e2e.test_codex_request_metadata import (
_completed,
@@ -75,7 +75,7 @@ async def test_codex_native_gateway_keeps_concurrent_route_ownership(
for_thread = await asyncio.gather(*(
_thread(transport, launch.runtime_model) for launch in (first, second)
))
- agent = object.__new__(CodexAgent)
+ agent = codex_agent_shell()
agent.controller = SimpleNamespace()
agent._prompt_state_agent_session_id = Mock(return_value=None)
agent._resolve_codex_agent_settings = lambda request: (None, request.selected_model, None, None)
diff --git a/tests/e2e/test_model_hub_engine_wire.py b/tests/e2e/test_model_hub_engine_wire.py
index 345444810..058be21b9 100644
--- a/tests/e2e/test_model_hub_engine_wire.py
+++ b/tests/e2e/test_model_hub_engine_wire.py
@@ -214,7 +214,8 @@ async def _through_engine(tmp_path, monkeypatch, protocol: str, *handlers):
async def _post(url: str, hop: dict, body: dict, *, timeout: float = 150) -> dict:
started = time.monotonic()
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as client:
- async with client.post(url, headers={"Authorization": f'Bearer {hop["token"]}'}, json=body) as response:
+ headers = {"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"]}
+ async with client.post(url, headers=headers, json=body) as response:
transport_error = None
try:
raw = await response.read()
@@ -495,7 +496,8 @@ async def test_consumer_cancel_closes_upstream_and_keeps_the_source(tmp_path, mo
async with _through_engine(tmp_path, monkeypatch, protocol, handler) as harness:
url, body = _frontend_request(protocol, harness.hop, stream=True)
async with aiohttp.ClientSession() as client:
- async with client.post(url, headers={"Authorization": f'Bearer {harness.hop["token"]}'},
+ async with client.post(url, headers={"Authorization": f'Bearer {harness.hop["token"]}',
+ **harness.hop["request_headers"]},
json=body) as response:
assert response.status == 200
await response.content.readuntil(b"partial")
diff --git a/tests/e2e/test_model_hub_google.py b/tests/e2e/test_model_hub_google.py
index c72830e76..1a0224332 100644
--- a/tests/e2e/test_model_hub_google.py
+++ b/tests/e2e/test_model_hub_google.py
@@ -97,7 +97,7 @@ async def test_real_google_frontend_uses_pinned_engine_and_reports_serving_origi
async with aiohttp.ClientSession() as client:
async with client.post(
base + endpoint,
- headers={"Authorization": f'Bearer {hop["token"]}'}, json=body,
+ headers={"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"]}, json=body,
) as response:
raw = await response.read()
unsupported_reason = None
diff --git a/tests/e2e/test_model_hub_guards.py b/tests/e2e/test_model_hub_guards.py
index ed034ca47..4d4c5196d 100644
--- a/tests/e2e/test_model_hub_guards.py
+++ b/tests/e2e/test_model_hub_guards.py
@@ -83,10 +83,8 @@ def test_g2_source_order_write_and_chain_reorder_are_divergent(
mock_llm_upstream,
model_hub_app,
) -> None:
- """G2: the orphan order endpoint persists order without applying it."""
+ """G2: the default Source order persists, and never reorders a manual chain (#1897)."""
- # Open decisions D-1..D-4 do not assign the B3 endpoint-divergence
- # decision; this baseline records the current split without inventing one.
first, second, original_hops = _two_source_chain(
model_hub_app, mock_llm_upstream
)
@@ -118,9 +116,10 @@ def test_g2_source_order_write_and_chain_reorder_are_divergent(
f"/api/models/agents/claude/chain?model={MENU_MODEL}"
)
assert chain_after.status == 200, chain_after.json()
+ # Reorder without an order returns the current projection; a manual array keeps its order.
assert [
hop["source_id"] for hop in chain_after.json()["chain"]["chain"]
- ] == reversed_order
+ ] == [hop["source_id"] for hop in original_hops]
def test_g3_malformed_json_and_business_refusals_are_client_errors(
diff --git a/tests/e2e/test_model_hub_migration_persisted.py b/tests/e2e/test_model_hub_migration_persisted.py
index bda24e50c..44d2ea126 100644
--- a/tests/e2e/test_model_hub_migration_persisted.py
+++ b/tests/e2e/test_model_hub_migration_persisted.py
@@ -187,8 +187,10 @@ def test_f4_unproven_shell_key_is_copied_without_validation(
assert result.status == 200, result.json()
assert result.json()["applied"] == 1
assert paths[0].read_bytes() == before
- assert len(app.client.get("/api/models/sources").json()["sources"]) == 1
+ # Check migration before the Sources page read below schedules its
+ # own independent background inventory refresh.
assert mock_llm_upstream.requests() == []
+ assert len(app.client.get("/api/models/sources").json()["sources"]) == 1
@pytest.mark.parametrize("shape", ["settings", "shell"])
@@ -225,9 +227,11 @@ def test_f4_custom_api_key_refusing_bearer_is_copied_without_validation(
assert migrated.status == 200, migrated.json()
assert migrated.json()["applied"] == 1
assert paths[0].read_bytes() == before
+ # Check migration before the Sources page read below schedules its
+ # own independent background inventory refresh.
+ assert mock_llm_upstream.requests() == []
[source] = app.client.get("/api/models/sources").json()["sources"]
assert source["verification_pending"]
- assert mock_llm_upstream.requests() == []
@pytest.mark.parametrize("profile,writer", [
@@ -349,7 +353,10 @@ def test_f4_shell_data_roles_allow_http_migration_without_changing_data(
assert app.client.post("/api/models/migration/scan", {}).json()["scan"]["items"] == []
[email protected]("damage", ["missing", "corrupt"])
[email protected]("damage", ["missing", pytest.param("corrupt", marks=pytest.mark.xfail(strict=True, reason=(
+ "on a running engine the reload reads the previous projection's credentials to find stale model names, "
+ "and a content-corrupt old document raises there; fixed separately"
+)))])
def test_f4_replace_migrated_bearer_without_old_secret_retains_cpa_transport(
model_hub_app_factory, mock_llm_upstream, damage,
):
diff --git a/tests/e2e/test_model_hub_mock_upstream.py b/tests/e2e/test_model_hub_mock_upstream.py
index a7c555c8a..a8dd52c8f 100644
--- a/tests/e2e/test_model_hub_mock_upstream.py
+++ b/tests/e2e/test_model_hub_mock_upstream.py
@@ -15,6 +15,7 @@ from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import ProxyHandler, Request, build_opener
+import psutil
import pytest
import yaml
@@ -242,6 +243,17 @@ def _send_through_real_engine(
return status, captured[0]["body"]
+def _opencode_generation_records(app) -> list[dict[str, Any]]:
+ """The process record of each OpenCode generation the app runs (#2329)."""
+
+ records = app.avibe_home / "runtime" / "opencode" / "generations"
+ return [
+ json.loads(path.read_text(encoding="utf-8"))
+ for path in sorted(records.glob("*.json"))
+ if not path.name.endswith(".overlay.json")
+ ]
+
+
def _send_through_opencode_gateway_engine(
model_hub_app_factory,
mock_llm_upstream: MockLLMUpstream,
@@ -373,7 +385,7 @@ def _send_through_opencode_gateway_engine(
assert set(projected_providers["avibe-anthropic"]["models"]) == {
"claude-opus-5"
}
- assert not (app.avibe_home / "logs" / "opencode_server.json").exists()
+ assert not _opencode_generation_records(app)
started = app.client.post("/api/models/runtime/start", {})
assert started.status == 200, started.json()
@@ -508,13 +520,10 @@ def _send_through_opencode_gateway_engine(
"high"
] == variant
- pid_info = json.loads(
- (app.avibe_home / "logs" / "opencode_server.json").read_text(
- encoding="utf-8"
- )
- )
+ # The one OpenCode generation serving the turn, the controller's own child.
+ (pid_info,) = _opencode_generation_records(app)
assert app._controller is not None
- assert pid_info["owner_pid"] == app._controller.pid
+ assert psutil.Process(pid_info["pid"]).ppid() == app._controller.pid
providers_status, _, providers_payload = _json_request(
f"http://{pid_info['host']}:{pid_info['port']}",
"/config/providers",
@@ -607,8 +616,18 @@ def test_opencode_v4_s4_variant_shapes_are_frozen_against_mock_capture(
)
assert captured_body["model"] == fixture["stored_model"]
- for key, value in fixture["upstream_fragment"].items():
- assert captured_body.get(key) == value, captured_body
+ # What the variant sets must survive; fields OpenCode adds on its own vary by its version.
+ assert _contains(captured_body, fixture["upstream_fragment"]), captured_body
+
+
+def _contains(actual: object, expected: object) -> bool:
+ """Whether ``actual`` holds ``expected``: every key of an expected mapping, recursively; anything else equal."""
+
+ if isinstance(expected, dict):
+ return isinstance(actual, dict) and all(
+ key in actual and _contains(actual[key], value) for key, value in expected.items()
+ )
+ return actual == expected
def test_opencode_responses_turn_completes_through_openai_chat_upstream(
@@ -770,16 +789,17 @@ def test_mock_upstream_required_key_uses_the_configured_protocol_header(
assert _json_request(mock_llm_upstream.url, "/v1/models")[0] == 200
[email protected]("scheme", ["bearer", "either"])
@pytest.mark.parametrize("surface", ["models", "probe", "buffered"])
@pytest.mark.parametrize("header", ["missing", "wrong", "x-api-key", "bearer"])
def test_mock_upstream_bearer_opt_in_preserves_authentication_shape(
- mock_llm_upstream, surface, header,
+ mock_llm_upstream, scheme, surface, header,
) -> None:
- """A custom Anthropic relay can require Bearer, not either auth header."""
+ """A custom Anthropic relay can require Bearer, or take the key in either auth header."""
key = "fixture-static-bearer"
_configure(
mock_llm_upstream.url, protocol="anthropic",
- required_api_key=key, required_auth_scheme="bearer",
+ required_api_key=key, required_auth_scheme=scheme,
)
headers = {
"missing": {},
@@ -796,7 +816,8 @@ def test_mock_upstream_bearer_opt_in_preserves_authentication_shape(
),
headers=headers,
)
- assert status == (401 if header != "bearer" else 400 if surface == "probe" else 200)
+ accepted = header == "bearer" or (scheme == "either" and header == "x-api-key")
+ assert status == (401 if not accepted else 400 if surface == "probe" else 200)
@pytest.mark.parametrize("protocol", PROTOCOL_CASES)
diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.py
index c3903decb..cb3f5c8e1 100644
--- a/tests/e2e/test_model_hub_routing.py
+++ b/tests/e2e/test_model_hub_routing.py
@@ -502,6 +502,8 @@ def test_mh_routing_010_model_not_found_stays_request_scoped_through_real_gatewa
"stream_started": False,
"http_status": 404,
"upstream_error_code": "not_found_error" if protocol == "anthropic" else "model_not_found",
+ # The upstream's own message, persisted since #2376.
+ "upstream_detail": f"model {target} not found",
}
first.configure(model_errors={})
base_url, token = await gateway.endpoint(
@@ -720,79 +722,6 @@ def test_mh_claude_launch_001_settings_cannot_bypass_the_configured_route(
assert native_settings.read_text() == native_payload
-def _seed_codex_native_login(home) -> None:
- _write(
- home / ".codex" / "auth.json",
- (
- '{"auth_mode":"chatgpt","tokens":'
- '{"access_token":"codex-native-e2e-123456"}}'
- ),
- )
- _write(
- home / ".codex" / "config.toml",
- 'cli_auth_credentials_store = "file"\n',
- )
-
-
-def test_d1_subscription_added_after_api_key_is_appended_at_tail(
- mock_llm_upstream,
- model_hub_app,
-) -> None:
- """D1: current placement appends a later native subscription."""
-
- # D-1 remains open: current shipped behavior appends at tail, so the API
- # key precedes and can burn before the later subscription.
- _configure_protocol(
- mock_llm_upstream,
- "openai_responses",
- models=[{"id": "gpt-5.3-codex"}],
- )
- api_source, _ = _create_source(
- model_hub_app,
- mock_llm_upstream,
- protocol="openai_responses",
- nonce="scn_d100000000000001",
- )
- _seed_codex_native_login(model_hub_app.home)
- scan = model_hub_app.client.post("/api/models/migration/scan", {})
- scan_body = scan.json()
- assert scan.status == 200, scan_body
- [native_item] = [
- item
- for item in scan_body["scan"]["items"]
- if item["kind"] == "oauth_native"
- ]
- applied = model_hub_app.client.post(
- "/api/models/migration/apply", {"item_ids": [native_item["id"]]}
- )
- applied_body = applied.json()
- assert applied.status == 200, applied_body
- native_source = next(
- source
- for source in applied_body["sources"]
- if (
- source["vendor"] == "openai"
- and source["kind"] == "subscription"
- and source["supply_channel"] == "native_cli"
- )
- )
-
- mode = model_hub_app.client.patch(
- "/api/models/agents/codex/mode", {"mode": "hub"}
- )
- assert mode.status == 200, mode.json()
-
- agent = model_hub_app.client.get(
- "/api/models/agents/codex/sources"
- )
- assert agent.status == 200, agent.json()
- agent_body = agent.json()
- assert agent_body["agent"]["sources"]["order"] == [
- api_source["id"],
- native_source["id"],
- ]
-
-
def _prepare_probe_chain(
app,
first_upstream: MockLLMUpstream,
@@ -990,7 +919,8 @@ def test_replaced_shared_key_keeps_source_identity_and_reaches_upstream_once(
replaced_port = after_replace.json()["runtime"]["status"][
"listening"
]["port"]
- assert replaced_port != first_port
+ # A Source save hot-reloads the running engine (#2138): same process, same port.
+ assert replaced_port == first_port
app.restart_controller()
mock_llm_upstream.reset_requests()
@@ -1157,6 +1087,11 @@ def test_d5_nonrefreshable_401_marks_the_key_for_repair(
assert next_probe.json()["probe"]["source_id"] == second["id"]
[email protected](strict=True, reason=(
+ "D-4 gap: the managed engine never forwards an upstream error's headers (its status errors "
+ "carry none, whatever passthrough-headers says), so Retry-After never reaches Avibe and a "
+ "5xx cools for the local 30-36 s backoff only (#2666)"
+))
def test_d6_server_error_preserves_later_retry_after_through_real_engine(
model_hub_app_factory,
mock_llm_upstream,
diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.py
index dbc771f04..1622214f2 100644
--- a/tests/e2e/test_model_hub_sources.py
+++ b/tests/e2e/test_model_hub_sources.py
@@ -37,6 +37,18 @@ def _configure_protocol(
upstream.reset_requests()
+def _require_key(upstream: MockLLMUpstream, key: str) -> None:
+ """Make the mock refuse its data surfaces without ``key``, as a real API-key endpoint does.
+
+ A model-free probe never proves a key (#1920): the declared interface's
+ model listing does, only where it refuses a request without the key
+ (#1936). The engine sends a custom-origin Anthropic key as Bearer, and
+ observation sends the protocol's header, so the mock takes either.
+ """
+
+ upstream.configure(required_api_key=key, required_auth_scheme="either")
+
+
def _source_payload(
upstream: MockLLMUpstream,
*,
@@ -76,6 +88,7 @@ def _create_source(
),
**(extra or {}),
}
+ _require_key(upstream, payload["key"])
response = app.client.post("/api/models/sources", payload)
body = response.json()
assert response.status == 201, body
@@ -88,14 +101,15 @@ def _create_source(
"protocol",
["anthropic", "openai_responses", "openai_chat"],
)
-def test_b1_auto_observe_selects_protocol_from_response_shape(
+def test_b1_auto_observe_needs_a_declared_protocol_to_prove_the_key(
mock_llm_upstream: MockLLMUpstream,
model_hub_app,
protocol: str,
) -> None:
- """B1: auto observation proves each protocol from response evidence."""
+ """B1: Auto never proves a key; the declared interface's key-gated listing does (#1920, #1936)."""
_configure_protocol(mock_llm_upstream, protocol)
+ _require_key(mock_llm_upstream, SYNTHETIC_API_KEY)
request = _source_payload(mock_llm_upstream, protocol=protocol)
request.pop("kind")
request.pop("display_name")
@@ -108,6 +122,26 @@ def test_b1_auto_observe_selects_protocol_from_response_shape(
body = response.json()
assert response.status == 200, body
assert body["contract_version"] == CONTRACT_VERSION
+ # A model-free probe's schema error shows a shape, never the key, and Auto
+ # never asks a listing, which names no protocol.
+ assert body["observation"] == {
+ "contract_version": CONTRACT_VERSION,
+ "outcome": "adapter_error",
+ "reachable": True,
+ "authenticated": "unknown",
+ "protocol": None,
+ "discovery": "not_attempted",
+ "models": [],
+ "model_metadata": [],
+ }
+ assert "/v1/models" not in [item["path"] for item in mock_llm_upstream.requests()]
+
+ mock_llm_upstream.reset_requests()
+ response = model_hub_app.client.post(
+ "/api/models/sources/observe", {**request, "protocol": protocol}
+ )
+ body = response.json()
+ assert response.status == 200, body
assert body["observation"] == {
"contract_version": CONTRACT_VERSION,
"outcome": "observed",
@@ -199,12 +233,12 @@ def test_b3_discovered_model_persists_only_contract_fields(
"models_endpoint",
["http_404", "http_500", "malformed_json"],
)
-def test_b4_inventory_failure_requires_consent_then_commits_error_source(
+def test_b4_inventory_failure_requires_consent_then_commits_unverified_source(
mock_llm_upstream: MockLLMUpstream,
model_hub_app,
models_endpoint: str,
) -> None:
- """B4: protocol proof survives an independently failed inventory."""
+ """B4: with no readable key-gated listing nothing proves the key; only an explicit unverified save commits."""
_configure_protocol(mock_llm_upstream, "openai_chat")
mock_llm_upstream.configure(models_endpoint=models_endpoint)
@@ -218,33 +252,42 @@ def test_b4_inventory_failure_requires_consent_then_commits_error_source(
}[models_endpoint],
)
- rejected = model_hub_app.client.post(
- "/api/models/sources", payload
- )
- rejected_body = rejected.json()
- assert rejected.status == 422, rejected_body
- assert rejected_body["error"] == "discovery_failed"
- assert rejected_body["detail"].endswith("inventory_unavailable")
- assert rejected_body["observation"]["protocol"] == "openai_chat"
- assert rejected_body["observation"]["discovery"] == "failed"
+ # Nothing proves the key (#1936), so the create is never observed and the
+ # inventory waiver has nothing to waive.
+ for attempt in (payload, {**payload, "accept_unavailable_inventory": True}):
+ rejected = model_hub_app.client.post("/api/models/sources", attempt)
+ rejected_body = rejected.json()
+ assert rejected.status == 422, rejected_body
+ assert rejected_body["error"] == "discovery_failed"
+ assert rejected_body["detail"].endswith("observation_failed")
+ assert rejected_body["observation"] == {
+ "contract_version": CONTRACT_VERSION,
+ "outcome": "adapter_error",
+ "reachable": True,
+ "authenticated": "unknown",
+ "protocol": None,
+ "discovery": "not_attempted",
+ "models": [],
+ "model_metadata": [],
+ }
assert model_hub_app.client.get(
"/api/models/sources"
).json()["sources"] == []
+ # Explicit consent (#1920): the declared interface is saved unverified, unprobed.
+ mock_llm_upstream.reset_requests()
accepted = model_hub_app.client.post(
- "/api/models/sources",
- {**payload, "accept_unavailable_inventory": True},
+ "/api/models/sources", {**payload, "save_unverified": True}
)
accepted_body = accepted.json()
assert accepted.status == 201, accepted_body
source = accepted_body["source"]
assert source["protocol"] == "openai_chat"
assert source["models"] == []
- assert source["state"] == {
- "status": "error",
- "retry_at": None,
- "detail_key": "models.source.error.unclassified",
- }
+ assert source["verification_pending"]
+ assert source["state"]["status"] == "standby"
+ # No probe: a background inventory refresh may still read the listing.
+ assert [item for item in mock_llm_upstream.requests() if item["method"] == "POST"] == []
@pytest.mark.xfail(
@@ -314,10 +357,13 @@ def test_b6_replace_key_rolls_back_then_rename_and_retarget_commit(
assert revocation_journal.stat().st_mtime_ns > journal_mtime
assert json.loads(revocation_journal.read_text(encoding="utf-8")) == []
+ # The endpoint now takes the replacement key, and its listing proves it.
+ replacement_key = "sk-model-hub-e2e-replacement"
mock_llm_upstream.configure(auth="ok")
+ _require_key(mock_llm_upstream, replacement_key)
replaced = model_hub_app.client.put(
f"/api/models/sources/{source['id']}/credential",
- {"key": "sk-model-hub-e2e-replacement"},
+ {"key": replacement_key},
)
replaced_body = replaced.json()
assert replaced.status == 200, replaced_body
@@ -332,6 +378,7 @@ def test_b6_replace_key_rolls_back_then_rename_and_retarget_commit(
with MockLLMUpstream() as replacement_upstream:
_configure_protocol(replacement_upstream)
+ _require_key(replacement_upstream, replacement_key)
retargeted = model_hub_app.client.patch(
f"/api/models/sources/{source['id']}",
{"base_url": replacement_upstream.url},
@@ -388,9 +435,11 @@ def test_b7_delete_guard_requires_exact_echo_before_force(
assert refused.status == 409, refusal
assert refusal["error"] == "source_in_route_chain"
assert refusal["would_remove_hops"]
- assert refusal["would_interrupt"] == [
- {"backend": "claude", "model_id": MENU_MODEL, "agents": []}
- ]
+ # Deleting the only Source strands every protected menu row it supplied,
+ # passthrough included (#1897): pin the chained row, not the menus' contents.
+ assert {
+ "backend": "claude", "model_id": MENU_MODEL, "agents": []
+ } in refusal["would_interrupt"]
stale_hops = [dict(hop) for hop in refusal["would_remove_hops"]]
stale_hops[0]["model_id"] = "stale-confirmed-model"
@@ -483,13 +532,30 @@ def test_b8_refresh_force_is_body_only_in_the_current_http_contract(
# Open decision B6 has no D-1..D-4 identifier in plan section 5:
# normalize destructive force transport or retain the current split.
- source = _create_guarded_source(model_hub_app, mock_llm_upstream)
+ # An API-key hop needs no inventory membership (#1897), so an emptied
+ # listing strands nothing on its own. Refresh drops a hop where another
+ # Source still lists the model and automatic matching narrows to it (#1934).
+ _configure_protocol(mock_llm_upstream, "anthropic", models=[{"id": MENU_MODEL}])
+ _create_source(
+ model_hub_app, mock_llm_upstream, nonce="scn_b800000000000001",
+ vendor="anthropic", display_name="Listing E2E source",
+ )
+ source, _ = _create_source(
+ model_hub_app, mock_llm_upstream, nonce="scn_b800000000000002",
+ vendor="anthropic", display_name="Emptied E2E source",
+ )
+ mode = model_hub_app.client.patch("/api/models/agents/claude/mode", {"mode": "hub"})
+ assert mode.status == 200, mode.json()
endpoint = f"/api/models/sources/{source['id']}/refresh"
mock_llm_upstream.configure(models=[])
refused = model_hub_app.client.post(endpoint, {})
refusal = refused.json()
assert refused.status == 409, refusal
assert refusal["error"] == "source_model_in_route_chain"
+ assert any(
+ hop["backend"] == "claude" and hop["source_id"] == source["id"] and hop["model_id"] == MENU_MODEL
+ for hop in refusal["would_remove_hops"]
+ ), refusal["would_remove_hops"]
query_force = model_hub_app.client.post(
f"{endpoint}?force=true",
@@ -603,7 +669,6 @@ def test_b10_custom_models_and_free_text_tiers_obey_ownership_rules(
"high",
"xhigh",
"max",
- "ultra",
]
assert catalog_model["reasoning_efforts_source"] == "catalog"
managed = model_hub_app.client.patch(
@@ -707,7 +772,6 @@ def test_b10_custom_models_and_free_text_tiers_obey_ownership_rules(
"high",
"xhigh",
"max",
- "ultra",
]
assert refreshed_catalog_model["reasoning_efforts_source"] == "catalog"
events = model_hub_app.client.get("/api/models/events?limit=20").json()[
diff --git a/tests/e2e/test_model_hub_usage_events.py b/tests/e2e/test_model_hub_usage_events.py
index e376ce07a..eee6de312 100644
--- a/tests/e2e/test_model_hub_usage_events.py
+++ b/tests/e2e/test_model_hub_usage_events.py
@@ -20,6 +20,14 @@ from tests.e2e.test_model_hub_sources import (
pytestmark = pytest.mark.e2e_model_hub
+# The counters these scenarios seed and read back; a report's cost and cache-write
+# totals (#2189) are additive and owned by the pricing tests.
+_SCENARIO_COUNTERS = ("requests", "token_reports", "input_tokens", "cached_input_tokens", "output_tokens")
+
+
+def _counts(totals: dict) -> dict:
+ return {key: totals[key] for key in _SCENARIO_COUNTERS}
+
@pytest.fixture
def usage_analytics_app(model_hub_app_factory):
@@ -87,7 +95,7 @@ def test_e2_usage_windows_are_bounded(
body = response.json()
assert response.status == 200, body
assert body["usage"]["window_days"] == expected
- assert body["usage"]["totals"] == {
+ assert _counts(body["usage"]["totals"]) == {
"requests": 0,
"token_reports": 0,
"input_tokens": 0,
@@ -167,7 +175,7 @@ def test_e2_usage_reports_reconcile_across_http_ipc_and_restart(
expected = expected_hourly if window == "24h" else expected_daily
assert report["window_key"] == window
assert report["granularity"] == ("hour" if window == "24h" else "day")
- assert report["totals"] == expected
+ assert _counts(report["totals"]) == expected
buckets = report["buckets"]
assert len(buckets) == count
assert len({bucket["key"] for bucket in buckets}) == count
@@ -217,16 +225,16 @@ def test_e2_usage_reports_reconcile_across_http_ipc_and_restart(
assert response.status == 400, response.json()
repeated = model_hub_app.client.get("/api/models/usage?window=24h&window=24h")
assert repeated.status == 200, repeated.json()
- assert repeated.json()["usage"]["totals"] == expected_hourly
+ assert _counts(repeated.json()["usage"]["totals"]) == expected_hourly
legacy = model_hub_app.client.get("/api/models/usage?days=7").json()["usage"]
- assert legacy["totals"] == expected_daily
+ assert _counts(legacy["totals"]) == expected_daily
assert "buckets" not in legacy
model_hub_app.restart_controller()
for window, expected in (("24h", expected_hourly), ("7d", expected_daily)):
response = model_hub_app.client.get(f"/api/models/usage?window={window}")
assert response.status == 200, response.json()
- assert response.json()["usage"]["totals"] == expected
+ assert _counts(response.json()["usage"]["totals"]) == expected
def test_e2_daily_only_history_is_not_invented_as_hourly_usage(
@@ -260,11 +268,11 @@ def test_e2_daily_only_history_is_not_invented_as_hourly_usage(
with model_hub_app_factory(before_start=seed_legacy) as app:
daily = app.client.get("/api/models/usage?window=7d")
assert daily.status == 200, daily.json()
- assert daily.json()["usage"]["totals"] == counts
+ assert _counts(daily.json()["usage"]["totals"]) == counts
hourly = app.client.get("/api/models/usage?window=24h")
assert hourly.status == 200, hourly.json()
report = hourly.json()["usage"]
- assert report["totals"] == dict.fromkeys(counts, 0)
+ assert _counts(report["totals"]) == dict.fromkeys(counts, 0)
assert any(not bucket["history_complete"] for bucket in report["buckets"])
assert not any(bucket["rows"] for bucket in report["buckets"])
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 22799379a..60ffb3e65 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -2170,11 +2170,11 @@ scenarios:
layer: e2e-auto
test: tests/e2e/test_model_hub_runtime.py::test_a5_controller_restart_during_oauth_poll_reports_engine_down
- id: B1
- name: Automatic observation selects protocol from response evidence
+ name: Automatic observation never proves a key; a declared protocol's key-gated listing does
status: assert
kind: protocol
layer: e2e-auto
- test: tests/e2e/test_model_hub_sources.py::test_b1_auto_observe_selects_protocol_from_response_shape
+ test: tests/e2e/test_model_hub_sources.py::test_b1_auto_observe_needs_a_declared_protocol_to_prove_the_key
- id: B2
name: Manual protocol mismatch is refused with proof evidence
status: assert
@@ -2188,11 +2188,11 @@ scenarios:
layer: e2e-auto
test: tests/e2e/test_model_hub_sources.py::test_b3_discovered_model_persists_only_contract_fields
- id: B4
- name: Unavailable inventory requires explicit acceptance before commit
+ name: An unprovable key commits only through an explicit unverified save
status: assert
kind: recovery
layer: e2e-auto
- test: tests/e2e/test_model_hub_sources.py::test_b4_inventory_failure_requires_consent_then_commits_error_source
+ test: tests/e2e/test_model_hub_sources.py::test_b4_inventory_failure_requires_consent_then_commits_unverified_source
- id: B5
name: Replayed source creation nonce is idempotent
status: xfail
@@ -2270,11 +2270,12 @@ scenarios:
owning_layer: manual live-vendor regression
evidence: docs/plans/model-hub-e2e-test-plan.md#c-oauth-lifecycle-c30c40-partial-by-1
- id: D1
- name: A later native subscription is appended after an API-key source
- status: baseline
+ name: A later subscription is placed ahead of an API-key source
+ status: assert
kind: placement
- layer: e2e-auto
- test: tests/e2e/test_model_hub_routing.py::test_d1_subscription_added_after_api_key_is_appended_at_tail
+ # A hermetic E2E cannot add a subscription: a native takeover validates its grant with the provider.
+ layer: contract
+ test: tests/test_model_hub_resolution.py::test_new_subscription_joins_only_the_agents_its_catalog_serves
- id: D2
name: A healthy first hop reaches the upstream through the real engine
status: assert
@@ -2311,7 +2312,7 @@ scenarios:
test: tests/e2e/test_model_hub_routing.py::test_d5_nonrefreshable_401_marks_the_key_for_repair
- id: D6
name: A server error honors later upstream advice through the real engine
- status: assert
+ status: xfail
kind: failover
layer: e2e-auto
test: tests/e2e/test_model_hub_routing.py::test_d6_server_error_preserves_later_retry_after_through_real_engine
@@ -2426,8 +2427,8 @@ scenarios:
layer: e2e-auto
test: tests/e2e/test_model_hub_guards.py::test_g1_guard_echo_missing_agents_does_not_loop
- id: G2
- name: Source-order write and chain reorder retain their current divergence
- status: baseline
+ name: The default Source order persists and never reorders a manual chain
+ status: assert
kind: compatibility
layer: e2e-auto
test: tests/e2e/test_model_hub_guards.py::test_g2_source_order_write_and_chain_reorder_are_divergent
@@ -2534,6 +2535,5 @@ next_priority:
- B5
- B8
- B9
- - D1
- - G2
+ - D6
- G3
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 68b2deb90..fe227f511 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -2352,6 +2352,7 @@ def test_direct_mode_refuses_chain_and_probe(tmp_path):
def test_new_subscription_joins_only_the_agents_its_catalog_serves(tmp_path):
+ """D1: a later subscription is placed ahead of API keys, where its fixed catalog serves the menu (D-1, #2156)."""
key = _source("src_placekey01", ("claude-opus-4-6",))
config = _config([key])
service, _, _ = _service(tmp_path, config)