From 13575cc9cf89869cad27389972472b90232a9051 Mon Sep 17 00:00:00 2001 From: lavshashank Date: Sun, 15 Nov 2026 21:53:27 +0530 Subject: [PATCH 1/2] Keep ProoflineError typed across pickle, copy and process pools BaseException rebuilds an exception as type(self)(*self.args). ProoflineError passes only its status message to Exception.__init__, so the rebuild called ProoflineError("Proofline request failed (HTTP n).") and raised TypeError. pickle, copy and deepcopy all failed, and one problem raised in a ProcessPoolExecutor worker broke the whole pool with BrokenProcessPool instead of reaching the caller. __reduce__ now rebuilds the error from status, type and detail and restores title, refusal, repository_name and any notes as state. str and repr are unchanged, and the token, which redaction already removed, is never part of the error. --- README.md | 2 +- proofline/_transport.py | 6 ++++ tests/test_http.py | 77 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1bc220e3..b8eb2b3d 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ When no token is passed, the clients read `PROOFLINE_TOKEN` from the environment ## Errors and refusals -A refused request raises `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repository_name`. `RunNowRefusal` names the type of `refusal`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. The token is redacted from every text field, and `repr` and `str` show only the status. +A refused request raises `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repository_name`. `RunNowRefusal` names the type of `refusal`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. The token is redacted from every text field, and `repr` and `str` show only the status. `ProoflineError` survives `pickle` and `copy` with all of these fields, so an error raised in a `ProcessPoolExecutor` or `multiprocessing` worker reaches the caller typed. ```python from proofline import ProoflineError diff --git a/proofline/_transport.py b/proofline/_transport.py index bd51befd..eb9fca35 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -106,6 +106,12 @@ def __init__( def __repr__(self) -> str: return f"ProoflineError(status={self.status})" + def __reduce__(self) -> tuple[Any, ...]: + # BaseException rebuilds an error as type(self)(*self.args), and args holds + # only the status message. Rebuild from the fields and restore the rest, so + # pickle, copy and process pools keep the typed problem and its refusal. + return type(self), (self.status, self.type, self.detail), self.__dict__.copy() + def token_value(token: str | SecretStr | None) -> SecretStr: secret = ( diff --git a/tests/test_http.py b/tests/test_http.py index f62d93f6..e7476cb4 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1,10 +1,13 @@ from __future__ import annotations import asyncio +import copy import gzip import inspect import json import logging +import multiprocessing +import pickle import socket import subprocess import sys @@ -13,6 +16,7 @@ import tomllib import traceback from collections.abc import AsyncIterator +from concurrent.futures import ProcessPoolExecutor from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from pathlib import Path @@ -606,6 +610,7 @@ async def test_review_requests_return_each_documented_refusal( assert decoded["environment"]["display_name"] == f"{PRIVATE} [redacted]" diagnostic = repr(error) + str(error) + "".join(traceback.format_exception(error)) assert PRIVATE not in diagnostic and TOKEN not in diagnostic + assert_round_trips(error) assert len(server.requests) == len(REVIEW_REQUESTS) @@ -684,6 +689,78 @@ async def test_problem_without_detail_keeps_status_and_title(mode: str) -> None: assert len(server.requests) == 1 +def problem_fields(error: ProoflineError) -> tuple[Any, ...]: + refusal = None if error.refusal is None else error.refusal.to_dict() + return ( + type(error), + error.status, + error.type, + error.detail, + error.title, + refusal, + error.repository_name, + str(error), + repr(error), + ) + + +def assert_round_trips(error: ProoflineError) -> None: + copies = [copy.copy(error), copy.deepcopy(error)] + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + data = pickle.dumps(error, protocol=protocol) + assert TOKEN.encode() not in data + copies.append(pickle.loads(data)) + for restored in copies: + assert restored is not error + assert problem_fields(restored) == problem_fields(error) + + +@pytest.mark.parametrize( + "error", + [ + _transport.invalid_response(), + _transport.timeout_error(), + _transport.redirect_error(307), + ProoflineError(409, "urn:proofline:conflict", "busy", title="Conflict"), + ], + ids=["invalid-response", "timeout", "redirect", "keyword-fields"], +) +def test_sdk_problems_round_trip_through_pickle_and_copy(error: ProoflineError) -> None: + error.add_note("kept with the error state") + assert_round_trips(error) + assert pickle.loads(pickle.dumps(error)).__notes__ == ["kept with the error state"] + + +def finding_in_worker(url: str) -> CustomerFinding: + with ProoflineClient(SecretStr(TOKEN), base_url=url) as client: + return client.get_finding(ORG, FINDING) + + +def test_problem_raised_in_a_worker_process_reaches_the_caller_typed() -> None: + with Server( + lambda request, index: Reply( + 403, + {"type": "urn:proofline:forbidden", "title": "Forbidden", "detail": f"no {TOKEN}"}, + ) + ) as server: + context = multiprocessing.get_context("spawn") + with ProcessPoolExecutor(max_workers=1, mp_context=context) as pool: + with pytest.raises(ProoflineError) as raised: + pool.submit(finding_in_worker, server.url).result(timeout=60) + # The pool survives the refusal and keeps serving later work. + with pytest.raises(ProoflineError) as again: + pool.submit(finding_in_worker, server.url).result(timeout=60) + for error in (raised.value, again.value): + assert (error.status, error.type, error.title) == ( + 403, + "urn:proofline:forbidden", + "Forbidden", + ) + assert error.detail == "no [redacted]" + assert repr(error) == "ProoflineError(status=403)" + assert len(server.requests) == 2 + + @MODES @pytest.mark.parametrize("status", [401, 403, 404]) async def test_authority_problems_do_not_retry_or_disclose_secrets( From be9f11c2e35be88e9dfa963e4ad96df54a75b8c5 Mon Sep 17 00:00:00 2001 From: lavshashank Date: Sun, 15 Nov 2026 22:12:27 +0530 Subject: [PATCH 2/2] Check that worker tracebacks stay free of problem text and the token A process pool chains the worker's formatted traceback to the error the parent receives. Assert it names only the status, like repr and str, and carries neither the private detail nor the token. --- tests/test_http.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/test_http.py b/tests/test_http.py index e7476cb4..204fb992 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -740,7 +740,11 @@ def test_problem_raised_in_a_worker_process_reaches_the_caller_typed() -> None: with Server( lambda request, index: Reply( 403, - {"type": "urn:proofline:forbidden", "title": "Forbidden", "detail": f"no {TOKEN}"}, + { + "type": "urn:proofline:forbidden", + "title": "Forbidden", + "detail": f"{PRIVATE} {TOKEN}", + }, ) ) as server: context = multiprocessing.get_context("spawn") @@ -756,8 +760,13 @@ def test_problem_raised_in_a_worker_process_reaches_the_caller_typed() -> None: "urn:proofline:forbidden", "Forbidden", ) - assert error.detail == "no [redacted]" + assert error.detail == f"{PRIVATE} [redacted]" assert repr(error) == "ProoflineError(status=403)" + # The pool chains the worker's formatted traceback as __cause__; it stays static. + assert error.__cause__ is not None + diagnostic = "".join(traceback.format_exception(error)) + assert "Proofline request failed (HTTP 403)." in diagnostic + assert PRIVATE not in diagnostic and TOKEN not in diagnostic assert len(server.requests) == 2