Skip to content

Keep ProoflineError typed across pickle, copy and process pools - #51

Open
lavshashank wants to merge 2 commits into
prooflinedev:mainfrom
lavshashank:fix/picklable-proofline-error
Open

lavshashank wants to merge 2 commits into
prooflinedev:mainfrom
lavshashank:fix/picklable-proofline-error

Conversation

@lavshashank

Copy link
Copy Markdown

Problem

ProoflineError cannot be pickled or copied:

>>> pickle.loads(pickle.dumps(ProoflineError(403, "urn:x", "detail")))
TypeError: ProoflineError.__init__() missing 2 required positional arguments: 'type' and 'detail'

BaseException rebuilds an exception as type(self)(*self.args). ProoflineError.__init__
passes only its status message to Exception.__init__, so args is
("Proofline request failed (HTTP 403).",), and the rebuild calls the constructor without
type and detail. copy.copy and copy.deepcopy fail the same way.

Motivation

The real-world failure is concurrency. When a ProcessPoolExecutor worker raises a
ProoflineError, the parent cannot unpickle it, and the pool shuts down with
BrokenProcessPool. With 4 jobs on a 2-worker pool, each getting a 403 from the API, all 4
futures fail with BrokenProcessPool. The caller never sees the status, title, detail or
typed refusal, and unrelated pending jobs fail as well. The same applies to
multiprocessing.Pool, loop.run_in_executor with a process pool, and task queues that
serialize results with pickle. These are common ways to fan out review exports or review
requests across repositories.

Implementation

proofline/_transport.py: ProoflineError.__reduce__ returns
(type(self), (self.status, self.type, self.detail), self.__dict__.copy()).
Pickle and copy rebuild the error through its real constructor, then restore title,
refusal, repository_name and any add_note notes as instance state. Nothing under
proofline/_generated/ changes: the attrs refusal models already pickle.

README.md: one sentence under "Errors and refusals" stating the guarantee.

Technical decisions

  • __reduce__ instead of changing args. Passing every field to Exception.__init__
    would change str(error) into a tuple and break the documented rule that repr and
    str show only the status.
  • State is a copy of __dict__. Fields added later and notes are kept without
    maintaining a list of names.
  • Secrets. The pickled bytes contain detail and the refusal, because the caller needs
    them in the parent process. They never contain the token: problem() redacts it before
    the error is built, and every round-trip test asserts the token is absent from the bytes.
  • Diagnostics across processes. A process pool chains the worker's formatted traceback
    as __cause__. The test asserts that the chain names only the status, matching the repo's
    existing diagnostic tests.
  • Out of scope. Subclasses with a different constructor signature. The SDK defines none,
    and supporting them would need a module-level rebuild function for a case that doesn't
    exist.

Testing

tests/test_http.py:

  • test_review_requests_return_each_documented_refusal (existing; 10 refusal reasons ×
    sync/async) now also asserts that every refusal survives copy, deepcopy and pickle
    protocols 0–5. Type, status, type URN, detail, title, refusal.to_dict(),
    repository_name, str and repr must be equal, and the token must be absent from the
    pickled bytes.
  • test_sdk_problems_round_trip_through_pickle_and_copy: errors the SDK creates itself
    (invalid response, timeout, redirect, keyword fields) round-trip, and notes are kept.
  • test_problem_raised_in_a_worker_process_reaches_the_caller_typed (integration): a
    spawn-based ProcessPoolExecutor worker calls the loopback HTTP server and gets a 403.
    The parent receives a typed ProoflineError with the token redacted, its traceback chain
    holds no private text or token, and a second job on the same pool also completes, so the
    pool survives.

Against the original _transport.py, these tests give 25 failed (TypeError, and
BrokenProcessPool for the pool test). With the change they all pass.

Verification

python3 scripts/check.py on Python 3.13.12 (the CI command):

main @ 45b27ba this branch
generation check, contracts passed passed
ruff check / format passed (213 files) passed (213 files)
mypy 207 files, no issues 207 files, no issues
pytest 140 passed 145 passed
wheel and sdist install smoke passed passed

End-to-end reproduction, run from the repository root:

import pickle
from concurrent.futures import ProcessPoolExecutor
from uuid import uuid4
from proofline import ProoflineClient, ProoflineError
from tests.http_server import Reply, Server

def fetch(url):
    with ProoflineClient("demo-token", base_url=url) as client:
        return client.get_finding(uuid4(), uuid4())

if __name__ == "__main__":
    problem = {"type": "urn:proofline:forbidden", "title": "Forbidden", "detail": "Token lacks reviews:read."}
    with Server(lambda request, index: Reply(403, problem)) as server:
        with ProcessPoolExecutor(max_workers=2) as pool:
            for future in [pool.submit(fetch, server.url) for _ in range(4)]:
                try:
                    future.result(timeout=60)
                except ProoflineError as error:
                    print("typed", error.status, error.type, error.detail)
                except Exception as error:
                    print("FAIL", type(error).__name__)
  • main: FAIL BrokenProcessPool × 4
  • this branch: typed 403 urn:proofline:forbidden Token lacks reviews:read. × 4

Proofline review

I installed Proofline on my own account (lavshashank, limited to a fork of this repository)
and reviewed this change as a PR inside the fork
(lavshashank#1).

Run Head Trigger Scope Time / cost Result
1 13575cc manual full, 45b27ba..13575cc 44 s / 60.03 credits no findings
2 be9f11c automatic on push incremental, 13 of 85 lines in 1 file 1 m 19 s / 62.71 credits no findings
3 be9f11c manual rerun full, 45b27ba..be9f11c 46 s / 77.18 credits no findings

The walkthrough described the change correctly in three steps: the rebuild hook, then the
round-trip and pool tests, then the README guarantee. A clean result is not proof, so I
also checked the points below myself:

  • Added after review (run 2): a process pool chains the worker's formatted traceback to
    the parent's error. Proofline did not raise this. I asserted the chain contains only the
    status text, matching this repository's diagnostic tests (commit be9f11c).
  • Kept as is: the pickled bytes include detail. That is the purpose of the change; the
    token is never part of the error.
  • Kept as is: no support for subclasses with other constructors (none exist).
  • Checks evidence: forks run no Actions, so Proofline saw only its own check. I ran the
    exact CI command locally (table above).

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.
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.

mohsen1 commented Nov 17, 2026

Copy link
Copy Markdown
Member

Codex review: Please merge current main and resolve the error/transport/test conflicts while retaining the current structured-error fields and redaction behavior. Rerun the pickle/copy/process-pool regressions and scripts/check.py on the resolved head.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants