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.

fix(model-hub): close the proxy executor's tracked edges (#2593)

Call White3f1c551b4928
diff --git a/core/handlers/model_hub/hosted_executor.py b/core/handlers/model_hub/hosted_executor.py
index 4d0f98d12..ab2d94aa0 100644
--- a/core/handlers/model_hub/hosted_executor.py
+++ b/core/handlers/model_hub/hosted_executor.py
@@ -47,6 +47,8 @@ _IMAGES_TOTAL_MAX_BYTES: Final = 64 * 1024 * 1024
# Image events per response: the requested partials and the final, with a small margin.
_IMAGE_EVENT_MARGIN: Final = 2
_SNIPPET_CHARS: Final = 500
+# The url_citation annotations one response's record reads; an executor's answer cites tens.
+_MAX_CITATIONS: Final = 256
_X_POST_HOSTS: Final = ("x.com", "twitter.com", "www.x.com", "www.twitter.com", "mobile.twitter.com")
_X_SEARCH_CALLS: Final = frozenset({"x_keyword_search", "x_semantic_search", "x_user_search", "x_thread_fetch"})
_IMAGE_MIME: Final = {"png": "image/png", "jpeg": "image/jpeg", "jpg": "image/jpeg", "webp": "image/webp"}
@@ -176,6 +178,8 @@ def executor_request(call: ExecutorCall, source: ModelHubSourceConfig, model_id:
"instructions": instructions,
"input": [{"role": "user", "content": query}],
"tools": [declaration],
+ # Forced, as the call probe forces it: a model answering from memory runs no search.
+ "tool_choice": "required",
"store": False,
"max_output_tokens": _RESPONSES_OUTPUT_TOKENS,
}
@@ -244,9 +248,9 @@ class ResponsesStreamReader:
return
except RecursionError:
raise ExecutorResponseRefused("modelHub.hostedTools.unreadable") from None
- if not isinstance(payload, dict):
+ kind = payload.get("type") if isinstance(payload, dict) else None
+ if not isinstance(kind, str):
return
- kind = payload.get("type")
item = payload.get("item")
if kind == "response.image_generation_call.partial_image":
self._count_image(payload.get("partial_image_b64"))
@@ -358,7 +362,7 @@ def _settled(response: Mapping[str, Any], sources: list[dict[str, Any]], say: Sa
any other or missing ending is a failure.
"""
- status = response.get("status")
+ status = _text_field(response, "status")
if status == "completed":
return {"status": "completed", "sources": sources}
ended = _ended_without("", response, say) if status in {"failed", "incomplete"} else say(
@@ -369,19 +373,26 @@ def _settled(response: Mapping[str, Any], sources: list[dict[str, Any]], say: Sa
return failed_record(ended, sources)
+def _text_field(item: Mapping[str, Any], key: str) -> str | None:
+ """A provider field read as text; anything else is absent."""
+
+ value = item.get(key)
+ return value if isinstance(value, str) else None
+
+
def _responses_call_tool(item: Mapping[str, Any]) -> str | None:
kind = item.get("type")
if kind == "web_search_call":
return "web_search"
if kind == "image_generation_call":
return "image_generation"
- if kind == "custom_tool_call" and item.get("name") in _X_SEARCH_CALLS:
+ if kind == "custom_tool_call" and _text_field(item, "name") in _X_SEARCH_CALLS:
return "x_search"
return None
def _ended_without(tool: str, response: Mapping[str, Any], say: Say) -> str:
- status = response.get("status")
+ status = _text_field(response, "status")
if status in {"failed", "incomplete"}:
details = response.get("incomplete_details")
reason = details.get("reason") if isinstance(details, dict) else None
@@ -404,6 +415,7 @@ def _cited_sources(parts: list[Mapping[str, Any]], *, x_posts_only: bool) -> lis
"""Each cited URL once, in citation order, with the sentence its span sits in as the snippet."""
sources: list[dict[str, Any]] = []
+ budget = _MAX_CITATIONS
for part in parts:
text = part["text"]
citations = [
@@ -411,12 +423,13 @@ def _cited_sources(parts: list[Mapping[str, Any]], *, x_posts_only: bool) -> lis
for note in (part.get("annotations") if isinstance(part.get("annotations"), list) else ())
if isinstance(note, dict) and note.get("type") == "url_citation"
and isinstance(note.get("url"), str) and note["url"]
- ]
- spans = [
+ ][:budget]
+ budget -= len(citations)
+ spans = sorted(
(note["start_index"], note["end_index"], note["url"])
for note in citations
if _valid_span(note.get("start_index"), note.get("end_index"), len(text))
- ]
+ )
for note in citations:
url = note["url"]
if x_posts_only and not _is_x_post(url):
@@ -465,6 +478,8 @@ _LIST_MARKER = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s*")
def excerpt(text: str, start: int, end: int, url: str, spans: list[tuple[int, int, str]]) -> str | None:
"""The answer text a citation span belongs to, without citation markers (``vibey-hosted-tools.md`` §12 item 24).
+ ``spans`` are the text's citation spans, in text order.
+
The executor asks for one list item per result, each ending in its
citation, so a span on a line that cites only its own URL takes that whole
line. On a line that cites several sources, it takes its sentence: the one
@@ -481,7 +496,7 @@ def excerpt(text: str, start: int, end: int, url: str, spans: list[tuple[int, in
else:
region_start, region_end = _sentence(text, start, end, line_start, line_end)
pieces, cursor = [], region_start
- for span_start, span_end, _url in sorted(spans):
+ for span_start, span_end, _url in spans:
if span_end <= region_start or span_start >= region_end:
continue
pieces.append(text[cursor:max(cursor, span_start)])
@@ -517,16 +532,18 @@ def _image_result(
# The one failure-precedence rule: a provider-marked failed call fails the call.
return ExecutorResult(failed_record(say("modelHub.hostedTools.callFailed", tool="image_generation")))
done = [call for call in calls if call.get("status") == "completed" and isinstance(call.get("result"), str)]
- if done and done[-1]["result"] and failure is None and (readout.response or {}).get("status") != "completed":
+ image = done[-1] if done and done[-1]["result"] else None
+ status = _text_field(readout.response or {}, "status")
+ if failure is None and (status == "incomplete" or (image is not None and status != "completed")):
+ # Success is the allow-list: a response that stopped early, before or after its image, is not completed.
settled = _settled(readout.response or {}, [], say)
return ExecutorResult({**settled, "sources": []})
- if failure is not None or not done or not done[-1]["result"]:
+ if failure is not None or image is None:
error = failure or (
say("modelHub.hostedTools.callEnded", tool="image_generation", status=str(calls[-1].get("status")))
if calls else _ended_without("image_generation", readout.response or {}, say)
)
return ExecutorResult(failed_record(error))
- image = done[-1]
output_format = str(image.get("output_format") or "png").lower()
mime = _IMAGE_MIME.get(output_format)
if mime is None:
@@ -573,7 +590,10 @@ def _anthropic_record(message: Any, say: Say) -> ExecutorResult:
if isinstance(found, dict):
errors.append(str(found.get("error_code") or "unknown"))
continue
- for result in found if isinstance(found, list) else ():
+ if not isinstance(found, list):
+ # Only a list, possibly empty, is a result; anything else is not an answer.
+ return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable")))
+ for result in found:
if isinstance(result, dict) and isinstance(result.get("url"), str) and result["url"]:
source = {"url": result["url"]}
for key in ("title", "page_age"):
@@ -590,7 +610,7 @@ def _anthropic_record(message: Any, say: Say) -> ExecutorResult:
and citation["url"]
and isinstance(citation.get("cited_text"), str)
and citation["cited_text"].strip()
- ]
+ ][:_MAX_CITATIONS]
# Results keep the provider's order; a cited result gains the text it was cited for.
sources = _merge_sources(results, cited)
if errors:
@@ -599,14 +619,14 @@ def _anthropic_record(message: Any, say: Say) -> ExecutorResult:
text = say("modelHub.hostedTools.callFailed", tool="web_search")
return ExecutorResult(failed_record(f"{text} ({', '.join(errors)})", sources))
# Success is an allow-list here too: an early stop is incomplete, anything else unknown fails.
- stop = message.get("stop_reason")
+ stop = _text_field(message, "stop_reason")
if stop in {"end_turn", "stop_sequence"}:
- uses = {
+ uses = [
block.get("id") for block in blocks
if block.get("type") == "server_tool_use" and block.get("name") == "web_search"
- }
- answered = {block.get("tool_use_id") for block in blocks if block.get("type") == "web_search_tool_result"}
- if not uses <= answered:
+ ]
+ answered = [block.get("tool_use_id") for block in blocks if block.get("type") == "web_search_tool_result"]
+ if not all(isinstance(ident, str) and ident for ident in (*uses, *answered)) or not set(uses) <= set(answered):
# A finished response must carry every search's result block, even an empty one.
return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable"), sources))
return ExecutorResult({"status": "completed", "sources": sources})
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index a0a97efe7..22605dd3b 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -6186,15 +6186,16 @@ class ModelHubService:
# Cancelled after admission, before a handle: the wire
# facts already observed are still billed, so still metered.
cancelled_observed = cancelled_early.observed
- raise
+ # Raised as a plain cancellation: the deadline converts
+ # only that into its timeout, and any other canceller
+ # reads it as its own.
+ raise asyncio.CancelledError() from None
break
finally:
release_owner()
if handle.stream is not None:
- async for chunk in handle.stream:
- if refused is not None:
- continue
- try:
+ try:
+ async for chunk in handle.stream:
if reader is not None:
# An image event is megabytes of JSON: parse it off the controller loop.
await asyncio.to_thread(reader.feed, chunk)
@@ -6202,12 +6203,20 @@ class ModelHubService:
raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge")
else:
body.extend(chunk)
- except ExecutorResponseRefused as broken:
- # The response broke a bound: the call failed. Its usage is still metered.
- refused = broken.key
+ except ExecutorResponseRefused as broken:
+ # The response broke a bound: the call failed, and nothing more
+ # of it is read. Its usage is still metered, from the outcome
+ # when the call already has one (a buffered response does).
+ refused = broken.key
+ await self._engine_call(handle.close_stream())
+ if handle.outcome_available:
+ outcome = await self._engine_call(handle.outcome())
+ return
outcome = await self._engine_call(handle.outcome())
async def settle() -> None:
+ # The call ended now; a slow close must not move its usage to a later slice.
+ ended_at = self.now()
try:
if handle is not None:
# Bounded like the gateway's own teardown: a stuck close must
@@ -6222,6 +6231,7 @@ class ModelHubService:
model_id=model_id,
outcome=outcome,
observed=handle.observed if handle is not None else cancelled_observed,
+ at=ended_at,
)
try:
@@ -9424,6 +9434,7 @@ class ModelHubService:
model_id: str,
outcome: RawCallOutcome | None,
observed: ProtocolSSEState | None,
+ at: datetime | None = None,
) -> None:
"""Fold one bodyless upstream call into the usage ledger, best-effort.
@@ -9448,6 +9459,8 @@ class ModelHubService:
the vendor had already billed. The writer's own bounded wait keeps the
ordinary path leaving the row on disk before the caller sees its outcome,
without putting an unresponsive disk in front of the next failover hop.
+
+ ``at`` is when the call ended, when its caller settles it later than that.
"""
usage = _call_usage(outcome, observed)
@@ -9462,7 +9475,7 @@ class ModelHubService:
source_id=source_id,
model_id=model_id,
usage=usage,
- at=self.now(),
+ at=at or self.now(),
)
)
diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.md
index 55a0ac7db..7d3364af2 100644
--- a/docs/plans/agent-core-contracts/model-hub-consumer.md
+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md
@@ -118,8 +118,9 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
- An executor Source whose identity changed since launch (base URL, credential) is "no longer available".
- The gateway runs that executor and no other: one native request in the executor Source's own protocol, with
the overlay's declaration and no reasoning effort. Search tools ask for a numbered list of results with one
- or two cited sentences each. `image_generation` renders the prompt at the given size and requests partial
- images.
+ or two cited sentences each. On Responses the tool is forced (`tool_choice: "required"`), as the call probe
+ that verified it forces it; Anthropic is asked in the message alone. `image_generation` renders the prompt at
+ the given size and requests partial images.
- Every outcome of a well-formed call is a 200 with `{"record", "execution"?}`, in the
`ToolResultMessage.hosted` encoding. `execution` is present exactly when an executor ran. A call that
reaches none (no verified executor, or the bound Source was removed or is ineligible) has a `failed` record.
@@ -127,11 +128,12 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
`status: completed`; Anthropic `end_turn` or `stop_sequence`) and nothing failed. A response that stopped
early (Responses `incomplete`; Anthropic `max_tokens` or `pause_turn`) is `incomplete`. Any reported failure
(a failed call or outcome, an Anthropic search error), or any other or missing ending, is `failed`. Both keep
- any partial sources. An unreadable response, including one nested past the decoder's limit, is `failed`. The
- record's `error` is in the user's language.
+ any partial sources. An unreadable response, including one nested past the decoder's limit or one whose
+ fields are not of their kind, is `failed`. The record's `error` is in the user's language.
- The record's search `sources` keep the executor's order. A snippet is the answer text its citation belongs
to: the list item when that item cites only that source, else its sentence, with the citation markers
- removed. An Anthropic result keeps its `cited_text`. X search lists the cited posts.
+ removed. An Anthropic result keeps its `cited_text`. X search lists the cited posts. A response's first 256
+ citations are read.
- For `image_generation`, the record has no `images` key. `generation` carries the resolved `revised_prompt`,
`size` and `quality`, and `images` carries `[{mime, data}]` in base64. Vibey saves the bytes through its
session media sink and adds the path records itself. The image must decode, within 24 MiB. The stream may
diff --git a/tests/test_model_hub_hosted_executor.py b/tests/test_model_hub_hosted_executor.py
index d03311ec3..004bba796 100644
--- a/tests/test_model_hub_hosted_executor.py
+++ b/tests/test_model_hub_hosted_executor.py
@@ -15,6 +15,7 @@ import gzip
import json
import threading
from dataclasses import replace
+from datetime import timedelta
import aiohttp
import pytest
@@ -25,12 +26,12 @@ from core.handlers.model_hub import hosted_executor as executor_module
from core.handlers.model_hub import service as service_module
from core.handlers.model_hub.adapter import InvokeCancelledError, RawOutcomeKind
from core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digest
-from core.handlers.model_hub.hosted_executor import excerpt
+from core.handlers.model_hub.hosted_executor import ResponsesReadout, anthropic_result, excerpt, responses_result
from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp
from core.handlers.model_hub.pricing import PriceTable
from core.handlers.model_hub.stream_wire import ProtocolSSEState, ProtocolUsageReport
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
-from core.handlers.model_hub.usage import UsageWriter
+from core.handlers.model_hub.usage import BoundedUsageLedger, UsageWriter
from modules.agents.model_hub import ModelHubRuntimeRouter
from core.run_settlement import SETTLED_BY_STOPPED
from tests.test_model_hub_l3 import (
@@ -185,7 +186,7 @@ def _hosted_result(tool, answer):
async def test_a_proxied_search_runs_one_native_request_and_answers_its_canonical_record(
tmp_path, tool, executor, arguments, frames, body_fields, sources,
):
- """MH-HOSTED-GATEWAY-004: the bound executor only, no effort, the overlay declaration, excerpts, metering."""
+ """MH-HOSTED-GATEWAY-004: the bound executor only, no effort, the overlay declaration forced, excerpts, metering."""
usage = ProtocolUsageReport.of(input_tokens=5369, cached_input_tokens=256, output_tokens=307)
service = _vibey_service(tmp_path, _sources(), handles=[
@@ -199,9 +200,13 @@ async def test_a_proxied_search_runs_one_native_request_and_answers_its_canonica
assert service.adapter.invocations == [(executor[0], executor[1], "vibey")]
sent = service.adapter.requests[0]
assert sent.protocol == "openai_responses"
- assert "reasoning" not in sent and "tool_choice" not in sent
+ assert "reasoning" not in sent
+ # Forced, as the call probe that verified it forces it.
+ assert sent["tool_choice"] == "required"
assert {key: sent[key] for key in body_fields} == body_fields
- assert set(sent) - set(body_fields) == {"model", "instructions", "input", "store", "max_output_tokens"}
+ assert set(sent) - set(body_fields) == {
+ "model", "instructions", "input", "tool_choice", "store", "max_output_tokens",
+ }
query = sent["input"][0]["content"]
assert query.startswith(arguments["query"])
if tool == "x_search":
@@ -504,6 +509,83 @@ async def test_an_image_the_executor_cannot_vouch_for_is_a_failed_record(tmp_pat
assert "images" not in answer and "execution" in answer
+async def test_an_image_response_that_stopped_before_its_image_is_incomplete(tmp_path):
+ """MH-HOSTED-GATEWAY-005: completion is the allow-list for images too; an early stop is incomplete, not failed."""
+
+ frames = (
+ _event({"type": "response.output_item.done", "item": {
+ "type": "image_generation_call", "id": "ig_1", "status": "generating",
+ }}),
+ _event({"type": "response.incomplete", "response": {
+ "id": "resp_1", "status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"},
+ }}),
+ )
+ service = _vibey_service(tmp_path, _sources(), handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), frames),
+ ])
+ _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))
+ status, answer = await _call(service, "image_generation", {
+ "arguments": {"prompt": "a boat"}, "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},
+ })
+ assert status == 200
+ assert answer["record"]["status"] == "incomplete" and "max_output_tokens" in answer["record"]["error"]
+ assert "images" not in answer
+
+
+async def test_a_call_is_metered_in_the_slice_it_ended_in(tmp_path):
+ """MH-HOSTED-GATEWAY-004: a slow close of the executor's stream does not move the call's usage to a later day."""
+
+ clock = [NOW]
+
+ class SlowClose(LiveInvokeHandle):
+ async def close_stream(self) -> None:
+ clock[0] = NOW + timedelta(days=2)
+ await super().close_stream()
+
+ usage = ProtocolUsageReport.of(input_tokens=10, cached_input_tokens=0, output_tokens=1)
+ service = _vibey_service(tmp_path, _sources(), handles=[
+ SlowClose(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI, usage=usage), _responses(WEB_CALL, WEB_ANSWER)),
+ ])
+ # One clock for the call and the ledger, as in production.
+ service.now = lambda: clock[0]
+ service.usage = BoundedUsageLedger(tmp_path / "usage-clocked.json", now=lambda: clock[0])
+ service.usage_writer = UsageWriter(service.usage)
+ _bind(service, "web_search", (XAI, "grok-4.6"))
+ status, _answer = await _call(service, "web_search", {
+ "arguments": {"query": "q"}, "executor": {"source_id": XAI, "model_id": "grok-4.6"},
+ })
+ assert status == 200
+ rows = json.loads(service.usage.path.read_text(encoding="utf-8"))
+ assert {row["day"] for row in rows} == {NOW.astimezone().date().isoformat()}
+
+
[email protected]("protocol", ["openai_responses", "anthropic"])
+def test_a_record_reads_a_bounded_number_of_citations(protocol):
+ """MH-HOSTED-GATEWAY-004: however many citations an answer carries, its record reads a bounded number."""
+
+ posts = [(f"Post {number}.", f"https://x.com/a/status/{number}", 0) for number in range(300)]
+
+ def say(key, **_values):
+ return key
+
+ if protocol == "openai_responses":
+ answer = {"type": "message", "role": "assistant", "content": [_cited(posts)]}
+ readout = ResponsesReadout(items=[X_CALL, answer], response={"status": "completed"})
+ record = responses_result("x_search", readout, say).record
+ else:
+ record = anthropic_result(json.dumps({"type": "message", "stop_reason": "end_turn", "content": [
+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "q"}},
+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": []},
+ {"type": "text", "text": "Posts.", "citations": [
+ {"type": "web_search_result_location", "url": url, "cited_text": sentence} for sentence, url, _ in posts
+ ]},
+ ]}).encode(), say).record
+ assert record["status"] == "completed"
+ assert [source["url"] for source in record["sources"]] == [url for _, url, _ in posts[:256]]
+
+
@pytest.mark.asyncio
async def test_one_failed_anthropic_search_fails_the_call_and_keeps_the_results_that_arrived(tmp_path):
"""MH-HOSTED-GATEWAY-005: failure precedence is the same on both protocols."""
@@ -575,6 +657,14 @@ INCOMPLETE = (
}}),
)
DEEP = "[" * 100_000 + "]" * 100_000
+ANTHROPIC_FOUND = [{"type": "web_search_result", "url": PAGE_A, "title": "Releases"}]
+
+
+def _anthropic(stop_reason, *, use_id="srvtoolu_1", found=ANTHROPIC_FOUND) -> tuple[bytes]:
+ return (json.dumps({"type": "message", "stop_reason": stop_reason, "content": [
+ {"type": "server_tool_use", "id": use_id, "name": "web_search", "input": {"query": "q"}},
+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": found},
+ ]}).encode(),)
@pytest.mark.asyncio
@@ -601,6 +691,17 @@ DEEP = "[" * 100_000 + "]" * 100_000
"could not be read", []),
("anthropic_nested_too_deep", (ANTHROPIC, "claude-haiku-4-5"), (DEEP.encode(),), "failed",
"could not be read", []),
+ # A provider field that is not the text it should be reads as unknown, never as a 500.
+ ("responses_status_not_text", (XAI, "grok-4.6"), (*INCOMPLETE[:1], _event({
+ "type": "response.completed", "response": {"id": "resp_1", "status": {"value": "completed"}},
+ })), "failed", "unknown", [{"url": PAGE_A}, {"url": PAGE_B}]),
+ ("anthropic_stop_reason_not_text", (ANTHROPIC, "claude-haiku-4-5"), _anthropic({"value": "end_turn"}), "failed",
+ "unknown", [{"url": PAGE_A, "title": "Releases"}]),
+ ("anthropic_search_id_not_text", (ANTHROPIC, "claude-haiku-4-5"), _anthropic("end_turn", use_id={"id": 1}),
+ "failed", "could not be read", [{"url": PAGE_A, "title": "Releases"}]),
+ # Only a list, even an empty one, is a search's results.
+ ("anthropic_results_not_a_list", (ANTHROPIC, "claude-haiku-4-5"), _anthropic("end_turn", found=None), "failed",
+ "could not be read", []),
])
async def test_only_a_response_that_completed_completes_the_call(tmp_path, case, executor, chunks, status, error, sources):
"""MH-HOSTED-GATEWAY-005: completion is an allow-list on both protocols; anything unreadable fails cleanly."""
@@ -693,8 +794,13 @@ async def test_items_only_the_terminal_response_carries_are_kept(tmp_path):
@pytest.mark.asyncio
-async def test_a_call_cancelled_before_its_handle_is_still_metered(tmp_path):
- """MH-HOSTED-GATEWAY-005: wire facts observed after admission are billed, so they reach the usage ledger."""
[email protected]("ended_by", ["caller", "deadline"])
+async def test_a_call_cancelled_before_its_handle_is_still_metered(tmp_path, monkeypatch, ended_by):
+ """MH-HOSTED-GATEWAY-005: wire facts observed after admission are billed, so they reach the usage ledger.
+
+ The engine reports a cancellation after admission with its own error type;
+ when the call's deadline caused it, the call is a timed-out record.
+ """
service = _vibey_service(tmp_path, _sources())
_bind(service, "web_search", (XAI, "grok-4.6"))
@@ -703,21 +809,33 @@ async def test_a_call_cancelled_before_its_handle_is_still_metered(tmp_path):
async def cancelled_after_admission(source_id, model_id, request, stream, origin, *, on_admitted=None):
on_admitted()
+ if ended_by == "deadline":
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ raise InvokeCancelledError(observed) from None
raise InvokeCancelledError(observed)
+ if ended_by == "deadline":
+ monkeypatch.setattr(service_module, "call_timeout", lambda _tool: 0.05)
service.adapter.invoke = cancelled_after_admission
gateway = ModelHubTurnGateway(service)
router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
try:
hop = await router.resolve_hop("menu-alias", process_scope="vibey:cancel", turn_id="turn-cancel")
- with pytest.raises(asyncio.CancelledError):
- await service.run_hosted_tool(
- "web_search",
- {"arguments": {"query": "q"}, "executor": {"source_id": XAI, "model_id": "grok-4.6"}},
- bindings=gateway.correlation.hosted_executor_bindings(
- backend="vibey", token=hop["token"], request_metadata={"avibe_turn_id": "turn-cancel"},
- )[1],
- )
+ call = service.run_hosted_tool(
+ "web_search",
+ {"arguments": {"query": "q"}, "executor": {"source_id": XAI, "model_id": "grok-4.6"}},
+ bindings=gateway.correlation.hosted_executor_bindings(
+ backend="vibey", token=hop["token"], request_metadata={"avibe_turn_id": "turn-cancel"},
+ )[1],
+ )
+ if ended_by == "caller":
+ with pytest.raises(asyncio.CancelledError):
+ await call
+ else:
+ answer = await call
+ assert answer["record"]["status"] == "failed" and "timed out" in answer["record"]["error"]
finally:
await gateway.close()
assert _usage_of(service, XAI)
@@ -745,14 +863,33 @@ async def test_an_encoded_proxy_call_body_is_refused(tmp_path):
assert service.adapter.invocations == []
+class _CountedHandle(LiveInvokeHandle):
+ """A response whose chunks record when they are read."""
+
+ def __init__(self, outcome, chunks):
+ self.read: list[bytes] = []
+ super().__init__(outcome, chunks)
+
+ def _iterate(self, chunks):
+ async def iterate():
+ for chunk in chunks:
+ self.read.append(chunk)
+ yield chunk
+ return iterate()
+
+
@pytest.mark.asyncio
async def test_a_buffered_executor_response_is_bounded(tmp_path, monkeypatch):
- """MH-HOSTED-GATEWAY-005: an oversized buffered body fails the call instead of growing without bound."""
+ """MH-HOSTED-GATEWAY-005: an oversized buffered body fails the call instead of growing without bound.
+
+ Once refused, the response is not read any further, and the call is still metered from its outcome.
+ """
monkeypatch.setattr(service_module, "EXECUTOR_RESPONSE_MAX_BYTES", 64)
- service = _vibey_service(tmp_path, _sources(), handles=[
- LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=ANTHROPIC), (b"{" + b" " * 128 + b"}",)),
- ])
+ oversized = b"{" + b" " * 128
+ usage = ProtocolUsageReport.of(input_tokens=900, cached_input_tokens=0, output_tokens=40)
+ handle = _CountedHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=ANTHROPIC, usage=usage), (oversized, b"}"))
+ service = _vibey_service(tmp_path, _sources(), handles=[handle])
_bind(service, "web_search", (ANTHROPIC, "claude-haiku-4-5"))
status, answer = await _call(service, "web_search", {
"arguments": {"query": "q"}, "executor": {"source_id": ANTHROPIC, "model_id": "claude-haiku-4-5"},
@@ -760,6 +897,8 @@ async def test_a_buffered_executor_response_is_bounded(tmp_path, monkeypatch):
assert status == 200
assert answer["record"]["status"] == "failed" and "larger than allowed" in answer["record"]["error"]
assert "execution" in answer
+ assert handle.read == [oversized]
+ assert _usage_of(service, ANTHROPIC)
@pytest.mark.asyncio