Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
373 changes: 337 additions & 36 deletions gateway/app.py

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions gateway/control_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,36 @@ async def resp_is_cancelled(org: str, rid: str) -> bool:
return False


# ── a provider's refusal of a task's connection, seen where its model calls pass ────────────────────────────────────
# The process that saw it may not be the one whose turn loop must stop on it. Keyed by the task alone (every caller knows
# the session id), one item per task, the last refusal written over the one before. An hour is longer than any turn waits
# to read it; the turn takes only a refusal made after it started.
REFUSAL_TTL_S = 3600


def _refusal_id(sid: str) -> str:
return f"refusal::{sid}"


async def refusal_put(sid: str, rec: dict) -> None:
"""Record the task's latest refusal (the model-call door's _note_relay_refusal). Raises on a store error: the caller
counts it."""
cont = await _container()
doc_id = _refusal_id(sid)
await _retryable(lambda: cont.upsert_item({**rec, "id": doc_id, "pk": doc_id, "ts": time.time(), "ttl": REFUSAL_TTL_S}))


async def refusal_get(sid: str) -> dict | None:
"""The task's latest refusal, or None when none was recorded. Raises on a store error."""
cont = await _container()
cex = _exceptions()
try:
doc = await cont.read_item(_refusal_id(sid), partition_key=_refusal_id(sid))
except cex.CosmosResourceNotFoundError:
return None
return {k: doc.get(k) for k in ("at", "kind", "status", "provider", "conn", "model", "said")}


async def try_lock(name: str, ttl_s: int) -> bool:
"""One-shot distributed mutex via atomic create_item: returns True iff WE created the lock doc
(nobody else holds it), False if it already exists (another holder — skip this cycle). Per-item
Expand Down
12 changes: 9 additions & 3 deletions gateway/tests/test_entra_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,15 @@ def test_a_turn_refused_on_an_entra_connection_does_not_speak_of_a_key():
for err in (entra, role):
assert gw._provider_refused(err) # so the turn stops here and does not try another connection
said = gw._refusal_message({"provider": "azure", "auth": "entra"}, err)
assert said == f"Your azure connection was refused: {err}" and " key " not in said
assert gw._refusal_message({"provider": "azure"}, role) == f"Your azure key was refused: {role}"
assert gw._refusal_message({"provider": "openai"}, "") == "Your openai key was refused: the provider returned an error"
assert said == (f"Your Azure OpenAI connection was refused: {gw._as_sentence(err)} "
"Check this connection with Azure OpenAI, or replace or remove it under Bring Your Own Key.")
assert " key " not in said
assert gw._refusal_message({"provider": "azure"}, role) == (
f"Your Azure OpenAI key was refused: {role}. Check this key with Azure OpenAI, or replace or remove it under "
"Bring Your Own Key.")
assert gw._refusal_message({"provider": "openai"}, "") == (
"Your OpenAI key was refused: the provider returned an error. Check this key with OpenAI, or replace or remove it "
"under Bring Your Own Key.")


def test_another_secret_or_scope_is_another_token(monkeypatch):
Expand Down
24 changes: 15 additions & 9 deletions gateway/tests/test_provider_failure_reason.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ def test_a_quota_that_passes_with_a_wait_is_a_rate_limit_and_an_empty_account_is
def test_a_rate_limit_says_the_key_was_not_refused_and_to_wait():
err = "tokenrouter: 429 Too Many Requests"
said = gw._refusal_message(CONN, err)
assert said.startswith("tokenrouter rate-limited this task (too many requests for now; your key was not refused).")
assert "Wait a minute and try again." in said and said.endswith(err)
assert said.startswith("TokenRouter rate-limited this task (too many requests for now; your key was not refused).")
assert "Wait a minute and try again." in said and said.endswith(err + ".")


@pytest.mark.parametrize("err,wait", [
Expand All @@ -88,9 +88,11 @@ def test_the_wait_the_provider_names_is_passed_on(err, wait):

def test_an_empty_account_and_a_refused_model_say_what_to_do():
quota = gw._refusal_message(CONN, "Error code: 429 - {'error': {'code': 'insufficient_quota'}}")
assert quota.startswith("Your tokenrouter account has no quota or credit left for this key; add credit with tokenrouter")
assert quota.startswith("Your TokenRouter account has no quota or credit left for this key: Error code: 429")
assert quota.endswith("Add credit with TokenRouter, or replace or remove this key under Bring Your Own Key.")
model = gw._refusal_message(CONN, "tokenrouter 403: your key is not allowed to use model claude-opus-5")
assert model.startswith("tokenrouter refused this model for your key (the key itself was accepted). Choose another model")
assert model.startswith("TokenRouter refused this model for your key (the key itself was accepted): tokenrouter 403")
assert model.endswith("Choose another model, or enable this one for your account with TokenRouter.")
for said in (quota, model):
assert "was refused:" not in said

Expand All @@ -102,14 +104,16 @@ def test_a_custom_endpoint_is_called_by_the_connections_name():
said = gw._refusal_message(custom, "429: Rate limit reached. Please try again in 2s.")
assert said.startswith("My DeepSeek rate-limited this task (too many requests for now; your key was not refused).")
said = gw._refusal_message(custom, "Error code: 429 - insufficient_quota")
assert said.startswith("Your My DeepSeek account has no quota or credit left for this key; add credit with My DeepSeek")
assert said.startswith("Your My DeepSeek account has no quota or credit left for this key: ")
assert said.endswith("Add credit with My DeepSeek, or replace or remove this key under Bring Your Own Key.")
assert gw._refusal_message({"_vendor": "custom"}, "401 invalid api key").startswith("Your custom endpoint key was refused")
assert gw._refusal_message({**CONN, "name": "integration:My TR"}, "401 invalid api key").startswith("Your tokenrouter key was refused")
assert gw._refusal_message({**CONN, "name": "integration:My TR"}, "401 invalid api key").startswith("Your TokenRouter key was refused")


def test_a_refused_key_reads_as_before_and_an_entra_connection_is_never_a_key():
assert gw._refusal_message(CONN, "OpenAI API error (401): invalid api key") == \
"Your tokenrouter key was refused: OpenAI API error (401): invalid api key"
("Your TokenRouter key was refused: OpenAI API error (401): invalid api key. "
"Check this key with TokenRouter, or replace or remove it under Bring Your Own Key.")
entra = {"provider": "azure", "auth": "entra"}
for err in ("hr API error (401): x", "429 rate limit", "429 insufficient_quota", "403: not allowed to use model gpt-5.4"):
assert "key" not in gw._refusal_message(entra, err).replace(err, "")
Expand Down Expand Up @@ -143,5 +147,7 @@ def test_the_detail_carries_none_of_the_providers_text_and_other_failures_add_no

def test_the_refusal_branch_sets_the_message_and_the_detail_together():
src = (pathlib.Path(__file__).resolve().parents[1] / "app.py").read_text()
i = src.index('rec["error_message"] = _refusal_message(conn, _last_err)')
assert 'rec["provider_failure"] = _provider_failure_detail(_last_err)' in src[i:i + 200]
i = src.index('rec["error_message"] = _refusal_message(conn, _last_err, _kind)')
assert 'rec["provider_failure"] = _provider_failure_detail(_last_err, _kind,' in src[i:i + 200]
# the provider's words reach both without the key
assert '_last_err = _without_key(_last_err, str(conn.get("api_key") or ""))' in src[i - 400:i]
Loading
Loading