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): write only current refusals, validate evidence on load, close config edges (#2642)

Call Whited85c8658a76f
diff --git a/config/v2_config.py b/config/v2_config.py
index 1d4b48170..aef9f846c 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -3074,9 +3074,17 @@ def is_model_hub_model_id(value: object) -> bool:
def model_hub_executor_order(value: object, *, tool: str) -> tuple[str, ...]:
- """A saved executor order: distinct Source ids. The one grammar the config loader and the API share."""
+ """A saved executor order: one or more distinct Source ids (automatic is its absence, never an empty list).
- if not isinstance(value, list) or not all(is_model_hub_source_id(item) for item in value) or len(set(value)) != len(value):
+ The one grammar the config loader and the API share.
+ """
+
+ if (
+ not isinstance(value, list)
+ or not value
+ or not all(is_model_hub_source_id(item) for item in value)
+ or len(set(value)) != len(value)
+ ):
raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.executor_order' must be distinct Source ids")
return tuple(value)
@@ -3129,13 +3137,16 @@ class ModelHubHostedToolConfig:
enabled = payload.get("enabled", True)
if not isinstance(enabled, bool):
raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.enabled' must be a boolean")
- # Only the fields this tool knows are read; another tool's field was ignored above.
- order = payload.get("executor_order") if "executor_order" in known else None
- default = payload.get("default_model") if "default_model" in known else None
+ # Only the fields this tool knows are read; another tool's field was ignored above. A field is decided by its
+ # presence: the writer omits an unset one, so a present null is damage and goes through the grammar.
+ has_order = "executor_order" in known and "executor_order" in payload
+ has_default = "default_model" in known and "default_model" in payload
return cls(
enabled=enabled,
- executor_order=model_hub_executor_order(order, tool=tool) if order is not None else None,
- default_image=ModelHubImageModelChoice.from_payload(default, tool=tool) if default is not None else None,
+ executor_order=model_hub_executor_order(payload["executor_order"], tool=tool) if has_order else None,
+ default_image=(
+ ModelHubImageModelChoice.from_payload(payload["default_model"], tool=tool) if has_default else None
+ ),
)
def to_payload(self) -> dict:
diff --git a/core/handlers/model_hub/capability_evidence.py b/core/handlers/model_hub/capability_evidence.py
index 0a655c827..c2bbad35b 100644
--- a/core/handlers/model_hub/capability_evidence.py
+++ b/core/handlers/model_hub/capability_evidence.py
@@ -28,7 +28,7 @@ from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Callable, Iterable, Literal, Mapping, Optional
-from config.v2_config import ModelHubSourceConfig
+from config.v2_config import ModelHubSourceConfig, is_model_hub_model_id, is_model_hub_source_id
from .retry import source_identity
from .state_file import write_state_document
@@ -54,6 +54,15 @@ HOSTED_TOOL_ASPECTS: Mapping[str, tuple[str, ...]] = {
}
EXECUTION_MODES: frozenset[str] = frozenset({"native", "executor", "direct"})
_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
+_DIGEST_RE = re.compile(r"sha256:[0-9a-f]{64}")
+
+
+def _encodable(text: str) -> bool:
+ try:
+ text.encode("utf-8")
+ except UnicodeEncodeError:
+ return False
+ return True
@dataclass(frozen=True)
@@ -119,15 +128,16 @@ class EvidenceRecord:
"""``verified`` only: how the call ran."""
def __post_init__(self) -> None:
- for name in ("source_id", "model_id", "wire", "source_identity"):
- value = getattr(self, name)
- if not isinstance(value, str) or not value:
- raise ValueError(f"evidence {name} must be a non-empty string")
+ # The shared identifier rules, so a damaged state file's record is unknown, never echoed by a read.
+ if not is_model_hub_source_id(self.source_id) or not is_model_hub_model_id(self.model_id):
+ raise ValueError("evidence names a Source id and a canonical model id")
+ if not all(isinstance(value, str) and _DIGEST_RE.fullmatch(value) for value in (self.wire, self.source_identity)):
+ raise ValueError("evidence wire and source identity are sha256 digests")
if self.status == "unsupported":
if self.mode is not None or not isinstance(self.detail, str):
raise ValueError("a refusal carries its detail and no mode")
- if not 0 < len(self.detail) <= DETAIL_MAX_CHARS:
- raise ValueError(f"evidence detail is at most {DETAIL_MAX_CHARS} characters")
+ if not 0 < len(self.detail) <= DETAIL_MAX_CHARS or not _encodable(self.detail):
+ raise ValueError(f"evidence detail is encodable text of at most {DETAIL_MAX_CHARS} characters")
elif self.status == "verified":
if self.detail is not None or self.mode not in EXECUTION_MODES:
raise ValueError("a success carries its mode and no detail")
@@ -339,36 +349,71 @@ class CapabilityEvidenceStore:
self._persisted = {item.key: item for item in kept if item.status == "verified"}
@staticmethod
- def _supersedes(record: EvidenceRecord, existing: Optional[EvidenceRecord]) -> bool:
- """The one ordering rule every write follows: per key, the newest record of the current wire wins.
+ def _supersedes(record: EvidenceRecord, existing: Optional[EvidenceRecord], current: Mapping[str, str]) -> bool:
+ """The one ordering rule every write follows: per key, the newest current record wins.
- Writes settle concurrently, so arrival order is not time order. A record replaces one of another identity
- (or, for a refusal, another wire) at once; within the same one, only a newer record replaces it.
+ Writes settle concurrently, so arrival order is not time order. ``record`` is always current: the writers
+ drop one of a superseded identity or wire before they get here. It replaces a stored record that is no
+ longer current at once (another identity, or for a refusal another wire, the one ``record`` proves
+ current), and a current one only if it is newer.
"""
- if existing is None or existing.source_identity != record.source_identity:
- return True
- if record.status == "unsupported" and existing.wire != record.wire:
- return True
- return record.observed_at > existing.observed_at
+ return (
+ existing is None
+ or current.get(existing.source_id) != existing.source_identity
+ or (record.status == "unsupported" and existing.wire != record.wire)
+ or record.observed_at > existing.observed_at
+ )
+
+ @staticmethod
+ def _live_locked(
+ live: Callable[[], Iterable[ModelHubSourceConfig]],
+ ) -> tuple[dict[str, ModelHubSourceConfig], dict[str, str]]:
+ """The Sources as they are now, read under the store lock so no write prunes against an older snapshot."""
- def write_refusal(self, record: EvidenceRecord, *, live: Iterable[ModelHubSourceConfig]) -> None:
+ sources = {source.id: source for source in live()}
+ return sources, {source_id: identity_digest(source) for source_id, source in sources.items()}
+
+ def write_refusal(
+ self,
+ record: EvidenceRecord,
+ *,
+ live: Callable[[], Iterable[ModelHubSourceConfig]],
+ wire_for: Callable[[ModelHubSourceConfig, str], str],
+ ) -> None:
"""Record a refusal: memory first, then the file; a failed write is logged, not raised."""
- self.write_refusals([record], live=live)
+ self.write_refusals([record], live=live, wire_for=wire_for)
+
+ def write_refusals(
+ self,
+ records: Iterable[EvidenceRecord],
+ *,
+ live: Callable[[], Iterable[ModelHubSourceConfig]],
+ wire_for: Callable[[ModelHubSourceConfig, str], str],
+ ) -> None:
+ """Record refusals learned on requests that may have been admitted before a Source or model changed.
+
+ Only a refusal of the Source as it is now, under the wire it renders now, is written: one learned under a
+ superseded identity or wire describes nothing that routes, and must not replace a current one.
+ """
- def write_refusals(self, records: Iterable[EvidenceRecord], *, live: Iterable[ModelHubSourceConfig]) -> None:
records = list(records)
- identities = {source.id: identity_digest(source) for source in live}
- for record in records:
- if record.status != "unsupported":
- raise ValueError("write_refusals writes refusals only")
- if identities.get(record.source_id) != record.source_identity:
- raise ValueError("evidence must be written for a live Source's current identity")
+ if any(record.status != "unsupported" for record in records):
+ raise ValueError("write_refusals writes refusals only")
with self._lock:
+ sources, identities = self._live_locked(live)
updated = dict(self._records)
for record in records:
- if self._supersedes(record, updated.get(record.key)):
+ source = sources.get(record.source_id)
+ if (
+ source is None
+ or identities[record.source_id] != record.source_identity
+ or wire_for(source, record.model_id) != record.wire
+ ):
+ logger.info("Model Hub dropped a refusal learned under a superseded Source identity or wire")
+ continue
+ if self._supersedes(record, updated.get(record.key), identities):
updated[record.key] = record
kept = self._write_locked(updated, identities)
self._remember({item.key: item for item in kept})
@@ -382,7 +427,7 @@ class CapabilityEvidenceStore:
self,
record: EvidenceRecord,
*,
- live: Iterable[ModelHubSourceConfig],
+ live: Callable[[], Iterable[ModelHubSourceConfig]],
now: datetime,
) -> None:
"""Record a real success: memory at once, the file at most hourly per key.
@@ -393,11 +438,11 @@ class CapabilityEvidenceStore:
if record.status != "verified":
raise ValueError("note_success writes successes only")
- identities = {source.id: identity_digest(source) for source in live}
- if identities.get(record.source_id) != record.source_identity:
- return
with self._lock:
- if not self._supersedes(record, self._records.get(record.key)):
+ _sources, identities = self._live_locked(live)
+ if identities.get(record.source_id) != record.source_identity or not self._supersedes(
+ record, self._records.get(record.key), identities
+ ):
return
updated = dict(self._records)
updated[record.key] = record
@@ -421,15 +466,15 @@ class CapabilityEvidenceStore:
self,
matches: Callable[[EvidenceRecord], bool],
*,
- live: Iterable[ModelHubSourceConfig],
+ live: Callable[[], Iterable[ModelHubSourceConfig]],
) -> int:
"""Remove the refusals ``matches`` selects: the file first, then memory; a failed write raises.
Returns how many were removed; zero writes nothing.
"""
- identities = {source.id: identity_digest(source) for source in live}
with self._lock:
+ _sources, identities = self._live_locked(live)
removed = [
key for key, record in self._records.items() if record.status == "unsupported" and matches(record)
]
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 6b8813736..7d7d046f2 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -6059,7 +6059,8 @@ class ModelHubService:
usage=ProtocolUsageReport.of(input_tokens=0, cached_input_tokens=0, output_tokens=spec.tokens_per_image),
counts={},
)
- if cost is None or cost.usd is None:
+ if cost is None or not cost.usd:
+ # An estimate of zero means the model's rate is unknown, never that an image is free.
return None
return {"usd": cost.usd, "basis": "estimated"}
@@ -6120,7 +6121,7 @@ class ModelHubService:
"""Clear under the Source mutation lock, so the identities it keeps are the ones the config holds."""
try:
- await asyncio.to_thread(self.capability_evidence.clear, matches, live=config.sources)
+ await asyncio.to_thread(self.capability_evidence.clear, matches, live=lambda: config.sources)
except OSError:
logger.warning("Model Hub could not persist an evidence clear; nothing changed", exc_info=True)
raise ModelHubError("state_write_failed", status=500) from None
@@ -6149,7 +6150,12 @@ class ModelHubService:
for model_id, feature, detail in refusals
]
if records:
- await asyncio.to_thread(self.capability_evidence.write_refusals, records, live=self.store.load().sources)
+ await asyncio.to_thread(
+ self.capability_evidence.write_refusals,
+ records,
+ live=lambda: self.store.load().sources,
+ wire_for=evidence.wire_for,
+ )
async def record_hosted_success(
self, source: ModelHubSourceConfig, model_id: str, tool: str, mode: str,
@@ -6167,7 +6173,7 @@ class ModelHubService:
mode=mode, # type: ignore[arg-type]
)
await asyncio.to_thread(
- self.capability_evidence.note_success, record, live=self.store.load().sources, now=record.observed_at,
+ self.capability_evidence.note_success, record, live=lambda: self.store.load().sources, now=record.observed_at,
)
def _effort_refused(self, source: ModelHubSourceConfig, model_id: str, request: Any) -> bool:
@@ -6261,25 +6267,24 @@ class ModelHubService:
)
if learned is None:
return None
- try:
- # Routing state: memory takes it before the re-render that follows, even if the file write fails.
- await asyncio.to_thread(
- self.capability_evidence.write_refusal,
- EvidenceRecord(
- source_id=source.id,
- model_id=model_id,
- feature=learned.feature,
- status="unsupported",
- observed_at=self.now(),
- wire=self.hosted_evidence().wire_for(source, model_id),
- source_identity=identity_digest(source),
- detail=learned.detail,
- ),
- live=self.store.load().sources,
- )
- except ValueError:
- # The Source changed identity while the request ran: the refusal describes nothing that exists now.
- logger.info("Model Hub dropped capability evidence for a Source that changed identity")
+ evidence = self.hosted_evidence()
+ # Routing state: memory takes it before the re-render that follows, even if the file write fails. The store
+ # drops it if the Source or the model's rendering changed while the request ran.
+ await asyncio.to_thread(
+ self.capability_evidence.write_refusal,
+ EvidenceRecord(
+ source_id=source.id,
+ model_id=model_id,
+ feature=learned.feature,
+ status="unsupported",
+ observed_at=self.now(),
+ wire=evidence.wire_for(source, model_id),
+ source_identity=identity_digest(source),
+ detail=learned.detail,
+ ),
+ live=lambda: self.store.load().sources,
+ wire_for=evidence.wire_for,
+ )
return learned
def _admits_hosted(self, content: HostedContent, source: ModelHubSourceConfig, model_id: str) -> bool:
diff --git a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
index b427d9f34..c326a9bc2 100644
--- a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
+++ b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
@@ -23,7 +23,7 @@
"Moment": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$" },
"Status": {
"type": "object",
- "description": "Passive evidence for the tool. latest_ok is the latest real success (an in-memory projection, current even while file writes are throttled); refused lists the current refusals; verified lists the persisted successes, one per (Source, model), from which Source chips derive.",
+ "description": "Passive evidence for the tool, read from memory, the one evidence history (the file catches up at most hourly per success). latest_ok is the newest success whose Source still has the identity it ran under; refused lists the current refusals; verified lists the successes, one per (Source, model), from which Source chips derive.",
"required": ["latest_ok", "refused", "verified"],
"additionalProperties": false,
"properties": {
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 5e7feb7f4..8a3593ce4 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -226,8 +226,8 @@ The evidence store, its record and its owner are the capability model's §3. v2
- `status: {latest_ok, refused[]}` (§8.1): `latest_ok` is `{source_id, model_id, mode: "native" | "executor" |
"direct", at}` or null (`direct` for an image call), the latest positive record; `refused[]` is `[{source_id, model_id, aspect, at, reason}]`, the
current negative records, with `aspect` `call` or `replay` and `reason` the record's detail (HTTP status and
- upstream machine code, never provider prose); `verified[]` is `[{source_id, model_id, mode, at}]`, the persisted
- positive records, one per pair, from which the Source chips derive (hosted evidence lives on this read, which
+ upstream machine code, never provider prose); `verified[]` is `[{source_id, model_id, mode, at}]`, the positive
+ records in memory (current, not as of the last hourly file write), one per pair, from which the Source chips derive (hosted evidence lives on this read, which
the clears answer; the Source read keeps effort evidence);
- `latest_ok` is the newest identity-valid success in memory (§3.2), not the newest file record;
- search tools: `executor_order` (saved, null when automatic), `effective_order` (as the gateway would try now),
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index a1f2f5d72..944bc7222 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -198,6 +198,9 @@ scenarios:
- tests/test_model_hub_capability_evidence.py::test_successes_reach_memory_at_once_and_the_file_at_most_hourly
- tests/test_model_hub_capability_evidence.py::test_the_newest_success_is_kept_whatever_order_settlements_land_in
- tests/test_model_hub_capability_evidence.py::test_the_newest_refusal_is_kept_whatever_order_settlements_land_in
+ - tests/test_model_hub_capability_evidence.py::test_a_refusal_learned_under_a_superseded_wire_never_replaces_the_current_one
+ - tests/test_model_hub_capability_evidence.py::test_a_current_refusal_replaces_one_from_an_older_engine_whatever_its_time
+ - tests/test_model_hub_capability_evidence.py::test_a_write_reads_the_sources_as_they_are_when_it_runs
- tests/test_model_hub_capability_evidence.py::test_a_refusal_holds_in_memory_when_its_write_fails
- tests/test_model_hub_capability_evidence.py::test_a_clear_is_persisted_before_it_takes_effect
- tests/test_model_hub_capability_evidence.py::test_a_changed_source_identity_is_pruned_at_the_next_write
@@ -214,6 +217,7 @@ scenarios:
test: tests/test_model_hub_hosted_tools_config.py::test_the_tools_api_writes_one_field_of_one_tool_at_a_time
related_tests:
- tests/test_model_hub_hosted_tools_config.py::test_an_image_models_card_price_is_only_an_unqualified_list_price
+ - tests/test_model_hub_hosted_tools_config.py::test_an_estimated_image_price_of_zero_is_no_unit_price
- tests/test_model_hub_hosted_tools_resolution.py::test_a_relay_is_any_endpoint_but_the_vendors_own_by_the_engines_endpoint_identity
- tests/test_model_hub_hosted_tools_resolution.py::test_the_tools_read_states_saved_and_effective_values_and_what_real_use_showed
- tests/test_model_hub_hosted_tools_resolution.py::test_a_put_changes_only_the_fields_it_names
diff --git a/tests/test_model_hub_capability_evidence.py b/tests/test_model_hub_capability_evidence.py
index 838e0083a..6fef3b4cb 100644
--- a/tests/test_model_hub_capability_evidence.py
+++ b/tests/test_model_hub_capability_evidence.py
@@ -52,6 +52,12 @@ def _wire(source: ModelHubSourceConfig, *, engine: str = ENGINE, avibe: str = AV
return wire_stamp(engine=engine, avibe=avibe, source=source, model_id="grok-4.6")
+def WIRE_FOR(source: ModelHubSourceConfig, model_id: str) -> str:
+ """The wire this process renders now, as the service's ``HostedEvidence.wire_for`` states it."""
+
+ return wire_stamp(engine=ENGINE, avibe=AVIBE, source=source, model_id=model_id)
+
+
def _refusal(source: ModelHubSourceConfig, feature: EvidenceFeature, **changes) -> EvidenceRecord:
fields = dict(
source_id=source.id,
@@ -123,7 +129,7 @@ def test_a_refusal_holds_until_the_wire_or_the_source_changes(tmp_path, case, cu
source = _source()
store = _store(tmp_path)
for feature in (CALL, ULTRA):
- store.write_refusal(_refusal(source, feature), live=[source])
+ store.write_refusal(_refusal(source, feature), live=lambda: [source], wire_for=WIRE_FOR)
now_source, wire = current(source)
for feature in (CALL, ULTRA):
assert (store.refusal(now_source, "grok-4.6", feature, wire=wire) is not None) is applies
@@ -133,8 +139,8 @@ def test_a_success_never_replaces_a_refusal_and_never_routes(tmp_path):
"""MH-HOSTED-003: a success that settles after a concurrent refusal must not erase it; both are kept."""
source = _source()
store = _store(tmp_path)
- store.write_refusal(_refusal(source, CALL), live=[source])
- store.note_success(_success(source, CALL, observed_at=NOW + timedelta(seconds=1)), live=[source], now=NOW)
+ store.write_refusal(_refusal(source, CALL), live=lambda: [source], wire_for=WIRE_FOR)
+ store.note_success(_success(source, CALL, observed_at=NOW + timedelta(seconds=1)), live=lambda: [source], now=NOW)
assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
assert {record.status for record in store.records()} == {"verified", "unsupported"}
@@ -155,14 +161,14 @@ def test_successes_reach_memory_at_once_and_the_file_at_most_hourly(tmp_path, mo
def seen(store, source):
return store.get(source.id, "grok-4.6", CALL, "verified").observed_at
- store.note_success(_success(source, CALL), live=live, now=NOW)
- store.note_success(_success(other, CALL, observed_at=NOW + timedelta(minutes=5)), live=live, now=NOW + timedelta(minutes=5))
- store.note_success(_success(source, CALL, observed_at=NOW + timedelta(minutes=10)), live=live, now=NOW + timedelta(minutes=10))
+ store.note_success(_success(source, CALL), live=lambda: live, now=NOW)
+ store.note_success(_success(other, CALL, observed_at=NOW + timedelta(minutes=5)), live=lambda: live, now=NOW + timedelta(minutes=5))
+ store.note_success(_success(source, CALL, observed_at=NOW + timedelta(minutes=10)), live=lambda: live, now=NOW + timedelta(minutes=10))
assert len(writes) == 2
assert (seen(store, source), seen(store, other)) == (NOW + timedelta(minutes=10), NOW + timedelta(minutes=5))
assert seen(CapabilityEvidenceStore(path), source) == NOW
- store.note_success(_success(source, CALL, observed_at=NOW + timedelta(hours=2)), live=live, now=NOW + timedelta(hours=2))
+ store.note_success(_success(source, CALL, observed_at=NOW + timedelta(hours=2)), live=lambda: live, now=NOW + timedelta(hours=2))
assert len(writes) == 3
assert seen(CapabilityEvidenceStore(path), source) == NOW + timedelta(hours=2)
@@ -171,7 +177,7 @@ def test_successes_reach_memory_at_once_and_the_file_at_most_hourly(tmp_path, mo
at = NOW + timedelta(hours=2, minutes=1)
store.note_success(
_success(rotated, CALL, observed_at=at, source_identity=identity_digest(rotated), wire=_wire(rotated)),
- live=[rotated, other], now=at,
+ live=lambda: [rotated, other], now=at,
)
assert len(writes) == 4
assert seen(CapabilityEvidenceStore(path), rotated) == at
@@ -183,8 +189,8 @@ def test_the_newest_success_is_kept_whatever_order_settlements_land_in(tmp_path)
source = _source()
store = CapabilityEvidenceStore(path)
later = NOW + timedelta(seconds=2)
- store.note_success(_success(source, CALL, observed_at=later), live=[source], now=later)
- store.note_success(_success(source, CALL), live=[source], now=later)
+ store.note_success(_success(source, CALL, observed_at=later), live=lambda: [source], now=later)
+ store.note_success(_success(source, CALL), live=lambda: [source], now=later)
assert store.get(source.id, "grok-4.6", CALL, "verified").observed_at == later
assert CapabilityEvidenceStore(path).get(source.id, "grok-4.6", CALL, "verified").observed_at == later
@@ -194,14 +200,37 @@ def test_the_newest_refusal_is_kept_whatever_order_settlements_land_in(tmp_path)
source = _source()
store = _store(tmp_path)
later = NOW + timedelta(seconds=2)
- store.write_refusal(_refusal(source, CALL, observed_at=later, detail="400 newer"), live=[source])
- store.write_refusal(_refusal(source, CALL, detail="400 older"), live=[source])
+ store.write_refusal(_refusal(source, CALL, observed_at=later, detail="400 newer"), live=lambda: [source], wire_for=WIRE_FOR)
+ store.write_refusal(_refusal(source, CALL, detail="400 older"), live=lambda: [source], wire_for=WIRE_FOR)
kept = store.refusal(source, "grok-4.6", CALL, wire=_wire(source))
assert (kept.observed_at, kept.detail) == (later, "400 newer")
- # Learned under another engine, the older-in-time record still replaces it: the stored one no longer applies.
- moved = _wire(source, engine="model-hub-engine-v8.0.28-1")
- store.write_refusal(_refusal(source, CALL, wire=moved), live=[source])
- assert store.refusal(source, "grok-4.6", CALL, wire=moved) is not None
+
+
+def test_a_refusal_learned_under_a_superseded_wire_never_replaces_the_current_one(tmp_path):
+ """MH-HOSTED-003: a request admitted before the model's tiers changed settles last; its refusal is dropped, so the
+ refusal learned under the wire rendered now keeps routing."""
+ source = _source()
+ retiered = replace(source, models=[replace(source.models[0], reasoning_efforts=["low"])])
+ store = _store(tmp_path)
+ current = _refusal(retiered, CALL, observed_at=NOW + timedelta(seconds=2), wire=_wire(retiered))
+ store.write_refusal(current, live=lambda: [retiered], wire_for=WIRE_FOR)
+ store.write_refusal(_refusal(source, CALL), live=lambda: [retiered], wire_for=WIRE_FOR)
+ assert store.refusal(retiered, "grok-4.6", CALL, wire=_wire(retiered)) == current
+
+
+def test_a_current_refusal_replaces_one_from_an_older_engine_whatever_its_time(tmp_path):
+ """MH-HOSTED-003: a record the file kept from another engine no longer applies, so a current one replaces it."""
+ path = tmp_path / "model_hub_capability_evidence.json"
+ source = _source()
+ old_engine = "model-hub-engine-v8.0.20-1"
+ stale = _refusal(source, CALL, observed_at=NOW + timedelta(days=1), wire=_wire(source, engine=old_engine))
+ CapabilityEvidenceStore(path).write_refusal(
+ stale, live=lambda: [source],
+ wire_for=lambda source, model_id: wire_stamp(engine=old_engine, avibe=AVIBE, source=source, model_id=model_id),
+ )
+ store = CapabilityEvidenceStore(path)
+ store.write_refusal(_refusal(source, CALL), live=lambda: [source], wire_for=WIRE_FOR)
+ assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)).observed_at == NOW
def test_a_refusal_holds_in_memory_when_its_write_fails(tmp_path, monkeypatch, caplog):
@@ -216,7 +245,7 @@ def test_a_refusal_holds_in_memory_when_its_write_fails(tmp_path, monkeypatch, c
monkeypatch.setattr(capability_evidence, "write_state_document", full_disk)
with caplog.at_level(logging.WARNING):
- store.write_refusal(_refusal(source, CALL), live=[source])
+ store.write_refusal(_refusal(source, CALL), live=lambda: [source], wire_for=WIRE_FOR)
assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
assert "holds until restart" in caplog.text
@@ -229,9 +258,9 @@ def test_a_clear_is_persisted_before_it_takes_effect(tmp_path, monkeypatch):
path = tmp_path / "model_hub_capability_evidence.json"
source = _source()
store = CapabilityEvidenceStore(path)
- store.write_refusal(_refusal(source, CALL), live=[source])
- store.write_refusal(_refusal(source, ULTRA), live=[source])
- store.note_success(_success(source, CALL), live=[source], now=NOW)
+ store.write_refusal(_refusal(source, CALL), live=lambda: [source], wire_for=WIRE_FOR)
+ store.write_refusal(_refusal(source, ULTRA), live=lambda: [source], wire_for=WIRE_FOR)
+ store.note_success(_success(source, CALL), live=lambda: [source], now=NOW)
persist = capability_evidence.write_state_document
def full_disk(*_args):
@@ -239,12 +268,12 @@ def test_a_clear_is_persisted_before_it_takes_effect(tmp_path, monkeypatch):
monkeypatch.setattr(capability_evidence, "write_state_document", full_disk)
with pytest.raises(OSError):
- store.clear(lambda record: record.feature == CALL, live=[source])
+ store.clear(lambda record: record.feature == CALL, live=lambda: [source])
assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
monkeypatch.setattr(capability_evidence, "write_state_document", persist)
- assert store.clear(lambda record: record.feature == CALL, live=[source]) == 1
- assert store.clear(lambda record: record.feature == CALL, live=[source]) == 0
+ assert store.clear(lambda record: record.feature == CALL, live=lambda: [source]) == 1
+ assert store.clear(lambda record: record.feature == CALL, live=lambda: [source]) == 0
reloaded = CapabilityEvidenceStore(path)
assert reloaded.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is None
assert reloaded.refusal(source, "grok-4.6", ULTRA, wire=_wire(source)) is not None
@@ -255,11 +284,11 @@ def test_the_bound_evicts_display_history_before_any_refusal(tmp_path):
"""MH-HOSTED-003: a refusal holds until a clear or a change; the record bound never re-enables a feature."""
source = _source()
store = CapabilityEvidenceStore(tmp_path / "model_hub_capability_evidence.json", max_records=3)
- store.write_refusal(_refusal(source, CALL, observed_at=NOW - timedelta(days=400)), live=[source])
+ store.write_refusal(_refusal(source, CALL, observed_at=NOW - timedelta(days=400)), live=lambda: [source], wire_for=WIRE_FOR)
for index, tool in enumerate(("web_search", "x_search", "image_generate")):
feature = EvidenceFeature.hosted(tool, "call")
- store.note_success(_success(source, feature, observed_at=NOW + timedelta(hours=index)), live=[source], now=NOW)
- store.write_refusal(_refusal(source, ULTRA), live=[source])
+ store.note_success(_success(source, feature, observed_at=NOW + timedelta(hours=index)), live=lambda: [source], now=NOW)
+ store.write_refusal(_refusal(source, ULTRA), live=lambda: [source], wire_for=WIRE_FOR)
assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
assert store.refusal(source, "grok-4.6", ULTRA, wire=_wire(source)) is not None
@@ -287,14 +316,39 @@ def test_a_released_sources_identity_digest_is_unchanged(marker, digest):
def test_a_changed_source_identity_is_pruned_at_the_next_write(tmp_path):
store = _store(tmp_path)
keep, rekeyed = _source("src_keep0001"), _source("src_swap0001")
- store.write_refusal(_refusal(keep, CALL), live=[keep, rekeyed])
- store.write_refusal(_refusal(rekeyed, CALL), live=[keep, rekeyed])
+ store.write_refusal(_refusal(keep, CALL), live=lambda: [keep, rekeyed], wire_for=WIRE_FOR)
+ store.write_refusal(_refusal(rekeyed, CALL), live=lambda: [keep, rekeyed], wire_for=WIRE_FOR)
replaced = replace(rekeyed, credential_ref="cred_rotated")
- store.write_refusal(_refusal(keep, REPLAY), live=[keep, replaced])
+ store.write_refusal(_refusal(keep, REPLAY), live=lambda: [keep, replaced], wire_for=WIRE_FOR)
assert {record.source_id for record in store.records()} == {"src_keep0001"}
- with pytest.raises(ValueError):
- store.write_refusal(_refusal(rekeyed, CALL), live=[keep, replaced])
+ # A refusal learned before the rotation settles after it: it describes nothing that exists now, and is dropped.
+ store.write_refusal(_refusal(rekeyed, CALL), live=lambda: [keep, replaced], wire_for=WIRE_FOR)
+ assert {record.source_id for record in store.records()} == {"src_keep0001"}
+
+
+def test_a_write_reads_the_sources_as_they_are_when_it_runs(tmp_path):
+ """MH-HOSTED-003: a write that waited for the lock prunes against the Sources then, not an older snapshot, so it
+ never removes what a newer Source made valid."""
+ import threading
+
+ store = _store(tmp_path)
+ source, added = _source(), _source("src_added001")
+ sources = [source]
+ with store._lock:
+ # Another write holds the lock: this one waits, then must see the Source that write added.
+ waiting = threading.Thread(
+ target=store.write_refusal, args=(_refusal(source, ULTRA),),
+ kwargs={"live": lambda: list(sources), "wire_for": WIRE_FOR},
+ )
+ waiting.start()
+ waiting.join(0.1)
+ sources.append(added)
+ store.write_refusal(_refusal(added, CALL), live=lambda: list(sources), wire_for=WIRE_FOR)
+ waiting.join(5)
+ assert {(record.source_id, record.feature) for record in store.records()} == {
+ ("src_xai00001", ULTRA), ("src_added001", CALL),
+ }
def test_persisted_records_match_the_schema_and_rc_era_ones_are_pruned(tmp_path):
@@ -302,8 +356,8 @@ def test_persisted_records_match_the_schema_and_rc_era_ones_are_pruned(tmp_path)
path = tmp_path / "model_hub_capability_evidence.json"
store = CapabilityEvidenceStore(path)
source = _source()
- store.write_refusal(_refusal(source, ULTRA), live=[source])
- store.note_success(_success(source, CALL), live=[source], now=NOW)
+ store.write_refusal(_refusal(source, ULTRA), live=lambda: [source], wire_for=WIRE_FOR)
+ store.note_success(_success(source, CALL), live=lambda: [source], now=NOW)
schema = json.loads((CONTRACTS / "capability-evidence.schema.json").read_text())
validator = Draft7Validator(schema, registry=Registry().with_resources([(schema["$id"], Resource.from_contents(schema))]))
written = json.loads(path.read_text())
@@ -317,7 +371,15 @@ def test_persisted_records_match_the_schema_and_rc_era_ones_are_pruned(tmp_path)
"basis": "probe", "observed_at": "2026-10-14T00:00:00Z", "engine": ENGINE, "shape": 1,
"source_identity": identity_digest(source),
}
- path.write_text(json.dumps([*written, rc_era, {**written[0], "status": "maybe"}]))
+ # A damaged file's record is unknown and pruned, never echoed by a read: the shared identifier rules apply on load.
+ damaged = [
+ {**written[0], "model_id": "grok-\ud800"},
+ {**written[0], "model_id": " grok-4.6"},
+ {**written[0], "source_id": "xai"},
+ {**written[0], "wire": "engine-x"},
+ {**next(item for item in written if item["status"] == "unsupported"), "detail": "400 \ud800"},
+ ]
+ path.write_text(json.dumps([*written, rc_era, {**written[0], "status": "maybe"}, *damaged]))
assert len(CapabilityEvidenceStore(path).records()) == 2
assert not validator.is_valid(rc_era)
@@ -352,7 +414,7 @@ def test_lookups_after_construction_never_touch_the_disk(tmp_path, monkeypatch):
"""MH-HOSTED-003: the store reads its file when built at startup; no lookup or write reads it again."""
path = tmp_path / "model_hub_capability_evidence.json"
source = _source()
- CapabilityEvidenceStore(path).write_refusal(_refusal(source, CALL), live=[source])
+ CapabilityEvidenceStore(path).write_refusal(_refusal(source, CALL), live=lambda: [source], wire_for=WIRE_FOR)
store = CapabilityEvidenceStore(path)
assert len(store.records()) == 1
@@ -373,7 +435,7 @@ def test_lookups_after_construction_never_touch_the_disk(tmp_path, monkeypatch):
monkeypatch.setattr(Path, "read_text", read_text)
for _ in range(50):
assert store.refusal(source, "grok-4.6", CALL, wire=_wire(source)) is not None
- store.write_refusal(_refusal(source, REPLAY), live=[source])
+ store.write_refusal(_refusal(source, REPLAY), live=lambda: [source], wire_for=WIRE_FOR)
assert store.refusal(source, "grok-4.6", REPLAY, wire=_wire(source)) is not None
assert touched == []
@@ -387,7 +449,7 @@ def test_a_read_never_waits_for_a_write_on_a_slow_disk(tmp_path, monkeypatch):
path = tmp_path / "model_hub_capability_evidence.json"
source = _source()
store = CapabilityEvidenceStore(path)
- store.write_refusal(_refusal(source, CALL), live=[source])
+ store.write_refusal(_refusal(source, CALL), live=lambda: [source], wire_for=WIRE_FOR)
on_disk = threading.Event()
release = threading.Event()
@@ -399,7 +461,7 @@ def test_a_read_never_waits_for_a_write_on_a_slow_disk(tmp_path, monkeypatch):
persist(target, payload)
monkeypatch.setattr(capability_evidence, "write_state_document", slow_disk)
- writer = threading.Thread(target=store.write_refusal, args=(_refusal(source, REPLAY),), kwargs={"live": [source]})
+ writer = threading.Thread(target=store.write_refusal, args=(_refusal(source, REPLAY),), kwargs={"live": lambda: [source], "wire_for": WIRE_FOR})
writer.start()
try:
assert on_disk.wait(5)
diff --git a/tests/test_model_hub_evidence_rules.py b/tests/test_model_hub_evidence_rules.py
index 2c50038be..378ef3d5d 100644
--- a/tests/test_model_hub_evidence_rules.py
+++ b/tests/test_model_hub_evidence_rules.py
@@ -258,7 +258,8 @@ async def test_a_refused_effort_still_waits_for_a_capable_hop_that_is_cooling_do
source_identity=identity_digest(refusing),
detail="400 invalid_request_error",
),
- live=[refusing, cooling],
+ live=lambda: [refusing, cooling],
+ wire_for=service.hosted_evidence().wire_for,
)
request = ModelHubRequest({"input": "hi", "reasoning": {"effort": "ultra"}}, protocol="openai_responses")
@@ -352,7 +353,8 @@ async def test_a_refusing_runnable_hop_never_makes_recovery_spin(tmp_path):
source_identity=identity_digest(refusing),
detail="400 invalid_request_error",
),
- live=[refusing, cooling],
+ live=lambda: [refusing, cooling],
+ wire_for=service.hosted_evidence().wire_for,
)
passes = 0
resolve = service.resolve
@@ -439,7 +441,8 @@ def test_the_picker_menu_states_which_efforts_routing_refuses_in_menu_values(tmp
source_identity=identity_digest(source),
detail="400 invalid_request_error",
),
- live=live,
+ live=lambda: live,
+ wire_for=service.hosted_evidence().wire_for,
)
agent = service.get_agent_sources("vibey")
diff --git a/tests/test_model_hub_hosted_pinning.py b/tests/test_model_hub_hosted_pinning.py
index 7aa2da3d1..95bef8c99 100644
--- a/tests/test_model_hub_hosted_pinning.py
+++ b/tests/test_model_hub_hosted_pinning.py
@@ -64,7 +64,11 @@ def _refuse(service, source, model_id, tool, aspect, *, engine=None):
),
source_identity=identity_digest(source), detail="400 invalid_request_error",
),
- live=service.store.config.sources,
+ live=lambda: service.store.config.sources,
+ # The wire this refusal was learned under, as the process that learned it rendered it.
+ wire_for=lambda source, model_id: wire_stamp(
+ engine=engine or service.engine_stamp, avibe=service.avibe_release, source=source, model_id=model_id,
+ ),
)
@@ -626,7 +630,8 @@ def test_a_replay_is_admitted_exactly_where_the_hops_facts_assume_it(tmp_path, r
status="unsupported", observed_at=NOW, wire=evidence.wire_for(source, "grok-4.6"),
source_identity=identity_digest(source), detail="400 invalid_request_error",
),
- live=[source],
+ live=lambda: [source],
+ wire_for=evidence.wire_for,
)
content = HostedContent(replays=frozenset({"web_search"}))
assert admits(content, source=source, model_id="grok-4.6", spec_for=hosted_tool_spec, evidence=evidence) is admitted
diff --git a/tests/test_model_hub_hosted_tools_config.py b/tests/test_model_hub_hosted_tools_config.py
index d3a207022..cb7befe15 100644
--- a/tests/test_model_hub_hosted_tools_config.py
+++ b/tests/test_model_hub_hosted_tools_config.py
@@ -103,6 +103,11 @@ DEGRADED = [
# Saved values are never resolved: an order naming a Source that is gone is kept and skipped when read.
("order-source-gone", {"web_search": {"executor_order": ["src_gone0001"]}}, {"web_search": (True, ("src_gone0001",), None)}, False),
("entry-not-an-object", {"x_search": None}, {"x_search": OFF}, True),
+ # The writer omits an unset field, so a present null is damage like any other bad value.
+ ("null-order", {"web_search": {"executor_order": None}}, {"web_search": OFF}, True),
+ ("null-default", {"image_generate": {"default_model": None}}, {"image_generate": OFF}, True),
+ # Automatic is the order's absence; an empty list would read as a saved order that behaves as automatic.
+ ("empty-order", {"web_search": {"executor_order": []}}, {"web_search": OFF}, True),
]
@@ -208,7 +213,8 @@ def _refuse(service, source, model_id, feature):
observed_at=service.now(), wire=evidence.wire_for(source, model_id),
source_identity=identity_digest(source), detail="400 invalid_request_error",
),
- live=[source],
+ live=lambda: [source],
+ wire_for=evidence.wire_for,
)
@@ -333,3 +339,19 @@ def test_an_image_models_card_price_is_only_an_unqualified_list_price(tmp_path,
_validate_status(status)
image = next(tool for tool in status["tools"] if tool["name"] == "image_generate")
assert [model["price"] for model in image["models"]] == [expected]
+
+
[email protected]("valued,expected", [(0.0, None), (0.067, {"usd": 0.067, "basis": "estimated"})])
+def test_an_estimated_image_price_of_zero_is_no_unit_price(tmp_path, monkeypatch, valued, expected):
+ """MH-HOSTED-004: an estimate the pricing owner values at zero means the rate is unknown, never a free image."""
+ from types import SimpleNamespace
+
+ from core.handlers.model_hub import hosted_tools as hosted_tools_module
+ from vibe.backend_model_catalog import ImageModelSpec
+
+ spec = ImageModelSpec("gemini-3-image", "Nano Banana", "images", ("images",), (), tokens_per_image=1290)
+ monkeypatch.setattr(hosted_tools_module, "provider_image_models", lambda vendor: (spec,) if vendor == "xai" else ())
+ service, _store = _api_service(tmp_path)
+ monkeypatch.setattr(service, "hosted_call_cost", lambda *_args, **_kwargs: SimpleNamespace(usd=valued))
+ image = next(tool for tool in service.hosted_tools_status()["hosted_tools"]["tools"] if tool["name"] == "image_generate")
+ assert [model["price"] for model in image["models"]] == [expected]
diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.py
index 0e5c4ec3f..0a7e95750 100644
--- a/tests/test_model_hub_hosted_tools_resolution.py
+++ b/tests/test_model_hub_hosted_tools_resolution.py
@@ -128,7 +128,8 @@ def _evidence(tmp_path, *refused) -> HostedEvidence:
status="unsupported", observed_at=NOW, wire=evidence.wire_for(source, model_id),
source_identity=identity_digest(source), detail="400 invalid_request_error",
),
- live=ALL,
+ live=lambda: ALL,
+ wire_for=evidence.wire_for,
)
return evidence
@@ -222,7 +223,7 @@ def test_the_tools_read_states_saved_and_effective_values_and_what_real_use_show
status="verified", observed_at=NOW, wire=evidence.wire_for(XAI, "grok-fast"),
source_identity=identity_digest(XAI), mode="executor",
),
- live=ALL, now=NOW,
+ live=lambda: ALL, now=NOW,
)
config = _config({"web_search": ModelHubHostedToolConfig(executor_order=("src_oai00001",))})
status = hosted_tools_status(config, evidence=evidence, spec_for=_spec_for, image_price=lambda _source, _spec: None)
@@ -267,7 +268,7 @@ def test_the_latest_success_is_the_newest_in_time_not_in_text(tmp_path):
status="verified", observed_at=at, wire=evidence.wire_for(source, model_id),
source_identity=identity_digest(source), mode="executor",
),
- live=ALL, now=at,
+ live=lambda: ALL, now=at,
)
status = hosted_tools_status(_config(), evidence=evidence, spec_for=_spec_for, image_price=lambda _s, _m: None)
web = next(tool for tool in status["tools"] if tool["name"] == "web_search")
@@ -288,7 +289,7 @@ def test_the_latest_success_is_the_newest_one_whose_source_is_still_the_same(tmp
status="verified", observed_at=at, wire=evidence.wire_for(source, model_id),
source_identity=identity_digest(source), mode="executor",
),
- live=ALL, now=at,
+ live=lambda: ALL, now=at,
)
succeed(XAI, "grok-fast", NOW)
@@ -351,6 +352,7 @@ def test_a_put_changes_only_the_fields_it_names(tool, payload, expected):
# Only the saved choices reset with null; a null switch must not turn a cost-bearing tool back on.
("web_search", {"enabled": None}, "invalid_parameter"),
("web_search", {"executor_order": ["not-a-source"]}, "invalid_parameter"),
+ ("web_search", {"executor_order": []}, "invalid_parameter"),
("image_generate", {"default_model": {"source_id": "openai", "model_id": "gpt-image-2"}}, "invalid_parameter"),
# A padded id would be saved and then never match the catalog id it names.
("image_generate", {"default_model": {"source_id": "src_oai00001", "model_id": " gpt-image-2 "}}, "invalid_parameter"),