Skip to content

The agent that grows with you

fix(connectors): log each connector outcome after the body is checked

Siddharth Balyan626eeec28778
diff --git a/tests/tools/test_connector_wire_identity.py b/tests/tools/test_connector_wire_identity.py
index f09a1b13c5b..2d825409f6b 100644
--- a/tests/tools/test_connector_wire_identity.py
+++ b/tests/tools/test_connector_wire_identity.py
@@ -19,6 +19,8 @@ class _Response:
self.headers = {"x-request-id": request_id}
def json(self):
+ if isinstance(self._body, Exception):
+ raise self._body
return self._body
@@ -172,3 +174,48 @@ def test_operation_logs_open_transitions_and_settle(caplog):
f"connection op {op} settled by all_resolved: gmail=connected",
]
assert json.dumps(operation.snapshot()) # snapshot still serializes
+
+
+def _outcomes(caplog):
+ return [(r.levelno, r.getMessage()) for r in caplog.records if r.name == "tools.managed_gateway_identity"]
+
+
+def test_a_200_whose_body_failed_is_a_warning_with_the_request_id(caplog):
+ """The outcome line follows the checked body: a failed call inside the execute envelope and a body
+ that does not parse are both failures, and both keep the gateway's request id."""
+ from tools.connectors.gateway.errors import ToolGatewayError
+ from tools.connectors.gateway.merge import PlannedCall
+
+ failed_call = {"results": [{"error": {"code": "CONNECTION_REQUIRED", "message": "connect gmail"}}]}
+ transport = _Transport(_Response(200, failed_call, request_id="exec-id"),
+ _Response(200, ValueError("not json"), request_id="junk-id"))
+ client = _client(transport, call=CallRef(tool_call_id="call-3"))
+ plan = PlannedCall(position=0, name="gmail_send_email", connector="gmail", tool="GMAIL_SEND_EMAIL", arguments={})
+ with caplog.at_level(logging.DEBUG, logger="tools.managed_gateway_identity"):
+ assert client.execute([plan])[0]["error"]["code"] == "CONNECTION_REQUIRED"
+ with pytest.raises(ToolGatewayError) as raised:
+ client.schemas(["X"])
+ assert raised.value.request_id == "junk-id" and raised.value.code == "INVALID_RESPONSE"
+ assert _outcomes(caplog) == [
+ (logging.WARNING, "connector connectors.execute 200 CONNECTION_REQUIRED request_id=exec-id dispatch=call-3"),
+ (logging.WARNING, "connector connectors.schemas 200 INVALID_RESPONSE request_id=junk-id dispatch=call-3"),
+ ]
+
+
+def test_portal_tools_304_is_a_success_and_a_bad_body_a_failure(caplog):
+ from tools.connectors.portal.client import NotModified, PortalConnectorClient
+ from tools.connectors.portal.errors import PortalToolsUnavailable
+
+ transport = _Transport(_Response(304, None, request_id="same-id"), _Response(200, [], request_id="bad-id"))
+ client = PortalConnectorClient(transport=transport, endpoint_resolver=lambda: "https://portal.test",
+ header_provider=lambda url: {"Authorization": "Bearer t"})
+ with caplog.at_level(logging.DEBUG, logger="tools.managed_gateway_identity"):
+ assert isinstance(client.tools("gmail", if_none_match="etag-1"), NotModified)
+ with pytest.raises(PortalToolsUnavailable) as raised:
+ client.tools("gmail")
+ assert raised.value.request_id == "bad-id"
+ assert _outcomes(caplog) == [
+ (logging.DEBUG, "connector portal.connectors.tools 304 - request_id=same-id dispatch=-"),
+ (logging.WARNING, "connector portal.connectors.tools 200 INVALID_RESPONSE request_id=bad-id dispatch=-"),
+ ]
+
diff --git a/tools/connectors/gateway/client.py b/tools/connectors/gateway/client.py
index 3f99a19e1c2..17eff69730b 100644
--- a/tools/connectors/gateway/client.py
+++ b/tools/connectors/gateway/client.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import logging
import os
import uuid
+from dataclasses import dataclass
from typing import Any, Callable, Optional, Protocol, Sequence
import requests
@@ -38,6 +39,16 @@ SCHEMAS_TIMEOUT_SECONDS = 10.0
_MAX_RETRIES = 1
+@dataclass(frozen=True)
+class _Reply:
+ """A 2xx answer before its body is checked; the outcome line is written once the body is read."""
+
+ payload: Any
+ status: int
+ request_id: Optional[str]
+ route: str
+
+
class Transport(Protocol):
def request(
@@ -92,21 +103,20 @@ class ConnectorClient:
body = wire.ConnectorSearchRequest(
queries=[wire.ConnectorSearchQuery(**q) for q in queries]
).model_dump(by_alias=True, exclude_none=True)
- payload = self._post(
+ reply = self._post(
wire.CONNECTOR_SEARCH_PATH, body,
timeout=SEARCH_TIMEOUT_SECONDS, retries=0,
)
- parsed = wire.ConnectorSearchResponse.model_validate(payload)
- return parsed.model_dump()
+ return self._checked(wire.ConnectorSearchResponse, reply, "connector search").model_dump()
def schemas(self, tools: Sequence[str]) -> dict[str, Any]:
body = wire.ConnectorSchemasRequest(tools=list(tools)).model_dump(
by_alias=True
)
- payload = self._post(
+ reply = self._post(
wire.CONNECTOR_SCHEMAS_PATH, body, timeout=SCHEMAS_TIMEOUT_SECONDS
)
- return wire.ConnectorSchemasResponse.model_validate(payload).model_dump()
+ return self._checked(wire.ConnectorSchemasResponse, reply, "connector schemas").model_dump()
def connections(
self, connectors: Sequence[str], *, reinitiate: bool = False, alias: Optional[str] = None,
@@ -119,8 +129,8 @@ class ConnectorClient:
connectors=list(connectors), reinitiate=reinitiate, alias=alias, connection_id=connection_id,
return_to=return_to, op=op, initiator=self._initiator,
).model_dump(by_alias=True, exclude_none=True)
- payload = self._post(wire.CONNECTOR_CONNECTIONS_PATH, body, retries=0)
- return wire.ConnectorConnectionsResponse.model_validate(payload).model_dump()
+ reply = self._post(wire.CONNECTOR_CONNECTIONS_PATH, body, retries=0)
+ return self._checked(wire.ConnectorConnectionsResponse, reply, "connector connections").model_dump()
def list_connectors(self, *, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> list[dict[str, Any]]:
"""Every page of the session's toolkit list, each typed whole. ``timeout`` applies per page: the
@@ -132,8 +142,8 @@ class ConnectorClient:
path = f"{wire.CONNECTORS_PATH}?limit=50"
if cursor:
path += f"&cursor={cursor}"
- page = self._parse(wire.ConnectorListResponse, self._request("GET", path, None, timeout=timeout),
- "connector list page")
+ page = self._checked(wire.ConnectorListResponse, self._request("GET", path, None, timeout=timeout),
+ "connector list page")
items.extend(item.model_dump(by_alias=True) for item in page.items)
cursor = page.next_cursor
if not cursor:
@@ -146,12 +156,33 @@ class ConnectorClient:
"""One account's row; ``None`` when the gateway no longer knows it. A 429 raises ``RateLimited``.
``timeout`` is the watcher's remaining deadline, so a stalled read cannot outlive its operation."""
try:
- payload = self._request("GET", f"{wire.CONNECTOR_ACCOUNTS_PATH}/{connection_id}", None, timeout=timeout)
+ reply = self._request("GET", f"{wire.CONNECTOR_ACCOUNTS_PATH}/{connection_id}", None, timeout=timeout)
except GatewayUnavailable as exc:
if exc.code == "connection_not_found":
return None
raise
- return self._parse(wire.ConnectorAccount, payload, "connector account").model_dump(by_alias=True)
+ return self._checked(wire.ConnectorAccount, reply, "connector account").model_dump(by_alias=True)
+
+ def _checked(self, model: Any, reply: _Reply, what: str) -> Any:
+ """Parse a 2xx body and write its outcome line: a body that does not parse is a failure,
+ logged with the gateway's request id like any failed status."""
+ try:
+ parsed = self._parse(model, reply.payload, what)
+ except ToolGatewayError as exc:
+ exc.status, exc.request_id = reply.status, reply.request_id
+ self._log(reply, exc.code)
+ raise
+ if not isinstance(parsed, wire.ConnectorExecuteResponse):
+ self._log(reply)
+ return parsed
+ # The execute envelope answers 200 even when a call failed; each failed call is a failure line.
+ failed = [result.error.code for result in parsed.results if result.error is not None]
+ for code in failed or [None]:
+ self._log(reply, code)
+ return parsed
+
+ def _log(self, reply: _Reply, code: Optional[str] = None) -> None:
+ log_connector_outcome(reply.route, reply.status, code=code, request_id=reply.request_id, call=self._call)
@staticmethod
def _parse(model: Any, payload: Any, what: str) -> Any:
@@ -179,13 +210,13 @@ class ConnectorClient:
).model_dump(by_alias=True, exclude_none=True)
# Keep the key dispatch-local so its retry reuses it without a shared store.
idempotency_key = str(uuid.uuid4())
- payload = self._post(
+ reply = self._post(
wire.CONNECTOR_EXECUTE_PATH,
body,
timeout=EXECUTE_TIMEOUT_SECONDS,
idempotency_key=idempotency_key,
)
- parsed = wire.ConnectorExecuteResponse.model_validate(payload)
+ parsed = self._checked(wire.ConnectorExecuteResponse, reply, "connector execute response")
return [_result_dict(result) for result in parsed.results]
def _post(
@@ -196,7 +227,7 @@ class ConnectorClient:
timeout: float = DEFAULT_TIMEOUT_SECONDS,
idempotency_key: Optional[str] = None,
retries: int = _MAX_RETRIES,
- ) -> Any:
+ ) -> _Reply:
return self._request(
"POST", path, body,
timeout=timeout, idempotency_key=idempotency_key, retries=retries,
@@ -211,7 +242,9 @@ class ConnectorClient:
timeout: float = DEFAULT_TIMEOUT_SECONDS,
idempotency_key: Optional[str] = None,
retries: int = _MAX_RETRIES,
- ) -> Any:
+ ) -> _Reply:
+ """The 2xx reply, unchecked; the caller logs its outcome once the body is read. A failed
+ status is logged and raised here."""
origin = self._endpoint_resolver()
if not origin:
raise GatewayUnavailable(
@@ -237,8 +270,7 @@ class ConnectorClient:
status = int(getattr(response, "status_code", 0))
request_id = response_request_id(response)
if 200 <= status < 300:
- log_connector_outcome(route, status, request_id=request_id, call=self._call)
- return response.json()
+ return _Reply(_safe_json(response), status, request_id, route)
error = parse_gateway_error(status, _safe_json(response), getattr(response, "headers", None))
error.request_id = error.request_id or request_id
diff --git a/tools/connectors/portal/client.py b/tools/connectors/portal/client.py
index 00eba8d68a0..40c159ff77a 100644
--- a/tools/connectors/portal/client.py
+++ b/tools/connectors/portal/client.py
@@ -102,7 +102,7 @@ class PortalConnectorClient:
validate_slug(slug)
headers = {"If-None-Match": if_none_match} if if_none_match else None
try:
- response, status = self._request("GET", f"/api/v1/connectors/{slug}/tools", headers=headers)
+ response, status, route = self._request("GET", f"/api/v1/connectors/{slug}/tools", headers=headers)
except ToolGatewayError as exc:
missing_route = isinstance(exc, GatewayUnavailable) and exc.code != "connector_not_found"
if type(exc) is not ToolGatewayError and not missing_route:
@@ -116,38 +116,38 @@ class PortalConnectorClient:
) from exc
if status == 304:
return NotModified()
- listing = self._parse(ConnectorToolsListing, response, status, PortalToolsUnavailable, "portal tools unavailable")
+ listing = self._parse(ConnectorToolsListing, response, status, route, PortalToolsUnavailable, "portal tools unavailable")
etag = getattr(response, "headers", {}).get("etag")
return listing.model_copy(update={"etag": etag}) if isinstance(etag, str) and etag else listing
def catalog(self) -> ConnectorCatalogResponse:
- response, status = self._request("GET", "/api/v1/connectors/catalog")
- return self._parse(ConnectorCatalogResponse, response, status, PortalConnectorUnavailable, "portal catalog unavailable")
+ response, status, route = self._request("GET", "/api/v1/connectors/catalog")
+ return self._parse(ConnectorCatalogResponse, response, status, route, PortalConnectorUnavailable, "portal catalog unavailable")
def list_accounts(self) -> list[dict[str, Any]]:
- response, status = self._request("GET", "/api/v1/connectors/accounts")
- inventory = self._parse(ConnectorAccountsResponse, response, status, PortalConnectorUnavailable, "portal accounts unavailable")
+ response, status, route = self._request("GET", "/api/v1/connectors/accounts")
+ inventory = self._parse(ConnectorAccountsResponse, response, status, route, PortalConnectorUnavailable, "portal accounts unavailable")
return [account.model_dump(by_alias=True) for account in inventory.accounts]
def rename_account(self, connection_id: str, alias: str) -> dict[str, Any]:
path = f"/api/v1/connectors/accounts/{quote(connection_id, safe='')}"
- response, status = self._request("PATCH", path, {"alias": alias})
- account = self._parse(ConnectorAccount, response, status, PortalConnectorUnavailable, "portal accounts unavailable")
+ response, status, route = self._request("PATCH", path, {"alias": alias})
+ account = self._parse(ConnectorAccount, response, status, route, PortalConnectorUnavailable, "portal accounts unavailable")
return account.model_dump(by_alias=True)
def delete_account(self, connection_id: str) -> dict[str, Any]:
path = f"/api/v1/connectors/accounts/{quote(connection_id, safe='')}"
- response, status = self._request("DELETE", path)
- removed = self._parse(RemovedConnectorAccount, response, status, PortalConnectorUnavailable, "portal accounts unavailable")
+ response, status, route = self._request("DELETE", path)
+ removed = self._parse(RemovedConnectorAccount, response, status, route, PortalConnectorUnavailable, "portal accounts unavailable")
return removed.model_dump(by_alias=True)
def policy(self) -> ConnectorPolicyResponse:
- response, status = self._request("GET", "/api/v1/connectors/policy")
- return self._parse(ConnectorPolicyResponse, response, status, PortalConnectorUnavailable, "portal policy unavailable")
+ response, status, route = self._request("GET", "/api/v1/connectors/policy")
+ return self._parse(ConnectorPolicyResponse, response, status, route, PortalConnectorUnavailable, "portal policy unavailable")
def set_policy(self, body: dict[str, Any]) -> ConnectorPolicyWriteResponse:
- response, status = self._request("PUT", "/api/v1/connectors/policy", body)
- return self._parse(ConnectorPolicyWriteResponse, response, status, PortalConnectorUnavailable, "portal policy unavailable")
+ response, status, route = self._request("PUT", "/api/v1/connectors/policy", body)
+ return self._parse(ConnectorPolicyWriteResponse, response, status, route, PortalConnectorUnavailable, "portal policy unavailable")
def _request(
self,
@@ -156,7 +156,9 @@ class PortalConnectorClient:
body: dict[str, Any] | None = None,
*,
headers: dict[str, str] | None = None,
- ) -> tuple[Any, int]:
+ ) -> tuple[Any, int, str]:
+ """The answer, its status and route key. A failed status is logged and raised here; a 2xx is
+ logged by ``_parse`` once its body is checked."""
url = f"{self.origin()}{path}"
headers = self._authorized_headers(url, headers)
try:
@@ -171,18 +173,23 @@ class PortalConnectorClient:
error.request_id = error.request_id or request_id
log_connector_outcome(_route_key(path), status, code=error.code, request_id=error.request_id)
raise error
- log_connector_outcome(_route_key(path), status, request_id=request_id)
- return response, status
+ if status == 304:
+ log_connector_outcome(_route_key(path), status, request_id=request_id)
+ return response, status, _route_key(path)
@staticmethod
- def _parse(model, response: Any, status: int, error_type, message: str):
+ def _parse(model, response: Any, status: int, route: str, error_type, message: str):
+ request_id = response_request_id(response)
try:
payload = response.json()
if not isinstance(payload, Mapping):
raise ValueError("response must be an object")
- return model.model_validate(payload)
+ parsed = model.model_validate(payload)
except (AttributeError, TypeError, ValueError, ValidationError) as exc:
- raise error_type(message, code="INVALID_RESPONSE", status=status) from exc
+ log_connector_outcome(route, status, code="INVALID_RESPONSE", request_id=request_id)
+ raise error_type(message, code="INVALID_RESPONSE", status=status, request_id=request_id) from exc
+ log_connector_outcome(route, status, request_id=request_id)
+ return parsed
def _route_key(path: str) -> str:
diff --git a/tools/managed_gateway_identity.py b/tools/managed_gateway_identity.py
index 72f30702dfe..160441704aa 100644
--- a/tools/managed_gateway_identity.py
+++ b/tools/managed_gateway_identity.py
@@ -123,9 +123,11 @@ def log_connector_outcome(
route: str, status: Optional[int], *, code: Optional[str] = None, request_id: Optional[str] = None,
call: Optional[CallRef] = None,
) -> None:
- """One line per connector HTTP outcome: failures at WARNING, success and expected misses at DEBUG."""
- failed = status is None or not 200 <= status < 300
- level = logging.WARNING if failed and code not in _EXPECTED_MISSES else logging.DEBUG
+ """One line per connector HTTP outcome: failures at WARNING, success and expected misses at DEBUG.
+
+ The ``code`` makes a line a failure, not the status: a 200 whose body failed carries one, and a
+ 304 that refreshed a cached list does not."""
+ level = logging.WARNING if code is not None and code not in _EXPECTED_MISSES else logging.DEBUG
logger.log(
level, "connector %s %s %s request_id=%s dispatch=%s",
route, status if status is not None else "transport", code or "-", request_id or "-",