Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
25 changes: 25 additions & 0 deletions github-copilot/copilot/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,29 @@

_COPILOT_HOST = "githubcopilot.com" # api.githubcopilot.com plus the api.<plan>.githubcopilot.com variants


def _is_connection_bound_replay_error(status_code: int | None, message: str) -> bool:
return status_code == 401 and "input item does not belong to this connection" in (message or "").lower()


def _classify_responses_error(error, *, status_code, error_code, message, body, model):
# The classifier's combined message can also contain unrelated body fields. When a
# structured body exists, inspect only its actual message, not a code or metadata.
if isinstance(body, dict) and body:
nested = body.get("error")
detail = nested.get("message") if isinstance(nested, dict) else body.get("message")
else:
detail = getattr(error, "message", "")
if isinstance(detail, str) and _is_connection_bound_replay_error(status_code, detail):
return {"reason": "invalid_encrypted_content", "retryable": False,
"should_rotate_credential": False, "should_fallback": False}
return None


# Constructor kwargs for the profile's L3 fields. ``github_responses`` is persisted on encrypted reasoning
# items in session history: renaming it orphans every stored blob (one cold cache + dropped reasoning on resume).
RESPONSES_PROFILE_FIELDS: dict[str, Any] = {
"classify_api_error": _classify_responses_error,
# The backend binds replayed item ids to a connection; a stale id 401s even when short (#32716).
"responses_replay_item_ids": False,
"responses_prompt_cache_key": False,
Expand All @@ -37,6 +57,11 @@ def _is_copilot_host(base_url: str) -> bool:
class CopilotResponsesMixin:
"""Endpoint ownership, catalog-clamped reasoning payloads and the ``/chat/completions`` carriers."""

def is_stale_credential_error(self, *, status_code: int | None, message: str) -> bool:
if _is_connection_bound_replay_error(status_code, message):
return False
return super().is_stale_credential_error(status_code=status_code, message=message)

def reasoning_payload(self, model: str | None, reasoning_config: dict | None, *, base_url: str) -> dict | None:
from .catalog import clamp_github_reasoning_effort, github_model_reasoning_efforts

Expand Down
104 changes: 104 additions & 0 deletions github-copilot/tests/test_copilot_replay_classification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Copilot connection-bound Responses items are not expired credentials."""

import httpx
import openai
import pytest

from agent.error_classifier import FailoverReason, classify_api_error
from providers import get_provider_profile


REPLAY_MESSAGE = "Input item does not belong to this connection"


def api_error(status, message):
body = {"error": {"message": message}} if message is not None else {"error": {}}
response = httpx.Response(status, json=body, request=httpx.Request("POST", "https://api.githubcopilot.com/responses"))
return openai.APIStatusError(f"Error code: {status} - {body}", response=response, body=body)


def test_connection_bound_replay_401_is_not_auth_or_failover():
verdict = classify_api_error(api_error(401, REPLAY_MESSAGE), provider="copilot", model="test-model")
assert verdict.reason is FailoverReason.invalid_encrypted_content
assert verdict.retryable is False
assert verdict.should_rotate_credential is False
assert verdict.should_fallback is False


@pytest.mark.parametrize("status,message", [
(401, "The access token has expired"),
(401, "Input item belongs to another connection"),
(401, None),
(400, REPLAY_MESSAGE),
(403, REPLAY_MESSAGE),
(500, REPLAY_MESSAGE),
])
def test_nonmatching_errors_are_not_classified_as_invalid_encrypted_content(status, message):
profile = get_provider_profile("copilot")
assert profile.classify_api_error(
api_error(status, message), status_code=status, error_code="", message=(message or "").lower(),
body={}, model="test-model",
) is None


def test_real_token_expiry_remains_auth():
verdict = classify_api_error(api_error(401, "The access token has expired"), provider="copilot")
assert verdict.reason is FailoverReason.auth
assert verdict.should_rotate_credential is True


def test_replay_401_never_triggers_broad_stale_credential_predicate():
profile = get_provider_profile("copilot")
message = f"Error code: 400 model_not_available_for_integrator; {REPLAY_MESSAGE}"
assert profile.is_stale_credential_error(status_code=401, message=message) is False


def test_genuine_stale_integrator_error_still_triggers_reexchange():
profile = get_provider_profile("copilot")
assert profile.is_stale_credential_error(status_code=400, message="model_not_available_for_integrator") is True


@pytest.mark.parametrize("status,message", [
(401, "The access token has expired"),
(401, "Input item belongs to another connection"),
(401, None),
(400, REPLAY_MESSAGE),
(403, REPLAY_MESSAGE),
(500, REPLAY_MESSAGE),
])
def test_nonmatching_errors_remain_on_generic_classifier(status, message):
verdict = classify_api_error(api_error(status, message), provider="copilot")
assert verdict.reason is not FailoverReason.invalid_encrypted_content


def test_malformed_body_does_not_match():
response = httpx.Response(401, text="{not-json", request=httpx.Request("POST", "https://api.githubcopilot.com/responses"))
error = openai.APIStatusError("Error code: 401", response=response, body="{not-json")
verdict = classify_api_error(error, provider="copilot")
assert verdict.reason is FailoverReason.auth


def test_phrase_in_non_message_field_does_not_match():
body = {"error": {"code": REPLAY_MESSAGE, "message": "Token expired"}}
response = httpx.Response(401, json=body, request=httpx.Request("POST", "https://api.githubcopilot.com/responses"))
error = openai.APIStatusError(f"Error code: 401 - {body}", response=response, body=body)
assert classify_api_error(error, provider="copilot").reason is FailoverReason.auth


def test_replay_classification_is_scoped_to_copilot_provider():
verdict = classify_api_error(api_error(401, REPLAY_MESSAGE), provider="openai")
assert verdict.reason is FailoverReason.auth


@pytest.mark.parametrize("base_url,expected", [
("https://api.githubcopilot.com", "copilot"),
("https://api.business.githubcopilot.com", "copilot"),
("https://relay.example.test", None),
("https://api.githubcopilot.com.example.test", None),
])
def test_custom_route_refresh_profile_respects_host(base_url, expected):
from types import SimpleNamespace
from agent.conversation_loop import _credential_refresh_profile

profile = _credential_refresh_profile(SimpleNamespace(provider="custom", base_url=base_url))
assert getattr(profile, "name", None) == expected
Loading