From ad572f4aa983fd55569f75c1ba08a39acf9bdfb5 Mon Sep 17 00:00:00 2001 From: Shiivu13 Date: Fri, 20 Nov 2026 08:01:58 +0530 Subject: [PATCH 1/2] Don't report caller errors as invalid API responses operation_errors() turned every exception that wasn't a ProoflineError or httpx.HTTPError into "Proofline returned an invalid API response" and dropped the context. That also caught errors raised while the request was still being built, like an unknown keyword or a dict passed as the body, so a local typo looked like a server problem and the traceback was gone. No request had even been sent. The retry transports now set a RESPONDED context var when a 2xx response comes back. operation_errors() only maps to the static problem after that; before it, the original exception propagates. Decode failures on a body that did arrive still map to invalid-response with the private body kept out of the traceback. --- proofline/_transport.py | 16 ++++++++++++++++ tests/test_http.py | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/proofline/_transport.py b/proofline/_transport.py index 5fa3e393..64a0d068 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -65,6 +65,9 @@ | RunNowRefusalViewType9 ) DEADLINE: ContextVar[float | None] = ContextVar("proofline_request_deadline", default=None) +# Set once a successful response reaches the client, so operation_errors can tell a +# body Proofline returned from an error raised before any request left the process. +RESPONDED: ContextVar[bool] = ContextVar("proofline_response_received", default=False) class BearerAuth(httpx2.Auth): @@ -163,6 +166,13 @@ def network_error(error: httpx2.HTTPError) -> ProoflineError: @contextmanager def operation_errors() -> Iterator[None]: + """Map failures inside one generated operation to ProoflineError. + + Only a response that arrived can be an invalid API response. An error raised + while the request is still being built, such as an unknown keyword or a body + of the wrong type, is the caller's and propagates unchanged. + """ + marker = RESPONDED.set(False) try: yield except ProoflineError: @@ -170,7 +180,11 @@ def operation_errors() -> Iterator[None]: except httpx2.HTTPError as error: raise network_error(error) from None except Exception: + if not RESPONDED.get(): + raise raise invalid_response() from None + finally: + RESPONDED.reset(marker) def timeout_error() -> ProoflineError: @@ -458,6 +472,7 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: raise unreadable_problem(response.status_code) response.stream = DeadlineStream(response.stream, response.status_code, deadline) if 200 <= response.status_code < 300: + RESPONDED.set(True) return response try: response.read() @@ -509,6 +524,7 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response raise unreadable_problem(response.status_code) response.stream = AsyncDeadlineStream(response.stream, response.status_code, deadline) if 200 <= response.status_code < 300: + RESPONDED.set(True) return response try: await response.aread() diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..5cdcfea7 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -774,6 +774,47 @@ async def test_successful_private_body_decoder_failure_is_static(mode: str) -> N assert TOKEN not in "".join(traceback.format_exception(error)) +@MODES +async def test_caller_errors_before_any_request_are_not_reported_as_api_responses( + mode: str, +) -> None: + # Nothing reaches Proofline, so nothing can be an invalid Proofline response: the + # caller's mistake keeps its own type, message and traceback. + with Server(lambda request, index: Reply(body=finding())) as server: + async with session(mode, server.url) as client: + with pytest.raises(TypeError, match="limt"): + await call(client, "list_reviews", ORG, limt=5) + with pytest.raises(AttributeError, match="to_dict"): + await call(client, "request_patch_review", ORG, REPOSITORY, body={"patch": "x"}) + # Methods generated from the contract share the same mapping. + with pytest.raises(AttributeError, match="to_dict"): + await call(client, "request_scan", ORG, REPOSITORY, body={"budget_credits": 1}) + with pytest.raises(TypeError) as raised: + await call(client, "get_finding", ORG) + assert raised.value.__traceback__ is not None + assert not isinstance(raised.value, ProoflineError) + assert server.requests == [] + + +@MODES +async def test_a_body_that_arrives_still_decodes_to_the_static_sdk_problem(mode: str) -> None: + # A caller error earlier on the same client must not change how a later reply maps. + with Server(lambda request, index: Reply(body={"id": PRIVATE})) as server: + async with session(mode, server.url) as client: + with pytest.raises(TypeError): + await call(client, "list_reviews", ORG, limt=5) + scan = models.ScanRequestBody(budget_credits=1, request_id=REVIEW) + for name, args, kwargs in [ + ("get_finding", (ORG, FINDING), {}), + ("request_scan", (ORG, REPOSITORY), {"body": scan}), + ]: + with pytest.raises(ProoflineError) as raised: + await call(client, name, *args, **kwargs) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + assert PRIVATE not in "".join(traceback.format_exception(raised.value)) + assert len(server.requests) == 2 + + @MODES async def test_redirect_never_contacts_other_origin(mode: str) -> None: with Server(lambda request, index: Reply(body=finding())) as other: From 2828130f9296f60f44143c7cdf113ed08a7748e1 Mon Sep 17 00:00:00 2001 From: Shiivu13 Date: Fri, 20 Nov 2026 08:18:12 +0530 Subject: [PATCH 2/2] Keep problems nested past the JSON limit typed Proofline caught this on the first commit: RESPONDED was only set for 2xx, so a 4xx/5xx body nested deeper than json can decode raised RecursionError inside problem(), and operation_errors let it through because the flag was still false. Before that commit the catch-all had turned it into invalid-response. Two changes: - problem() treats RecursionError like any other undecodable body, so the caller gets the real status and "HTTP error without a problem document". This also fixes export_reviews and the MCP calls, which leaked the same RecursionError on main because they don't go through operation_errors at all. - The transports set RESPONDED as soon as any response comes back, not only on 2xx, so anything unexpected while handling a server reply still maps to the SDK problem. --- proofline/_transport.py | 11 ++++++----- tests/test_http.py | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/proofline/_transport.py b/proofline/_transport.py index 64a0d068..71907e39 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -65,8 +65,8 @@ | RunNowRefusalViewType9 ) DEADLINE: ContextVar[float | None] = ContextVar("proofline_request_deadline", default=None) -# Set once a successful response reaches the client, so operation_errors can tell a -# body Proofline returned from an error raised before any request left the process. +# Set once any response reaches the client, so operation_errors can tell a failure +# caused by what Proofline sent from an error raised before a request left the process. RESPONDED: ContextVar[bool] = ContextVar("proofline_response_received", default=False) @@ -293,7 +293,8 @@ def text(value: object) -> bool: def problem(response: httpx2.Response, token: SecretStr) -> ProoflineError: try: body = response.json() - except (ValueError, UnicodeError): + except (ValueError, UnicodeError, RecursionError): + # Nesting deeper than the decoder allows still fits in 8 MiB. body = None if not isinstance(body, dict): return ProoflineError( @@ -461,6 +462,7 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: response = self._inner.handle_request(request) finally: IO_DEADLINE.reset(marker) + RESPONDED.set(True) if 300 <= response.status_code < 400: response.close() raise redirect_error(response.status_code) from None @@ -472,7 +474,6 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: raise unreadable_problem(response.status_code) response.stream = DeadlineStream(response.stream, response.status_code, deadline) if 200 <= response.status_code < 300: - RESPONDED.set(True) return response try: response.read() @@ -513,6 +514,7 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response response = await self._inner.handle_async_request(request) except TimeoutError: raise httpx2.ReadTimeout("The request deadline expired.") from None + RESPONDED.set(True) if 300 <= response.status_code < 400: await response.aclose() raise redirect_error(response.status_code) from None @@ -524,7 +526,6 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response raise unreadable_problem(response.status_code) response.stream = AsyncDeadlineStream(response.stream, response.status_code, deadline) if 200 <= response.status_code < 300: - RESPONDED.set(True) return response try: await response.aread() diff --git a/tests/test_http.py b/tests/test_http.py index 5cdcfea7..07f128bc 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -815,6 +815,33 @@ async def test_a_body_that_arrives_still_decodes_to_the_static_sdk_problem(mode: assert len(server.requests) == 2 +@MODES +@pytest.mark.parametrize("status", [400, 500]) +async def test_problem_nested_past_the_decoder_limit_stays_a_typed_problem( + mode: str, status: int +) -> None: + # Nesting deeper than json allows fits well inside 8 MiB and raises RecursionError. + deep = b"[" * 100_000 + b"]" * 100_000 + with Server(lambda request, index: Reply(status, deep)) as server: + async with session(mode, server.url) as client: + scan = models.ScanRequestBody(budget_credits=1, request_id=REVIEW) + for name, args, kwargs in [ + ("get_finding", (ORG, FINDING), {}), + ("request_scan", (ORG, REPOSITORY), {"body": scan}), + ( + "export_reviews", + (ORG, "reviews"), + {"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-02T00:00:00Z"}, + ), + ]: + with pytest.raises(ProoflineError) as raised: + await call(client, name, *args, **kwargs) + assert raised.value.status == status + assert raised.value.detail == ( + "Proofline returned an HTTP error without a problem document." + ) + + @MODES async def test_redirect_never_contacts_other_origin(mode: str) -> None: with Server(lambda request, index: Reply(body=finding())) as other: