From e28b03a48a474a8456959f628451f9a64272b5b4 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Fri, 20 Nov 2026 16:15:44 +0530 Subject: [PATCH 01/75] Add on_poll callback to wait_for_review in sync and async clients --- README.md | 1 + proofline/client.py | 23 +++++++++++++++++++++++ tests/test_http.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/README.md b/README.md index 3c7a6ca9..9274f72d 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ outcome = client.wait_for_review( organization_id, requested.review_id, head_commit_sha=head_commit_sha, + on_poll=lambda review: print(f"Review status: {review.status}"), ) if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) diff --git a/proofline/client.py b/proofline/client.py index dda559a3..bf37148e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,6 +5,7 @@ import math from asyncio import sleep as async_sleep from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from inspect import isawaitable from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -545,6 +546,7 @@ def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + on_poll: Callable[[CustomerReviewDetail], None] | None = None, ) -> ReviewOutcome: """Wait for recorded review completion or return TIMED_OUT. @@ -553,6 +555,9 @@ def wait_for_review( head_commit_sha holds the outcome to that commit. A review pinned to another head ends the wait on that read and is never COMPLETED. + + When on_poll is provided, it is called on each review poll with the + latest CustomerReviewDetail. """ if not math.isfinite(timeout) or timeout < 0: @@ -570,6 +575,8 @@ def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise + if on_poll is not None: + on_poll(last) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) @@ -940,7 +947,19 @@ async def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + on_poll: Callable[[CustomerReviewDetail], Awaitable[None] | None] | None = None, ) -> ReviewOutcome: + """Wait for recorded review completion or return TIMED_OUT. + + A name lookup still running at the deadline returns TIMED_OUT; it never + reports completion. + + head_commit_sha holds the outcome to that commit. A review pinned to + another head ends the wait on that read and is never COMPLETED. + + When on_poll is provided, it is invoked on each review poll with the + latest CustomerReviewDetail (supports both sync and async callbacks). + """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") _head_commit(head_commit_sha) @@ -956,6 +975,10 @@ async def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise + if on_poll is not None: + res = on_poll(last) + if isawaitable(res): + await res if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..867e4e6c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2586,3 +2586,36 @@ def respond(request: Request, index: int) -> Reply: assert len(exported.rows) == 1 assert exported.rows[0]["claim"] == row["claim"] assert exported.next_cursor == "next-page" + + +@MODES +async def test_wait_for_review_invokes_on_poll_callback( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + calls: list[str] = [] + + def sync_poll_callback(review_detail: Any) -> None: + calls.append(f"sync:{review_detail.status}") + + async def async_poll_callback(review_detail: Any) -> None: + calls.append(f"async:{review_detail.status}") + + responses = [review("RUNNING"), review()] + + with Server(lambda request, index: Reply(body=responses[index])) as server: + async with session(mode, server.url) as client: + cb = async_poll_callback if mode == "async" else sync_poll_callback + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + on_poll=cb, + ) + assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) + prefix = "async" if mode == "async" else "sync" + assert calls == [f"{prefix}:RUNNING", f"{prefix}:COMPLETED"] + assert len(server.requests) == 2 + assert clock.delays == [5] From 67eeae4dc77962fe32cb81b3dc90a157bdaa1250 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 17:53:05 +0530 Subject: [PATCH 02/75] Address Proofline review findings: bound async callback await by remaining timeout and test sync callback in async client --- proofline/client.py | 9 ++++++++- tests/test_http.py | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/proofline/client.py b/proofline/client.py index bf37148e..d9747029 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -4,6 +4,7 @@ import math from asyncio import sleep as async_sleep +from asyncio import wait_for as async_wait_for from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from inspect import isawaitable from string import hexdigits @@ -978,7 +979,13 @@ async def wait_for_review( if on_poll is not None: res = on_poll(last) if isawaitable(res): - await res + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + break + try: + await async_wait_for(res, timeout=remaining_budget) + except TimeoutError: + break if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) diff --git a/tests/test_http.py b/tests/test_http.py index 867e4e6c..31354629 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2619,3 +2619,19 @@ async def async_poll_callback(review_detail: Any) -> None: assert calls == [f"{prefix}:RUNNING", f"{prefix}:COMPLETED"] assert len(server.requests) == 2 assert clock.delays == [5] + + # Assert async client also works with regular synchronous callbacks returning None + if mode == "async": + sync_calls: list[str] = [] + with Server(lambda request, index: Reply(body=responses[index])) as server: + async with session("async", server.url) as client: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + on_poll=lambda r: sync_calls.append(r.status), + ) + assert result.status == "COMPLETED" + assert sync_calls == ["RUNNING", "COMPLETED"] From 68588e443c63e04a24c4ec5266eb896d6e250951 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 18:01:07 +0530 Subject: [PATCH 03/75] Address all 4 Proofline review findings: classify review before on_poll, close coroutines on expired budget, distinguish callback TimeoutError, and add timeout test --- proofline/client.py | 41 +++++++++++++++++++++++++++++++---------- tests/test_http.py | 11 +++++++++++ 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index d9747029..4de468dc 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,9 +3,13 @@ from __future__ import annotations import math -from asyncio import sleep as async_sleep -from asyncio import wait_for as async_wait_for -from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from asyncio import ( + sleep as async_sleep, +) +from asyncio import ( + wait_for as async_wait_for, +) +from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterator from inspect import isawaitable from string import hexdigits from time import monotonic, sleep @@ -576,13 +580,15 @@ def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if on_poll is not None: - on_poll(last) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) + if on_poll is not None: + on_poll(last) if result is not None: return result + if (_transport.remaining() or 0) <= 0: + break sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) @@ -976,21 +982,36 @@ async def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise + if (_transport.remaining() or 0) <= 0: + break + result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None: res = on_poll(last) if isawaitable(res): remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: + if isinstance(res, Coroutine): + res.close() break + timed_out_box = [False] + + async def _run_callback() -> None: + try: + await res + except TimeoutError: + timed_out_box[0] = True + raise + try: - await async_wait_for(res, timeout=remaining_budget) - except TimeoutError: + await async_wait_for(_run_callback(), timeout=remaining_budget) + except TimeoutError as exc: + if timed_out_box[0]: + raise exc from None break - if (_transport.remaining() or 0) <= 0: - break - result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result + if (_transport.remaining() or 0) <= 0: + break await async_sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) diff --git a/tests/test_http.py b/tests/test_http.py index 31354629..00c3f9b9 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2635,3 +2635,14 @@ async def async_poll_callback(review_detail: Any) -> None: ) assert result.status == "COMPLETED" assert sync_calls == ["RUNNING", "COMPLETED"] + + # Assert async callback that blocks past the remaining budget returns TIMED_OUT + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + result = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=lambda r: asyncio.sleep(2.0), + ) + assert result.status == "TIMED_OUT" From 10142427453d24eb5a1d919bf546f85ad532f6a8 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 18:09:35 +0530 Subject: [PATCH 04/75] Address remaining Proofline review findings: preserve classified outcome on deadline expiry, record callback timeout distinction, and assert cancellation --- proofline/client.py | 21 ++++++++++++++++----- tests/test_http.py | 15 +++++++++++++-- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 4de468dc..5ce46c4f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -570,6 +570,7 @@ def wait_for_review( _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) last: CustomerReviewDetail | None = None + result: ReviewOutcome | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) interval = 5.0 try: @@ -591,6 +592,8 @@ def wait_for_review( break sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) + if result is not None: + return result timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: @@ -972,6 +975,7 @@ async def wait_for_review( _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) last: CustomerReviewDetail | None = None + result: ReviewOutcome | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) interval = 5.0 try: @@ -992,21 +996,26 @@ async def wait_for_review( if remaining_budget is not None and remaining_budget <= 0: if isinstance(res, Coroutine): res.close() + if result is not None: + return result break - timed_out_box = [False] + timed_out_in_callback = False - async def _run_callback() -> None: + async def _run() -> None: + nonlocal timed_out_in_callback try: await res except TimeoutError: - timed_out_box[0] = True + timed_out_in_callback = True raise try: - await async_wait_for(_run_callback(), timeout=remaining_budget) + await async_wait_for(_run(), timeout=remaining_budget) except TimeoutError as exc: - if timed_out_box[0]: + if timed_out_in_callback: raise exc from None + if result is not None: + return result break if result is not None: return result @@ -1014,6 +1023,8 @@ async def _run_callback() -> None: break await async_sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) + if result is not None: + return result timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: diff --git a/tests/test_http.py b/tests/test_http.py index 00c3f9b9..e3cbca45 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2636,13 +2636,24 @@ async def async_poll_callback(review_detail: Any) -> None: assert result.status == "COMPLETED" assert sync_calls == ["RUNNING", "COMPLETED"] - # Assert async callback that blocks past the remaining budget returns TIMED_OUT + # Assert async callback blocking past remaining budget returns TIMED_OUT and is cancelled + cancelled = False + + async def slow_callback(r: Any) -> None: + nonlocal cancelled + try: + await asyncio.sleep(2.0) + except asyncio.CancelledError: + cancelled = True + raise + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session("async", server.url) as client: result = await client.wait_for_review( ORG, REVIEW, timeout=0.2, - on_poll=lambda r: asyncio.sleep(2.0), + on_poll=slow_callback, ) assert result.status == "TIMED_OUT" + assert cancelled From cee956557126f47828c2ef935d0d37d947c36c38 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 20:41:48 +0530 Subject: [PATCH 05/75] Address Proofline findings: document on_poll delivery bounds, record deadline expiry to protect classified mismatch from cancellation exceptions --- README.md | 2 +- proofline/client.py | 15 ++++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9274f72d..32d6b081 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 5ce46c4f..7cef4dfc 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -562,7 +562,9 @@ def wait_for_review( another head ends the wait on that read and is never COMPLETED. When on_poll is provided, it is called on each review poll with the - latest CustomerReviewDetail. + latest CustomerReviewDetail. Only reviews fetched and validated before + the callback is reached are delivered; deadline expiry can suppress + delivery. """ if not math.isfinite(timeout) or timeout < 0: @@ -969,6 +971,8 @@ async def wait_for_review( When on_poll is provided, it is invoked on each review poll with the latest CustomerReviewDetail (supports both sync and async callbacks). + Only reviews fetched and validated before the callback is reached are + delivered; deadline expiry can suppress delivery. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -999,20 +1003,21 @@ async def wait_for_review( if result is not None: return result break - timed_out_in_callback = False + timed_out_box = [False] async def _run() -> None: - nonlocal timed_out_in_callback try: await res except TimeoutError: - timed_out_in_callback = True + # Mark that callback itself raised TimeoutError while running + timed_out_box[0] = True raise try: await async_wait_for(_run(), timeout=remaining_budget) except TimeoutError as exc: - if timed_out_in_callback: + # Re-raise only if callback itself explicitly raised TimeoutError + if timed_out_box[0] and (_transport.remaining() or 0) > 0: raise exc from None if result is not None: return result From b0c5a0acbd917cd8fe068d7ca8df1d9d4fe7c1b2 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 20:57:38 +0530 Subject: [PATCH 06/75] Address Proofline findings: pass deepcopy of review to on_poll, decouple callback task cancellation from wait return, and add tests --- proofline/client.py | 44 +++++++++++++++++++++++++------------------- tests/test_http.py | 38 +++++++++++++++++++++++--------------- 2 files changed, 48 insertions(+), 34 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 7cef4dfc..50437b5e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,13 +3,17 @@ from __future__ import annotations import math +from asyncio import ( + create_task as async_create_task, +) from asyncio import ( sleep as async_sleep, ) from asyncio import ( - wait_for as async_wait_for, + wait as async_wait, ) from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterator +from copy import deepcopy from inspect import isawaitable from string import hexdigits from time import monotonic, sleep @@ -84,6 +88,10 @@ from .outcomes import ReviewOutcome, outcome T = TypeVar("T") + + +async def _await_res(res: Awaitable[Any]) -> None: + await res AgentSessionPrompt = AgentSessionPromptType0 | AgentSessionPromptType1 _AgentSessionPromptModels = tuple[type[AgentSessionPromptType0], type[AgentSessionPromptType1]] _AGENT_SESSION_PROMPT_MODELS: _AgentSessionPromptModels = ( @@ -587,7 +595,7 @@ def wait_for_review( break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None: - on_poll(last) + on_poll(deepcopy(last)) if result is not None: return result if (_transport.remaining() or 0) <= 0: @@ -994,7 +1002,7 @@ async def wait_for_review( break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None: - res = on_poll(last) + res = on_poll(deepcopy(last)) if isawaitable(res): remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: @@ -1003,22 +1011,20 @@ async def wait_for_review( if result is not None: return result break - timed_out_box = [False] - - async def _run() -> None: - try: - await res - except TimeoutError: - # Mark that callback itself raised TimeoutError while running - timed_out_box[0] = True - raise - - try: - await async_wait_for(_run(), timeout=remaining_budget) - except TimeoutError as exc: - # Re-raise only if callback itself explicitly raised TimeoutError - if timed_out_box[0] and (_transport.remaining() or 0) > 0: - raise exc from None + + coro = res if isinstance(res, Coroutine) else _await_res(res) + task = async_create_task(coro) + done, pending = await async_wait({task}, timeout=remaining_budget) + if task in done: + # Re-raise any exception raised by callback + task.result() + else: + # Callback didn't finish within budget: cancel task without waiting + task.cancel() + # Observe task exception to silence unhandled task errors + task.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index e3cbca45..a598e58d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2636,24 +2636,32 @@ async def async_poll_callback(review_detail: Any) -> None: assert result.status == "COMPLETED" assert sync_calls == ["RUNNING", "COMPLETED"] - # Assert async callback blocking past remaining budget returns TIMED_OUT and is cancelled - cancelled = False - - async def slow_callback(r: Any) -> None: - nonlocal cancelled - try: - await asyncio.sleep(2.0) - except asyncio.CancelledError: - cancelled = True - raise + # Assert callback TimeoutError before deadline propagates + async def failing_callback(r: Any) -> None: + raise TimeoutError("callback failure") with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session("async", server.url) as client: - result = await client.wait_for_review( + with pytest.raises(TimeoutError, match="callback failure"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=failing_callback, + ) + + # Assert callback modifying review does not mutate returned review + def mutating_callback(r: Any) -> None: + r.status = "MUTATED" + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session(mode, server.url) as client: + res = await call( + client, + "wait_for_review", ORG, REVIEW, - timeout=0.2, - on_poll=slow_callback, + timeout=10, + on_poll=mutating_callback, ) - assert result.status == "TIMED_OUT" - assert cancelled + assert res.review.status != "MUTATED" From d494e22d9ff49ffd61ecd39ca3e338641eee97ac Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 21:10:24 +0530 Subject: [PATCH 07/75] Address Proofline findings: document on_poll exception propagation, handle cancellation during async_wait, and test mutation across all modes --- README.md | 2 +- proofline/client.py | 9 ++++++++- tests/test_http.py | 28 ++++++++++++++-------------- 3 files changed, 23 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 32d6b081..0e0f9aff 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery, and `on_poll` exceptions propagate even when the review has already been classified as terminal. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 50437b5e..da1dc972 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -1014,7 +1014,14 @@ async def wait_for_review( coro = res if isinstance(res, Coroutine) else _await_res(res) task = async_create_task(coro) - done, pending = await async_wait({task}, timeout=remaining_budget) + try: + done, pending = await async_wait({task}, timeout=remaining_budget) + except BaseException: + task.cancel() + task.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + raise if task in done: # Re-raise any exception raised by callback task.result() diff --git a/tests/test_http.py b/tests/test_http.py index a598e58d..ee1e85e6 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2650,18 +2650,18 @@ async def failing_callback(r: Any) -> None: on_poll=failing_callback, ) - # Assert callback modifying review does not mutate returned review - def mutating_callback(r: Any) -> None: - r.status = "MUTATED" + # Assert callback modifying review does not mutate returned review in both sync and async + def mutating_callback(r: Any) -> None: + r.status = "MUTATED" - with Server(lambda request, index: Reply(body=responses[1])) as server: - async with session(mode, server.url) as client: - res = await call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=10, - on_poll=mutating_callback, - ) - assert res.review.status != "MUTATED" + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session(mode, server.url) as client: + res = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=mutating_callback, + ) + assert res.review.status != "MUTATED" From e644eccf60e5732809cd4aa799c302d5a17dfb2a Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 21:18:50 +0530 Subject: [PATCH 08/75] Address Proofline findings: cancel and observe AsyncTask on expired budget, and assert invocation count in mutation test --- proofline/client.py | 8 ++++++++ tests/test_http.py | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/proofline/client.py b/proofline/client.py index da1dc972..133d0b54 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,6 +3,9 @@ from __future__ import annotations import math +from asyncio import ( + Task as AsyncTask, +) from asyncio import ( create_task as async_create_task, ) @@ -1008,6 +1011,11 @@ async def wait_for_review( if remaining_budget is not None and remaining_budget <= 0: if isinstance(res, Coroutine): res.close() + elif isinstance(res, AsyncTask): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index ee1e85e6..78acf038 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2651,7 +2651,11 @@ async def failing_callback(r: Any) -> None: ) # Assert callback modifying review does not mutate returned review in both sync and async + mutated_count = 0 + def mutating_callback(r: Any) -> None: + nonlocal mutated_count + mutated_count += 1 r.status = "MUTATED" with Server(lambda request, index: Reply(body=responses[1])) as server: @@ -2664,4 +2668,5 @@ def mutating_callback(r: Any) -> None: timeout=10, on_poll=mutating_callback, ) + assert mutated_count == 1 assert res.review.status != "MUTATED" From 6081d63ae33cafe84f880d118add1dc131fcfb6c Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 21:46:40 +0530 Subject: [PATCH 09/75] Address Proofline findings: document non-interruptibility of synchronous callbacks, and cancel/observe Futures and Tasks on budget expiry --- README.md | 2 +- proofline/client.py | 22 +++++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0e0f9aff..285ce492 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery, and `on_poll` exceptions propagate even when the review has already been classified as terminal. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery, and `on_poll` exceptions propagate even when the review has already been classified as terminal. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 133d0b54..32f0411a 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,6 +3,9 @@ from __future__ import annotations import math +from asyncio import ( + Future as AsyncFuture, +) from asyncio import ( Task as AsyncTask, ) @@ -575,7 +578,8 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. + delivery. Synchronous callbacks must return before a terminal result can + be delivered and the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: @@ -983,7 +987,9 @@ async def wait_for_review( When on_poll is provided, it is invoked on each review poll with the latest CustomerReviewDetail (supports both sync and async callbacks). Only reviews fetched and validated before the callback is reached are - delivered; deadline expiry can suppress delivery. + delivered; deadline expiry can suppress delivery. Synchronous callbacks + must return before a terminal result can be delivered and the polling + deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1011,7 +1017,7 @@ async def wait_for_review( if remaining_budget is not None and remaining_budget <= 0: if isinstance(res, Coroutine): res.close() - elif isinstance(res, AsyncTask): + elif isinstance(res, (AsyncTask, AsyncFuture)): res.cancel() res.add_done_callback( lambda t: t.exception() if not t.cancelled() else None @@ -1029,6 +1035,11 @@ async def wait_for_review( task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) + if isinstance(res, (AsyncTask, AsyncFuture)): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) raise if task in done: # Re-raise any exception raised by callback @@ -1040,6 +1051,11 @@ async def wait_for_review( task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) + if isinstance(res, (AsyncTask, AsyncFuture)): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) if result is not None: return result break From 8cf67180ea51f989124a30cb80983833c09de2f7 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 21:57:57 +0530 Subject: [PATCH 10/75] Address Proofline findings: recheck deadline before callback delivery, record timeout winner vs callback completion, and add watchdog timeout test --- proofline/client.py | 100 +++++++++++++++++++++++--------------------- tests/test_http.py | 14 +++++++ 2 files changed, 67 insertions(+), 47 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 32f0411a..69788a60 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -601,8 +601,10 @@ def wait_for_review( if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) - if on_poll is not None: - on_poll(deepcopy(last)) + if on_poll is not None and (_transport.remaining() or 0) > 0: + snapshot = deepcopy(last) + if (_transport.remaining() or 0) > 0: + on_poll(snapshot) if result is not None: return result if (_transport.remaining() or 0) <= 0: @@ -1010,55 +1012,59 @@ async def wait_for_review( if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) - if on_poll is not None: - res = on_poll(deepcopy(last)) - if isawaitable(res): - remaining_budget = _transport.remaining() - if remaining_budget is not None and remaining_budget <= 0: - if isinstance(res, Coroutine): - res.close() - elif isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( + if on_poll is not None and (_transport.remaining() or 0) > 0: + snapshot = deepcopy(last) + if (_transport.remaining() or 0) > 0: + res = on_poll(snapshot) + if isawaitable(res): + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + if isinstance(res, Coroutine): + res.close() + elif isinstance(res, (AsyncTask, AsyncFuture)): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + if result is not None: + return result + break + + coro = res if isinstance(res, Coroutine) else _await_res(res) + task = async_create_task(coro) + timed_out_waiting = False + try: + done, pending = await async_wait({task}, timeout=remaining_budget) + if task not in done: + timed_out_waiting = True + except BaseException: + task.cancel() + task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - if result is not None: - return result - break - - coro = res if isinstance(res, Coroutine) else _await_res(res) - task = async_create_task(coro) - try: - done, pending = await async_wait({task}, timeout=remaining_budget) - except BaseException: - task.cancel() - task.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - if isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( + if isinstance(res, (AsyncTask, AsyncFuture)): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + raise + if not timed_out_waiting and task in done: + # Callback completion won over deadline timeout + task.result() + else: + # Timeout won over callback completion + task.cancel() + task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - raise - if task in done: - # Re-raise any exception raised by callback - task.result() - else: - # Callback didn't finish within budget: cancel task without waiting - task.cancel() - # Observe task exception to silence unhandled task errors - task.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - if isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - if result is not None: - return result - break + if isinstance(res, (AsyncTask, AsyncFuture)): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + if result is not None: + return result + break if result is not None: return result if (_transport.remaining() or 0) <= 0: diff --git a/tests/test_http.py b/tests/test_http.py index 78acf038..4e7145d5 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2650,6 +2650,20 @@ async def failing_callback(r: Any) -> None: on_poll=failing_callback, ) + # Assert async callback that stays pending beyond the budget times out under watchdog + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + res = await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=lambda r: asyncio.sleep(5.0), + ), + timeout=2.0, + ) + assert res.status == "TIMED_OUT" + # Assert callback modifying review does not mutate returned review in both sync and async mutated_count = 0 From 2d64b3b69ad3f60b75b666d7a9e934fa7e5ef568 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 22:05:19 +0530 Subject: [PATCH 11/75] Address Proofline findings: document cancellation-time exception consumption, and latch callback error propagation against absolute deadline --- README.md | 2 +- proofline/client.py | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 285ce492..571a7c67 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery, and `on_poll` exceptions propagate even when the review has already been classified as terminal. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Inline failures and awaitable failures that finish before the timeout propagate, but cancellation-time failures do not. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 69788a60..157cfb92 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -989,9 +989,11 @@ async def wait_for_review( When on_poll is provided, it is invoked on each review poll with the latest CustomerReviewDetail (supports both sync and async callbacks). Only reviews fetched and validated before the callback is reached are - delivered; deadline expiry can suppress delivery. Synchronous callbacks - must return before a terminal result can be delivered and the polling - deadline cannot interrupt them. + delivered; deadline expiry can suppress delivery. Inline failures and + awaitable failures that finish before the timeout propagate, but + cancellation-time failures do not. Synchronous callbacks must return + before a terminal result can be delivered and the polling deadline + cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1032,11 +1034,8 @@ async def wait_for_review( coro = res if isinstance(res, Coroutine) else _await_res(res) task = async_create_task(coro) - timed_out_waiting = False try: done, pending = await async_wait({task}, timeout=remaining_budget) - if task not in done: - timed_out_waiting = True except BaseException: task.cancel() task.add_done_callback( @@ -1048,11 +1047,12 @@ async def wait_for_review( lambda t: t.exception() if not t.cancelled() else None ) raise - if not timed_out_waiting and task in done: - # Callback completion won over deadline timeout + # Latch against absolute deadline before propagating callback errors + if (_transport.remaining() or 0) > 0 and task in done: + # Callback completed before deadline expired task.result() else: - # Timeout won over callback completion + # Deadline expired task.cancel() task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None From f734620a9438e6dc7ee5925a7bedd0a0eb11dac1 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 22:14:04 +0530 Subject: [PATCH 12/75] Address Proofline findings: qualify mismatch outcome regarding callback exceptions, record callback completion time, and verify cancellation signaling --- README.md | 2 +- proofline/client.py | 22 +++++++++++++++++----- tests/test_http.py | 18 ++++++++++++++++-- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 571a7c67..4e0579a4 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Inline failures and awaitable failures that finish before the timeout propagate, but cancellation-time failures do not. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Inline failures and awaitable failures that finish before the timeout propagate, but cancellation-time failures do not. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 157cfb92..2ae5ccea 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -1033,7 +1033,15 @@ async def wait_for_review( break coro = res if isinstance(res, Coroutine) else _await_res(res) - task = async_create_task(coro) + completed_at: list[float] = [] + + async def _runner() -> None: + try: + await coro + finally: + completed_at.append(monotonic()) + + task = async_create_task(_runner()) try: done, pending = await async_wait({task}, timeout=remaining_budget) except BaseException: @@ -1047,12 +1055,16 @@ async def wait_for_review( lambda t: t.exception() if not t.cancelled() else None ) raise - # Latch against absolute deadline before propagating callback errors - if (_transport.remaining() or 0) > 0 and task in done: - # Callback completed before deadline expired + # Record completion time in runner to decide whether to propagate + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + if cb_finished_in_budget and task in done: + # Callback finished within budget: propagate any error or success task.result() else: - # Deadline expired + # Deadline expired before callback finished task.cancel() task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None diff --git a/tests/test_http.py b/tests/test_http.py index 4e7145d5..efcd251b 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2650,7 +2650,18 @@ async def failing_callback(r: Any) -> None: on_poll=failing_callback, ) - # Assert async callback that stays pending beyond the budget times out under watchdog + # Assert async callback signals cancellation and client returns without blocking on cleanup + cancellation_requested = asyncio.Event() + cleanup_blocked = asyncio.Event() + + async def blocking_cleanup_callback(r: Any) -> None: + try: + await asyncio.sleep(5.0) + except asyncio.CancelledError: + cancellation_requested.set() + await cleanup_blocked.wait() + raise + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session("async", server.url) as client: res = await asyncio.wait_for( @@ -2658,11 +2669,14 @@ async def failing_callback(r: Any) -> None: ORG, REVIEW, timeout=0.2, - on_poll=lambda r: asyncio.sleep(5.0), + on_poll=blocking_cleanup_callback, ), timeout=2.0, ) assert res.status == "TIMED_OUT" + await asyncio.sleep(0) + assert cancellation_requested.is_set() + cleanup_blocked.set() # Assert callback modifying review does not mutate returned review in both sync and async mutated_count = 0 From 1141343cd4286f10be8189fd69acd1605e1811eb Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 22:25:43 +0530 Subject: [PATCH 13/75] Address Proofline findings: sync docstring on_poll propagation, inline done futures, and test watchdog cleanup --- README.md | 2 +- proofline/client.py | 97 +++++++++++++++++++++++++-------------------- tests/test_http.py | 38 ++++++++++++++---- 3 files changed, 85 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 4e0579a4..50aa2419 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Inline failures and awaitable failures that finish before the timeout propagate, but cancellation-time failures do not. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Inline failures and awaitable failures that finish before the timeout propagate (though awaitable failures can be suppressed when the callback returns after the deadline), but cancellation-time failures do not. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 2ae5ccea..82e188fb 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -578,8 +578,10 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. Synchronous callbacks must return before a terminal result can - be delivered and the polling deadline cannot interrupt them. + delivery. on_poll exceptions propagate even when a terminal outcome + has already been determined. Synchronous callbacks must return before a + terminal result can be delivered and the polling deadline cannot + interrupt them. """ if not math.isfinite(timeout) or timeout < 0: @@ -990,10 +992,12 @@ async def wait_for_review( latest CustomerReviewDetail (supports both sync and async callbacks). Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Inline failures and - awaitable failures that finish before the timeout propagate, but - cancellation-time failures do not. Synchronous callbacks must return - before a terminal result can be delivered and the polling deadline - cannot interrupt them. + awaitable failures that finish before the timeout propagate (though + awaitable failures can be suppressed when the callback returns after + the deadline), but cancellation-time failures do not. on_poll + exceptions propagate even when a terminal outcome has already been + determined. Synchronous callbacks must return before a terminal result + can be delivered and the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1032,51 +1036,56 @@ async def wait_for_review( return result break - coro = res if isinstance(res, Coroutine) else _await_res(res) - completed_at: list[float] = [] + if isinstance(res, (AsyncTask, AsyncFuture)) and res.done(): + res.result() + else: + coro = res if isinstance(res, Coroutine) else _await_res(res) + completed_at: list[float] = [] + + async def _runner() -> None: + try: + await coro + finally: + completed_at.append(monotonic()) - async def _runner() -> None: + task = async_create_task(_runner()) try: - await coro - finally: - completed_at.append(monotonic()) - - task = async_create_task(_runner()) - try: - done, pending = await async_wait({task}, timeout=remaining_budget) - except BaseException: - task.cancel() - task.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - if isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( + done, pending = await async_wait( + {task}, timeout=remaining_budget + ) + except BaseException: + task.cancel() + task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - raise - # Record completion time in runner to decide whether to propagate - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val - ) - if cb_finished_in_budget and task in done: - # Callback finished within budget: propagate any error or success - task.result() - else: - # Deadline expired before callback finished - task.cancel() - task.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None + if isinstance(res, (AsyncTask, AsyncFuture)): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + raise + # Record completion time in runner to decide whether to propagate + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val ) - if isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( + if cb_finished_in_budget and task in done: + # Finished in budget: propagate any error or success + task.result() + else: + # Deadline expired before callback finished + task.cancel() + task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - if result is not None: - return result - break + if isinstance(res, (AsyncTask, AsyncFuture)): + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + if result is not None: + return result + break if result is not None: return result if (_transport.remaining() or 0) <= 0: diff --git a/tests/test_http.py b/tests/test_http.py index efcd251b..4bdf2653 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2650,6 +2650,23 @@ async def failing_callback(r: Any) -> None: on_poll=failing_callback, ) + # Assert already-done failed future propagates inline + def failed_future_callback(r: Any) -> asyncio.Future[None]: + loop = asyncio.get_running_loop() + fut: asyncio.Future[None] = loop.create_future() + fut.set_exception(ValueError("inline future error")) + return fut + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="inline future error"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=failed_future_callback, + ) + # Assert async callback signals cancellation and client returns without blocking on cleanup cancellation_requested = asyncio.Event() cleanup_blocked = asyncio.Event() @@ -2664,19 +2681,26 @@ async def blocking_cleanup_callback(r: Any) -> None: with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session("async", server.url) as client: - res = await asyncio.wait_for( + client_task = asyncio.create_task( client.wait_for_review( ORG, REVIEW, timeout=0.2, on_poll=blocking_cleanup_callback, - ), - timeout=2.0, + ) ) - assert res.status == "TIMED_OUT" - await asyncio.sleep(0) - assert cancellation_requested.is_set() - cleanup_blocked.set() + try: + done, _ = await asyncio.wait({client_task}, timeout=2.0) + assert client_task in done + res = client_task.result() + assert res.status == "TIMED_OUT" + await asyncio.sleep(0) + assert cancellation_requested.is_set() + finally: + cleanup_blocked.set() + if not client_task.done(): + client_task.cancel() + await asyncio.wait({client_task}) # Assert callback modifying review does not mutate returned review in both sync and async mutated_count = 0 From c548ecaa9e53f12ec4777665743124dcfa7fca20 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 22:47:37 +0530 Subject: [PATCH 14/75] Address Proofline findings: clarify sync on_poll in README, record done callback timestamp on future, and test coroutine isolation --- README.md | 6 +++++- proofline/client.py | 21 ++++++++++++++------- tests/test_http.py | 12 ++++++++++-- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 50aa2419..29367230 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,11 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Inline failures and awaitable failures that finish before the timeout propagate (though awaitable failures can be suppressed when the callback returns after the deadline), but cancellation-time failures do not. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`ProoflineClient` requires a synchronous `on_poll` callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. + +With `AsyncProoflineClient`, `wait_for_review` can be awaited and `on_poll` supports both synchronous callbacks and awaitables (such as coroutines and futures). Inline failures and awaitable failures observed before the deadline propagate (though awaitable failures can be suppressed when returned or observed after the deadline), but cancellation-time failures do not. + +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 82e188fb..df5fd6b5 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -992,12 +992,12 @@ async def wait_for_review( latest CustomerReviewDetail (supports both sync and async callbacks). Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Inline failures and - awaitable failures that finish before the timeout propagate (though - awaitable failures can be suppressed when the callback returns after - the deadline), but cancellation-time failures do not. on_poll - exceptions propagate even when a terminal outcome has already been - determined. Synchronous callbacks must return before a terminal result - can be delivered and the polling deadline cannot interrupt them. + awaitable failures observed before the deadline propagate (though + awaitables that complete or are observed after the deadline or during + cancellation do not). on_poll exceptions propagate even when a terminal + outcome has already been determined. Synchronous callbacks must return + before a terminal result can be delivered and the polling deadline + cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1041,12 +1041,19 @@ async def wait_for_review( else: coro = res if isinstance(res, Coroutine) else _await_res(res) completed_at: list[float] = [] + if isinstance(res, (AsyncTask, AsyncFuture)): + res.add_done_callback( + lambda _: completed_at.append(monotonic()) + if not completed_at + else None + ) async def _runner() -> None: try: await coro finally: - completed_at.append(monotonic()) + if not completed_at: + completed_at.append(monotonic()) task = async_create_task(_runner()) try: diff --git a/tests/test_http.py b/tests/test_http.py index 4bdf2653..d4d2642c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2600,6 +2600,7 @@ def sync_poll_callback(review_detail: Any) -> None: async def async_poll_callback(review_detail: Any) -> None: calls.append(f"async:{review_detail.status}") + review_detail.status = "MUTATED" responses = [review("RUNNING"), review()] @@ -2617,6 +2618,7 @@ async def async_poll_callback(review_detail: Any) -> None: assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) prefix = "async" if mode == "async" else "sync" assert calls == [f"{prefix}:RUNNING", f"{prefix}:COMPLETED"] + assert result.review.status == "COMPLETED" assert len(server.requests) == 2 assert clock.delays == [5] @@ -2705,20 +2707,26 @@ async def blocking_cleanup_callback(r: Any) -> None: # Assert callback modifying review does not mutate returned review in both sync and async mutated_count = 0 - def mutating_callback(r: Any) -> None: + def sync_mutating_callback(r: Any) -> None: + nonlocal mutated_count + mutated_count += 1 + r.status = "MUTATED" + + async def async_mutating_callback(r: Any) -> None: nonlocal mutated_count mutated_count += 1 r.status = "MUTATED" with Server(lambda request, index: Reply(body=responses[1])) as server: async with session(mode, server.url) as client: + mut_cb = async_mutating_callback if mode == "async" else sync_mutating_callback res = await call( client, "wait_for_review", ORG, REVIEW, timeout=10, - on_poll=mutating_callback, + on_poll=mut_cb, ) assert mutated_count == 1 assert res.review.status != "MUTATED" From 56241187d9e151519c9343357f036ee25b382072 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 22:52:03 +0530 Subject: [PATCH 15/75] Address Proofline findings: close unstarted callback coroutine on cancellation and test classified outcome on callback timeout --- proofline/client.py | 8 ++++++++ tests/test_http.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/proofline/client.py b/proofline/client.py index df5fd6b5..035e6265 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -1048,7 +1048,11 @@ async def wait_for_review( else None ) + wrapper_started = False + async def _runner() -> None: + nonlocal wrapper_started + wrapper_started = True try: await coro finally: @@ -1070,6 +1074,8 @@ async def _runner() -> None: res.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) + elif isinstance(res, Coroutine) and not wrapper_started: + res.close() raise # Record completion time in runner to decide whether to propagate deadline_val = _transport.DEADLINE.get() @@ -1090,6 +1096,8 @@ async def _runner() -> None: res.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) + elif isinstance(res, Coroutine) and not wrapper_started: + res.close() if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index d4d2642c..62a24a95 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2704,6 +2704,41 @@ async def blocking_cleanup_callback(r: Any) -> None: client_task.cancel() await asyncio.wait({client_task}) + # Assert classified outcome survives callback expiration + cancellation_requested_term = asyncio.Event() + cleanup_blocked_term = asyncio.Event() + + async def blocking_cleanup_callback_term(r: Any) -> None: + try: + await asyncio.sleep(5.0) + except asyncio.CancelledError: + cancellation_requested_term.set() + await cleanup_blocked_term.wait() + raise + + with Server(lambda request, index: Reply(body=review())) as server: + async with session("async", server.url) as client: + term_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=blocking_cleanup_callback_term, + ) + ) + try: + done, _ = await asyncio.wait({term_task}, timeout=2.0) + assert term_task in done + res = term_task.result() + assert res.status == "COMPLETED" + await asyncio.sleep(0) + assert cancellation_requested_term.is_set() + finally: + cleanup_blocked_term.set() + if not term_task.done(): + term_task.cancel() + await asyncio.wait({term_task}) + # Assert callback modifying review does not mutate returned review in both sync and async mutated_count = 0 From 1416b9892c00f41a09b3e0c5c83f52c3755705b8 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:00:37 +0530 Subject: [PATCH 16/75] Address Proofline findings: wait on futures directly, seed deepcopy with UNSET, close generators, and document optional sync on_poll --- README.md | 2 +- proofline/client.py | 77 +++++++++++++++++++++++++++------------------ tests/test_http.py | 4 +++ 3 files changed, 51 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 29367230..41930bbb 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`ProoflineClient` requires a synchronous `on_poll` callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. With `AsyncProoflineClient`, `wait_for_review` can be awaited and `on_poll` supports both synchronous callbacks and awaitables (such as coroutines and futures). Inline failures and awaitable failures observed before the deadline propagate (though awaitable failures can be suppressed when returned or observed after the deadline), but cancellation-time failures do not. diff --git a/proofline/client.py b/proofline/client.py index 035e6265..b4b9a26e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -18,7 +18,7 @@ from asyncio import ( wait as async_wait, ) -from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Generator, Iterator from copy import deepcopy from inspect import isawaitable from string import hexdigits @@ -604,7 +604,7 @@ def wait_for_review( break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: - snapshot = deepcopy(last) + snapshot = deepcopy(last, {id(UNSET): UNSET}) if (_transport.remaining() or 0) > 0: on_poll(snapshot) if result is not None: @@ -1019,13 +1019,13 @@ async def wait_for_review( break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: - snapshot = deepcopy(last) + snapshot = deepcopy(last, {id(UNSET): UNSET}) if (_transport.remaining() or 0) > 0: res = on_poll(snapshot) if isawaitable(res): remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - if isinstance(res, Coroutine): + if isinstance(res, (Coroutine, Generator)): res.close() elif isinstance(res, (AsyncTask, AsyncFuture)): res.cancel() @@ -1036,18 +1036,41 @@ async def wait_for_review( return result break - if isinstance(res, (AsyncTask, AsyncFuture)) and res.done(): - res.result() - else: - coro = res if isinstance(res, Coroutine) else _await_res(res) - completed_at: list[float] = [] - if isinstance(res, (AsyncTask, AsyncFuture)): + if isinstance(res, (AsyncTask, AsyncFuture)): + if res.done(): + res.result() + else: + completed_at: list[float] = [] res.add_done_callback( lambda _: completed_at.append(monotonic()) - if not completed_at - else None ) - + try: + done, _ = await async_wait( + {res}, timeout=remaining_budget + ) + except BaseException: + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + raise + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + if cb_finished_in_budget or res in done: + res.result() + else: + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + if result is not None: + return result + break + else: + coro = res + completed_at = [] wrapper_started = False async def _runner() -> None: @@ -1056,12 +1079,11 @@ async def _runner() -> None: try: await coro finally: - if not completed_at: - completed_at.append(monotonic()) + completed_at.append(monotonic()) task = async_create_task(_runner()) try: - done, pending = await async_wait( + done, _ = await async_wait( {task}, timeout=remaining_budget ) except BaseException: @@ -1069,34 +1091,27 @@ async def _runner() -> None: task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - if isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - elif isinstance(res, Coroutine) and not wrapper_started: + if ( + isinstance(res, (Coroutine, Generator)) + and not wrapper_started + ): res.close() raise - # Record completion time in runner to decide whether to propagate deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) if cb_finished_in_budget and task in done: - # Finished in budget: propagate any error or success task.result() else: - # Deadline expired before callback finished task.cancel() task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - if isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - elif isinstance(res, Coroutine) and not wrapper_started: + if ( + isinstance(res, (Coroutine, Generator)) + and not wrapper_started + ): res.close() if result is not None: return result diff --git a/tests/test_http.py b/tests/test_http.py index 62a24a95..2f9d8ca1 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2597,9 +2597,13 @@ async def test_wait_for_review_invokes_on_poll_callback( def sync_poll_callback(review_detail: Any) -> None: calls.append(f"sync:{review_detail.status}") + if review_detail.status == "RUNNING": + assert review_detail.completed_at is UNSET async def async_poll_callback(review_detail: Any) -> None: calls.append(f"async:{review_detail.status}") + if review_detail.status == "RUNNING": + assert review_detail.completed_at is UNSET review_detail.status = "MUTATED" responses = [review("RUNNING"), review()] From 8d6fb95efbce6ec3353e4f8e83cfcac8b569844a Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:06:05 +0530 Subject: [PATCH 17/75] Address Proofline findings: require timely observation for future results, test pending future cancellation, and isolate watchdogs in subprocess --- proofline/client.py | 2 +- tests/test_http.py | 145 ++++++++++++++++++++++++-------------------- 2 files changed, 81 insertions(+), 66 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index b4b9a26e..b0383d53 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -1058,7 +1058,7 @@ async def wait_for_review( cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - if cb_finished_in_budget or res in done: + if cb_finished_in_budget and res in done: res.result() else: res.cancel() diff --git a/tests/test_http.py b/tests/test_http.py index 2f9d8ca1..e94720a8 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2673,75 +2673,90 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: on_poll=failed_future_callback, ) - # Assert async callback signals cancellation and client returns without blocking on cleanup - cancellation_requested = asyncio.Event() - cleanup_blocked = asyncio.Event() - - async def blocking_cleanup_callback(r: Any) -> None: - try: - await asyncio.sleep(5.0) - except asyncio.CancelledError: - cancellation_requested.set() - await cleanup_blocked.wait() - raise + # Assert synchronous callback returning pending Future is cancelled on deadline expiry + pending_fut: asyncio.Future[None] | None = None + + def pending_future_callback(r: Any) -> asyncio.Future[None]: + nonlocal pending_fut + loop = asyncio.get_running_loop() + pending_fut = loop.create_future() + return pending_fut with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session("async", server.url) as client: - client_task = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=blocking_cleanup_callback, - ) - ) - try: - done, _ = await asyncio.wait({client_task}, timeout=2.0) - assert client_task in done - res = client_task.result() - assert res.status == "TIMED_OUT" - await asyncio.sleep(0) - assert cancellation_requested.is_set() - finally: - cleanup_blocked.set() - if not client_task.done(): - client_task.cancel() - await asyncio.wait({client_task}) - - # Assert classified outcome survives callback expiration - cancellation_requested_term = asyncio.Event() - cleanup_blocked_term = asyncio.Event() - - async def blocking_cleanup_callback_term(r: Any) -> None: - try: - await asyncio.sleep(5.0) - except asyncio.CancelledError: - cancellation_requested_term.set() - await cleanup_blocked_term.wait() - raise - - with Server(lambda request, index: Reply(body=review())) as server: - async with session("async", server.url) as client: - term_task = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=blocking_cleanup_callback_term, - ) + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=pending_future_callback, ) - try: - done, _ = await asyncio.wait({term_task}, timeout=2.0) - assert term_task in done - res = term_task.result() - assert res.status == "COMPLETED" - await asyncio.sleep(0) - assert cancellation_requested_term.is_set() - finally: - cleanup_blocked_term.set() - if not term_task.done(): - term_task.cancel() - await asyncio.wait({term_task}) + assert res.status == "TIMED_OUT" + assert pending_fut is not None + assert pending_fut.cancelled() + + # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant + # tasks cannot stall teardown. + watchdog_code = """ +import asyncio +from typing import Any +from tests.test_http import session, Server, Reply, review, ORG, REVIEW + +async def main() -> None: + cancellation_requested = asyncio.Event() + cleanup_blocked = asyncio.Event() + + async def blocking_cleanup_callback(r: Any) -> None: + try: + await asyncio.sleep(5.0) + except asyncio.CancelledError: + cancellation_requested.set() + await cleanup_blocked.wait() + raise + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=blocking_cleanup_callback, + ) + assert res.status == "TIMED_OUT" + await asyncio.sleep(0) + assert cancellation_requested.is_set() + cleanup_blocked.set() + + cancellation_requested_term = asyncio.Event() + cleanup_blocked_term = asyncio.Event() + + async def blocking_cleanup_callback_term(r: Any) -> None: + try: + await asyncio.sleep(5.0) + except asyncio.CancelledError: + cancellation_requested_term.set() + await cleanup_blocked_term.wait() + raise + + with Server(lambda request, index: Reply(body=review())) as server: + async with session("async", server.url) as client: + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=blocking_cleanup_callback_term, + ) + assert res.status == "COMPLETED" + await asyncio.sleep(0) + assert cancellation_requested_term.is_set() + cleanup_blocked_term.set() + +asyncio.run(main()) +""" + subprocess.run( + [sys.executable, "-c", watchdog_code], + check=True, + timeout=10, + ) # Assert callback modifying review does not mutate returned review in both sync and async mutated_count = 0 From 41b673d1d89e255992809135db078207b1212695 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:11:12 +0530 Subject: [PATCH 18/75] Address Proofline findings: guard coroutine close, clarify callable on_poll contract and cancellation failure suppression, move pending future test into watchdog subprocess, and test inline callback mutation isolation --- README.md | 2 +- proofline/client.py | 35 ++++++++++++++++++++------------ tests/test_http.py | 49 +++++++++++++++++++++++++-------------------- 3 files changed, 50 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 41930bbb..ee110c22 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited and `on_poll` supports both synchronous callbacks and awaitables (such as coroutines and futures). Inline failures and awaitable failures observed before the deadline propagate (though awaitable failures can be suppressed when returned or observed after the deadline), but cancellation-time failures do not. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Inline failures and awaitable failures observed before the deadline propagate, but failures occurring after the polling wait cancels or discards the callback are suppressed. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index b0383d53..62b38f00 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -988,16 +988,16 @@ async def wait_for_review( head_commit_sha holds the outcome to that commit. A review pinned to another head ends the wait on that read and is never COMPLETED. - When on_poll is provided, it is invoked on each review poll with the - latest CustomerReviewDetail (supports both sync and async callbacks). - Only reviews fetched and validated before the callback is reached are - delivered; deadline expiry can suppress delivery. Inline failures and - awaitable failures observed before the deadline propagate (though - awaitables that complete or are observed after the deadline or during - cancellation do not). on_poll exceptions propagate even when a terminal - outcome has already been determined. Synchronous callbacks must return - before a terminal result can be delivered and the polling deadline - cannot interrupt them. + When on_poll is provided, it must be a callable that accepts the review + snapshot and returns None or an awaitable (supporting both sync and + async callbacks). Only reviews fetched and validated before the callback + is reached are delivered; deadline expiry can suppress delivery. Inline + failures and awaitable failures observed before the deadline propagate, + but failures occurring after the polling wait cancels or discards the + callback are suppressed. on_poll exceptions propagate even when a + terminal outcome has already been determined. Synchronous callbacks must + return before a terminal result can be delivered and the polling + deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1026,7 +1026,10 @@ async def wait_for_review( remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: if isinstance(res, (Coroutine, Generator)): - res.close() + try: + res.close() + except BaseException: + pass elif isinstance(res, (AsyncTask, AsyncFuture)): res.cancel() res.add_done_callback( @@ -1095,7 +1098,10 @@ async def _runner() -> None: isinstance(res, (Coroutine, Generator)) and not wrapper_started ): - res.close() + try: + res.close() + except BaseException: + pass raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( @@ -1112,7 +1118,10 @@ async def _runner() -> None: isinstance(res, (Coroutine, Generator)) and not wrapper_started ): - res.close() + try: + res.close() + except BaseException: + pass if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index e94720a8..d8c70e0f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2629,6 +2629,11 @@ async def async_poll_callback(review_detail: Any) -> None: # Assert async client also works with regular synchronous callbacks returning None if mode == "async": sync_calls: list[str] = [] + + def inline_sync_cb(r: Any) -> None: + sync_calls.append(r.status) + r.status = "MUTATED" + with Server(lambda request, index: Reply(body=responses[index])) as server: async with session("async", server.url) as client: result = await call( @@ -2637,10 +2642,11 @@ async def async_poll_callback(review_detail: Any) -> None: ORG, REVIEW, timeout=100, - on_poll=lambda r: sync_calls.append(r.status), + on_poll=inline_sync_cb, ) assert result.status == "COMPLETED" assert sync_calls == ["RUNNING", "COMPLETED"] + assert result.review.status == "COMPLETED" # Assert callback TimeoutError before deadline propagates async def failing_callback(r: Any) -> None: @@ -2673,27 +2679,6 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: on_poll=failed_future_callback, ) - # Assert synchronous callback returning pending Future is cancelled on deadline expiry - pending_fut: asyncio.Future[None] | None = None - - def pending_future_callback(r: Any) -> asyncio.Future[None]: - nonlocal pending_fut - loop = asyncio.get_running_loop() - pending_fut = loop.create_future() - return pending_fut - - with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: - async with session("async", server.url) as client: - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=pending_future_callback, - ) - assert res.status == "TIMED_OUT" - assert pending_fut is not None - assert pending_fut.cancelled() - # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. watchdog_code = """ @@ -2702,6 +2687,26 @@ def pending_future_callback(r: Any) -> asyncio.Future[None]: from tests.test_http import session, Server, Reply, review, ORG, REVIEW async def main() -> None: + pending_fut: asyncio.Future[None] | None = None + + def pending_future_callback(r: Any) -> asyncio.Future[None]: + nonlocal pending_fut + loop = asyncio.get_running_loop() + pending_fut = loop.create_future() + return pending_fut + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=pending_future_callback, + ) + assert res.status == "TIMED_OUT" + assert pending_fut is not None + assert pending_fut.cancelled() + cancellation_requested = asyncio.Event() cleanup_blocked = asyncio.Event() From 21d5ef1ddb10dba59eace67908d929c417393d4d Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:18:15 +0530 Subject: [PATCH 19/75] Address Proofline findings: deadline-aware snapshotting, drain completed futures directly, close unstarted coroutines safely, and verify suspending callback within budget --- README.md | 2 +- proofline/client.py | 81 +++++++++++++++++++++++++++++++++------------ tests/test_http.py | 18 ++++++++++ 3 files changed, 78 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index ee110c22..534c6137 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Inline failures and awaitable failures observed before the deadline propagate, but failures occurring after the polling wait cancels or discards the callback are suppressed. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 62b38f00..4191adab 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -18,9 +18,9 @@ from asyncio import ( wait as async_wait, ) -from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Generator, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from copy import deepcopy -from inspect import isawaitable +from inspect import CORO_CREATED, getcoroutinestate, isawaitable, iscoroutine from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -213,6 +213,31 @@ def _export_page_limit(max_pages: int) -> None: raise ValueError("Export pagination requires max_pages 1..1000.") +class _DeadlineExhausted(Exception): + """Raised to abort deepcopy when the transport deadline expires.""" + + +class _DeadlineMemo(dict[int, Any]): + def __contains__(self, key: object) -> bool: + if (_transport.remaining() or 0) <= 0: + raise _DeadlineExhausted() + return super().__contains__(key) + + def __setitem__(self, key: int, value: Any) -> None: + if (_transport.remaining() or 0) <= 0: + raise _DeadlineExhausted() + super().__setitem__(key, value) + + +def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | None: + if (_transport.remaining() or 0) <= 0: + return None + try: + return deepcopy(detail, _DeadlineMemo({id(UNSET): UNSET})) + except _DeadlineExhausted: + return None + + def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None: cursor = page.next_cursor if cursor is None: @@ -604,8 +629,8 @@ def wait_for_review( break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: - snapshot = deepcopy(last, {id(UNSET): UNSET}) - if (_transport.remaining() or 0) > 0: + snapshot = _snapshot_review(last) + if snapshot is not None and (_transport.remaining() or 0) > 0: on_poll(snapshot) if result is not None: return result @@ -993,11 +1018,11 @@ async def wait_for_review( async callbacks). Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Inline failures and awaitable failures observed before the deadline propagate, - but failures occurring after the polling wait cancels or discards the - callback are suppressed. on_poll exceptions propagate even when a - terminal outcome has already been determined. Synchronous callbacks must - return before a terminal result can be delivered and the polling - deadline cannot interrupt them. + but the deadline can suppress awaitable failures even before cancellation + or discard, including when an outcome is already classified. on_poll + exceptions propagate even when a terminal outcome has already been + determined. Synchronous callbacks must return before a terminal result + can be delivered and the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1019,22 +1044,26 @@ async def wait_for_review( break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: - snapshot = deepcopy(last, {id(UNSET): UNSET}) - if (_transport.remaining() or 0) > 0: + snapshot = _snapshot_review(last) + if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) if isawaitable(res): remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - if isinstance(res, (Coroutine, Generator)): + if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: try: res.close() except BaseException: pass elif isinstance(res, (AsyncTask, AsyncFuture)): - res.cancel() - res.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) + if res.done(): + if not res.cancelled(): + res.exception() + else: + res.cancel() + res.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) if result is not None: return result break @@ -1064,10 +1093,16 @@ async def wait_for_review( if cb_finished_in_budget and res in done: res.result() else: - res.cancel() - res.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) + if res.done(): + if not res.cancelled(): + res.exception() + else: + res.cancel() + res.add_done_callback( + lambda t: t.exception() + if not t.cancelled() + else None + ) if result is not None: return result break @@ -1095,8 +1130,9 @@ async def _runner() -> None: lambda t: t.exception() if not t.cancelled() else None ) if ( - isinstance(res, (Coroutine, Generator)) + iscoroutine(res) and not wrapper_started + and getcoroutinestate(res) == CORO_CREATED ): try: res.close() @@ -1115,8 +1151,9 @@ async def _runner() -> None: lambda t: t.exception() if not t.cancelled() else None ) if ( - isinstance(res, (Coroutine, Generator)) + iscoroutine(res) and not wrapper_started + and getcoroutinestate(res) == CORO_CREATED ): try: res.close() diff --git a/tests/test_http.py b/tests/test_http.py index d8c70e0f..8a76e81d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2755,6 +2755,24 @@ async def blocking_cleanup_callback_term(r: Any) -> None: assert cancellation_requested_term.is_set() cleanup_blocked_term.set() + resumed_within_budget = False + + async def suspending_callback(r: Any) -> None: + nonlocal resumed_within_budget + await asyncio.sleep(0.05) + resumed_within_budget = True + + with Server(lambda request, index: Reply(body=review())) as server: + async with session("async", server.url) as client: + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=suspending_callback, + ) + assert res.status == "COMPLETED" + assert resumed_within_budget + asyncio.run(main()) """ subprocess.run( From ee8e3cccc4f856389eebed69410b73daa8e6b21a Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:28:06 +0530 Subject: [PATCH 20/75] Address Proofline findings: iterative snapshotting to prevent RecursionError, skip closed loop futures, and assert nested mutation isolation --- proofline/client.py | 176 +++++++++++++++++++++++++++++++++----------- tests/test_http.py | 35 +++++++++ 2 files changed, 170 insertions(+), 41 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 4191adab..45e8270f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,6 +2,8 @@ from __future__ import annotations +import copy +import datetime import math from asyncio import ( Future as AsyncFuture, @@ -213,29 +215,141 @@ def _export_page_limit(max_pages: int) -> None: raise ValueError("Export pagination requires max_pages 1..1000.") -class _DeadlineExhausted(Exception): - """Raised to abort deepcopy when the transport deadline expires.""" - +def _is_immutable(val: Any) -> bool: + return ( + val is None + or val is UNSET + or isinstance( + val, + (int, float, str, bool, bytes, UUID, datetime.date, datetime.datetime), + ) + ) -class _DeadlineMemo(dict[int, Any]): - def __contains__(self, key: object) -> bool: - if (_transport.remaining() or 0) <= 0: - raise _DeadlineExhausted() - return super().__contains__(key) - def __setitem__(self, key: int, value: Any) -> None: - if (_transport.remaining() or 0) <= 0: - raise _DeadlineExhausted() - super().__setitem__(key, value) +def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: + if hasattr(obj, "__dict__"): + return list(obj.__dict__.items()) + slots: set[str] = set() + for cls in type(obj).__mro__: + s = getattr(cls, "__slots__", None) + if s: + if isinstance(s, str): + slots.add(s) + else: + slots.update(s) + result: list[tuple[str, Any]] = [] + for attr in slots: + if attr.startswith("__") and attr.endswith("__"): + continue + if hasattr(obj, attr): + result.append((attr, getattr(obj, attr))) + return result def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | None: if (_transport.remaining() or 0) <= 0: return None + + memo: dict[int, Any] = {id(UNSET): UNSET} + root = copy.copy(detail) + memo[id(detail)] = root + + stack: list[tuple[Any, Any, bool, Any]] = [] + for attr, val in _get_obj_attrs(detail): + stack.append((root, attr, True, val)) + + while stack: + if (_transport.remaining() or 0) <= 0: + return None + + parent, key, is_attr, val = stack.pop() + + if _is_immutable(val): + if is_attr: + setattr(parent, key, val) + else: + parent[key] = val + continue + + val_id = id(val) + if val_id in memo: + resolved = memo[val_id] + if is_attr: + setattr(parent, key, resolved) + else: + parent[key] = resolved + continue + + if isinstance(val, dict): + new_dict: dict[Any, Any] = {} + memo[val_id] = new_dict + if is_attr: + setattr(parent, key, new_dict) + else: + parent[key] = new_dict + for k, v in val.items(): + stack.append((new_dict, k, False, v)) + elif isinstance(val, list): + new_list = [None] * len(val) + memo[val_id] = new_list + if is_attr: + setattr(parent, key, new_list) + else: + parent[key] = new_list + for idx, item in enumerate(val): + stack.append((new_list, idx, False, item)) + elif isinstance(val, tuple): + if all(_is_immutable(x) for x in val): + if is_attr: + setattr(parent, key, val) + else: + parent[key] = val + else: + new_list = [None] * len(val) + memo[val_id] = new_list + if is_attr: + setattr(parent, key, new_list) + else: + parent[key] = new_list + for idx, item in enumerate(val): + stack.append((new_list, idx, False, item)) + elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): + new_obj = copy.copy(val) + memo[val_id] = new_obj + if is_attr: + setattr(parent, key, new_obj) + else: + parent[key] = new_obj + for attr, attr_val in _get_obj_attrs(val): + stack.append((new_obj, attr, True, attr_val)) + else: + try: + resolved = deepcopy(val, memo) + except Exception: + resolved = val + if is_attr: + setattr(parent, key, resolved) + else: + parent[key] = resolved + + return root + + +def _safe_cleanup_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: try: - return deepcopy(detail, _DeadlineMemo({id(UNSET): UNSET})) - except _DeadlineExhausted: - return None + loop = fut.get_loop() + if loop.is_closed(): + return + if fut.done(): + if not fut.cancelled(): + fut.exception() + else: + fut.cancel() + fut.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) + except BaseException: + pass def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None: @@ -1019,10 +1133,9 @@ async def wait_for_review( is reached are delivered; deadline expiry can suppress delivery. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation - or discard, including when an outcome is already classified. on_poll - exceptions propagate even when a terminal outcome has already been - determined. Synchronous callbacks must return before a terminal result - can be delivered and the polling deadline cannot interrupt them. + or discard, including when an outcome is already classified. Synchronous + callbacks must return before a terminal result can be delivered and the + polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1056,14 +1169,7 @@ async def wait_for_review( except BaseException: pass elif isinstance(res, (AsyncTask, AsyncFuture)): - if res.done(): - if not res.cancelled(): - res.exception() - else: - res.cancel() - res.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) + _safe_cleanup_future(res) if result is not None: return result break @@ -1081,10 +1187,7 @@ async def wait_for_review( {res}, timeout=remaining_budget ) except BaseException: - res.cancel() - res.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) + _safe_cleanup_future(res) raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( @@ -1093,16 +1196,7 @@ async def wait_for_review( if cb_finished_in_budget and res in done: res.result() else: - if res.done(): - if not res.cancelled(): - res.exception() - else: - res.cancel() - res.add_done_callback( - lambda t: t.exception() - if not t.cancelled() - else None - ) + _safe_cleanup_future(res) if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index 8a76e81d..1325adff 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2788,11 +2788,15 @@ def sync_mutating_callback(r: Any) -> None: nonlocal mutated_count mutated_count += 1 r.status = "MUTATED" + r.actions.publish = True + r.additional_properties["mutated"] = "mutated_value" async def async_mutating_callback(r: Any) -> None: nonlocal mutated_count mutated_count += 1 r.status = "MUTATED" + r.actions.publish = True + r.additional_properties["mutated"] = "mutated_value" with Server(lambda request, index: Reply(body=responses[1])) as server: async with session(mode, server.url) as client: @@ -2807,3 +2811,34 @@ async def async_mutating_callback(r: Any) -> None: ) assert mutated_count == 1 assert res.review.status != "MUTATED" + assert res.review.actions.publish is False + assert "mutated" not in res.review.additional_properties + + # Assert deeply nested extension fields do not trigger RecursionError in snapshot + deep_container: dict[str, Any] = {} + curr = deep_container + for _ in range(3000): + curr["child"] = {} + curr = curr["child"] + curr["val"] = "deepest" + + nested_detail_received = False + + def deep_extension_cb(r: Any) -> None: + nonlocal nested_detail_received + assert r.additional_properties["deep"]["child"] is not None + nested_detail_received = True + + deep_review = {**responses[1], "deep": deep_container} + with Server(lambda request, index: Reply(body=deep_review)) as server: + async with session(mode, server.url) as client: + res = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=deep_extension_cb, + ) + assert res.status == "COMPLETED" + assert nested_detail_received From 33632892b07bc5f752a480212c2889c34c030891 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:38:20 +0530 Subject: [PATCH 21/75] Address Proofline findings: incremental bounded snapshotting, retrieve exceptions before loop check, runner deadline check, and in-memory deep snapshot test --- README.md | 2 +- proofline/client.py | 225 +++++++++++++++++++++++++++++--------------- tests/test_http.py | 39 ++++---- 3 files changed, 169 insertions(+), 97 deletions(-) diff --git a/README.md b/README.md index 534c6137..e310ed79 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 45e8270f..773f5e14 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -21,7 +21,6 @@ wait as async_wait, ) from collections.abc import AsyncIterator, Awaitable, Callable, Iterator -from copy import deepcopy from inspect import CORO_CREATED, getcoroutinestate, isawaitable, iscoroutine from string import hexdigits from time import monotonic, sleep @@ -246,108 +245,171 @@ def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: return result +_ITEM_TASK = 1 +_DICT_EXPAND = 2 +_LIST_EXPAND = 3 +_OBJ_EXPAND = 4 +_EXPAND_BATCH_SIZE = 64 + + +def _deadline_expired() -> bool: + budget = _transport.remaining() + return budget is not None and budget <= 0 + + def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | None: - if (_transport.remaining() or 0) <= 0: + if _deadline_expired(): return None memo: dict[int, Any] = {id(UNSET): UNSET} root = copy.copy(detail) memo[id(detail)] = root - stack: list[tuple[Any, Any, bool, Any]] = [] - for attr, val in _get_obj_attrs(detail): - stack.append((root, attr, True, val)) + stack: list[Any] = [(_OBJ_EXPAND, root, iter(_get_obj_attrs(detail)))] while stack: - if (_transport.remaining() or 0) <= 0: + if _deadline_expired(): return None - parent, key, is_attr, val = stack.pop() + task_type, target, it_or_key, *extra = stack.pop() - if _is_immutable(val): - if is_attr: - setattr(parent, key, val) + if task_type == _ITEM_TASK: + key, is_attr, val = it_or_key, extra[0], extra[1] + if _is_immutable(val): + if is_attr: + setattr(target, key, val) + else: + target[key] = val + continue + val_id = id(val) + if val_id in memo: + resolved = memo[val_id] + if is_attr: + setattr(target, key, resolved) + else: + target[key] = resolved + continue + if isinstance(val, dict): + new_dict: dict[Any, Any] = {} + memo[val_id] = new_dict + if is_attr: + setattr(target, key, new_dict) + else: + target[key] = new_dict + stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) + elif isinstance(val, list): + new_list: list[Any] = [] + memo[val_id] = new_list + if is_attr: + setattr(target, key, new_list) + else: + target[key] = new_list + stack.append((_LIST_EXPAND, new_list, iter(val))) + elif isinstance(val, tuple): + if all(_is_immutable(x) for x in val): + resolved = val + else: + resolved = tuple( + memo[id(x)] + if id(x) in memo + else (x if _is_immutable(x) else copy.deepcopy(x, memo)) + for x in val + ) + memo[val_id] = resolved + if is_attr: + setattr(target, key, resolved) + else: + target[key] = resolved + elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): + new_obj = copy.copy(val) + memo[val_id] = new_obj + if is_attr: + setattr(target, key, new_obj) + else: + target[key] = new_obj + stack.append((_OBJ_EXPAND, new_obj, iter(_get_obj_attrs(val)))) else: - parent[key] = val - continue + try: + resolved = copy.deepcopy(val, memo) + except Exception: + resolved = val + if is_attr: + setattr(target, key, resolved) + else: + target[key] = resolved - val_id = id(val) - if val_id in memo: - resolved = memo[val_id] - if is_attr: - setattr(parent, key, resolved) + elif task_type == _DICT_EXPAND: + target_dict, it = target, it_or_key + for _ in range(_EXPAND_BATCH_SIZE): + try: + k, v = next(it) + except StopIteration: + break + if _is_immutable(v): + target_dict[k] = v + elif id(v) in memo: + target_dict[k] = memo[id(v)] + else: + stack.append((_DICT_EXPAND, target_dict, it)) + stack.append((_ITEM_TASK, target_dict, k, False, v)) + break else: - parent[key] = resolved - continue + stack.append((_DICT_EXPAND, target_dict, it)) - if isinstance(val, dict): - new_dict: dict[Any, Any] = {} - memo[val_id] = new_dict - if is_attr: - setattr(parent, key, new_dict) - else: - parent[key] = new_dict - for k, v in val.items(): - stack.append((new_dict, k, False, v)) - elif isinstance(val, list): - new_list = [None] * len(val) - memo[val_id] = new_list - if is_attr: - setattr(parent, key, new_list) - else: - parent[key] = new_list - for idx, item in enumerate(val): - stack.append((new_list, idx, False, item)) - elif isinstance(val, tuple): - if all(_is_immutable(x) for x in val): - if is_attr: - setattr(parent, key, val) + elif task_type == _LIST_EXPAND: + target_list, it = target, it_or_key + for _ in range(_EXPAND_BATCH_SIZE): + try: + v = next(it) + except StopIteration: + break + if _is_immutable(v): + target_list.append(v) + elif id(v) in memo: + target_list.append(memo[id(v)]) else: - parent[key] = val + idx = len(target_list) + target_list.append(None) + stack.append((_LIST_EXPAND, target_list, it)) + stack.append((_ITEM_TASK, target_list, idx, False, v)) + break else: - new_list = [None] * len(val) - memo[val_id] = new_list - if is_attr: - setattr(parent, key, new_list) + stack.append((_LIST_EXPAND, target_list, it)) + + elif task_type == _OBJ_EXPAND: + new_obj, it = target, it_or_key + for _ in range(_EXPAND_BATCH_SIZE): + try: + attr, attr_val = next(it) + except StopIteration: + break + if _is_immutable(attr_val): + setattr(new_obj, attr, attr_val) + elif id(attr_val) in memo: + setattr(new_obj, attr, memo[id(attr_val)]) else: - parent[key] = new_list - for idx, item in enumerate(val): - stack.append((new_list, idx, False, item)) - elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): - new_obj = copy.copy(val) - memo[val_id] = new_obj - if is_attr: - setattr(parent, key, new_obj) - else: - parent[key] = new_obj - for attr, attr_val in _get_obj_attrs(val): - stack.append((new_obj, attr, True, attr_val)) - else: - try: - resolved = deepcopy(val, memo) - except Exception: - resolved = val - if is_attr: - setattr(parent, key, resolved) + stack.append((_OBJ_EXPAND, new_obj, it)) + stack.append((_ITEM_TASK, new_obj, attr, True, attr_val)) + break else: - parent[key] = resolved + stack.append((_OBJ_EXPAND, new_obj, it)) return root def _safe_cleanup_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: try: - loop = fut.get_loop() - if loop.is_closed(): - return if fut.done(): if not fut.cancelled(): fut.exception() - else: - fut.cancel() - fut.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) + return + loop = fut.get_loop() + if loop.is_closed(): + return + fut.cancel() + fut.add_done_callback( + lambda t: t.exception() if not t.cancelled() else None + ) except BaseException: pass @@ -1129,7 +1191,9 @@ async def wait_for_review( When on_poll is provided, it must be a callable that accepts the review snapshot and returns None or an awaitable (supporting both sync and - async callbacks). Only reviews fetched and validated before the callback + async callbacks). Callbacks must return promptly even when they return + an awaitable, because the polling deadline cannot interrupt the + invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation @@ -1208,6 +1272,17 @@ async def wait_for_review( async def _runner() -> None: nonlocal wrapper_started wrapper_started = True + deadline_val = _transport.DEADLINE.get() + if deadline_val is not None and monotonic() > deadline_val: + if ( + iscoroutine(coro) + and getcoroutinestate(coro) == CORO_CREATED + ): + try: + coro.close() + except BaseException: + pass + return try: await coro finally: diff --git a/tests/test_http.py b/tests/test_http.py index 1325adff..04e78b06 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2814,7 +2814,7 @@ async def async_mutating_callback(r: Any) -> None: assert res.review.actions.publish is False assert "mutated" not in res.review.additional_properties - # Assert deeply nested extension fields do not trigger RecursionError in snapshot + # Test snapshot directly with an in-memory deep extension and custom tuple to bypass HTTP JSON deep_container: dict[str, Any] = {} curr = deep_container for _ in range(3000): @@ -2822,23 +2822,20 @@ async def async_mutating_callback(r: Any) -> None: curr = curr["child"] curr["val"] = "deepest" - nested_detail_received = False - - def deep_extension_cb(r: Any) -> None: - nonlocal nested_detail_received - assert r.additional_properties["deep"]["child"] is not None - nested_detail_received = True - - deep_review = {**responses[1], "deep": deep_container} - with Server(lambda request, index: Reply(body=deep_review)) as server: - async with session(mode, server.url) as client: - res = await call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=10, - on_poll=deep_extension_cb, - ) - assert res.status == "COMPLETED" - assert nested_detail_received + detail = CustomerReviewDetail.from_dict(responses[1]) + detail.additional_properties["deep"] = deep_container + detail.additional_properties["custom_tuple"] = ({"nested": "val"}, 42) + + from proofline.client import _snapshot_review + + snap = _snapshot_review(detail) + assert snap is not None + assert snap.additional_properties["deep"]["child"] is not None + assert snap is not detail + assert snap.additional_properties is not detail.additional_properties + assert isinstance(snap.additional_properties["custom_tuple"], tuple) + assert ( + snap.additional_properties["custom_tuple"][0] + is not detail.additional_properties["custom_tuple"][0] + ) + assert snap.additional_properties["custom_tuple"][0]["nested"] == "val" From bfa56be2852fce9713faf33117188f779461a284 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:49:59 +0530 Subject: [PATCH 22/75] Address Proofline findings: iterative tuple snapshotting, check loop closed before future wait, close suspended coroutines, and thorough test assertions --- proofline/client.py | 95 +++++++++++++++++++++++++++++++++++++-------- tests/test_http.py | 85 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 162 insertions(+), 18 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 773f5e14..bd0c85c3 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -21,7 +21,7 @@ wait as async_wait, ) from collections.abc import AsyncIterator, Awaitable, Callable, Iterator -from inspect import CORO_CREATED, getcoroutinestate, isawaitable, iscoroutine +from inspect import CORO_CREATED, CORO_SUSPENDED, getcoroutinestate, isawaitable, iscoroutine from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -249,6 +249,8 @@ def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: _DICT_EXPAND = 2 _LIST_EXPAND = 3 _OBJ_EXPAND = 4 +_TUPLE_EXPAND = 5 +_TUPLE_FINALIZE = 6 _EXPAND_BATCH_SIZE = 64 @@ -306,20 +308,26 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non target[key] = new_list stack.append((_LIST_EXPAND, new_list, iter(val))) elif isinstance(val, tuple): - if all(_is_immutable(x) for x in val): - resolved = val + if len(val) == 0: + memo[val_id] = () + if is_attr: + setattr(target, key, ()) + else: + target[key] = () else: - resolved = tuple( - memo[id(x)] - if id(x) in memo - else (x if _is_immutable(x) else copy.deepcopy(x, memo)) - for x in val + temp_list: list[Any] = [] + stack.append( + ( + _TUPLE_FINALIZE, + target, + key, + is_attr, + val_id, + val, + temp_list, + ) ) - memo[val_id] = resolved - if is_attr: - setattr(target, key, resolved) - else: - target[key] = resolved + stack.append((_TUPLE_EXPAND, temp_list, iter(val))) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): new_obj = copy.copy(val) memo[val_id] = new_obj @@ -394,6 +402,44 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: stack.append((_OBJ_EXPAND, new_obj, it)) + elif task_type == _TUPLE_EXPAND: + temp_list, it = target, it_or_key + for _ in range(_EXPAND_BATCH_SIZE): + try: + v = next(it) + except StopIteration: + break + if _is_immutable(v): + temp_list.append(v) + elif id(v) in memo: + temp_list.append(memo[id(v)]) + else: + idx = len(temp_list) + temp_list.append(None) + stack.append((_TUPLE_EXPAND, temp_list, it)) + stack.append((_ITEM_TASK, temp_list, idx, False, v)) + break + else: + stack.append((_TUPLE_EXPAND, temp_list, it)) + + elif task_type == _TUPLE_FINALIZE: + key, is_attr, val_id, orig_val, temp_list = ( + it_or_key, + extra[0], + extra[1], + extra[2], + extra[3], + ) + if all(a is b for a, b in zip(orig_val, temp_list)): + res_tuple = orig_val + else: + res_tuple = tuple(temp_list) + memo[val_id] = res_tuple + if is_attr: + setattr(target, key, res_tuple) + else: + target[key] = res_tuple + return root @@ -1227,7 +1273,10 @@ async def wait_for_review( if isawaitable(res): remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: + if ( + iscoroutine(res) + and getcoroutinestate(res) in (CORO_CREATED, CORO_SUSPENDED) + ): try: res.close() except BaseException: @@ -1242,6 +1291,15 @@ async def wait_for_review( if res.done(): res.result() else: + try: + res_loop = res.get_loop() + except Exception: + res_loop = None + if res_loop is not None and res_loop.is_closed(): + _safe_cleanup_future(res) + if result is not None: + return result + break completed_at: list[float] = [] res.add_done_callback( lambda _: completed_at.append(monotonic()) @@ -1276,7 +1334,8 @@ async def _runner() -> None: if deadline_val is not None and monotonic() > deadline_val: if ( iscoroutine(coro) - and getcoroutinestate(coro) == CORO_CREATED + and getcoroutinestate(coro) + in (CORO_CREATED, CORO_SUSPENDED) ): try: coro.close() @@ -1301,7 +1360,8 @@ async def _runner() -> None: if ( iscoroutine(res) and not wrapper_started - and getcoroutinestate(res) == CORO_CREATED + and getcoroutinestate(res) + in (CORO_CREATED, CORO_SUSPENDED) ): try: res.close() @@ -1322,7 +1382,8 @@ async def _runner() -> None: if ( iscoroutine(res) and not wrapper_started - and getcoroutinestate(res) == CORO_CREATED + and getcoroutinestate(res) + in (CORO_CREATED, CORO_SUSPENDED) ): try: res.close() diff --git a/tests/test_http.py b/tests/test_http.py index 04e78b06..87f18e3c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2633,6 +2633,8 @@ async def async_poll_callback(review_detail: Any) -> None: def inline_sync_cb(r: Any) -> None: sync_calls.append(r.status) r.status = "MUTATED" + r.actions.publish = True + r.additional_properties["mutated"] = "mutated_value" with Server(lambda request, index: Reply(body=responses[index])) as server: async with session("async", server.url) as client: @@ -2647,6 +2649,8 @@ def inline_sync_cb(r: Any) -> None: assert result.status == "COMPLETED" assert sync_calls == ["RUNNING", "COMPLETED"] assert result.review.status == "COMPLETED" + assert result.review.actions.publish is False + assert "mutated" not in result.review.additional_properties # Assert callback TimeoutError before deadline propagates async def failing_callback(r: Any) -> None: @@ -2830,12 +2834,91 @@ async def async_mutating_callback(r: Any) -> None: snap = _snapshot_review(detail) assert snap is not None - assert snap.additional_properties["deep"]["child"] is not None assert snap is not detail assert snap.additional_properties is not detail.additional_properties + + # Walk all 3,000 levels, assert the leaf value, and verify mutation leaves original unchanged + walk_snap = snap.additional_properties["deep"] + walk_orig = detail.additional_properties["deep"] + for _ in range(3000): + assert walk_snap is not walk_orig + walk_snap = walk_snap["child"] + walk_orig = walk_orig["child"] + assert walk_snap["val"] == "deepest" + assert walk_orig["val"] == "deepest" + + walk_snap["val"] = "mutated_leaf" + assert walk_orig["val"] == "deepest" + assert isinstance(snap.additional_properties["custom_tuple"], tuple) assert ( snap.additional_properties["custom_tuple"][0] is not detail.additional_properties["custom_tuple"][0] ) assert snap.additional_properties["custom_tuple"][0]["nested"] == "val" + + # Tuple with deeply nested list must snapshot iteratively without RecursionError + deep_nested_list: Any = "leaf" + for _ in range(3000): + deep_nested_list = [deep_nested_list] + detail.additional_properties["tuple_with_deep_list"] = (deep_nested_list, 999) + snap_nested = _snapshot_review(detail) + assert snap_nested is not None + assert isinstance(snap_nested.additional_properties["tuple_with_deep_list"], tuple) + curr_l = snap_nested.additional_properties["tuple_with_deep_list"][0] + for _ in range(3000): + curr_l = curr_l[0] + assert curr_l == "leaf" + + # Assert pending future on closed loop skips wait + if mode == "async": + other_loop = asyncio.new_event_loop() + closed_fut = other_loop.create_future() + other_loop.close() + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: closed_fut, + ) + assert res.status == "COMPLETED" + + # Assert already-suspended native coroutine is closed if deadline is expired + suspended_cleaned_up = False + + async def coroutine_with_finally() -> None: + nonlocal suspended_cleaned_up + try: + loop = asyncio.get_running_loop() + fut: asyncio.Future[None] = loop.create_future() + await fut + finally: + suspended_cleaned_up = True + + suspended_coro = coroutine_with_finally() + try: + suspended_coro.send(None) + except StopIteration: + pass + + def poll_with_expired_suspended_coro(r: Any) -> Any: + _transport.DEADLINE.set(0.0) + return suspended_coro + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=poll_with_expired_suspended_coro, + ) + assert res.status == "COMPLETED" + assert suspended_cleaned_up From 9ebe0a201ff996aebd5d0af3c5a237c0113ab95a Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sat, 21 Nov 2026 23:59:38 +0530 Subject: [PATCH 23/75] Address Proofline findings: reject foreign-loop futures, reuse memoized tuples in finalization, copy memoryviews, reject unsupported mutables, and enforce safe tuple size --- README.md | 2 +- proofline/client.py | 45 ++++++++++++++++++----- tests/test_http.py | 89 +++++++++++++++++++++++++++++++++++++++------ 3 files changed, 115 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index e310ed79..f1700df2 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any pending futures returned by `on_poll` must belong to the polling event loop. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index bd0c85c3..0a8915a3 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -14,6 +14,9 @@ from asyncio import ( create_task as async_create_task, ) +from asyncio import ( + get_running_loop as async_get_running_loop, +) from asyncio import ( sleep as async_sleep, ) @@ -252,6 +255,7 @@ def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: _TUPLE_EXPAND = 5 _TUPLE_FINALIZE = 6 _EXPAND_BATCH_SIZE = 64 +_MAX_SAFE_TUPLE_SIZE = 1000 def _deadline_expired() -> bool: @@ -308,6 +312,8 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non target[key] = new_list stack.append((_LIST_EXPAND, new_list, iter(val))) elif isinstance(val, tuple): + if len(val) > _MAX_SAFE_TUPLE_SIZE: + return None if len(val) == 0: memo[val_id] = () if is_attr: @@ -328,6 +334,18 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non ) ) stack.append((_TUPLE_EXPAND, temp_list, iter(val))) + elif isinstance(val, (memoryview, bytearray)): + if isinstance(val, bytearray): + resolved = bytearray(val) + elif val.readonly: + resolved = memoryview(bytes(val)) + else: + resolved = memoryview(bytearray(val)) + memo[val_id] = resolved + if is_attr: + setattr(target, key, resolved) + else: + target[key] = resolved elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): new_obj = copy.copy(val) memo[val_id] = new_obj @@ -339,8 +357,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: try: resolved = copy.deepcopy(val, memo) - except Exception: - resolved = val + except Exception as exc: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) from exc + memo[val_id] = resolved if is_attr: setattr(target, key, resolved) else: @@ -430,11 +451,14 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non extra[2], extra[3], ) - if all(a is b for a, b in zip(orig_val, temp_list)): + if val_id in memo: + res_tuple = memo[val_id] + elif all(a is b for a, b in zip(orig_val, temp_list)): res_tuple = orig_val + memo[val_id] = res_tuple else: res_tuple = tuple(temp_list) - memo[val_id] = res_tuple + memo[val_id] = res_tuple if is_attr: setattr(target, key, res_tuple) else: @@ -1237,7 +1261,8 @@ async def wait_for_review( When on_poll is provided, it must be a callable that accepts the review snapshot and returns None or an awaitable (supporting both sync and - async callbacks). Callbacks must return promptly even when they return + async callbacks). Any pending futures returned by on_poll must belong to + the running event loop. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Inline @@ -1295,11 +1320,13 @@ async def wait_for_review( res_loop = res.get_loop() except Exception: res_loop = None - if res_loop is not None and res_loop.is_closed(): + running_loop = async_get_running_loop() + if res_loop is not running_loop or res_loop.is_closed(): _safe_cleanup_future(res) - if result is not None: - return result - break + raise ValueError( + "Pending callback futures must belong " + "to the running event loop." + ) completed_at: list[float] = [] res.add_done_callback( lambda _: completed_at.append(monotonic()) diff --git a/tests/test_http.py b/tests/test_http.py index 87f18e3c..5fa03d5f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2687,6 +2687,7 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: # tasks cannot stall teardown. watchdog_code = """ import asyncio +import time from typing import Any from tests.test_http import session, Server, Reply, review, ORG, REVIEW @@ -2713,15 +2714,19 @@ def pending_future_callback(r: Any) -> asyncio.Future[None]: cancellation_requested = asyncio.Event() cleanup_blocked = asyncio.Event() + cancellation_time = 0.0 async def blocking_cleanup_callback(r: Any) -> None: + nonlocal cancellation_time try: await asyncio.sleep(5.0) except asyncio.CancelledError: + cancellation_time = time.monotonic() cancellation_requested.set() await cleanup_blocked.wait() raise + start_t = time.monotonic() with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session("async", server.url) as client: res = await client.wait_for_review( @@ -2733,19 +2738,24 @@ async def blocking_cleanup_callback(r: Any) -> None: assert res.status == "TIMED_OUT" await asyncio.sleep(0) assert cancellation_requested.is_set() + assert cancellation_time >= start_t + 0.2 - 0.02 cleanup_blocked.set() cancellation_requested_term = asyncio.Event() cleanup_blocked_term = asyncio.Event() + cancellation_time_term = 0.0 async def blocking_cleanup_callback_term(r: Any) -> None: + nonlocal cancellation_time_term try: await asyncio.sleep(5.0) except asyncio.CancelledError: + cancellation_time_term = time.monotonic() cancellation_requested_term.set() await cleanup_blocked_term.wait() raise + start_term_t = time.monotonic() with Server(lambda request, index: Reply(body=review())) as server: async with session("async", server.url) as client: res = await client.wait_for_review( @@ -2757,13 +2767,14 @@ async def blocking_cleanup_callback_term(r: Any) -> None: assert res.status == "COMPLETED" await asyncio.sleep(0) assert cancellation_requested_term.is_set() + assert cancellation_time_term >= start_term_t + 0.2 - 0.02 cleanup_blocked_term.set() resumed_within_budget = False async def suspending_callback(r: Any) -> None: nonlocal resumed_within_budget - await asyncio.sleep(0.05) + await asyncio.sleep(0.2) resumed_within_budget = True with Server(lambda request, index: Reply(body=review())) as server: @@ -2870,7 +2881,7 @@ async def async_mutating_callback(r: Any) -> None: curr_l = curr_l[0] assert curr_l == "leaf" - # Assert pending future on closed loop skips wait + # Assert pending future on closed loop or foreign loop raises ValueError if mode == "async": other_loop = asyncio.new_event_loop() closed_fut = other_loop.create_future() @@ -2878,15 +2889,28 @@ async def async_mutating_callback(r: Any) -> None: with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - res = await call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=10, - on_poll=lambda r: closed_fut, - ) - assert res.status == "COMPLETED" + with pytest.raises(ValueError, match="running event loop"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: closed_fut, + ) + + foreign_loop = asyncio.new_event_loop() + foreign_fut = foreign_loop.create_future() + try: + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="running event loop"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: foreign_fut, + ) + finally: + foreign_loop.close() # Assert already-suspended native coroutine is closed if deadline is expired suspended_cleaned_up = False @@ -2922,3 +2946,46 @@ def poll_with_expired_suspended_coro(r: Any) -> Any: ) assert res.status == "COMPLETED" assert suspended_cleaned_up + + # Cyclic tuple whose list points back to it + cyclic_list: list[Any] = [] + cyclic_tuple = (cyclic_list, "tuple_leaf") + cyclic_list.append(cyclic_tuple) + + detail_cyclic = CustomerReviewDetail.from_dict(responses[1]) + detail_cyclic.additional_properties["cyclic_tuple"] = cyclic_tuple + + snap_cyclic = _snapshot_review(detail_cyclic) + assert snap_cyclic is not None + snap_tup = snap_cyclic.additional_properties["cyclic_tuple"] + snap_lst = snap_tup[0] + assert snap_lst[0] is snap_tup + + # Writable memoryview copied to independent storage + orig_bytearray = bytearray(b"hello") + orig_view = memoryview(orig_bytearray) + detail_view = CustomerReviewDetail.from_dict(responses[1]) + detail_view.additional_properties["memview"] = orig_view + + snap_view = _snapshot_review(detail_view) + assert snap_view is not None + copied_view = snap_view.additional_properties["memview"] + assert isinstance(copied_view, memoryview) + assert not copied_view.readonly + copied_view[0] = ord(b"X") + assert orig_bytearray == bytearray(b"hello") + assert bytes(copied_view) == b"Xello" + + # Unsupported mutable value rejected + import threading + + detail_unsupported = CustomerReviewDetail.from_dict(responses[1]) + detail_unsupported.additional_properties["bad"] = threading.Lock() + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_unsupported) + + # Safe finalization size for tuples skips snapshot delivery + huge_tuple = tuple(range(1001)) + detail_huge = CustomerReviewDetail.from_dict(responses[1]) + detail_huge.additional_properties["huge"] = huge_tuple + assert _snapshot_review(detail_huge) is None From ffd492bb6b49992643e65d42f9df43237cc23d28 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 00:15:15 +0530 Subject: [PATCH 24/75] Address Proofline findings: leave foreign-loop futures untouched, exact immutable scalar types, copy container subclasses, buffer size limits, document snapshot failure modes, and in-memory stubbed watchdog --- README.md | 4 +- proofline/client.py | 73 +++++++++--- tests/test_http.py | 279 +++++++++++++++++++++++++++++--------------- 3 files changed, 249 insertions(+), 107 deletions(-) diff --git a/README.md b/README.md index f1700df2..2ab6a5f9 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any pending futures returned by `on_poll` must belong to the polling event loop. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any pending futures returned by `on_poll` must belong to the polling event loop. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 0a8915a3..0cd78ee1 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -217,14 +217,23 @@ def _export_page_limit(max_pages: int) -> None: raise ValueError("Export pagination requires max_pages 1..1000.") +_IMMUTABLE_TYPES: set[type] = { + int, + float, + str, + bool, + bytes, + UUID, + datetime.date, + datetime.datetime, +} + + def _is_immutable(val: Any) -> bool: return ( val is None or val is UNSET - or isinstance( - val, - (int, float, str, bool, bytes, UUID, datetime.date, datetime.datetime), - ) + or type(val) in _IMMUTABLE_TYPES ) @@ -256,6 +265,7 @@ def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: _TUPLE_FINALIZE = 6 _EXPAND_BATCH_SIZE = 64 _MAX_SAFE_TUPLE_SIZE = 1000 +_MAX_SAFE_BUFFER_SIZE = 65_536 def _deadline_expired() -> bool: @@ -295,7 +305,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: target[key] = resolved continue - if isinstance(val, dict): + if type(val) is dict: new_dict: dict[Any, Any] = {} memo[val_id] = new_dict if is_attr: @@ -303,7 +313,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: target[key] = new_dict stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) - elif isinstance(val, list): + elif type(val) is list: new_list: list[Any] = [] memo[val_id] = new_list if is_attr: @@ -311,7 +321,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: target[key] = new_list stack.append((_LIST_EXPAND, new_list, iter(val))) - elif isinstance(val, tuple): + elif type(val) is tuple: if len(val) > _MAX_SAFE_TUPLE_SIZE: return None if len(val) == 0: @@ -334,7 +344,31 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non ) ) stack.append((_TUPLE_EXPAND, temp_list, iter(val))) + elif isinstance(val, dict): + new_dict = copy.copy(val) + new_dict.clear() + memo[val_id] = new_dict + if is_attr: + setattr(target, key, new_dict) + else: + target[key] = new_dict + stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, new_dict, iter(_get_obj_attrs(val)))) + elif isinstance(val, list): + new_list = copy.copy(val) + new_list.clear() + memo[val_id] = new_list + if is_attr: + setattr(target, key, new_list) + else: + target[key] = new_list + stack.append((_LIST_EXPAND, new_list, iter(val))) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) elif isinstance(val, (memoryview, bytearray)): + if len(val) > _MAX_SAFE_BUFFER_SIZE: + return None if isinstance(val, bytearray): resolved = bytearray(val) elif val.readonly: @@ -469,13 +503,20 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non def _safe_cleanup_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: try: + try: + loop = fut.get_loop() + except Exception: + return + try: + running_loop = async_get_running_loop() + except Exception: + return + if loop is not running_loop or loop.is_closed(): + return if fut.done(): if not fut.cancelled(): fut.exception() return - loop = fut.get_loop() - if loop.is_closed(): - return fut.cancel() fut.add_done_callback( lambda t: t.exception() if not t.cancelled() else None @@ -849,7 +890,10 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. on_poll exceptions propagate even when a terminal outcome + delivery. Oversized tuples or buffers in review extension data skip + on_poll snapshot delivery even with time remaining, and snapshot copy + errors on unsupported mutable values propagate before on_poll runs. + on_poll exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. @@ -1265,8 +1309,11 @@ async def wait_for_review( the running event loop. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback - is reached are delivered; deadline expiry can suppress delivery. Inline - failures and awaitable failures observed before the deadline propagate, + is reached are delivered; deadline expiry can suppress delivery. Oversized + tuples or buffers in review extension data skip on_poll snapshot delivery + even with time remaining, and snapshot copy errors on unsupported mutable + values propagate before on_poll runs. Inline failures and awaitable failures + observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. Synchronous callbacks must return before a terminal result can be delivered and the diff --git a/tests/test_http.py b/tests/test_http.py index 5fa03d5f..8c2f1bed 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2689,109 +2689,154 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: import asyncio import time from typing import Any -from tests.test_http import session, Server, Reply, review, ORG, REVIEW +from proofline import AsyncProoflineClient +from proofline._generated.models.customer_review_detail import CustomerReviewDetail +from tests.test_http import review, ORG, REVIEW async def main() -> None: - pending_fut: asyncio.Future[None] | None = None + running_detail = CustomerReviewDetail.from_dict(review("RUNNING")) + completed_detail = CustomerReviewDetail.from_dict(review()) - def pending_future_callback(r: Any) -> asyncio.Future[None]: - nonlocal pending_fut - loop = asyncio.get_running_loop() - pending_fut = loop.create_future() - return pending_fut + async def fake_running(org: Any, rev: Any) -> Any: + return running_detail - with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: - async with session("async", server.url) as client: - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=pending_future_callback, - ) - assert res.status == "TIMED_OUT" - assert pending_fut is not None - assert pending_fut.cancelled() + async def fake_completed(org: Any, rev: Any) -> Any: + return completed_detail - cancellation_requested = asyncio.Event() - cleanup_blocked = asyncio.Event() - cancellation_time = 0.0 + async with AsyncProoflineClient( + token="test_token", base_url="https://api.proofline.sh" + ) as client: + # Case 1: Pending same-loop Future that times out + pending_fut: asyncio.Future[None] | None = None - async def blocking_cleanup_callback(r: Any) -> None: - nonlocal cancellation_time - try: - await asyncio.sleep(5.0) - except asyncio.CancelledError: - cancellation_time = time.monotonic() - cancellation_requested.set() - await cleanup_blocked.wait() - raise - - start_t = time.monotonic() - with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: - async with session("async", server.url) as client: - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=blocking_cleanup_callback, - ) - assert res.status == "TIMED_OUT" - await asyncio.sleep(0) - assert cancellation_requested.is_set() - assert cancellation_time >= start_t + 0.2 - 0.02 - cleanup_blocked.set() - - cancellation_requested_term = asyncio.Event() - cleanup_blocked_term = asyncio.Event() - cancellation_time_term = 0.0 - - async def blocking_cleanup_callback_term(r: Any) -> None: - nonlocal cancellation_time_term - try: - await asyncio.sleep(5.0) - except asyncio.CancelledError: - cancellation_time_term = time.monotonic() - cancellation_requested_term.set() - await cleanup_blocked_term.wait() - raise - - start_term_t = time.monotonic() - with Server(lambda request, index: Reply(body=review())) as server: - async with session("async", server.url) as client: - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=blocking_cleanup_callback_term, - ) - assert res.status == "COMPLETED" - await asyncio.sleep(0) - assert cancellation_requested_term.is_set() - assert cancellation_time_term >= start_term_t + 0.2 - 0.02 - cleanup_blocked_term.set() - - resumed_within_budget = False - - async def suspending_callback(r: Any) -> None: - nonlocal resumed_within_budget - await asyncio.sleep(0.2) - resumed_within_budget = True - - with Server(lambda request, index: Reply(body=review())) as server: - async with session("async", server.url) as client: - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=5.0, - on_poll=suspending_callback, - ) - assert res.status == "COMPLETED" - assert resumed_within_budget + def pending_future_callback(r: Any) -> asyncio.Future[None]: + nonlocal pending_fut + loop = asyncio.get_running_loop() + pending_fut = loop.create_future() + return pending_fut + + client.get_review = fake_running # type: ignore + + start_t1 = time.monotonic() + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=pending_future_callback, + ) + assert res.status == "TIMED_OUT" + assert pending_fut is not None + assert pending_fut.cancelled() + assert time.monotonic() >= start_t1 + 0.2 - 0.02 + + # Case 2: Pending same-loop Future that completes within budget without cancellation + completed_fut = asyncio.get_running_loop().create_future() + + async def complete_fut_soon() -> None: + await asyncio.sleep(0.05) + completed_fut.set_result(None) + + def completing_future_callback(r: Any) -> asyncio.Future[None]: + asyncio.create_task(complete_fut_soon()) + return completed_fut + + client.get_review = fake_completed # type: ignore + + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=completing_future_callback, + ) + assert res.status == "COMPLETED" + assert completed_fut.done() + assert not completed_fut.cancelled() + + # Case 3: Blocking cleanup callback on non-terminal review + cancellation_requested = asyncio.Event() + cleanup_blocked = asyncio.Event() + cancellation_time = 0.0 + + async def blocking_cleanup_callback(r: Any) -> None: + nonlocal cancellation_time + try: + await asyncio.sleep(5.0) + except asyncio.CancelledError: + cancellation_time = time.monotonic() + cancellation_requested.set() + await cleanup_blocked.wait() + raise + + client.get_review = fake_running # type: ignore + + start_t3 = time.monotonic() + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=blocking_cleanup_callback, + ) + assert res.status == "TIMED_OUT" + await asyncio.sleep(0) + assert cancellation_requested.is_set() + assert cancellation_time >= start_t3 + 0.2 - 0.02 + cleanup_blocked.set() + + # Case 4: Blocking cleanup callback on terminal review + cancellation_requested_term = asyncio.Event() + cleanup_blocked_term = asyncio.Event() + cancellation_time_term = 0.0 + + async def blocking_cleanup_callback_term(r: Any) -> None: + nonlocal cancellation_time_term + try: + await asyncio.sleep(5.0) + except asyncio.CancelledError: + cancellation_time_term = time.monotonic() + cancellation_requested_term.set() + await cleanup_blocked_term.wait() + raise + + client.get_review = fake_completed # type: ignore + + start_t4 = time.monotonic() + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=blocking_cleanup_callback_term, + ) + assert res.status == "COMPLETED" + await asyncio.sleep(0) + assert cancellation_requested_term.is_set() + assert cancellation_time_term >= start_t4 + 0.2 - 0.02 + cleanup_blocked_term.set() + + # Case 5: Suspending callback that succeeds within budget + resumed_within_budget = False + + async def suspending_callback(r: Any) -> None: + nonlocal resumed_within_budget + await asyncio.sleep(0.2) + resumed_within_budget = True + + client.get_review = fake_completed # type: ignore + + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=suspending_callback, + ) + assert res.status == "COMPLETED" + assert resumed_within_budget asyncio.run(main()) """ + checkout_root = Path(__file__).resolve().parent.parent subprocess.run( [sys.executable, "-c", watchdog_code], + cwd=str(checkout_root), check=True, timeout=10, ) @@ -2876,10 +2921,14 @@ async def async_mutating_callback(r: Any) -> None: snap_nested = _snapshot_review(detail) assert snap_nested is not None assert isinstance(snap_nested.additional_properties["tuple_with_deep_list"], tuple) + orig_l = detail.additional_properties["tuple_with_deep_list"][0] curr_l = snap_nested.additional_properties["tuple_with_deep_list"][0] for _ in range(3000): + assert curr_l is not orig_l curr_l = curr_l[0] + orig_l = orig_l[0] assert curr_l == "leaf" + assert orig_l == "leaf" # Assert pending future on closed loop or foreign loop raises ValueError if mode == "async": @@ -2989,3 +3038,49 @@ def poll_with_expired_suspended_coro(r: Any) -> Any: detail_huge = CustomerReviewDetail.from_dict(responses[1]) detail_huge.additional_properties["huge"] = huge_tuple assert _snapshot_review(detail_huge) is None + + # Oversized buffer skips snapshot delivery + oversized_buf = bytearray(65_537) + detail_buf = CustomerReviewDetail.from_dict(responses[1]) + detail_buf.additional_properties["buf"] = oversized_buf + assert _snapshot_review(detail_buf) is None + + # Scalar subclass instance and attributes copied + class CustomStr(str): + pass + + custom_scalar = CustomStr("scalar_val") + custom_scalar.attached_list = ["mut"] # type: ignore[attr-defined] + detail_scalar = CustomerReviewDetail.from_dict(responses[1]) + detail_scalar.additional_properties["scalar"] = custom_scalar + + snap_scalar = _snapshot_review(detail_scalar) + assert snap_scalar is not None + copied_scalar = snap_scalar.additional_properties["scalar"] + assert type(copied_scalar) is CustomStr + assert copied_scalar is not custom_scalar + assert copied_scalar.attached_list is not custom_scalar.attached_list + assert copied_scalar.attached_list == ["mut"] + + # Container subclass (defaultdict) preserves type, default_factory, and attributes + from collections import defaultdict + + class CustomDict(defaultdict[str, list[str]]): + pass + + dd = CustomDict(list) + dd["k"].append("val") + dd.extra_attr = ["extra"] # type: ignore[attr-defined] + detail_dd = CustomerReviewDetail.from_dict(responses[1]) + detail_dd.additional_properties["dd"] = dd + + snap_dd = _snapshot_review(detail_dd) + assert snap_dd is not None + copied_dd = snap_dd.additional_properties["dd"] + assert isinstance(copied_dd, CustomDict) + assert copied_dd is not dd + assert copied_dd["k"] is not dd["k"] + assert copied_dd["k"] == ["val"] + assert copied_dd["missing"] == [] + assert copied_dd.extra_attr is not dd.extra_attr + assert copied_dd.extra_attr == ["extra"] From dd2f57d674c162e465f1f3bc50bf54fd744667d9 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 00:22:31 +0530 Subject: [PATCH 25/75] Address Proofline findings: reject already-suspended coroutines, close unstarted generators/coroutines inline, traverse private and dict slots, check multidimensional buffer nbytes, and bound timeout elapsed times --- proofline/client.py | 130 +++++++++++++++++++++++++++++--------------- tests/test_http.py | 89 +++++++++++++++++++++--------- 2 files changed, 148 insertions(+), 71 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 0cd78ee1..a0d7ce3a 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -24,7 +24,15 @@ wait as async_wait, ) from collections.abc import AsyncIterator, Awaitable, Callable, Iterator -from inspect import CORO_CREATED, CORO_SUSPENDED, getcoroutinestate, isawaitable, iscoroutine +from inspect import ( + CORO_CREATED, + GEN_CREATED, + getcoroutinestate, + getgeneratorstate, + isawaitable, + iscoroutine, + isgenerator, +) from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -238,23 +246,29 @@ def _is_immutable(val: Any) -> bool: def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: - if hasattr(obj, "__dict__"): - return list(obj.__dict__.items()) - slots: set[str] = set() + result: dict[str, Any] = {} + if hasattr(obj, "__dict__") and isinstance(obj.__dict__, dict): + result.update(obj.__dict__) + for cls in type(obj).__mro__: - s = getattr(cls, "__slots__", None) - if s: - if isinstance(s, str): - slots.add(s) - else: - slots.update(s) - result: list[tuple[str, Any]] = [] - for attr in slots: - if attr.startswith("__") and attr.endswith("__"): + raw_slots = getattr(cls, "__slots__", None) + if not raw_slots: continue - if hasattr(obj, attr): - result.append((attr, getattr(obj, attr))) - return result + slot_names = [raw_slots] if isinstance(raw_slots, str) else raw_slots + for s in slot_names: + if s in ("__dict__", "__weakref__"): + continue + if s.startswith("__") and not s.endswith("__"): + attr_name = f"_{cls.__name__.lstrip('_')}{s}" + else: + attr_name = s + if attr_name not in result and hasattr(obj, attr_name): + try: + result[attr_name] = getattr(obj, attr_name) + except AttributeError: + pass + + return list(result.items()) _ITEM_TASK = 1 @@ -367,7 +381,8 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) elif isinstance(val, (memoryview, bytearray)): - if len(val) > _MAX_SAFE_BUFFER_SIZE: + byte_count = val.nbytes if isinstance(val, memoryview) else len(val) + if byte_count > _MAX_SAFE_BUFFER_SIZE: return None if isinstance(val, bytearray): resolved = bytearray(val) @@ -1343,12 +1358,19 @@ async def wait_for_review( if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) if isawaitable(res): + if iscoroutine(res) and getcoroutinestate(res) != CORO_CREATED: + raise ValueError("Callbacks must return unstarted coroutines.") + if isgenerator(res) and getgeneratorstate(res) != GEN_CREATED: + raise ValueError("Callbacks must return unstarted coroutines.") + remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - if ( - iscoroutine(res) - and getcoroutinestate(res) in (CORO_CREATED, CORO_SUSPENDED) - ): + if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: + try: + res.close() + except BaseException: + pass + elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: try: res.close() except BaseException: @@ -1369,7 +1391,6 @@ async def wait_for_review( res_loop = None running_loop = async_get_running_loop() if res_loop is not running_loop or res_loop.is_closed(): - _safe_cleanup_future(res) raise ValueError( "Pending callback futures must belong " "to the running event loop." @@ -1408,8 +1429,15 @@ async def _runner() -> None: if deadline_val is not None and monotonic() > deadline_val: if ( iscoroutine(coro) - and getcoroutinestate(coro) - in (CORO_CREATED, CORO_SUSPENDED) + and getcoroutinestate(coro) == CORO_CREATED + ): + try: + coro.close() + except BaseException: + pass + elif ( + isgenerator(coro) + and getgeneratorstate(coro) == GEN_CREATED ): try: coro.close() @@ -1431,16 +1459,23 @@ async def _runner() -> None: task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - if ( - iscoroutine(res) - and not wrapper_started - and getcoroutinestate(res) - in (CORO_CREATED, CORO_SUSPENDED) - ): - try: - res.close() - except BaseException: - pass + if not wrapper_started: + if ( + iscoroutine(res) + and getcoroutinestate(res) == CORO_CREATED + ): + try: + res.close() + except BaseException: + pass + elif ( + isgenerator(res) + and getgeneratorstate(res) == GEN_CREATED + ): + try: + res.close() + except BaseException: + pass raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( @@ -1453,16 +1488,23 @@ async def _runner() -> None: task.add_done_callback( lambda t: t.exception() if not t.cancelled() else None ) - if ( - iscoroutine(res) - and not wrapper_started - and getcoroutinestate(res) - in (CORO_CREATED, CORO_SUSPENDED) - ): - try: - res.close() - except BaseException: - pass + if not wrapper_started: + if ( + iscoroutine(res) + and getcoroutinestate(res) == CORO_CREATED + ): + try: + res.close() + except BaseException: + pass + elif ( + isgenerator(res) + and getgeneratorstate(res) == GEN_CREATED + ): + try: + res.close() + except BaseException: + pass if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index 8c2f1bed..d68ab62b 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2724,10 +2724,11 @@ def pending_future_callback(r: Any) -> asyncio.Future[None]: timeout=0.2, on_poll=pending_future_callback, ) + elapsed1 = time.monotonic() - start_t1 assert res.status == "TIMED_OUT" assert pending_fut is not None assert pending_fut.cancelled() - assert time.monotonic() >= start_t1 + 0.2 - 0.02 + assert 0.18 <= elapsed1 <= 0.35 # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() @@ -2776,10 +2777,12 @@ async def blocking_cleanup_callback(r: Any) -> None: timeout=0.2, on_poll=blocking_cleanup_callback, ) + elapsed3 = time.monotonic() - start_t3 assert res.status == "TIMED_OUT" await asyncio.sleep(0) assert cancellation_requested.is_set() assert cancellation_time >= start_t3 + 0.2 - 0.02 + assert 0.18 <= elapsed3 <= 0.35 cleanup_blocked.set() # Case 4: Blocking cleanup callback on terminal review @@ -2806,10 +2809,12 @@ async def blocking_cleanup_callback_term(r: Any) -> None: timeout=0.2, on_poll=blocking_cleanup_callback_term, ) + elapsed4 = time.monotonic() - start_t4 assert res.status == "COMPLETED" await asyncio.sleep(0) assert cancellation_requested_term.is_set() assert cancellation_time_term >= start_t4 + 0.2 - 0.02 + assert 0.18 <= elapsed4 <= 0.35 cleanup_blocked_term.set() # Case 5: Suspending callback that succeeds within budget @@ -2961,40 +2966,25 @@ async def async_mutating_callback(r: Any) -> None: finally: foreign_loop.close() - # Assert already-suspended native coroutine is closed if deadline is expired - suspended_cleaned_up = False + # Assert already-suspended native coroutine is rejected at callback boundary + async def dummy_coro() -> None: + await asyncio.sleep(0) - async def coroutine_with_finally() -> None: - nonlocal suspended_cleaned_up - try: - loop = asyncio.get_running_loop() - fut: asyncio.Future[None] = loop.create_future() - await fut - finally: - suspended_cleaned_up = True - - suspended_coro = coroutine_with_finally() + suspended_coro = dummy_coro() try: suspended_coro.send(None) except StopIteration: pass - def poll_with_expired_suspended_coro(r: Any) -> Any: - _transport.DEADLINE.set(0.0) - return suspended_coro - with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - res = await call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=10, - on_poll=poll_with_expired_suspended_coro, - ) - assert res.status == "COMPLETED" - assert suspended_cleaned_up + with pytest.raises(ValueError, match="unstarted coroutines"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: suspended_coro, + ) # Cyclic tuple whose list points back to it cyclic_list: list[Any] = [] @@ -3007,7 +2997,9 @@ def poll_with_expired_suspended_coro(r: Any) -> Any: snap_cyclic = _snapshot_review(detail_cyclic) assert snap_cyclic is not None snap_tup = snap_cyclic.additional_properties["cyclic_tuple"] + assert snap_tup is not cyclic_tuple snap_lst = snap_tup[0] + assert snap_lst is not cyclic_list assert snap_lst[0] is snap_tup # Writable memoryview copied to independent storage @@ -3045,6 +3037,15 @@ def poll_with_expired_suspended_coro(r: Any) -> Any: detail_buf.additional_properties["buf"] = oversized_buf assert _snapshot_review(detail_buf) is None + # Multidimensional memoryview checks nbytes against cap + multi_dim_raw = bytearray(100_000) + multi_dim_view = memoryview(multi_dim_raw).cast("B", shape=[10, 10_000]) + assert len(multi_dim_view) == 10 + assert multi_dim_view.nbytes == 100_000 + detail_multi_dim = CustomerReviewDetail.from_dict(responses[1]) + detail_multi_dim.additional_properties["multi_dim"] = multi_dim_view + assert _snapshot_review(detail_multi_dim) is None + # Scalar subclass instance and attributes copied class CustomStr(str): pass @@ -3084,3 +3085,37 @@ class CustomDict(defaultdict[str, list[str]]): assert copied_dd["missing"] == [] assert copied_dd.extra_attr is not dd.extra_attr assert copied_dd.extra_attr == ["extra"] + + # Traverse dictionary entries and slot descriptors including private slots + class SlotBase: + __slots__ = ("__private_slot", "public_slot") + + def __init__(self) -> None: + self.__private_slot = ["private_secret"] + self.public_slot = ["public_secret"] + + class SlotDerived(SlotBase): + pass + + slot_obj = SlotDerived() + slot_obj.extra_dict_attr = ["extra"] + + detail_slot = CustomerReviewDetail.from_dict(responses[1]) + detail_slot.additional_properties["slot_obj"] = slot_obj + + snap_slot = _snapshot_review(detail_slot) + assert snap_slot is not None + copied_slot_obj = snap_slot.additional_properties["slot_obj"] + assert copied_slot_obj is not slot_obj + assert ( + copied_slot_obj._SlotBase__private_slot # type: ignore[attr-defined] + is not slot_obj._SlotBase__private_slot + ) + assert ( + copied_slot_obj._SlotBase__private_slot # type: ignore[attr-defined] + == ["private_secret"] + ) + assert copied_slot_obj.public_slot is not slot_obj.public_slot + assert copied_slot_obj.public_slot == ["public_secret"] + assert copied_slot_obj.extra_dict_attr is not slot_obj.extra_dict_attr + assert copied_slot_obj.extra_dict_attr == ["extra"] From 0e26f2482f159c670a42e508757fbebd02f34765 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 00:36:03 +0530 Subject: [PATCH 26/75] Address Proofline findings: document unstarted coroutines, check deadline before coroutine validation, isolate tuple subclasses, and assert delivery order with request counts --- README.md | 2 +- proofline/client.py | 64 +++++++++++++++++------------ tests/test_http.py | 98 +++++++++++++++++++++++++++++++++++---------- 3 files changed, 116 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 2ab6a5f9..f43bd790 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any pending futures returned by `on_poll` must belong to the polling event loop. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index a0d7ce3a..18a397de 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -110,6 +110,8 @@ async def _await_res(res: Awaitable[Any]) -> None: await res + + AgentSessionPrompt = AgentSessionPromptType0 | AgentSessionPromptType1 _AgentSessionPromptModels = tuple[type[AgentSessionPromptType0], type[AgentSessionPromptType1]] _AGENT_SESSION_PROMPT_MODELS: _AgentSessionPromptModels = ( @@ -238,11 +240,7 @@ def _export_page_limit(max_pages: int) -> None: def _is_immutable(val: Any) -> bool: - return ( - val is None - or val is UNSET - or type(val) in _IMMUTABLE_TYPES - ) + return val is None or val is UNSET or type(val) in _IMMUTABLE_TYPES def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: @@ -335,15 +333,25 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: target[key] = new_list stack.append((_LIST_EXPAND, new_list, iter(val))) - elif type(val) is tuple: + elif isinstance(val, tuple): if len(val) > _MAX_SAFE_TUPLE_SIZE: return None if len(val) == 0: - memo[val_id] = () + if type(val) is tuple: + res_empty: Any = () + else: + try: + val_cls: Any = type(val) + res_empty = val_cls() + except Exception: + res_empty = () + memo[val_id] = res_empty + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, res_empty, iter(_get_obj_attrs(val)))) if is_attr: - setattr(target, key, ()) + setattr(target, key, res_empty) else: - target[key] = () + target[key] = res_empty else: temp_list: list[Any] = [] stack.append( @@ -506,8 +514,17 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non res_tuple = orig_val memo[val_id] = res_tuple else: - res_tuple = tuple(temp_list) + if type(orig_val) is tuple: + res_tuple = tuple(temp_list) + else: + try: + orig_cls: Any = type(orig_val) + res_tuple = orig_cls(temp_list) + except Exception: + res_tuple = tuple(temp_list) memo[val_id] = res_tuple + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + stack.append((_OBJ_EXPAND, res_tuple, iter(_get_obj_attrs(orig_val)))) if is_attr: setattr(target, key, res_tuple) else: @@ -533,9 +550,7 @@ def _safe_cleanup_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: fut.exception() return fut.cancel() - fut.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) + fut.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) except BaseException: pass @@ -1320,8 +1335,9 @@ async def wait_for_review( When on_poll is provided, it must be a callable that accepts the review snapshot and returns None or an awaitable (supporting both sync and - async callbacks). Any pending futures returned by on_poll must belong to - the running event loop. Callbacks must return promptly even when they return + async callbacks). Any coroutines returned by on_poll must be unstarted, and + any pending futures returned by on_poll must belong to the running event + loop. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Oversized @@ -1358,11 +1374,6 @@ async def wait_for_review( if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) if isawaitable(res): - if iscoroutine(res) and getcoroutinestate(res) != CORO_CREATED: - raise ValueError("Callbacks must return unstarted coroutines.") - if isgenerator(res) and getgeneratorstate(res) != GEN_CREATED: - raise ValueError("Callbacks must return unstarted coroutines.") - remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: @@ -1381,6 +1392,11 @@ async def wait_for_review( return result break + if iscoroutine(res) and getcoroutinestate(res) != CORO_CREATED: + raise ValueError("Callbacks must return unstarted coroutines.") + if isgenerator(res) and getgeneratorstate(res) != GEN_CREATED: + raise ValueError("Callbacks must return unstarted coroutines.") + if isinstance(res, (AsyncTask, AsyncFuture)): if res.done(): res.result() @@ -1400,9 +1416,7 @@ async def wait_for_review( lambda _: completed_at.append(monotonic()) ) try: - done, _ = await async_wait( - {res}, timeout=remaining_budget - ) + done, _ = await async_wait({res}, timeout=remaining_budget) except BaseException: _safe_cleanup_future(res) raise @@ -1451,9 +1465,7 @@ async def _runner() -> None: task = async_create_task(_runner()) try: - done, _ = await async_wait( - {task}, timeout=remaining_budget - ) + done, _ = await async_wait({task}, timeout=remaining_budget) except BaseException: task.cancel() task.add_done_callback( diff --git a/tests/test_http.py b/tests/test_http.py index d68ab62b..2a11bd27 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2593,22 +2593,22 @@ async def test_wait_for_review_invokes_on_poll_callback( mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: clock = Clock(monkeypatch) - calls: list[str] = [] + calls: list[tuple[str, int]] = [] + responses = [review("RUNNING"), review()] - def sync_poll_callback(review_detail: Any) -> None: - calls.append(f"sync:{review_detail.status}") - if review_detail.status == "RUNNING": - assert review_detail.completed_at is UNSET + with Server(lambda request, index: Reply(body=responses[index])) as server: - async def async_poll_callback(review_detail: Any) -> None: - calls.append(f"async:{review_detail.status}") - if review_detail.status == "RUNNING": - assert review_detail.completed_at is UNSET - review_detail.status = "MUTATED" + def sync_poll_callback(review_detail: Any) -> None: + calls.append((f"sync:{review_detail.status}", len(server.requests))) + if review_detail.status == "RUNNING": + assert review_detail.completed_at is UNSET - responses = [review("RUNNING"), review()] + async def async_poll_callback(review_detail: Any) -> None: + calls.append((f"async:{review_detail.status}", len(server.requests))) + if review_detail.status == "RUNNING": + assert review_detail.completed_at is UNSET + review_detail.status = "MUTATED" - with Server(lambda request, index: Reply(body=responses[index])) as server: async with session(mode, server.url) as client: cb = async_poll_callback if mode == "async" else sync_poll_callback result = await call( @@ -2621,22 +2621,22 @@ async def async_poll_callback(review_detail: Any) -> None: ) assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) prefix = "async" if mode == "async" else "sync" - assert calls == [f"{prefix}:RUNNING", f"{prefix}:COMPLETED"] + assert calls == [(f"{prefix}:RUNNING", 1), (f"{prefix}:COMPLETED", 2)] assert result.review.status == "COMPLETED" assert len(server.requests) == 2 assert clock.delays == [5] # Assert async client also works with regular synchronous callbacks returning None if mode == "async": - sync_calls: list[str] = [] + with Server(lambda request, index: Reply(body=responses[index])) as server: + sync_calls: list[tuple[str, int]] = [] - def inline_sync_cb(r: Any) -> None: - sync_calls.append(r.status) - r.status = "MUTATED" - r.actions.publish = True - r.additional_properties["mutated"] = "mutated_value" + def inline_sync_cb(r: Any) -> None: + sync_calls.append((r.status, len(server.requests))) + r.status = "MUTATED" + r.actions.publish = True + r.additional_properties["mutated"] = "mutated_value" - with Server(lambda request, index: Reply(body=responses[index])) as server: async with session("async", server.url) as client: result = await call( client, @@ -2647,7 +2647,7 @@ def inline_sync_cb(r: Any) -> None: on_poll=inline_sync_cb, ) assert result.status == "COMPLETED" - assert sync_calls == ["RUNNING", "COMPLETED"] + assert sync_calls == [("RUNNING", 1), ("COMPLETED", 2)] assert result.review.status == "COMPLETED" assert result.review.actions.publish is False assert "mutated" not in result.review.additional_properties @@ -2950,6 +2950,7 @@ async def async_mutating_callback(r: Any) -> None: timeout=10, on_poll=lambda r: closed_fut, ) + assert not closed_fut.done() foreign_loop = asyncio.new_event_loop() foreign_fut = foreign_loop.create_future() @@ -2963,6 +2964,7 @@ async def async_mutating_callback(r: Any) -> None: timeout=10, on_poll=lambda r: foreign_fut, ) + assert not foreign_fut.done() finally: foreign_loop.close() @@ -2986,6 +2988,34 @@ async def dummy_coro() -> None: on_poll=lambda r: suspended_coro, ) + # Started coroutine left untouched on deadline expiry + async def dummy_started() -> None: + await asyncio.sleep(10) + + started_c = dummy_started() + task_started = asyncio.create_task(started_c) + await asyncio.sleep(0) + + def started_coro_cb(r: Any) -> Any: + clock.now += 100.0 + return started_c + + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + res_expired = await client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=started_coro_cb, + ) + assert res_expired.status == "TIMED_OUT" + assert inspect.getcoroutinestate(started_c) == inspect.CORO_SUSPENDED + task_started.cancel() + try: + await task_started + except asyncio.CancelledError: + pass + # Cyclic tuple whose list points back to it cyclic_list: list[Any] = [] cyclic_tuple = (cyclic_list, "tuple_leaf") @@ -3119,3 +3149,29 @@ class SlotDerived(SlotBase): assert copied_slot_obj.public_slot == ["public_secret"] assert copied_slot_obj.extra_dict_attr is not slot_obj.extra_dict_attr assert copied_slot_obj.extra_dict_attr == ["extra"] + + # Tuple subclass preserves type, isolates elements, copies attributes, and respects size limit + class CustomTuple(tuple[Any, ...]): + pass + + ct = CustomTuple(([1, 2], {"a": "b"})) + ct.extra = ["tuple_attr"] # type: ignore[attr-defined] + detail_ct = CustomerReviewDetail.from_dict(responses[1]) + detail_ct.additional_properties["ct"] = ct + + snap_ct = _snapshot_review(detail_ct) + assert snap_ct is not None + copied_ct = snap_ct.additional_properties["ct"] + assert type(copied_ct) is CustomTuple + assert copied_ct is not ct + assert copied_ct[0] is not ct[0] + assert copied_ct[0] == [1, 2] + assert copied_ct[1] is not ct[1] + assert copied_ct[1] == {"a": "b"} + assert copied_ct.extra is not ct.extra + assert copied_ct.extra == ["tuple_attr"] + + huge_ct = CustomTuple(range(1001)) + detail_huge_ct = CustomerReviewDetail.from_dict(responses[1]) + detail_huge_ct.additional_properties["huge_ct"] = huge_ct + assert _snapshot_review(detail_huge_ct) is None From 758d45b8b037b02e3f45dcb702fafcca92e962d1 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 00:51:33 +0530 Subject: [PATCH 27/75] Address Proofline findings: safe wrapper cancellation, recompute remaining budget after setup, document copy error mismatch, and assert watchdog remaining budget --- README.md | 2 +- proofline/client.py | 99 +++++++++++++++++++++-------------------- tests/test_http.py | 104 +++++++++++++++++++++++++++++++++++++++----- 3 files changed, 147 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index f43bd790..b5de5b8c 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ if outcome.status != "COMPLETED": With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 18a397de..a0cd0155 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -510,7 +510,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non ) if val_id in memo: res_tuple = memo[val_id] - elif all(a is b for a, b in zip(orig_val, temp_list)): + elif type(orig_val) is tuple and all(a is b for a, b in zip(orig_val, temp_list)): res_tuple = orig_val memo[val_id] = res_tuple else: @@ -549,10 +549,45 @@ def _safe_cleanup_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: if not fut.cancelled(): fut.exception() return - fut.cancel() - fut.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) + try: + fut.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) + except BaseException: + pass + try: + fut.cancel() + except BaseException: + pass + except BaseException: + pass + + +def _safe_cleanup_task( + task: AsyncTask[Any], + res: Any, + wrapper_started: bool, +) -> None: + try: + try: + task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) + except BaseException: + pass + try: + task.cancel() + except BaseException: + pass except BaseException: pass + if not wrapper_started: + if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: + try: + res.close() + except BaseException: + pass + elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: + try: + res.close() + except BaseException: + pass def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None: @@ -1323,7 +1358,7 @@ async def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, - on_poll: Callable[[CustomerReviewDetail], Awaitable[None] | None] | None = None, + on_poll: Callable[[CustomerReviewDetail], Awaitable[object] | None] | None = None, ) -> ReviewOutcome: """Wait for recorded review completion or return TIMED_OUT. @@ -1415,6 +1450,12 @@ async def wait_for_review( res.add_done_callback( lambda _: completed_at.append(monotonic()) ) + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _safe_cleanup_future(res) + if result is not None: + return result + break try: done, _ = await async_wait({res}, timeout=remaining_budget) except BaseException: @@ -1464,30 +1505,16 @@ async def _runner() -> None: completed_at.append(monotonic()) task = async_create_task(_runner()) + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _safe_cleanup_task(task, res, wrapper_started) + if result is not None: + return result + break try: done, _ = await async_wait({task}, timeout=remaining_budget) except BaseException: - task.cancel() - task.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - if not wrapper_started: - if ( - iscoroutine(res) - and getcoroutinestate(res) == CORO_CREATED - ): - try: - res.close() - except BaseException: - pass - elif ( - isgenerator(res) - and getgeneratorstate(res) == GEN_CREATED - ): - try: - res.close() - except BaseException: - pass + _safe_cleanup_task(task, res, wrapper_started) raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( @@ -1496,27 +1523,7 @@ async def _runner() -> None: if cb_finished_in_budget and task in done: task.result() else: - task.cancel() - task.add_done_callback( - lambda t: t.exception() if not t.cancelled() else None - ) - if not wrapper_started: - if ( - iscoroutine(res) - and getcoroutinestate(res) == CORO_CREATED - ): - try: - res.close() - except BaseException: - pass - elif ( - isgenerator(res) - and getgeneratorstate(res) == GEN_CREATED - ): - try: - res.close() - except BaseException: - pass + _safe_cleanup_task(task, res, wrapper_started) if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index 2a11bd27..5c17e4b3 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2708,11 +2708,21 @@ async def fake_completed(org: Any, rev: Any) -> Any: ) as client: # Case 1: Pending same-loop Future that times out pending_fut: asyncio.Future[None] | None = None + fut_cancelled_time = 0.0 + cb_return_t1 = 0.0 def pending_future_callback(r: Any) -> asyncio.Future[None]: - nonlocal pending_fut + nonlocal pending_fut, cb_return_t1 + time.sleep(0.1) loop = asyncio.get_running_loop() pending_fut = loop.create_future() + + def record_cancel(_: Any) -> None: + nonlocal fut_cancelled_time + fut_cancelled_time = time.monotonic() + + pending_fut.add_done_callback(record_cancel) + cb_return_t1 = time.monotonic() return pending_fut client.get_review = fake_running # type: ignore @@ -2721,14 +2731,17 @@ def pending_future_callback(r: Any) -> asyncio.Future[None]: res = await client.wait_for_review( ORG, REVIEW, - timeout=0.2, + timeout=0.3, on_poll=pending_future_callback, ) elapsed1 = time.monotonic() - start_t1 assert res.status == "TIMED_OUT" + await asyncio.sleep(0) assert pending_fut is not None assert pending_fut.cancelled() - assert 0.18 <= elapsed1 <= 0.35 + wait_duration1 = fut_cancelled_time - cb_return_t1 + assert 0.16 <= wait_duration1 <= 0.26 + assert 0.27 <= elapsed1 <= 0.45 # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() @@ -2758,7 +2771,7 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: cleanup_blocked = asyncio.Event() cancellation_time = 0.0 - async def blocking_cleanup_callback(r: Any) -> None: + async def blocking_cleanup_coro(r: Any) -> None: nonlocal cancellation_time try: await asyncio.sleep(5.0) @@ -2768,21 +2781,30 @@ async def blocking_cleanup_callback(r: Any) -> None: await cleanup_blocked.wait() raise + cb_return_t3 = 0.0 + + def blocking_cleanup_callback(r: Any) -> Any: + nonlocal cb_return_t3 + time.sleep(0.1) + cb_return_t3 = time.monotonic() + return blocking_cleanup_coro(r) + client.get_review = fake_running # type: ignore start_t3 = time.monotonic() res = await client.wait_for_review( ORG, REVIEW, - timeout=0.2, + timeout=0.3, on_poll=blocking_cleanup_callback, ) elapsed3 = time.monotonic() - start_t3 assert res.status == "TIMED_OUT" await asyncio.sleep(0) assert cancellation_requested.is_set() - assert cancellation_time >= start_t3 + 0.2 - 0.02 - assert 0.18 <= elapsed3 <= 0.35 + wait_duration3 = cancellation_time - cb_return_t3 + assert 0.16 <= wait_duration3 <= 0.26 + assert 0.27 <= elapsed3 <= 0.45 cleanup_blocked.set() # Case 4: Blocking cleanup callback on terminal review @@ -2790,7 +2812,7 @@ async def blocking_cleanup_callback(r: Any) -> None: cleanup_blocked_term = asyncio.Event() cancellation_time_term = 0.0 - async def blocking_cleanup_callback_term(r: Any) -> None: + async def blocking_cleanup_coro_term(r: Any) -> None: nonlocal cancellation_time_term try: await asyncio.sleep(5.0) @@ -2800,21 +2822,30 @@ async def blocking_cleanup_callback_term(r: Any) -> None: await cleanup_blocked_term.wait() raise + cb_return_t4 = 0.0 + + def blocking_cleanup_callback_term(r: Any) -> Any: + nonlocal cb_return_t4 + time.sleep(0.1) + cb_return_t4 = time.monotonic() + return blocking_cleanup_coro_term(r) + client.get_review = fake_completed # type: ignore start_t4 = time.monotonic() res = await client.wait_for_review( ORG, REVIEW, - timeout=0.2, + timeout=0.3, on_poll=blocking_cleanup_callback_term, ) elapsed4 = time.monotonic() - start_t4 assert res.status == "COMPLETED" await asyncio.sleep(0) assert cancellation_requested_term.is_set() - assert cancellation_time_term >= start_t4 + 0.2 - 0.02 - assert 0.18 <= elapsed4 <= 0.35 + wait_duration4 = cancellation_time_term - cb_return_t4 + assert 0.16 <= wait_duration4 <= 0.26 + assert 0.27 <= elapsed4 <= 0.45 cleanup_blocked_term.set() # Case 5: Suspending callback that succeeds within budget @@ -3016,6 +3047,38 @@ def started_coro_cb(r: Any) -> Any: except asyncio.CancelledError: pass + # Unrestricted awaitables returning values (e.g. int) accepted and result discarded + async def int_returning_callback(r: Any) -> int: + return 42 + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_int = await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=int_returning_callback, + ) + assert res_int.status == "COMPLETED" + + # Pending future exception during cancellation does not replace TIMED_OUT outcome + async def failing_cancel_coro(r: Any) -> None: + fut = asyncio.get_running_loop().create_future() + try: + await fut + except asyncio.CancelledError: + raise RuntimeError("error during cancellation") + + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + res_clean = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.1, + on_poll=failing_cancel_coro, + ) + assert res_clean.status == "TIMED_OUT" + # Cyclic tuple whose list points back to it cyclic_list: list[Any] = [] cyclic_tuple = (cyclic_list, "tuple_leaf") @@ -3175,3 +3238,22 @@ class CustomTuple(tuple[Any, ...]): detail_huge_ct = CustomerReviewDetail.from_dict(responses[1]) detail_huge_ct.additional_properties["huge_ct"] = huge_ct assert _snapshot_review(detail_huge_ct) is None + + # Nonempty tuple subclass with identical elements constructs distinct subclass instance + class IdenticalTuple(tuple[Any, ...]): + pass + + itup = IdenticalTuple((1, "str", False)) + itup.attr = ["orig_attr"] # type: ignore[attr-defined] + detail_itup = CustomerReviewDetail.from_dict(responses[1]) + detail_itup.additional_properties["itup"] = itup + + snap_itup = _snapshot_review(detail_itup) + assert snap_itup is not None + copied_itup = snap_itup.additional_properties["itup"] + assert type(copied_itup) is IdenticalTuple + assert copied_itup is not itup + assert copied_itup.attr is not itup.attr + assert copied_itup.attr == ["orig_attr"] + copied_itup.attr.append("mutated") + assert itup.attr == ["orig_attr"] From 448f5c6169a8c9df7b6ffa761fc8065be32fd2ab Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 07:46:43 +0530 Subject: [PATCH 28/75] Address Proofline findings: slot descriptors, dict key aliases, set member checks, tuple constructor fallbacks, memoryview shape, and task creation guards --- README.md | 2 +- proofline/client.py | 198 +++++++++++++++++++++++------------ tests/test_http.py | 246 ++++++++++++++++++++++++++++++++++---------- 3 files changed, 326 insertions(+), 120 deletions(-) diff --git a/README.md b/README.md index b5de5b8c..20b9e675 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard, including when an outcome is already classified. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index a0cd0155..9acafa29 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -243,10 +243,20 @@ def _is_immutable(val: Any) -> bool: return val is None or val is UNSET or type(val) in _IMMUTABLE_TYPES -def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: - result: dict[str, Any] = {} - if hasattr(obj, "__dict__") and isinstance(obj.__dict__, dict): - result.update(obj.__dict__) +def _assign_target(target: Any, key: Any, is_attr: bool, val: Any) -> None: + if is_attr: + slot_or_name, is_desc = key + if is_desc: + slot_or_name.__set__(target, val) + else: + setattr(target, slot_or_name, val) + else: + target[key] = val + + +def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: + items: list[tuple[Any, bool, Any]] = [] + seen_slots: set[int] = set() for cls in type(obj).__mro__: raw_slots = getattr(cls, "__slots__", None) @@ -260,13 +270,22 @@ def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: attr_name = f"_{cls.__name__.lstrip('_')}{s}" else: attr_name = s - if attr_name not in result and hasattr(obj, attr_name): + desc = cls.__dict__.get(attr_name) + if desc is not None and hasattr(desc, "__get__") and hasattr(desc, "__set__"): + if id(desc) in seen_slots: + continue + seen_slots.add(id(desc)) try: - result[attr_name] = getattr(obj, attr_name) + val = desc.__get__(obj, type(obj)) + items.append((desc, True, val)) except AttributeError: pass - return list(result.items()) + if hasattr(obj, "__dict__") and isinstance(obj.__dict__, dict): + for k, v in obj.__dict__.items(): + items.append((k, False, v)) + + return items _ITEM_TASK = 1 @@ -275,6 +294,8 @@ def _get_obj_attrs(obj: Any) -> list[tuple[str, Any]]: _OBJ_EXPAND = 4 _TUPLE_EXPAND = 5 _TUPLE_FINALIZE = 6 +_SET_FINALIZE = 7 +_DICT_ITEM_FINALIZE = 8 _EXPAND_BATCH_SIZE = 64 _MAX_SAFE_TUPLE_SIZE = 1000 _MAX_SAFE_BUFFER_SIZE = 65_536 @@ -304,34 +325,21 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if task_type == _ITEM_TASK: key, is_attr, val = it_or_key, extra[0], extra[1] if _is_immutable(val): - if is_attr: - setattr(target, key, val) - else: - target[key] = val + _assign_target(target, key, is_attr, val) continue val_id = id(val) if val_id in memo: - resolved = memo[val_id] - if is_attr: - setattr(target, key, resolved) - else: - target[key] = resolved + _assign_target(target, key, is_attr, memo[val_id]) continue if type(val) is dict: new_dict: dict[Any, Any] = {} memo[val_id] = new_dict - if is_attr: - setattr(target, key, new_dict) - else: - target[key] = new_dict + _assign_target(target, key, is_attr, new_dict) stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) elif type(val) is list: new_list: list[Any] = [] memo[val_id] = new_list - if is_attr: - setattr(target, key, new_list) - else: - target[key] = new_list + _assign_target(target, key, is_attr, new_list) stack.append((_LIST_EXPAND, new_list, iter(val))) elif isinstance(val, tuple): if len(val) > _MAX_SAFE_TUPLE_SIZE: @@ -342,16 +350,13 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: try: val_cls: Any = type(val) - res_empty = val_cls() + res_empty = tuple.__new__(val_cls, ()) except Exception: - res_empty = () + return None memo[val_id] = res_empty if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, res_empty, iter(_get_obj_attrs(val)))) - if is_attr: - setattr(target, key, res_empty) - else: - target[key] = res_empty + _assign_target(target, key, is_attr, res_empty) else: temp_list: list[Any] = [] stack.append( @@ -370,10 +375,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non new_dict = copy.copy(val) new_dict.clear() memo[val_id] = new_dict - if is_attr: - setattr(target, key, new_dict) - else: - target[key] = new_dict + _assign_target(target, key, is_attr, new_dict) stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_dict, iter(_get_obj_attrs(val)))) @@ -381,35 +383,49 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non new_list = copy.copy(val) new_list.clear() memo[val_id] = new_list - if is_attr: - setattr(target, key, new_list) - else: - target[key] = new_list + _assign_target(target, key, is_attr, new_list) stack.append((_LIST_EXPAND, new_list, iter(val))) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) + elif isinstance(val, (set, frozenset)): + if len(val) == 0: + try: + res_empty = type(val)() + except Exception: + return None + memo[val_id] = res_empty + _assign_target(target, key, is_attr, res_empty) + else: + temp_set_list: list[Any] = [] + stack.append((_SET_FINALIZE, target, key, is_attr, val_id, val, temp_set_list)) + stack.append((_LIST_EXPAND, temp_set_list, iter(val))) elif isinstance(val, (memoryview, bytearray)): byte_count = val.nbytes if isinstance(val, memoryview) else len(val) if byte_count > _MAX_SAFE_BUFFER_SIZE: return None + resolved: Any if isinstance(val, bytearray): resolved = bytearray(val) elif val.readonly: resolved = memoryview(bytes(val)) + if val.format != "B" or val.ndim > 1: + try: + resolved = resolved.cast(val.format, shape=val.shape) + except Exception: + pass else: resolved = memoryview(bytearray(val)) + if val.format != "B" or val.ndim > 1: + try: + resolved = resolved.cast(val.format, shape=val.shape) + except Exception: + pass memo[val_id] = resolved - if is_attr: - setattr(target, key, resolved) - else: - target[key] = resolved + _assign_target(target, key, is_attr, resolved) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): new_obj = copy.copy(val) memo[val_id] = new_obj - if is_attr: - setattr(target, key, new_obj) - else: - target[key] = new_obj + _assign_target(target, key, is_attr, new_obj) stack.append((_OBJ_EXPAND, new_obj, iter(_get_obj_attrs(val)))) else: try: @@ -419,10 +435,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non f"Unsupported mutable value in review extension data: {type(val).__name__}" ) from exc memo[val_id] = resolved - if is_attr: - setattr(target, key, resolved) - else: - target[key] = resolved + _assign_target(target, key, is_attr, resolved) elif task_type == _DICT_EXPAND: target_dict, it = target, it_or_key @@ -431,17 +444,29 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non k, v = next(it) except StopIteration: break - if _is_immutable(v): - target_dict[k] = v - elif id(v) in memo: - target_dict[k] = memo[id(v)] + k_done = _is_immutable(k) or id(k) in memo + res_k = k if _is_immutable(k) else memo.get(id(k)) + v_done = _is_immutable(v) or id(v) in memo + res_v = v if _is_immutable(v) else memo.get(id(v)) + + if k_done and v_done: + target_dict[res_k] = res_v else: + box = [res_k, res_v] stack.append((_DICT_EXPAND, target_dict, it)) - stack.append((_ITEM_TASK, target_dict, k, False, v)) + stack.append((_DICT_ITEM_FINALIZE, target_dict, box)) + if not v_done: + stack.append((_ITEM_TASK, box, 1, False, v)) + if not k_done: + stack.append((_ITEM_TASK, box, 0, False, k)) break else: stack.append((_DICT_EXPAND, target_dict, it)) + elif task_type == _DICT_ITEM_FINALIZE: + target_dict, box = target, it_or_key + target_dict[box[0]] = box[1] + elif task_type == _LIST_EXPAND: target_list, it = target, it_or_key for _ in range(_EXPAND_BATCH_SIZE): @@ -466,16 +491,16 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non new_obj, it = target, it_or_key for _ in range(_EXPAND_BATCH_SIZE): try: - attr, attr_val = next(it) + slot_or_name, is_desc, attr_val = next(it) except StopIteration: break if _is_immutable(attr_val): - setattr(new_obj, attr, attr_val) + _assign_target(new_obj, (slot_or_name, is_desc), True, attr_val) elif id(attr_val) in memo: - setattr(new_obj, attr, memo[id(attr_val)]) + _assign_target(new_obj, (slot_or_name, is_desc), True, memo[id(attr_val)]) else: stack.append((_OBJ_EXPAND, new_obj, it)) - stack.append((_ITEM_TASK, new_obj, attr, True, attr_val)) + stack.append((_ITEM_TASK, new_obj, (slot_or_name, is_desc), True, attr_val)) break else: stack.append((_OBJ_EXPAND, new_obj, it)) @@ -519,16 +544,33 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: try: orig_cls: Any = type(orig_val) - res_tuple = orig_cls(temp_list) + res_tuple = tuple.__new__(orig_cls, temp_list) except Exception: - res_tuple = tuple(temp_list) + return None memo[val_id] = res_tuple if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): stack.append((_OBJ_EXPAND, res_tuple, iter(_get_obj_attrs(orig_val)))) - if is_attr: - setattr(target, key, res_tuple) + _assign_target(target, key, is_attr, res_tuple) + + elif task_type == _SET_FINALIZE: + key, is_attr, val_id, orig_val, temp_set_list = ( + it_or_key, + extra[0], + extra[1], + extra[2], + extra[3], + ) + if val_id in memo: + res_set = memo[val_id] else: - target[key] = res_tuple + try: + res_set = type(orig_val)(temp_set_list) + except Exception: + return None + memo[val_id] = res_set + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + stack.append((_OBJ_EXPAND, res_set, iter(_get_obj_attrs(orig_val)))) + _assign_target(target, key, is_attr, res_set) return root @@ -1381,7 +1423,9 @@ async def wait_for_review( values propagate before on_poll runs. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation - or discard, including when an outcome is already classified. Synchronous + or discard (and a pending future's failure can be suppressed if its done + callback runs after the deadline), including when an outcome is already + classified. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. """ @@ -1504,7 +1548,29 @@ async def _runner() -> None: finally: completed_at.append(monotonic()) - task = async_create_task(_runner()) + runner_coro = _runner() + try: + task = async_create_task(runner_coro) + except BaseException: + if ( + iscoroutine(runner_coro) + and getcoroutinestate(runner_coro) == CORO_CREATED + ): + try: + runner_coro.close() + except BaseException: + pass + if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: + try: + res.close() + except BaseException: + pass + elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: + try: + res.close() + except BaseException: + pass + raise remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: _safe_cleanup_task(task, res, wrapper_started) diff --git a/tests/test_http.py b/tests/test_http.py index 5c17e4b3..60f636cb 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2683,6 +2683,34 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: on_poll=failed_future_callback, ) + # Assert remaining budget with controlled clock + wait_timeouts: list[float | None] = [] + orig_async_wait = client_module.async_wait + + async def tracking_wait(fs: Any, *, timeout: float | None = None) -> Any: + wait_timeouts.append(timeout) + return await orig_async_wait(fs, timeout=timeout) + + monkeypatch.setattr(client_module, "async_wait", tracking_wait) + + async def dummy_async_cb(r: Any) -> None: + pass + + def cb_consuming_clock(r: Any) -> Any: + clock.now += 35.0 + return dummy_async_cb(r) + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=cb_consuming_clock, + ) + assert wait_timeouts == [65.0] + monkeypatch.setattr(client_module, "async_wait", orig_async_wait) + # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. watchdog_code = """ @@ -2708,40 +2736,25 @@ async def fake_completed(org: Any, rev: Any) -> Any: ) as client: # Case 1: Pending same-loop Future that times out pending_fut: asyncio.Future[None] | None = None - fut_cancelled_time = 0.0 - cb_return_t1 = 0.0 def pending_future_callback(r: Any) -> asyncio.Future[None]: - nonlocal pending_fut, cb_return_t1 - time.sleep(0.1) + nonlocal pending_fut loop = asyncio.get_running_loop() pending_fut = loop.create_future() - - def record_cancel(_: Any) -> None: - nonlocal fut_cancelled_time - fut_cancelled_time = time.monotonic() - - pending_fut.add_done_callback(record_cancel) - cb_return_t1 = time.monotonic() return pending_fut client.get_review = fake_running # type: ignore - start_t1 = time.monotonic() res = await client.wait_for_review( ORG, REVIEW, - timeout=0.3, + timeout=0.2, on_poll=pending_future_callback, ) - elapsed1 = time.monotonic() - start_t1 assert res.status == "TIMED_OUT" await asyncio.sleep(0) assert pending_fut is not None assert pending_fut.cancelled() - wait_duration1 = fut_cancelled_time - cb_return_t1 - assert 0.16 <= wait_duration1 <= 0.26 - assert 0.27 <= elapsed1 <= 0.45 # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() @@ -2769,83 +2782,51 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: # Case 3: Blocking cleanup callback on non-terminal review cancellation_requested = asyncio.Event() cleanup_blocked = asyncio.Event() - cancellation_time = 0.0 async def blocking_cleanup_coro(r: Any) -> None: - nonlocal cancellation_time try: await asyncio.sleep(5.0) except asyncio.CancelledError: - cancellation_time = time.monotonic() cancellation_requested.set() await cleanup_blocked.wait() raise - cb_return_t3 = 0.0 - - def blocking_cleanup_callback(r: Any) -> Any: - nonlocal cb_return_t3 - time.sleep(0.1) - cb_return_t3 = time.monotonic() - return blocking_cleanup_coro(r) - client.get_review = fake_running # type: ignore - start_t3 = time.monotonic() res = await client.wait_for_review( ORG, REVIEW, - timeout=0.3, - on_poll=blocking_cleanup_callback, + timeout=0.2, + on_poll=blocking_cleanup_coro, ) - elapsed3 = time.monotonic() - start_t3 assert res.status == "TIMED_OUT" await asyncio.sleep(0) assert cancellation_requested.is_set() - wait_duration3 = cancellation_time - cb_return_t3 - assert 0.16 <= wait_duration3 <= 0.26 - assert 0.27 <= elapsed3 <= 0.45 cleanup_blocked.set() # Case 4: Blocking cleanup callback on terminal review cancellation_requested_term = asyncio.Event() cleanup_blocked_term = asyncio.Event() - cancellation_time_term = 0.0 async def blocking_cleanup_coro_term(r: Any) -> None: - nonlocal cancellation_time_term try: await asyncio.sleep(5.0) except asyncio.CancelledError: - cancellation_time_term = time.monotonic() cancellation_requested_term.set() await cleanup_blocked_term.wait() raise - cb_return_t4 = 0.0 - - def blocking_cleanup_callback_term(r: Any) -> Any: - nonlocal cb_return_t4 - time.sleep(0.1) - cb_return_t4 = time.monotonic() - return blocking_cleanup_coro_term(r) - client.get_review = fake_completed # type: ignore - start_t4 = time.monotonic() res = await client.wait_for_review( ORG, REVIEW, - timeout=0.3, - on_poll=blocking_cleanup_callback_term, + timeout=0.2, + on_poll=blocking_cleanup_coro_term, ) - elapsed4 = time.monotonic() - start_t4 assert res.status == "COMPLETED" await asyncio.sleep(0) assert cancellation_requested_term.is_set() - wait_duration4 = cancellation_time_term - cb_return_t4 - assert 0.16 <= wait_duration4 <= 0.26 - assert 0.27 <= elapsed4 <= 0.45 cleanup_blocked_term.set() # Case 5: Suspending callback that succeeds within budget @@ -3079,6 +3060,29 @@ async def failing_cancel_coro(r: Any) -> None: ) assert res_clean.status == "TIMED_OUT" + # Case with a waiter whose cancel() raises synchronously: + # assert called and outcome is TIMED_OUT + class SyncCancelRaisingFuture(asyncio.Future[None]): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(loop=loop) + self.cancel_called = False + + def cancel(self, msg: Any = None) -> bool: + self.cancel_called = True + raise RuntimeError("synchronous cancel error") + + fut_sync_cancel = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + res_sync_cancel = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.1, + on_poll=lambda r: fut_sync_cancel, + ) + assert res_sync_cancel.status == "TIMED_OUT" + assert fut_sync_cancel.cancel_called is True + # Cyclic tuple whose list points back to it cyclic_list: list[Any] = [] cyclic_tuple = (cyclic_list, "tuple_leaf") @@ -3257,3 +3261,139 @@ class IdenticalTuple(tuple[Any, ...]): assert copied_itup.attr == ["orig_attr"] copied_itup.attr.append("mutated") assert itup.attr == ["orig_attr"] + + # Oversized terminal reviews passed to both sync and async clients: + # on_poll skipped and outcome returned + detail_oversized = CustomerReviewDetail.from_dict(responses[1]) + detail_oversized.additional_properties["huge"] = tuple(range(1001)) + + for test_mode in ("sync", "async"): + oversized_poll_called = False + + def oversized_poll_cb(r: Any) -> None: + nonlocal oversized_poll_called + oversized_poll_called = True + + async with session(test_mode, "https://api.proofline.sh") as client: + if test_mode == "async": + async def fake_get_ov(*args: Any, **kwargs: Any) -> Any: + return detail_oversized + + monkeypatch.setattr(client, "get_review", fake_get_ov) + else: + def fake_get_ov_sync(*args: Any, **kwargs: Any) -> Any: + return detail_oversized + + monkeypatch.setattr(client, "get_review", fake_get_ov_sync) + + res_ov = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=oversized_poll_cb, + ) + assert res_ov.status == "COMPLETED" + assert not oversized_poll_called + + # Multidimensional memoryview shape and format preserved + raw_mv = bytearray(b"0123456789abcdef") + mv_orig = memoryview(raw_mv).cast("B", shape=[4, 4]) + detail_mv = CustomerReviewDetail.from_dict(responses[1]) + detail_mv.additional_properties["mv"] = mv_orig + + snap_mv = _snapshot_review(detail_mv) + assert snap_mv is not None + copied_mv = snap_mv.additional_properties["mv"] + assert isinstance(copied_mv, memoryview) + assert copied_mv.shape == (4, 4) + assert copied_mv.format == "B" + assert copied_mv[1, 2] == mv_orig[1, 2] + copied_mv[1, 2] = ord("Z") + assert raw_mv != bytearray(copied_mv) + + # Named tuple preserves named fields + from typing import NamedTuple + + class Point(NamedTuple): + x: int + y: int + + pt = Point(10, 20) + detail_pt = CustomerReviewDetail.from_dict(responses[1]) + detail_pt.additional_properties["pt"] = pt + + snap_pt = _snapshot_review(detail_pt) + assert snap_pt is not None + copied_pt = snap_pt.additional_properties["pt"] + assert type(copied_pt) is Point + assert copied_pt.x == 10 + assert copied_pt.y == 20 + + # Derived slot does not hide base slot + class BaseSlot: + __slots__ = ("shared_slot",) + + class DerivedSlot(BaseSlot): + __slots__ = ("shared_slot",) + + slot_inst = DerivedSlot() + BaseSlot.shared_slot.__set__(slot_inst, ["base_data"]) + DerivedSlot.shared_slot.__set__(slot_inst, ["derived_data"]) + detail_slots = CustomerReviewDetail.from_dict(responses[1]) + detail_slots.additional_properties["slots"] = slot_inst + + snap_slots = _snapshot_review(detail_slots) + assert snap_slots is not None + copied_slots = snap_slots.additional_properties["slots"] + assert type(copied_slots) is DerivedSlot + assert BaseSlot.shared_slot.__get__(copied_slots) == ["base_data"] + assert BaseSlot.shared_slot.__get__(copied_slots) is not BaseSlot.shared_slot.__get__(slot_inst) + assert DerivedSlot.shared_slot.__get__(copied_slots) == ["derived_data"] + assert DerivedSlot.shared_slot.__get__(copied_slots) is not DerivedSlot.shared_slot.__get__( + slot_inst + ) + + # Empty tuple subclass with required __init__ argument + class EmptyArgTuple(tuple[Any, ...]): + def __init__(self, required_arg: Any) -> None: + self.attr = "initialized" + + empty_tup_inst = tuple.__new__(EmptyArgTuple, ()) + empty_tup_inst.attr = "custom_attr" # type: ignore[attr-defined] + detail_empty_arg = CustomerReviewDetail.from_dict(responses[1]) + detail_empty_arg.additional_properties["empty_arg"] = empty_tup_inst + + snap_empty_arg = _snapshot_review(detail_empty_arg) + assert snap_empty_arg is not None + copied_empty_arg = snap_empty_arg.additional_properties["empty_arg"] + assert type(copied_empty_arg) is EmptyArgTuple + assert copied_empty_arg == () + assert copied_empty_arg.attr == "custom_attr" + + # Dict keys resolved through memo preserving alias with value + class KeyValObj: + def __init__(self, name: str) -> None: + self.name = name + + shared_obj = KeyValObj("shared_alias") + key_tup = (shared_obj, 1) + dict_with_alias = {key_tup: shared_obj} + detail_alias = CustomerReviewDetail.from_dict(responses[1]) + detail_alias.additional_properties["alias_dict"] = dict_with_alias + + snap_alias = _snapshot_review(detail_alias) + assert snap_alias is not None + copied_dict = snap_alias.additional_properties["alias_dict"] + for k, v in copied_dict.items(): + assert k is not key_tup + assert k[0] is v + assert v is not shared_obj + assert v.name == "shared_alias" + + # Set member containing oversized tuple skips snapshot delivery + set_with_huge_tuple = {tuple(range(1001))} + detail_set_huge = CustomerReviewDetail.from_dict(responses[1]) + detail_set_huge.additional_properties["set_huge"] = set_with_huge_tuple + assert _snapshot_review(detail_set_huge) is None From d085c9c174d07fbb0c45940c19c3a1e75f66670b Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 08:12:55 +0530 Subject: [PATCH 29/75] Address Proofline findings: detach overdue callbacks, current task guard, empty set attributes, memoryview cast errors, and test assertions --- proofline/client.py | 92 ++++++++++++++++++++++++++---------- tests/test_http.py | 113 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+), 26 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 9acafa29..78e75b6d 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -14,6 +14,9 @@ from asyncio import ( create_task as async_create_task, ) +from asyncio import ( + current_task as async_current_task, +) from asyncio import ( get_running_loop as async_get_running_loop, ) @@ -373,6 +376,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_TUPLE_EXPAND, temp_list, iter(val))) elif isinstance(val, dict): new_dict = copy.copy(val) + if new_dict is val: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) new_dict.clear() memo[val_id] = new_dict _assign_target(target, key, is_attr, new_dict) @@ -381,6 +388,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_OBJ_EXPAND, new_dict, iter(_get_obj_attrs(val)))) elif isinstance(val, list): new_list = copy.copy(val) + if new_list is val: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) new_list.clear() memo[val_id] = new_list _assign_target(target, key, is_attr, new_list) @@ -391,9 +402,14 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if len(val) == 0: try: res_empty = type(val)() - except Exception: - return None + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc memo[val_id] = res_empty + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, res_empty, iter(_get_obj_attrs(val)))) _assign_target(target, key, is_attr, res_empty) else: temp_set_list: list[Any] = [] @@ -411,19 +427,29 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if val.format != "B" or val.ndim > 1: try: resolved = resolved.cast(val.format, shape=val.shape) - except Exception: - pass + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc else: resolved = memoryview(bytearray(val)) if val.format != "B" or val.ndim > 1: try: resolved = resolved.cast(val.format, shape=val.shape) - except Exception: - pass + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc memo[val_id] = resolved _assign_target(target, key, is_attr, resolved) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): new_obj = copy.copy(val) + if new_obj is val: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) memo[val_id] = new_obj _assign_target(target, key, is_attr, new_obj) stack.append((_OBJ_EXPAND, new_obj, iter(_get_obj_attrs(val)))) @@ -565,8 +591,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: try: res_set = type(orig_val)(temp_set_list) - except Exception: - return None + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) from exc memo[val_id] = res_set if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): stack.append((_OBJ_EXPAND, res_set, iter(_get_obj_attrs(orig_val)))) @@ -575,7 +604,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non return root -def _safe_cleanup_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: +def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: try: try: loop = fut.get_loop() @@ -596,27 +625,26 @@ def _safe_cleanup_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: except BaseException: pass try: - fut.cancel() + loop.call_soon(fut.cancel) except BaseException: pass except BaseException: pass -def _safe_cleanup_task( +def _detach_overdue_task( task: AsyncTask[Any], res: Any, wrapper_started: bool, ) -> None: try: - try: - task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) - except BaseException: - pass - try: - task.cancel() - except BaseException: - pass + task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) + except BaseException: + pass + try: + loop = task.get_loop() + if loop.is_running() and not loop.is_closed(): + loop.call_soon(task.cancel) except BaseException: pass if not wrapper_started: @@ -1453,6 +1481,11 @@ async def wait_for_review( if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) if isawaitable(res): + if res is async_current_task(): + raise ValueError( + "Callbacks cannot return the running polling task." + ) + remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: @@ -1466,7 +1499,7 @@ async def wait_for_review( except BaseException: pass elif isinstance(res, (AsyncTask, AsyncFuture)): - _safe_cleanup_future(res) + _detach_overdue_future(res) if result is not None: return result break @@ -1496,14 +1529,14 @@ async def wait_for_review( ) remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - _safe_cleanup_future(res) + _detach_overdue_future(res) if result is not None: return result break try: done, _ = await async_wait({res}, timeout=remaining_budget) except BaseException: - _safe_cleanup_future(res) + _detach_overdue_future(res) raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( @@ -1512,7 +1545,7 @@ async def wait_for_review( if cb_finished_in_budget and res in done: res.result() else: - _safe_cleanup_future(res) + _detach_overdue_future(res) if result is not None: return result break @@ -1571,16 +1604,23 @@ async def _runner() -> None: except BaseException: pass raise + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + if task.done() and cb_finished_in_budget: + task.result() + remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - _safe_cleanup_task(task, res, wrapper_started) + _detach_overdue_task(task, res, wrapper_started) if result is not None: return result break try: done, _ = await async_wait({task}, timeout=remaining_budget) except BaseException: - _safe_cleanup_task(task, res, wrapper_started) + _detach_overdue_task(task, res, wrapper_started) raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( @@ -1589,7 +1629,7 @@ async def _runner() -> None: if cb_finished_in_budget and task in done: task.result() else: - _safe_cleanup_task(task, res, wrapper_started) + _detach_overdue_task(task, res, wrapper_started) if result is not None: return result break diff --git a/tests/test_http.py b/tests/test_http.py index 60f636cb..d56b4dff 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2711,6 +2711,41 @@ def cb_consuming_clock(r: Any) -> Any: assert wait_timeouts == [65.0] monkeypatch.setattr(client_module, "async_wait", orig_async_wait) + # Timely pending future failure propagates + timely_fut: asyncio.Future[None] = asyncio.get_running_loop().create_future() + + def timely_fail_cb(r: Any) -> asyncio.Future[None]: + timely_fut.set_exception(ValueError("timely failure")) + return timely_fut + + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="timely failure"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_fail_cb, + ) + + # Late-observed pending future failure preserves the classified outcome + late_fut: asyncio.Future[None] = asyncio.get_running_loop().create_future() + + def late_fail_cb(r: Any) -> asyncio.Future[None]: + clock.now += 150.0 + late_fut.set_exception(ValueError("late failure")) + return late_fut + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_late = await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=late_fail_cb, + ) + assert res_late.status == "COMPLETED" + # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. watchdog_code = """ @@ -2782,6 +2817,7 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: # Case 3: Blocking cleanup callback on non-terminal review cancellation_requested = asyncio.Event() cleanup_blocked = asyncio.Event() + cleanup_completed_3 = asyncio.Event() async def blocking_cleanup_coro(r: Any) -> None: try: @@ -2789,24 +2825,31 @@ async def blocking_cleanup_coro(r: Any) -> None: except asyncio.CancelledError: cancellation_requested.set() await cleanup_blocked.wait() + cleanup_completed_3.set() raise client.get_review = fake_running # type: ignore + start_t3 = time.monotonic() res = await client.wait_for_review( ORG, REVIEW, timeout=0.2, on_poll=blocking_cleanup_coro, ) + elapsed3 = time.monotonic() - start_t3 + assert 0.18 <= elapsed3 <= 0.60 assert res.status == "TIMED_OUT" await asyncio.sleep(0) + await asyncio.sleep(0) assert cancellation_requested.is_set() cleanup_blocked.set() + await cleanup_completed_3.wait() # Case 4: Blocking cleanup callback on terminal review cancellation_requested_term = asyncio.Event() cleanup_blocked_term = asyncio.Event() + cleanup_completed_4 = asyncio.Event() async def blocking_cleanup_coro_term(r: Any) -> None: try: @@ -2814,20 +2857,26 @@ async def blocking_cleanup_coro_term(r: Any) -> None: except asyncio.CancelledError: cancellation_requested_term.set() await cleanup_blocked_term.wait() + cleanup_completed_4.set() raise client.get_review = fake_completed # type: ignore + start_t4 = time.monotonic() res = await client.wait_for_review( ORG, REVIEW, timeout=0.2, on_poll=blocking_cleanup_coro_term, ) + elapsed4 = time.monotonic() - start_t4 + assert 0.18 <= elapsed4 <= 0.60 assert res.status == "COMPLETED" await asyncio.sleep(0) + await asyncio.sleep(0) assert cancellation_requested_term.is_set() cleanup_blocked_term.set() + await cleanup_completed_4.wait() # Case 5: Suspending callback that succeeds within budget resumed_within_budget = False @@ -3081,8 +3130,20 @@ def cancel(self, msg: Any = None) -> bool: on_poll=lambda r: fut_sync_cancel, ) assert res_sync_cancel.status == "TIMED_OUT" + await asyncio.sleep(0) assert fut_sync_cancel.cancel_called is True + # Current task cannot be returned by on_poll + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="running polling task"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: asyncio.current_task(), + ) + # Cyclic tuple whose list points back to it cyclic_list: list[Any] = [] cyclic_tuple = (cyclic_list, "tuple_leaf") @@ -3276,11 +3337,13 @@ def oversized_poll_cb(r: Any) -> None: async with session(test_mode, "https://api.proofline.sh") as client: if test_mode == "async": + async def fake_get_ov(*args: Any, **kwargs: Any) -> Any: return detail_oversized monkeypatch.setattr(client, "get_review", fake_get_ov) else: + def fake_get_ov_sync(*args: Any, **kwargs: Any) -> Any: return detail_oversized @@ -3386,6 +3449,7 @@ def __init__(self, name: str) -> None: snap_alias = _snapshot_review(detail_alias) assert snap_alias is not None copied_dict = snap_alias.additional_properties["alias_dict"] + assert len(copied_dict) == 1 for k, v in copied_dict.items(): assert k is not key_tup assert k[0] is v @@ -3397,3 +3461,52 @@ def __init__(self, name: str) -> None: detail_set_huge = CustomerReviewDetail.from_dict(responses[1]) detail_set_huge.additional_properties["set_huge"] = set_with_huge_tuple assert _snapshot_review(detail_set_huge) is None + + # Mutable object whose __copy__ returns self is rejected with TypeError + class SelfCopyList(list[Any]): + def __copy__(self) -> Any: + return self + + self_copy_inst = SelfCopyList([1, 2]) + detail_self_copy = CustomerReviewDetail.from_dict(responses[1]) + detail_self_copy.additional_properties["self_copy"] = self_copy_inst + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_self_copy) + + # Memoryview with invalid destination format for cast raises TypeError + import ctypes + + c_arr = (ctypes.c_int32 * 4)() + mv_ctypes = memoryview(c_arr) + detail_ctypes_mv = CustomerReviewDetail.from_dict(responses[1]) + detail_ctypes_mv.additional_properties["ctypes_mv"] = mv_ctypes + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_ctypes_mv) + + # Empty set subclass copies attributes + class CustomSet(set[Any]): + pass + + empty_custom_set = CustomSet() + empty_custom_set.custom_attr = ["set_attr"] # type: ignore[attr-defined] + detail_empty_set = CustomerReviewDetail.from_dict(responses[1]) + detail_empty_set.additional_properties["empty_set"] = empty_custom_set + + snap_empty_set = _snapshot_review(detail_empty_set) + assert snap_empty_set is not None + copied_empty_set = snap_empty_set.additional_properties["empty_set"] + assert type(copied_empty_set) is CustomSet + assert len(copied_empty_set) == 0 + assert copied_empty_set.custom_attr is not empty_custom_set.custom_attr + assert copied_empty_set.custom_attr == ["set_attr"] + + # Set subclass requiring extra constructor argument propagates TypeError + class RequiredArgSet(set[Any]): + def __init__(self, required_arg: Any) -> None: + super().__init__() + + req_set = set.__new__(RequiredArgSet) + detail_req_set = CustomerReviewDetail.from_dict(responses[1]) + detail_req_set.additional_properties["req_set"] = req_set + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_req_set) From 91244654585fbfe6463f95e68ee38d24124048fe Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 08:31:32 +0530 Subject: [PATCH 30/75] Address Proofline findings: safe cancellation wrapper, built-in Future exception retrieval, bytearray subclass preservation, slot descriptor enumeration, custom tzinfo copying, and test fixtures --- README.md | 2 +- proofline/client.py | 112 ++++++++++++++++++++++----------- tests/test_http.py | 149 ++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 215 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 20b9e675..b3a689cf 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 78e75b6d..d3e3ac2f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -38,7 +38,7 @@ ) from string import hexdigits from time import monotonic, sleep -from types import TracebackType +from types import MemberDescriptorType, TracebackType from typing import Any, Self, TypedDict, TypeVar, Unpack, cast from urllib.parse import quote from uuid import UUID @@ -238,12 +238,19 @@ def _export_page_limit(max_pages: int) -> None: bytes, UUID, datetime.date, - datetime.datetime, } def _is_immutable(val: Any) -> bool: - return val is None or val is UNSET or type(val) in _IMMUTABLE_TYPES + if val is None or val is UNSET or isinstance(val, type): + return True + t = type(val) + if t in _IMMUTABLE_TYPES: + return True + if t is datetime.datetime: + tz = val.tzinfo + return tz is None or type(tz) is datetime.timezone + return False def _assign_target(target: Any, key: Any, is_attr: bool, val: Any) -> None: @@ -262,24 +269,19 @@ def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: seen_slots: set[int] = set() for cls in type(obj).__mro__: - raw_slots = getattr(cls, "__slots__", None) - if not raw_slots: - continue - slot_names = [raw_slots] if isinstance(raw_slots, str) else raw_slots - for s in slot_names: - if s in ("__dict__", "__weakref__"): - continue - if s.startswith("__") and not s.endswith("__"): - attr_name = f"_{cls.__name__.lstrip('_')}{s}" - else: - attr_name = s - desc = cls.__dict__.get(attr_name) - if desc is not None and hasattr(desc, "__get__") and hasattr(desc, "__set__"): + for name, desc in cls.__dict__.items(): + if isinstance(desc, MemberDescriptorType) or ( + type(desc).__name__ == "member_descriptor" + and hasattr(desc, "__get__") + and hasattr(desc, "__set__") + ): + if name in ("__dict__", "__weakref__"): + continue if id(desc) in seen_slots: continue seen_slots.add(id(desc)) try: - val = desc.__get__(obj, type(obj)) + val = desc.__get__(obj, cls) items.append((desc, True, val)) except AttributeError: pass @@ -415,35 +417,64 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non temp_set_list: list[Any] = [] stack.append((_SET_FINALIZE, target, key, is_attr, val_id, val, temp_set_list)) stack.append((_LIST_EXPAND, temp_set_list, iter(val))) - elif isinstance(val, (memoryview, bytearray)): - byte_count = val.nbytes if isinstance(val, memoryview) else len(val) - if byte_count > _MAX_SAFE_BUFFER_SIZE: + elif isinstance(val, bytearray): + if len(val) > _MAX_SAFE_BUFFER_SIZE: return None - resolved: Any - if isinstance(val, bytearray): + try: + resolved = type(val)(val) + except Exception: resolved = bytearray(val) - elif val.readonly: - resolved = memoryview(bytes(val)) + memo[val_id] = resolved + _assign_target(target, key, is_attr, resolved) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, resolved, iter(_get_obj_attrs(val)))) + elif isinstance(val, memoryview): + if val.nbytes > _MAX_SAFE_BUFFER_SIZE: + return None + resolved_mv: Any + if val.readonly: + resolved_mv = memoryview(bytes(val)) if val.format != "B" or val.ndim > 1: try: - resolved = resolved.cast(val.format, shape=val.shape) + resolved_mv = resolved_mv.cast(val.format, shape=val.shape) except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " f"{type(val).__name__}" ) from exc else: - resolved = memoryview(bytearray(val)) + resolved_mv = memoryview(bytearray(val)) if val.format != "B" or val.ndim > 1: try: - resolved = resolved.cast(val.format, shape=val.shape) + resolved_mv = resolved_mv.cast(val.format, shape=val.shape) except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " f"{type(val).__name__}" ) from exc - memo[val_id] = resolved - _assign_target(target, key, is_attr, resolved) + memo[val_id] = resolved_mv + _assign_target(target, key, is_attr, resolved_mv) + elif isinstance(val, datetime.datetime): + if val.tzinfo is None or type(val.tzinfo) is datetime.timezone: + _assign_target(target, key, is_attr, val) + else: + tz = val.tzinfo + if id(tz) in memo: + copied_tz = memo[id(tz)] + else: + try: + copied_tz = copy.copy(tz) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(tz).__name__}" + ) from exc + memo[id(tz)] = copied_tz + if hasattr(tz, "__dict__") or hasattr(tz, "__slots__"): + stack.append((_OBJ_EXPAND, copied_tz, iter(_get_obj_attrs(tz)))) + new_dt = val.replace(tzinfo=copied_tz) + memo[val_id] = new_dt + _assign_target(target, key, is_attr, new_dt) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): new_obj = copy.copy(val) if new_obj is val: @@ -604,6 +635,13 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non return root +def _safe_cancel_target(target: Any) -> None: + try: + target.cancel() + except BaseException: + pass + + def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: try: try: @@ -618,14 +656,17 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: return if fut.done(): if not fut.cancelled(): - fut.exception() + try: + AsyncFuture.exception(fut) + except Exception: + pass return try: - fut.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) + fut.add_done_callback(lambda t: AsyncFuture.exception(t) if not t.cancelled() else None) except BaseException: pass try: - loop.call_soon(fut.cancel) + loop.call_soon(_safe_cancel_target, fut) except BaseException: pass except BaseException: @@ -638,13 +679,13 @@ def _detach_overdue_task( wrapper_started: bool, ) -> None: try: - task.add_done_callback(lambda t: t.exception() if not t.cancelled() else None) + task.add_done_callback(lambda t: AsyncTask.exception(t) if not t.cancelled() else None) except BaseException: pass try: loop = task.get_loop() if loop.is_running() and not loop.is_closed(): - loop.call_soon(task.cancel) + loop.call_soon(_safe_cancel_target, task) except BaseException: pass if not wrapper_started: @@ -1442,7 +1483,8 @@ async def wait_for_review( snapshot and returns None or an awaitable (supporting both sync and async callbacks). Any coroutines returned by on_poll must be unstarted, and any pending futures returned by on_poll must belong to the running event - loop. Callbacks must return promptly even when they return + loop. Callbacks cannot return the running polling task (doing so raises + ValueError). Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Oversized diff --git a/tests/test_http.py b/tests/test_http.py index d56b4dff..62d6c768 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2714,8 +2714,12 @@ def cb_consuming_clock(r: Any) -> Any: # Timely pending future failure propagates timely_fut: asyncio.Future[None] = asyncio.get_running_loop().create_future() - def timely_fail_cb(r: Any) -> asyncio.Future[None]: + async def fail_timely_soon() -> None: + await asyncio.sleep(0.01) timely_fut.set_exception(ValueError("timely failure")) + + def timely_fail_cb(r: Any) -> asyncio.Future[None]: + asyncio.create_task(fail_timely_soon()) return timely_fut with Server(lambda request, index: Reply(body=responses[0])) as server: @@ -2730,10 +2734,14 @@ def timely_fail_cb(r: Any) -> asyncio.Future[None]: # Late-observed pending future failure preserves the classified outcome late_fut: asyncio.Future[None] = asyncio.get_running_loop().create_future() + late_fut.add_done_callback(lambda _: setattr(clock, "now", clock.now + 200.0)) - def late_fail_cb(r: Any) -> asyncio.Future[None]: - clock.now += 150.0 + async def fail_late_soon() -> None: + await asyncio.sleep(0.01) late_fut.set_exception(ValueError("late failure")) + + def late_fail_cb(r: Any) -> asyncio.Future[None]: + asyncio.create_task(fail_late_soon()) return late_fut with Server(lambda request, index: Reply(body=responses[1])) as server: @@ -3099,15 +3107,25 @@ async def failing_cancel_coro(r: Any) -> None: except asyncio.CancelledError: raise RuntimeError("error during cancellation") - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: - res_clean = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.1, - on_poll=failing_cancel_coro, - ) - assert res_clean.status == "TIMED_OUT" + unhandled_exceptions: list[dict[str, Any]] = [] + loop = asyncio.get_running_loop() + old_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhandled_exceptions.append(ctx)) + try: + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + res_clean = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.1, + on_poll=failing_cancel_coro, + ) + assert res_clean.status == "TIMED_OUT" + await asyncio.sleep(0) + await asyncio.sleep(0) + assert unhandled_exceptions == [] + finally: + loop.set_exception_handler(old_handler) # Case with a waiter whose cancel() raises synchronously: # assert called and outcome is TIMED_OUT @@ -3360,6 +3378,45 @@ def fake_get_ov_sync(*args: Any, **kwargs: Any) -> Any: assert res_ov.status == "COMPLETED" assert not oversized_poll_called + # Lock-bearing reviews passed to both sync and async clients: + # TypeError propagates and on_poll is not called + import threading + + detail_lock = CustomerReviewDetail.from_dict(responses[1]) + detail_lock.additional_properties["lock"] = threading.Lock() + + for test_mode in ("sync", "async"): + lock_poll_called = False + + def lock_poll_cb(r: Any) -> None: + nonlocal lock_poll_called + lock_poll_called = True + + async with session(test_mode, "https://api.proofline.sh") as client: + if test_mode == "async": + + async def fake_get_lock(*args: Any, **kwargs: Any) -> Any: + return detail_lock + + monkeypatch.setattr(client, "get_review", fake_get_lock) + else: + + def fake_get_lock_sync(*args: Any, **kwargs: Any) -> Any: + return detail_lock + + monkeypatch.setattr(client, "get_review", fake_get_lock_sync) + + with pytest.raises(TypeError, match="Unsupported mutable value"): + await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=lock_poll_cb, + ) + assert not lock_poll_called + # Multidimensional memoryview shape and format preserved raw_mv = bytearray(b"0123456789abcdef") mv_orig = memoryview(raw_mv).cast("B", shape=[4, 4]) @@ -3510,3 +3567,71 @@ def __init__(self, required_arg: Any) -> None: detail_req_set.additional_properties["req_set"] = req_set with pytest.raises(TypeError, match="Unsupported mutable value"): _snapshot_review(detail_req_set) + + # Bytearray subclass preserves subclass type and copies instance attributes + class CustomByteArray(bytearray): + pass + + custom_ba = CustomByteArray(b"custom_bytes") + custom_ba.extra_attr = ["extra"] # type: ignore[attr-defined] + detail_custom_ba = CustomerReviewDetail.from_dict(responses[1]) + detail_custom_ba.additional_properties["custom_ba"] = custom_ba + snap_ba = _snapshot_review(detail_custom_ba) + assert snap_ba is not None + copied_ba = snap_ba.additional_properties["custom_ba"] + assert type(copied_ba) is CustomByteArray + assert copied_ba == b"custom_bytes" + assert copied_ba is not custom_ba + assert copied_ba.extra_attr is not custom_ba.extra_attr + assert copied_ba.extra_attr == ["extra"] + + # Class with exhausted __slots__ iterator has installed descriptors enumerated + class ExhaustedSlotsObj: + __slots__ = iter(["slot_attr"]) + + def __init__(self, val: Any) -> None: + self.slot_attr = val + + def __copy__(self) -> Any: + res = ExhaustedSlotsObj.__new__(ExhaustedSlotsObj) + res.slot_attr = self.slot_attr + return res + + orig_slots_inst = ExhaustedSlotsObj(["slot_val"]) + detail_slots = CustomerReviewDetail.from_dict(responses[1]) + detail_slots.additional_properties["exhausted_slots"] = orig_slots_inst + snap_slots = _snapshot_review(detail_slots) + assert snap_slots is not None + copied_slots_inst = snap_slots.additional_properties["exhausted_slots"] + assert copied_slots_inst is not orig_slots_inst + assert copied_slots_inst.slot_attr is not orig_slots_inst.slot_attr + assert copied_slots_inst.slot_attr == ["slot_val"] + + # Datetime with custom mutable tzinfo copies tzinfo and avoids leaking mutation + import datetime as dt_mod + + class CustomMutableTz(dt_mod.tzinfo): + def __init__(self, offset_minutes: int = 0) -> None: + self.offset_minutes = offset_minutes + self.tz_attr = ["tz_state"] + + def utcoffset(self, dt_val: Any) -> timedelta: + return timedelta(minutes=self.offset_minutes) + + def tzname(self, dt_val: Any) -> str: + return "CUSTOM" + + def dst(self, dt_val: Any) -> timedelta: + return timedelta(0) + + custom_tz_inst = CustomMutableTz(60) + dt_with_custom_tz = datetime(2026, 11, 22, 10, 0, 0, tzinfo=custom_tz_inst) + detail_dt = CustomerReviewDetail.from_dict(responses[1]) + detail_dt.additional_properties["custom_tz_dt"] = dt_with_custom_tz + snap_dt = _snapshot_review(detail_dt) + assert snap_dt is not None + copied_dt = snap_dt.additional_properties["custom_tz_dt"] + assert copied_dt == dt_with_custom_tz + assert copied_dt.tzinfo is not custom_tz_inst + assert copied_dt.tzinfo.tz_attr is not custom_tz_inst.tz_attr + assert copied_dt.tzinfo.tz_attr == ["tz_state"] From 194927020e3b7c438f5d2099322424efed26ed02 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 08:47:45 +0530 Subject: [PATCH 31/75] Address Proofline findings: non-overridable Future operations, coroutine state validation before deadline, bytearray base construction, datetime subclass copying, and test assertions --- proofline/client.py | 97 ++++++++++++++++++--------- tests/test_http.py | 155 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 190 insertions(+), 62 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index d3e3ac2f..328d5a5c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -347,9 +347,9 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non _assign_target(target, key, is_attr, new_list) stack.append((_LIST_EXPAND, new_list, iter(val))) elif isinstance(val, tuple): - if len(val) > _MAX_SAFE_TUPLE_SIZE: + if tuple.__len__(val) > _MAX_SAFE_TUPLE_SIZE: return None - if len(val) == 0: + if tuple.__len__(val) == 0: if type(val) is tuple: res_empty: Any = () else: @@ -375,7 +375,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non temp_list, ) ) - stack.append((_TUPLE_EXPAND, temp_list, iter(val))) + stack.append((_TUPLE_EXPAND, temp_list, tuple.__iter__(val))) elif isinstance(val, dict): new_dict = copy.copy(val) if new_dict is val: @@ -421,9 +421,12 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if len(val) > _MAX_SAFE_BUFFER_SIZE: return None try: - resolved = type(val)(val) - except Exception: - resolved = bytearray(val) + resolved = bytearray.__new__(type(val)) + bytearray.__init__(resolved, val) + except Exception as exc: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) from exc memo[val_id] = resolved _assign_target(target, key, is_attr, resolved) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): @@ -455,26 +458,49 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non memo[val_id] = resolved_mv _assign_target(target, key, is_attr, resolved_mv) elif isinstance(val, datetime.datetime): - if val.tzinfo is None or type(val.tzinfo) is datetime.timezone: - _assign_target(target, key, is_attr, val) - else: - tz = val.tzinfo - if id(tz) in memo: - copied_tz = memo[id(tz)] + if type(val) is datetime.datetime: + if val.tzinfo is None or type(val.tzinfo) is datetime.timezone: + _assign_target(target, key, is_attr, val) else: - try: - copied_tz = copy.copy(tz) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(tz).__name__}" - ) from exc - memo[id(tz)] = copied_tz - if hasattr(tz, "__dict__") or hasattr(tz, "__slots__"): - stack.append((_OBJ_EXPAND, copied_tz, iter(_get_obj_attrs(tz)))) - new_dt = val.replace(tzinfo=copied_tz) + tz = val.tzinfo + if id(tz) in memo: + copied_tz = memo[id(tz)] + else: + try: + copied_tz = copy.copy(tz) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(tz).__name__}" + ) from exc + if copied_tz is tz: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(tz).__name__}" + ) + memo[id(tz)] = copied_tz + if hasattr(tz, "__dict__") or hasattr(tz, "__slots__"): + stack.append((_OBJ_EXPAND, copied_tz, iter(_get_obj_attrs(tz)))) + new_dt = val.replace(tzinfo=copied_tz) + memo[val_id] = new_dt + _assign_target(target, key, is_attr, new_dt) + else: + try: + new_dt = copy.copy(val) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc + if new_dt is val: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) memo[val_id] = new_dt _assign_target(target, key, is_attr, new_dt) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, new_dt, iter(_get_obj_attrs(val)))) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): new_obj = copy.copy(val) if new_obj is val: @@ -654,15 +680,17 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: return if loop is not running_loop or loop.is_closed(): return - if fut.done(): - if not fut.cancelled(): + if AsyncFuture.done(fut): + if not AsyncFuture.cancelled(fut): try: AsyncFuture.exception(fut) except Exception: pass return try: - fut.add_done_callback(lambda t: AsyncFuture.exception(t) if not t.cancelled() else None) + fut.add_done_callback( + lambda t: AsyncFuture.exception(t) if not AsyncFuture.cancelled(t) else None + ) except BaseException: pass try: @@ -1522,12 +1550,22 @@ async def wait_for_review( snapshot = _snapshot_review(last) if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) + if res is not None and not isawaitable(res): + raise TypeError( + "Callbacks must return None or an awaitable, " + f"got {type(res).__name__}" + ) if isawaitable(res): if res is async_current_task(): raise ValueError( "Callbacks cannot return the running polling task." ) + if iscoroutine(res) and getcoroutinestate(res) != CORO_CREATED: + raise ValueError("Callbacks must return unstarted coroutines.") + if isgenerator(res) and getgeneratorstate(res) != GEN_CREATED: + raise ValueError("Callbacks must return unstarted coroutines.") + remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: @@ -1546,13 +1584,8 @@ async def wait_for_review( return result break - if iscoroutine(res) and getcoroutinestate(res) != CORO_CREATED: - raise ValueError("Callbacks must return unstarted coroutines.") - if isgenerator(res) and getgeneratorstate(res) != GEN_CREATED: - raise ValueError("Callbacks must return unstarted coroutines.") - if isinstance(res, (AsyncTask, AsyncFuture)): - if res.done(): + if AsyncFuture.done(res): res.result() else: try: diff --git a/tests/test_http.py b/tests/test_http.py index 62d6c768..73fc0be9 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -3024,16 +3024,23 @@ async def async_mutating_callback(r: Any) -> None: foreign_loop = asyncio.new_event_loop() foreign_fut = foreign_loop.create_future() try: + + def foreign_cb_expired(r: Any) -> Any: + clock.now += 200.0 + return foreign_fut + with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - with pytest.raises(ValueError, match="running event loop"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=10, - on_poll=lambda r: foreign_fut, - ) + res_foreign = await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=foreign_cb_expired, + ) + assert res_foreign.status == "COMPLETED" assert not foreign_fut.done() + assert not foreign_fut.cancelled() + assert not getattr(foreign_fut, "_callbacks", None) finally: foreign_loop.close() @@ -3057,7 +3064,7 @@ async def dummy_coro() -> None: on_poll=lambda r: suspended_coro, ) - # Started coroutine left untouched on deadline expiry + # Started coroutine raises ValueError even after deadline expiry without closing async def dummy_started() -> None: await asyncio.sleep(10) @@ -3071,13 +3078,13 @@ def started_coro_cb(r: Any) -> Any: with Server(lambda request, index: Reply(body=responses[0])) as server: async with session("async", server.url) as client: - res_expired = await client.wait_for_review( - ORG, - REVIEW, - timeout=5.0, - on_poll=started_coro_cb, - ) - assert res_expired.status == "TIMED_OUT" + with pytest.raises(ValueError, match="unstarted coroutines"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=started_coro_cb, + ) assert inspect.getcoroutinestate(started_c) == inspect.CORO_SUSPENDED task_started.cancel() try: @@ -3085,6 +3092,20 @@ def started_coro_cb(r: Any) -> Any: except asyncio.CancelledError: pass + # Non-None, non-awaitable callback return raises TypeError + def sync_int_cb(r: Any) -> Any: + return 42 + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + with pytest.raises(TypeError, match="Callbacks must return None or an awaitable"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=sync_int_cb, + ) + # Unrestricted awaitables returning values (e.g. int) accepted and result discarded async def int_returning_callback(r: Any) -> int: return 42 @@ -3100,7 +3121,11 @@ async def int_returning_callback(r: Any) -> int: assert res_int.status == "COMPLETED" # Pending future exception during cancellation does not replace TIMED_OUT outcome + detached_task: asyncio.Task[None] | None = None + async def failing_cancel_coro(r: Any) -> None: + nonlocal detached_task + detached_task = asyncio.current_task() fut = asyncio.get_running_loop().create_future() try: await fut @@ -3121,14 +3146,16 @@ async def failing_cancel_coro(r: Any) -> None: on_poll=failing_cancel_coro, ) assert res_clean.status == "TIMED_OUT" - await asyncio.sleep(0) - await asyncio.sleep(0) + assert detached_task is not None + await asyncio.wait({detached_task}) + assert detached_task.done() + assert isinstance(detached_task.exception(), RuntimeError) assert unhandled_exceptions == [] finally: loop.set_exception_handler(old_handler) # Case with a waiter whose cancel() raises synchronously: - # assert called and outcome is TIMED_OUT + # assert called and outcome is TIMED_OUT, and no unhandled exception reported class SyncCancelRaisingFuture(asyncio.Future[None]): def __init__(self, loop: asyncio.AbstractEventLoop) -> None: super().__init__(loop=loop) @@ -3138,18 +3165,25 @@ def cancel(self, msg: Any = None) -> bool: self.cancel_called = True raise RuntimeError("synchronous cancel error") - fut_sync_cancel = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: - res_sync_cancel = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.1, - on_poll=lambda r: fut_sync_cancel, - ) - assert res_sync_cancel.status == "TIMED_OUT" - await asyncio.sleep(0) - assert fut_sync_cancel.cancel_called is True + cancel_reports: list[dict[str, Any]] = [] + old_h = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: cancel_reports.append(ctx)) + try: + fut_sync_cancel = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + res_sync_cancel = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.1, + on_poll=lambda r: fut_sync_cancel, + ) + assert res_sync_cancel.status == "TIMED_OUT" + await asyncio.sleep(0) + assert fut_sync_cancel.cancel_called is True + assert cancel_reports == [] + finally: + loop.set_exception_handler(old_h) # Current task cannot be returned by on_poll with Server(lambda request, index: Reply(body=responses[0])) as server: @@ -3635,3 +3669,64 @@ def dst(self, dt_val: Any) -> timedelta: assert copied_dt.tzinfo is not custom_tz_inst assert copied_dt.tzinfo.tz_attr is not custom_tz_inst.tz_attr assert copied_dt.tzinfo.tz_attr == ["tz_state"] + + # Deceptive tuple subclass reporting len 1 with > 1000 items is skipped + class DeceptiveTuple(tuple[Any, ...]): + def __len__(self) -> int: + return 1 + + huge_tup_items = tuple(range(1001)) + deceptive_tup = tuple.__new__(DeceptiveTuple, huge_tup_items) + detail_deceptive = CustomerReviewDetail.from_dict(responses[1]) + detail_deceptive.additional_properties["deceptive"] = deceptive_tup + assert _snapshot_review(detail_deceptive) is None + + # Bytearray subclass rejecting single-buffer constructor is allocated via base methods + class SubByteArray(bytearray): + def __init__(self, required_arg: int) -> None: + super().__init__() + self.required_arg = required_arg + + sub_ba = bytearray.__new__(SubByteArray) + bytearray.__init__(sub_ba, b"sub_bytes") + sub_ba.required_arg = 100 + sub_ba.custom_attr = ["sub_attr"] + + detail_sub_ba = CustomerReviewDetail.from_dict(responses[1]) + detail_sub_ba.additional_properties["sub_ba"] = sub_ba + snap_sub_ba = _snapshot_review(detail_sub_ba) + assert snap_sub_ba is not None + copied_sub_ba = snap_sub_ba.additional_properties["sub_ba"] + assert type(copied_sub_ba) is SubByteArray + assert copied_sub_ba == b"sub_bytes" + assert copied_sub_ba.custom_attr is not sub_ba.custom_attr + assert copied_sub_ba.custom_attr == ["sub_attr"] + + # Datetime subclass cloned and instance attributes snapshotted + class SubDatetime(datetime): + pass + + sub_dt = SubDatetime(2026, 11, 22, 12, 0, 0, tzinfo=UTC) + sub_dt.sub_attr = ["dt_attr"] + detail_sub_dt = CustomerReviewDetail.from_dict(responses[1]) + detail_sub_dt.additional_properties["sub_dt"] = sub_dt + snap_sub_dt = _snapshot_review(detail_sub_dt) + assert snap_sub_dt is not None + copied_sub_dt = snap_sub_dt.additional_properties["sub_dt"] + assert type(copied_sub_dt) is SubDatetime + assert copied_sub_dt == sub_dt + assert copied_sub_dt is not sub_dt + assert copied_sub_dt.sub_attr is not sub_dt.sub_attr + assert copied_sub_dt.sub_attr == ["dt_attr"] + + # Mutable tzinfo returning self from __copy__ is rejected with TypeError + class SelfCopyTz(dt_mod.tzinfo): + def __copy__(self) -> Any: + return self + + self_copy_tz = SelfCopyTz() + dt_self_copy_tz = datetime(2026, 11, 22, 10, 0, 0, tzinfo=self_copy_tz) + detail_self_copy_tz = CustomerReviewDetail.from_dict(responses[1]) + detail_self_copy_tz.additional_properties["self_copy_tz"] = dt_self_copy_tz + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_self_copy_tz) From 0167ff747fee59d6fdc71f6c210ba74c8916d54a Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 09:07:49 +0530 Subject: [PATCH 32/75] Address review 31 findings: base future methods, loop ownership check before deadline, weakref rejection, datetime subclass zone rebuilding, bytearray/set builtins, and test quality --- proofline/client.py | 126 +++++++++++++++++++++------------- tests/test_http.py | 163 +++++++++++++++++++++++++++++++++----------- 2 files changed, 201 insertions(+), 88 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 328d5a5c..1899e9e7 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,6 +5,7 @@ import copy import datetime import math +import weakref from asyncio import ( Future as AsyncFuture, ) @@ -329,6 +330,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if task_type == _ITEM_TASK: key, is_attr, val = it_or_key, extra[0], extra[1] + if isinstance(val, (weakref.ref, weakref.ProxyType, weakref.CallableProxyType)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if _is_immutable(val): _assign_target(target, key, is_attr, val) continue @@ -401,7 +406,9 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) elif isinstance(val, (set, frozenset)): - if len(val) == 0: + set_len = set.__len__(val) if isinstance(val, set) else frozenset.__len__(val) + set_it = set.__iter__(val) if isinstance(val, set) else frozenset.__iter__(val) + if set_len == 0: try: res_empty = type(val)() except Exception as exc: @@ -416,9 +423,9 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: temp_set_list: list[Any] = [] stack.append((_SET_FINALIZE, target, key, is_attr, val_id, val, temp_set_list)) - stack.append((_LIST_EXPAND, temp_set_list, iter(val))) + stack.append((_LIST_EXPAND, temp_set_list, set_it)) elif isinstance(val, bytearray): - if len(val) > _MAX_SAFE_BUFFER_SIZE: + if bytearray.__len__(val) > _MAX_SAFE_BUFFER_SIZE: return None try: resolved = bytearray.__new__(type(val)) @@ -458,40 +465,46 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non memo[val_id] = resolved_mv _assign_target(target, key, is_attr, resolved_mv) elif isinstance(val, datetime.datetime): + tz = val.tzinfo + copied_tz = tz + if tz is not None and type(tz) is not datetime.timezone: + if id(tz) in memo: + copied_tz = memo[id(tz)] + else: + try: + copied_tz = copy.copy(tz) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(tz).__name__}" + ) from exc + if copied_tz is tz: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(tz).__name__}" + ) + memo[id(tz)] = copied_tz + if hasattr(tz, "__dict__") or hasattr(tz, "__slots__"): + stack.append((_OBJ_EXPAND, copied_tz, iter(_get_obj_attrs(tz)))) + if type(val) is datetime.datetime: - if val.tzinfo is None or type(val.tzinfo) is datetime.timezone: + if copied_tz is tz and (tz is None or type(tz) is datetime.timezone): _assign_target(target, key, is_attr, val) else: - tz = val.tzinfo - if id(tz) in memo: - copied_tz = memo[id(tz)] - else: - try: - copied_tz = copy.copy(tz) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(tz).__name__}" - ) from exc - if copied_tz is tz: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(tz).__name__}" - ) - memo[id(tz)] = copied_tz - if hasattr(tz, "__dict__") or hasattr(tz, "__slots__"): - stack.append((_OBJ_EXPAND, copied_tz, iter(_get_obj_attrs(tz)))) new_dt = val.replace(tzinfo=copied_tz) memo[val_id] = new_dt _assign_target(target, key, is_attr, new_dt) else: try: - new_dt = copy.copy(val) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc + new_dt = val.replace(tzinfo=copied_tz) + except Exception: + try: + new_dt = copy.copy(val) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc if new_dt is val: raise TypeError( "Unsupported mutable value in review extension data: " @@ -671,7 +684,7 @@ def _safe_cancel_target(target: Any) -> None: def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: try: try: - loop = fut.get_loop() + loop = AsyncFuture.get_loop(fut) except Exception: return try: @@ -688,8 +701,9 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: pass return try: - fut.add_done_callback( - lambda t: AsyncFuture.exception(t) if not AsyncFuture.cancelled(t) else None + AsyncFuture.add_done_callback( + fut, + lambda t: AsyncFuture.exception(t) if not AsyncFuture.cancelled(t) else None, ) except BaseException: pass @@ -707,11 +721,14 @@ def _detach_overdue_task( wrapper_started: bool, ) -> None: try: - task.add_done_callback(lambda t: AsyncTask.exception(t) if not t.cancelled() else None) + AsyncFuture.add_done_callback( + task, + lambda t: AsyncTask.exception(t) if not AsyncFuture.cancelled(t) else None, + ) except BaseException: pass try: - loop = task.get_loop() + loop = AsyncFuture.get_loop(task) if loop.is_running() and not loop.is_closed(): loop.call_soon(_safe_cancel_target, task) except BaseException: @@ -1125,7 +1142,18 @@ def wait_for_review( if on_poll is not None and (_transport.remaining() or 0) > 0: snapshot = _snapshot_review(last) if snapshot is not None and (_transport.remaining() or 0) > 0: - on_poll(snapshot) + res = on_poll(snapshot) + if isawaitable(res): + if iscoroutine(res): + try: + if getcoroutinestate(res) == CORO_CREATED: + res.close() + except Exception: + pass + raise TypeError( + "on_poll returned an awaitable; use AsyncProoflineClient " + "for async callbacks." + ) if result is not None: return result if (_transport.remaining() or 0) <= 0: @@ -1566,6 +1594,19 @@ async def wait_for_review( if isgenerator(res) and getgeneratorstate(res) != GEN_CREATED: raise ValueError("Callbacks must return unstarted coroutines.") + if isinstance(res, (AsyncTask, AsyncFuture)): + if not AsyncFuture.done(res): + try: + res_loop = AsyncFuture.get_loop(res) + except Exception: + res_loop = None + running_loop = async_get_running_loop() + if res_loop is not running_loop or res_loop.is_closed(): + raise ValueError( + "Pending callback futures must belong " + "to the running event loop." + ) + remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: @@ -1588,19 +1629,10 @@ async def wait_for_review( if AsyncFuture.done(res): res.result() else: - try: - res_loop = res.get_loop() - except Exception: - res_loop = None - running_loop = async_get_running_loop() - if res_loop is not running_loop or res_loop.is_closed(): - raise ValueError( - "Pending callback futures must belong " - "to the running event loop." - ) completed_at: list[float] = [] - res.add_done_callback( - lambda _: completed_at.append(monotonic()) + AsyncFuture.add_done_callback( + res, + lambda _: completed_at.append(monotonic()), ) remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: diff --git a/tests/test_http.py b/tests/test_http.py index 73fc0be9..16efdbbe 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2636,6 +2636,8 @@ def inline_sync_cb(r: Any) -> None: r.status = "MUTATED" r.actions.publish = True r.additional_properties["mutated"] = "mutated_value" + if r.assessments: + r.assessments[0].checks.receipt_recorded = False async with session("async", server.url) as client: result = await call( @@ -2651,6 +2653,7 @@ def inline_sync_cb(r: Any) -> None: assert result.review.status == "COMPLETED" assert result.review.actions.publish is False assert "mutated" not in result.review.additional_properties + assert result.review.assessments[0].checks.receipt_recorded is True # Assert callback TimeoutError before deadline propagates async def failing_callback(r: Any) -> None: @@ -2905,6 +2908,42 @@ async def suspending_callback(r: Any) -> None: assert res.status == "COMPLETED" assert resumed_within_budget + # Case 6: Pending future exception during cancellation does not replace TIMED_OUT + detached_task: asyncio.Task[None] | None = None + + async def failing_cancel_coro(r: Any) -> None: + nonlocal detached_task + detached_task = asyncio.current_task() + fut = asyncio.get_running_loop().create_future() + try: + await fut + except asyncio.CancelledError: + raise RuntimeError("error during cancellation") + + unhandled_exceptions: list[dict[str, Any]] = [] + loop = asyncio.get_running_loop() + old_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhandled_exceptions.append(ctx)) + try: + client.get_review = fake_running # type: ignore + res_clean = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=failing_cancel_coro, + ) + assert res_clean.status == "TIMED_OUT" + assert detached_task is not None + done, _ = await asyncio.wait({detached_task}, timeout=2.0) + assert detached_task in done + del detached_task + import gc + + gc.collect() + assert unhandled_exceptions == [] + finally: + loop.set_exception_handler(old_handler) + asyncio.run(main()) """ checkout_root = Path(__file__).resolve().parent.parent @@ -2924,6 +2963,8 @@ def sync_mutating_callback(r: Any) -> None: r.status = "MUTATED" r.actions.publish = True r.additional_properties["mutated"] = "mutated_value" + if r.assessments: + r.assessments[0].checks.receipt_recorded = False async def async_mutating_callback(r: Any) -> None: nonlocal mutated_count @@ -2931,6 +2972,8 @@ async def async_mutating_callback(r: Any) -> None: r.status = "MUTATED" r.actions.publish = True r.additional_properties["mutated"] = "mutated_value" + if r.assessments: + r.assessments[0].checks.receipt_recorded = False with Server(lambda request, index: Reply(body=responses[1])) as server: async with session(mode, server.url) as client: @@ -2947,6 +2990,7 @@ async def async_mutating_callback(r: Any) -> None: assert res.review.status != "MUTATED" assert res.review.actions.publish is False assert "mutated" not in res.review.additional_properties + assert res.review.assessments[0].checks.receipt_recorded is True # Test snapshot directly with an in-memory deep extension and custom tuple to bypass HTTP JSON deep_container: dict[str, Any] = {} @@ -3031,13 +3075,13 @@ def foreign_cb_expired(r: Any) -> Any: with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - res_foreign = await client.wait_for_review( - ORG, - REVIEW, - timeout=10, - on_poll=foreign_cb_expired, - ) - assert res_foreign.status == "COMPLETED" + with pytest.raises(ValueError, match="running event loop"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=foreign_cb_expired, + ) assert not foreign_fut.done() assert not foreign_fut.cancelled() assert not getattr(foreign_fut, "_callbacks", None) @@ -3120,40 +3164,6 @@ async def int_returning_callback(r: Any) -> int: ) assert res_int.status == "COMPLETED" - # Pending future exception during cancellation does not replace TIMED_OUT outcome - detached_task: asyncio.Task[None] | None = None - - async def failing_cancel_coro(r: Any) -> None: - nonlocal detached_task - detached_task = asyncio.current_task() - fut = asyncio.get_running_loop().create_future() - try: - await fut - except asyncio.CancelledError: - raise RuntimeError("error during cancellation") - - unhandled_exceptions: list[dict[str, Any]] = [] - loop = asyncio.get_running_loop() - old_handler = loop.get_exception_handler() - loop.set_exception_handler(lambda _loop, ctx: unhandled_exceptions.append(ctx)) - try: - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: - res_clean = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.1, - on_poll=failing_cancel_coro, - ) - assert res_clean.status == "TIMED_OUT" - assert detached_task is not None - await asyncio.wait({detached_task}) - assert detached_task.done() - assert isinstance(detached_task.exception(), RuntimeError) - assert unhandled_exceptions == [] - finally: - loop.set_exception_handler(old_handler) - # Case with a waiter whose cancel() raises synchronously: # assert called and outcome is TIMED_OUT, and no unhandled exception reported class SyncCancelRaisingFuture(asyncio.Future[None]): @@ -3166,6 +3176,7 @@ def cancel(self, msg: Any = None) -> bool: raise RuntimeError("synchronous cancel error") cancel_reports: list[dict[str, Any]] = [] + loop = asyncio.get_running_loop() old_h = loop.get_exception_handler() loop.set_exception_handler(lambda _loop, ctx: cancel_reports.append(ctx)) try: @@ -3684,6 +3695,8 @@ def __len__(self) -> int: # Bytearray subclass rejecting single-buffer constructor is allocated via base methods class SubByteArray(bytearray): def __init__(self, required_arg: int) -> None: + if not isinstance(required_arg, int) or isinstance(required_arg, bool): + raise TypeError("required_arg must be an int") super().__init__() self.required_arg = required_arg @@ -3730,3 +3743,71 @@ def __copy__(self) -> Any: detail_self_copy_tz.additional_properties["self_copy_tz"] = dt_self_copy_tz with pytest.raises(TypeError, match="Unsupported mutable value"): _snapshot_review(detail_self_copy_tz) + + # SubDatetime with custom mutable tzinfo rebuilds subclass with copied tzinfo + sub_dt_custom_tz = SubDatetime(2026, 11, 22, 12, 0, 0, tzinfo=custom_tz_inst) + sub_dt_custom_tz.sub_attr = ["dt_tz_attr"] + detail_sub_tz = CustomerReviewDetail.from_dict(responses[1]) + detail_sub_tz.additional_properties["sub_dt_tz"] = sub_dt_custom_tz + snap_sub_tz = _snapshot_review(detail_sub_tz) + assert snap_sub_tz is not None + copied_sub_tz = snap_sub_tz.additional_properties["sub_dt_tz"] + assert type(copied_sub_tz) is SubDatetime + assert copied_sub_tz == sub_dt_custom_tz + assert copied_sub_tz.tzinfo is not custom_tz_inst + assert copied_sub_tz.tzinfo.tz_attr is not custom_tz_inst.tz_attr + assert copied_sub_tz.sub_attr is not sub_dt_custom_tz.sub_attr + + # Deceptive set subclass returning len 0 with members copies all members + class DeceptiveSet(set[Any]): + def __len__(self) -> int: + return 0 + + deceptive_s = DeceptiveSet(["member1", "member2"]) + detail_deceptive_s = CustomerReviewDetail.from_dict(responses[1]) + detail_deceptive_s.additional_properties["deceptive_s"] = deceptive_s + snap_deceptive_s = _snapshot_review(detail_deceptive_s) + assert snap_deceptive_s is not None + copied_deceptive_s = snap_deceptive_s.additional_properties["deceptive_s"] + assert type(copied_deceptive_s) is DeceptiveSet + assert "member1" in copied_deceptive_s and "member2" in copied_deceptive_s + + # Deceptive bytearray subclass underreporting len with > 65536 bytes is skipped + class DeceptiveByteArray(bytearray): + def __len__(self) -> int: + return 1 + + huge_ba = bytearray.__new__(DeceptiveByteArray) + bytearray.__init__(huge_ba, b"x" * 65537) + detail_huge_ba = CustomerReviewDetail.from_dict(responses[1]) + detail_huge_ba.additional_properties["huge_ba"] = huge_ba + assert _snapshot_review(detail_huge_ba) is None + + # Weak references in snapshot extension data are rejected with TypeError + import weakref + + class TargetObj: + pass + + dummy_target = TargetObj() + weak_ref_obj = weakref.ref(dummy_target) + detail_weakref = CustomerReviewDetail.from_dict(responses[1]) + detail_weakref.additional_properties["weakref"] = weak_ref_obj + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_weakref) + + # Synchronous wait_for_review passed an async callback raises TypeError + async def async_cb_on_sync_client(r: Any) -> None: + pass + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("sync", server.url) as sync_cli: + with pytest.raises(TypeError, match="AsyncProoflineClient"): + await call( + sync_cli, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=async_cb_on_sync_client, + ) From c5661f988ffe3df1537fd365b5996a666c7419de Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 09:19:25 +0530 Subject: [PATCH 33/75] Address review 32 findings: detach overdue callbacks without cancelling, close generator awaitables, retrieve foreign future exceptions, datetime subclass zone validation, assessment test assertions, and document return-validation errors --- README.md | 6 +- proofline/client.py | 55 +++++++------- tests/test_http.py | 181 ++++++++++++++++++++++++++++++-------------- 3 files changed, 154 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index b3a689cf..430b2dc6 100644 --- a/README.md +++ b/README.md @@ -54,11 +54,11 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback. `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions propagate even when a terminal outcome has already been determined. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must not return an awaitable (doing so raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures even before cancellation or discard (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. Overdue callbacks are detached without cancelling them and may continue running. -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 1899e9e7..6afbaa14 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -505,7 +505,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non "Unsupported mutable value in review extension data: " f"{type(val).__name__}" ) from exc - if new_dt is val: + if new_dt is val or new_dt.tzinfo is not copied_tz: raise TypeError( "Unsupported mutable value in review extension data: " f"{type(val).__name__}" @@ -683,6 +683,13 @@ def _safe_cancel_target(target: Any) -> None: def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: try: + if AsyncFuture.done(fut): + if not AsyncFuture.cancelled(fut): + try: + AsyncFuture.exception(fut) + except Exception: + pass + return try: loop = AsyncFuture.get_loop(fut) except Exception: @@ -693,13 +700,6 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: return if loop is not running_loop or loop.is_closed(): return - if AsyncFuture.done(fut): - if not AsyncFuture.cancelled(fut): - try: - AsyncFuture.exception(fut) - except Exception: - pass - return try: AsyncFuture.add_done_callback( fut, @@ -707,10 +707,6 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: ) except BaseException: pass - try: - loop.call_soon(_safe_cancel_target, fut) - except BaseException: - pass except BaseException: pass @@ -727,12 +723,6 @@ def _detach_overdue_task( ) except BaseException: pass - try: - loop = AsyncFuture.get_loop(task) - if loop.is_running() and not loop.is_closed(): - loop.call_soon(_safe_cancel_target, task) - except BaseException: - pass if not wrapper_started: if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: try: @@ -1114,10 +1104,11 @@ def wait_for_review( delivery. Oversized tuples or buffers in review extension data skip on_poll snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before on_poll runs. - on_poll exceptions propagate even when a terminal outcome - has already been determined. Synchronous callbacks must return before a - terminal result can be delivered and the polling deadline cannot - interrupt them. + on_poll exceptions and return-validation errors propagate even when a + terminal outcome has already been determined and can prevent the waiter + from returning a classified outcome. Synchronous callbacks must not + return awaitables and must return before a terminal result can be + delivered; the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: @@ -1150,6 +1141,12 @@ def wait_for_review( res.close() except Exception: pass + elif isgenerator(res): + try: + if getgeneratorstate(res) == GEN_CREATED: + res.close() + except Exception: + pass raise TypeError( "on_poll returned an awaitable; use AsyncProoflineClient " "for async callbacks." @@ -1546,12 +1543,14 @@ async def wait_for_review( is reached are delivered; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip on_poll snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable - values propagate before on_poll runs. Inline failures and awaitable failures - observed before the deadline propagate, - but the deadline can suppress awaitable failures even before cancellation - or discard (and a pending future's failure can be suppressed if its done - callback runs after the deadline), including when an outcome is already - classified. Synchronous + values propagate before on_poll runs. Callback return-validation errors + and exceptions propagate even when a terminal outcome has already been + determined, preventing the waiter from returning a classified outcome. + Inline failures and awaitable failures observed before the deadline propagate, + but the deadline can suppress awaitable failures (and a pending future's + failure can be suppressed if its done callback runs after the deadline), + including when an outcome is already classified. Overdue callbacks are + detached without cancelling them and may continue running. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. """ diff --git a/tests/test_http.py b/tests/test_http.py index 16efdbbe..803263a4 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2636,8 +2636,9 @@ def inline_sync_cb(r: Any) -> None: r.status = "MUTATED" r.actions.publish = True r.additional_properties["mutated"] = "mutated_value" - if r.assessments: - r.assessments[0].checks.receipt_recorded = False + assert len(r.assessments) > 0 + assert r.assessments[0].checks.receipt_recorded is True + r.assessments[0].checks.receipt_recorded = False async with session("async", server.url) as client: result = await call( @@ -2738,13 +2739,15 @@ def timely_fail_cb(r: Any) -> asyncio.Future[None]: # Late-observed pending future failure preserves the classified outcome late_fut: asyncio.Future[None] = asyncio.get_running_loop().create_future() late_fut.add_done_callback(lambda _: setattr(clock, "now", clock.now + 200.0)) + producer_task: asyncio.Task[None] | None = None async def fail_late_soon() -> None: - await asyncio.sleep(0.01) + await asyncio.sleep(0) late_fut.set_exception(ValueError("late failure")) def late_fail_cb(r: Any) -> asyncio.Future[None]: - asyncio.create_task(fail_late_soon()) + nonlocal producer_task + producer_task = asyncio.create_task(fail_late_soon()) return late_fut with Server(lambda request, index: Reply(body=responses[1])) as server: @@ -2756,6 +2759,11 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: on_poll=late_fail_cb, ) assert res_late.status == "COMPLETED" + assert late_fut.done() + assert isinstance(late_fut.exception(), ValueError) + assert clock.now >= 200.0 + if producer_task is not None: + await producer_task # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. @@ -2780,7 +2788,7 @@ async def fake_completed(org: Any, rev: Any) -> Any: async with AsyncProoflineClient( token="test_token", base_url="https://api.proofline.sh" ) as client: - # Case 1: Pending same-loop Future that times out + # Case 1: Pending same-loop Future that times out is detached without cancelling pending_fut: asyncio.Future[None] | None = None def pending_future_callback(r: Any) -> asyncio.Future[None]: @@ -2800,7 +2808,8 @@ def pending_future_callback(r: Any) -> asyncio.Future[None]: assert res.status == "TIMED_OUT" await asyncio.sleep(0) assert pending_fut is not None - assert pending_fut.cancelled() + assert not pending_fut.cancelled() + assert not pending_fut.done() # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() @@ -2825,19 +2834,14 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: assert completed_fut.done() assert not completed_fut.cancelled() - # Case 3: Blocking cleanup callback on non-terminal review - cancellation_requested = asyncio.Event() - cleanup_blocked = asyncio.Event() - cleanup_completed_3 = asyncio.Event() + # Case 3: Overdue callback continues running without cancellation on non-terminal review + callback_running = asyncio.Event() + callback_finished = asyncio.Event() - async def blocking_cleanup_coro(r: Any) -> None: - try: - await asyncio.sleep(5.0) - except asyncio.CancelledError: - cancellation_requested.set() - await cleanup_blocked.wait() - cleanup_completed_3.set() - raise + async def continuing_coro(r: Any) -> None: + callback_running.set() + await asyncio.sleep(0.3) + callback_finished.set() client.get_review = fake_running # type: ignore @@ -2846,30 +2850,23 @@ async def blocking_cleanup_coro(r: Any) -> None: ORG, REVIEW, timeout=0.2, - on_poll=blocking_cleanup_coro, + on_poll=continuing_coro, ) elapsed3 = time.monotonic() - start_t3 assert 0.18 <= elapsed3 <= 0.60 assert res.status == "TIMED_OUT" - await asyncio.sleep(0) - await asyncio.sleep(0) - assert cancellation_requested.is_set() - cleanup_blocked.set() - await cleanup_completed_3.wait() - - # Case 4: Blocking cleanup callback on terminal review - cancellation_requested_term = asyncio.Event() - cleanup_blocked_term = asyncio.Event() - cleanup_completed_4 = asyncio.Event() - - async def blocking_cleanup_coro_term(r: Any) -> None: - try: - await asyncio.sleep(5.0) - except asyncio.CancelledError: - cancellation_requested_term.set() - await cleanup_blocked_term.wait() - cleanup_completed_4.set() - raise + assert callback_running.is_set() + assert not callback_finished.is_set() + await callback_finished.wait() + + # Case 4: Overdue callback continues running without cancellation on terminal review + callback_running_term = asyncio.Event() + callback_finished_term = asyncio.Event() + + async def continuing_coro_term(r: Any) -> None: + callback_running_term.set() + await asyncio.sleep(0.3) + callback_finished_term.set() client.get_review = fake_completed # type: ignore @@ -2878,16 +2875,14 @@ async def blocking_cleanup_coro_term(r: Any) -> None: ORG, REVIEW, timeout=0.2, - on_poll=blocking_cleanup_coro_term, + on_poll=continuing_coro_term, ) elapsed4 = time.monotonic() - start_t4 assert 0.18 <= elapsed4 <= 0.60 assert res.status == "COMPLETED" - await asyncio.sleep(0) - await asyncio.sleep(0) - assert cancellation_requested_term.is_set() - cleanup_blocked_term.set() - await cleanup_completed_4.wait() + assert callback_running_term.is_set() + assert not callback_finished_term.is_set() + await callback_finished_term.wait() # Case 5: Suspending callback that succeeds within budget resumed_within_budget = False @@ -2908,17 +2903,15 @@ async def suspending_callback(r: Any) -> None: assert res.status == "COMPLETED" assert resumed_within_budget - # Case 6: Pending future exception during cancellation does not replace TIMED_OUT + # Case 6: Overdue callback failure is observed without leaking to loop handler detached_task: asyncio.Task[None] | None = None + callback_trigger = asyncio.Event() - async def failing_cancel_coro(r: Any) -> None: + async def failing_overdue_coro(r: Any) -> None: nonlocal detached_task detached_task = asyncio.current_task() - fut = asyncio.get_running_loop().create_future() - try: - await fut - except asyncio.CancelledError: - raise RuntimeError("error during cancellation") + await callback_trigger.wait() + raise RuntimeError("error in overdue callback") unhandled_exceptions: list[dict[str, Any]] = [] loop = asyncio.get_running_loop() @@ -2930,12 +2923,14 @@ async def failing_cancel_coro(r: Any) -> None: ORG, REVIEW, timeout=0.2, - on_poll=failing_cancel_coro, + on_poll=failing_overdue_coro, ) assert res_clean.status == "TIMED_OUT" assert detached_task is not None + callback_trigger.set() done, _ = await asyncio.wait({detached_task}, timeout=2.0) assert detached_task in done + del done del detached_task import gc @@ -2944,6 +2939,24 @@ async def failing_cancel_coro(r: Any) -> None: finally: loop.set_exception_handler(old_handler) + # Case 7: Overdue callback awaiting the polling task is not cancelled + callback_completed_7 = asyncio.Event() + + async def awaiting_runner_callback(r: Any) -> None: + await asyncio.sleep(0.3) + callback_completed_7.set() + + client.get_review = fake_running # type: ignore + res_7 = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=awaiting_runner_callback, + ) + assert res_7.status == "TIMED_OUT" + await asyncio.sleep(0) + await callback_completed_7.wait() + asyncio.run(main()) """ checkout_root = Path(__file__).resolve().parent.parent @@ -2963,8 +2976,9 @@ def sync_mutating_callback(r: Any) -> None: r.status = "MUTATED" r.actions.publish = True r.additional_properties["mutated"] = "mutated_value" - if r.assessments: - r.assessments[0].checks.receipt_recorded = False + assert len(r.assessments) > 0 + assert r.assessments[0].checks.receipt_recorded is True + r.assessments[0].checks.receipt_recorded = False async def async_mutating_callback(r: Any) -> None: nonlocal mutated_count @@ -2972,8 +2986,9 @@ async def async_mutating_callback(r: Any) -> None: r.status = "MUTATED" r.actions.publish = True r.additional_properties["mutated"] = "mutated_value" - if r.assessments: - r.assessments[0].checks.receipt_recorded = False + assert len(r.assessments) > 0 + assert r.assessments[0].checks.receipt_recorded is True + r.assessments[0].checks.receipt_recorded = False with Server(lambda request, index: Reply(body=responses[1])) as server: async with session(mode, server.url) as client: @@ -3191,7 +3206,7 @@ def cancel(self, msg: Any = None) -> bool: ) assert res_sync_cancel.status == "TIMED_OUT" await asyncio.sleep(0) - assert fut_sync_cancel.cancel_called is True + assert fut_sync_cancel.cancel_called is False assert cancel_reports == [] finally: loop.set_exception_handler(old_h) @@ -3811,3 +3826,55 @@ async def async_cb_on_sync_client(r: Any) -> None: timeout=10, on_poll=async_cb_on_sync_client, ) + + # Synchronous wait_for_review closes generator awaitable in GEN_CREATED + import types + + @types.coroutine + def gen_coro_cb(r: Any) -> Any: + yield + + gen_cb_inst = gen_coro_cb(None) + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("sync", server.url) as sync_cli: + with pytest.raises(TypeError, match="AsyncProoflineClient"): + await call( + sync_cli, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: gen_cb_inst, + ) + assert inspect.getgeneratorstate(gen_cb_inst) == inspect.GEN_CLOSED + + # Detach overdue future retrieves exception from completed failed foreign future + foreign_loop_failed = asyncio.new_event_loop() + try: + failed_foreign_fut = foreign_loop_failed.create_future() + failed_foreign_fut.set_exception(RuntimeError("foreign future failed")) + from proofline.client import _detach_overdue_future + + _detach_overdue_future(failed_foreign_fut) + finally: + foreign_loop_failed.close() + + # Datetime subclass whose replace fails and fallback lacks copied_tz raises TypeError + class BrokenSubDatetime(datetime): + def __new__(cls, y: int, m: int, d: int, tzinfo: Any = None) -> Any: + return super().__new__(cls, y, m, d, tzinfo=tzinfo) + + def replace(self, **kwargs: Any) -> Any: + raise RuntimeError("cannot replace") + + def __copy__(self) -> Any: + return super().__new__( + BrokenSubDatetime, self.year, self.month, self.day, tzinfo=self.tzinfo + ) + + broken_dt = BrokenSubDatetime(2026, 11, 22, tzinfo=custom_tz_inst) + detail_broken_dt = CustomerReviewDetail.from_dict(responses[1]) + detail_broken_dt.additional_properties["broken_dt"] = broken_dt + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_broken_dt) From 2b097c96caf8eaa63411639e99869d0211c1f3ea Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 09:33:56 +0530 Subject: [PATCH 34/75] Address review 33 findings: built-in set operations bypassing subclass constructors, late future assertions, foreign future loop handling, and synchronous callback non-None checks --- README.md | 2 +- proofline/client.py | 102 +++++++++++++++++++++++++++++------ tests/test_http.py | 127 ++++++++++++++++++++++++++++++++++++-------- 3 files changed, 191 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 430b2dc6..8c0182e3 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must not return an awaitable (doing so raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. Overdue callbacks are detached without cancelling them and may continue running. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 6afbaa14..cb50ea1c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -27,6 +27,7 @@ from asyncio import ( wait as async_wait, ) +from collections import deque from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from inspect import ( CORO_CREATED, @@ -409,21 +410,63 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non set_len = set.__len__(val) if isinstance(val, set) else frozenset.__len__(val) set_it = set.__iter__(val) if isinstance(val, set) else frozenset.__iter__(val) if set_len == 0: - try: - res_empty = type(val)() - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc + if type(val) is set: + res_empty = set() + elif type(val) is frozenset: + res_empty = frozenset() + else: + try: + inst = type(val)() + if len(inst) != 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc + if isinstance(val, set): + res_empty = set.__new__(type(val)) + set.clear(res_empty) + else: + res_empty = frozenset.__new__(type(val), ()) + if set(res_empty) if isinstance(val, set) else frozenset(res_empty): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) memo[val_id] = res_empty if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, res_empty, iter(_get_obj_attrs(val)))) _assign_target(target, key, is_attr, res_empty) else: + if type(val) is not set and type(val) is not frozenset: + try: + inst = type(val)() + if len(inst) != 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc temp_set_list: list[Any] = [] stack.append((_SET_FINALIZE, target, key, is_attr, val_id, val, temp_set_list)) stack.append((_LIST_EXPAND, temp_set_list, set_it)) + elif isinstance(val, deque): + if len(val) > _MAX_SAFE_BUFFER_SIZE: + return None + new_deque: deque[Any] = deque(maxlen=val.maxlen) + memo[val_id] = new_deque + _assign_target(target, key, is_attr, new_deque) + stack.append((_LIST_EXPAND, new_deque, iter(val))) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, new_deque, iter(_get_obj_attrs(val)))) elif isinstance(val, bytearray): if bytearray.__len__(val) > _MAX_SAFE_BUFFER_SIZE: return None @@ -659,13 +702,36 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if val_id in memo: res_set = memo[val_id] else: - try: - res_set = type(orig_val)(temp_set_list) - except Exception as exc: + if type(orig_val) is set: + res_set = set(temp_set_list) + elif type(orig_val) is frozenset: + res_set = frozenset(temp_set_list) + elif isinstance(orig_val, set): + try: + res_set = set.__new__(type(orig_val)) + set.clear(res_set) + set.update(res_set, temp_set_list) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) from exc + else: # frozenset subclass + try: + res_set = frozenset.__new__(type(orig_val), temp_set_list) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) from exc + expected_members = set(temp_set_list) + if (set(res_set) if isinstance(orig_val, set) else frozenset(res_set)) != ( + expected_members if isinstance(orig_val, set) else frozenset(temp_set_list) + ): raise TypeError( "Unsupported mutable value in review extension data: " f"{type(orig_val).__name__}" - ) from exc + ) memo[val_id] = res_set if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): stack.append((_OBJ_EXPAND, res_set, iter(_get_obj_attrs(orig_val)))) @@ -1151,6 +1217,8 @@ def wait_for_review( "on_poll returned an awaitable; use AsyncProoflineClient " "for async callbacks." ) + if res is not None: + raise TypeError(f"Callbacks must return None, got {type(res).__name__}") if result is not None: return result if (_transport.remaining() or 0) <= 0: @@ -1549,8 +1617,10 @@ async def wait_for_review( Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), - including when an outcome is already classified. Overdue callbacks are - detached without cancelling them and may continue running. Synchronous + including when an outcome is already classified. When the deadline expires, + unstarted coroutines returned by on_poll are closed without being scheduled, + while already-running callback tasks and futures are detached without + cancellation and may continue running. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. """ @@ -1626,7 +1696,7 @@ async def wait_for_review( if isinstance(res, (AsyncTask, AsyncFuture)): if AsyncFuture.done(res): - res.result() + AsyncFuture.result(res) else: completed_at: list[float] = [] AsyncFuture.add_done_callback( @@ -1649,7 +1719,7 @@ async def wait_for_review( deadline_val is None or completed_at[0] <= deadline_val ) if cb_finished_in_budget and res in done: - res.result() + AsyncFuture.result(res) else: _detach_overdue_future(res) if result is not None: @@ -1733,7 +1803,7 @@ async def _runner() -> None: deadline_val is None or completed_at[0] <= deadline_val ) if cb_finished_in_budget and task in done: - task.result() + AsyncTask.result(task) else: _detach_overdue_task(task, res, wrapper_started) if result is not None: diff --git a/tests/test_http.py b/tests/test_http.py index 803263a4..1d8f56a2 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2750,20 +2750,31 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: producer_task = asyncio.create_task(fail_late_soon()) return late_fut - with Server(lambda request, index: Reply(body=responses[1])) as server: - async with session("async", server.url) as client: - res_late = await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=late_fail_cb, - ) - assert res_late.status == "COMPLETED" - assert late_fut.done() - assert isinstance(late_fut.exception(), ValueError) - assert clock.now >= 200.0 - if producer_task is not None: - await producer_task + unhandled_reports: list[dict[str, Any]] = [] + loop = asyncio.get_running_loop() + old_h = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhandled_reports.append(ctx)) + try: + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_late = await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=late_fail_cb, + ) + assert res_late.status == "COMPLETED" + assert late_fut.done() + assert clock.now >= 200.0 + if producer_task is not None: + await producer_task + del late_fut + import gc + + gc.collect() + assert unhandled_reports == [] + finally: + loop.set_exception_handler(old_h) # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. @@ -2940,22 +2951,27 @@ async def failing_overdue_coro(r: Any) -> None: loop.set_exception_handler(old_handler) # Case 7: Overdue callback awaiting the polling task is not cancelled + polling_waiter_task: asyncio.Task[Any] | None = None callback_completed_7 = asyncio.Event() async def awaiting_runner_callback(r: Any) -> None: - await asyncio.sleep(0.3) + assert polling_waiter_task is not None + outcome_inner = await polling_waiter_task + assert outcome_inner.status == "TIMED_OUT" callback_completed_7.set() client.get_review = fake_running # type: ignore - res_7 = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=awaiting_runner_callback, + polling_waiter_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=awaiting_runner_callback, + ) ) + res_7 = await polling_waiter_task assert res_7.status == "TIMED_OUT" - await asyncio.sleep(0) - await callback_completed_7.wait() + await asyncio.wait_for(callback_completed_7.wait(), timeout=1.0) asyncio.run(main()) """ @@ -3787,6 +3803,44 @@ def __len__(self) -> int: assert type(copied_deceptive_s) is DeceptiveSet assert "member1" in copied_deceptive_s and "member2" in copied_deceptive_s + # Set subclass whose constructor inserts extra member is rejected with TypeError + class InjectedSet(set[Any]): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.add("injected_shared_member") + + injected_s = InjectedSet(["orig_member"]) + detail_injected_s = CustomerReviewDetail.from_dict(responses[1]) + detail_injected_s.additional_properties["injected_s"] = injected_s + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_injected_s) + + # Standard built-in set and frozenset properly snapshotted + normal_s = {"member1", "member2"} + normal_fs = frozenset(["fs1", "fs2"]) + detail_sets = CustomerReviewDetail.from_dict(responses[1]) + detail_sets.additional_properties["normal_s"] = normal_s + detail_sets.additional_properties["normal_fs"] = normal_fs + snap_sets = _snapshot_review(detail_sets) + assert snap_sets is not None + assert snap_sets.additional_properties["normal_s"] == normal_s + assert snap_sets.additional_properties["normal_s"] is not normal_s + assert snap_sets.additional_properties["normal_fs"] == normal_fs + + # Deque traversed and snapshotted, and weakref inside deque rejected + from collections import deque + + dq: deque[Any] = deque(["elem1", ["nested_list"]]) + detail_dq = CustomerReviewDetail.from_dict(responses[1]) + detail_dq.additional_properties["dq"] = dq + snap_dq = _snapshot_review(detail_dq) + assert snap_dq is not None + copied_dq = snap_dq.additional_properties["dq"] + assert isinstance(copied_dq, deque) + assert copied_dq == dq + assert copied_dq is not dq + assert copied_dq[1] is not dq[1] + # Deceptive bytearray subclass underreporting len with > 65536 bytes is skipped class DeceptiveByteArray(bytearray): def __len__(self) -> int: @@ -3811,6 +3865,13 @@ class TargetObj: with pytest.raises(TypeError, match="Unsupported mutable value"): _snapshot_review(detail_weakref) + # Deque containing weak reference rejected with TypeError + dq_weakref: deque[Any] = deque([weak_ref_obj]) + detail_dq_weakref = CustomerReviewDetail.from_dict(responses[1]) + detail_dq_weakref.additional_properties["dq_weakref"] = dq_weakref + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_dq_weakref) + # Synchronous wait_for_review passed an async callback raises TypeError async def async_cb_on_sync_client(r: Any) -> None: pass @@ -3827,6 +3888,19 @@ async def async_cb_on_sync_client(r: Any) -> None: on_poll=async_cb_on_sync_client, ) + # Synchronous wait_for_review rejecting non-None return with TypeError + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("sync", server.url) as sync_cli: + with pytest.raises(TypeError, match="Callbacks must return None"): + await call( + sync_cli, + "wait_for_review", + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: False, + ) + # Synchronous wait_for_review closes generator awaitable in GEN_CREATED import types @@ -3851,12 +3925,19 @@ def gen_coro_cb(r: Any) -> Any: # Detach overdue future retrieves exception from completed failed foreign future foreign_loop_failed = asyncio.new_event_loop() + foreign_reports: list[dict[str, Any]] = [] + foreign_loop_failed.set_exception_handler(lambda _loop, ctx: foreign_reports.append(ctx)) try: - failed_foreign_fut = foreign_loop_failed.create_future() + failed_foreign_fut: Any = foreign_loop_failed.create_future() failed_foreign_fut.set_exception(RuntimeError("foreign future failed")) from proofline.client import _detach_overdue_future _detach_overdue_future(failed_foreign_fut) + del failed_foreign_fut + import gc + + gc.collect() + assert foreign_reports == [] finally: foreign_loop_failed.close() From c1900679506f139b20b6835860819079a80de1dc Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 10:19:19 +0530 Subject: [PATCH 35/75] Address review 34 findings: plain completion futures for callback awaitables, deque subclass instantiation, bounded snapshot copies without copy hooks, and test quality --- README.md | 2 +- proofline/client.py | 175 ++++++++++++++++++++++++++++---------------- tests/test_http.py | 102 ++++++++++++++++++++++---- 3 files changed, 201 insertions(+), 78 deletions(-) diff --git a/README.md b/README.md index 8c0182e3..21989463 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must not return an awaitable (doing so raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. diff --git a/proofline/client.py b/proofline/client.py index cb50ea1c..58be1b36 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,7 +2,6 @@ from __future__ import annotations -import copy import datetime import math import weakref @@ -38,6 +37,9 @@ iscoroutine, isgenerator, ) +from inspect import ( + signature as inspect_signature, +) from string import hexdigits from time import monotonic, sleep from types import MemberDescriptorType, TracebackType @@ -318,7 +320,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non return None memo: dict[int, Any] = {id(UNSET): UNSET} - root = copy.copy(detail) + root = object.__new__(type(detail)) memo[id(detail)] = root stack: list[Any] = [(_OBJ_EXPAND, root, iter(_get_obj_attrs(detail)))] @@ -383,24 +385,39 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non ) stack.append((_TUPLE_EXPAND, temp_list, tuple.__iter__(val))) elif isinstance(val, dict): - new_dict = copy.copy(val) - if new_dict is val: + if "__copy__" in type(val).__dict__: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) - new_dict.clear() + try: + from collections import defaultdict + + if isinstance(val, defaultdict): + new_dict = type(val)(val.default_factory) + else: + new_dict = dict.__new__(type(val)) + dict.clear(new_dict) + except Exception as exc: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) from exc memo[val_id] = new_dict _assign_target(target, key, is_attr, new_dict) stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_dict, iter(_get_obj_attrs(val)))) elif isinstance(val, list): - new_list = copy.copy(val) - if new_list is val: + if "__copy__" in type(val).__dict__: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) - new_list.clear() + try: + new_list = list.__new__(type(val)) + list.clear(new_list) + except Exception as exc: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) from exc memo[val_id] = new_list _assign_target(target, key, is_attr, new_list) stack.append((_LIST_EXPAND, new_list, iter(val))) @@ -409,29 +426,40 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non elif isinstance(val, (set, frozenset)): set_len = set.__len__(val) if isinstance(val, set) else frozenset.__len__(val) set_it = set.__iter__(val) if isinstance(val, set) else frozenset.__iter__(val) + if type(val) is not set and type(val) is not frozenset: + try: + if set_len == 0: + inspect_signature(type(val).__init__).bind(type(val)) + else: + inspect_signature(type(val).__init__).bind(type(val), ()) + except TypeError: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) if set_len == 0: if type(val) is set: res_empty = set() elif type(val) is frozenset: res_empty = frozenset() else: - try: - inst = type(val)() - if len(inst) != 0: + if isinstance(val, set): + try: + res_empty = set.__new__(type(val)) + set.clear(res_empty) + except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " f"{type(val).__name__}" - ) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc - if isinstance(val, set): - res_empty = set.__new__(type(val)) - set.clear(res_empty) + ) from exc else: - res_empty = frozenset.__new__(type(val), ()) + try: + res_empty = frozenset.__new__(type(val), ()) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc if set(res_empty) if isinstance(val, set) else frozenset(res_empty): raise TypeError( "Unsupported mutable value in review extension data: " @@ -442,26 +470,23 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_OBJ_EXPAND, res_empty, iter(_get_obj_attrs(val)))) _assign_target(target, key, is_attr, res_empty) else: - if type(val) is not set and type(val) is not frozenset: - try: - inst = type(val)() - if len(inst) != 0: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc temp_set_list: list[Any] = [] stack.append((_SET_FINALIZE, target, key, is_attr, val_id, val, temp_set_list)) stack.append((_LIST_EXPAND, temp_set_list, set_it)) elif isinstance(val, deque): if len(val) > _MAX_SAFE_BUFFER_SIZE: return None - new_deque: deque[Any] = deque(maxlen=val.maxlen) + if type(val) is deque: + new_deque: deque[Any] = deque(maxlen=val.maxlen) + else: + try: + new_deque = deque.__new__(type(val)) + deque.__init__(new_deque, maxlen=val.maxlen) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc memo[val_id] = new_deque _assign_target(target, key, is_attr, new_deque) stack.append((_LIST_EXPAND, new_deque, iter(val))) @@ -514,18 +539,18 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if id(tz) in memo: copied_tz = memo[id(tz)] else: - try: - copied_tz = copy.copy(tz) - except Exception as exc: + if "__copy__" in type(tz).__dict__: raise TypeError( "Unsupported mutable value in review extension data: " f"{type(tz).__name__}" - ) from exc - if copied_tz is tz: + ) + try: + copied_tz = datetime.tzinfo.__new__(type(tz)) + except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " f"{type(tz).__name__}" - ) + ) from exc memo[id(tz)] = copied_tz if hasattr(tz, "__dict__") or hasattr(tz, "__slots__"): stack.append((_OBJ_EXPAND, copied_tz, iter(_get_obj_attrs(tz)))) @@ -542,7 +567,18 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non new_dt = val.replace(tzinfo=copied_tz) except Exception: try: - new_dt = copy.copy(val) + new_dt = type(val).__new__( + type(val), + val.year, + val.month, + val.day, + val.hour, + val.minute, + val.second, + val.microsecond, + tzinfo=copied_tz, + fold=val.fold, + ) except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " @@ -558,23 +594,29 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_dt, iter(_get_obj_attrs(val)))) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): - new_obj = copy.copy(val) - if new_obj is val: + new_obj: Any + try: + if isinstance(val, str): + new_obj = str.__new__(type(val), val) + elif isinstance(val, bytes): + new_obj = bytes.__new__(type(val), val) + elif isinstance(val, int): + new_obj = int.__new__(type(val), val) + elif isinstance(val, float): + new_obj = float.__new__(type(val), val) + else: + new_obj = object.__new__(type(val)) + except Exception as exc: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" - ) + ) from exc memo[val_id] = new_obj _assign_target(target, key, is_attr, new_obj) stack.append((_OBJ_EXPAND, new_obj, iter(_get_obj_attrs(val)))) else: - try: - resolved = copy.deepcopy(val, memo) - except Exception as exc: - raise TypeError( - f"Unsupported mutable value in review extension data: {type(val).__name__}" - ) from exc - memo[val_id] = resolved - _assign_target(target, key, is_attr, resolved) + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) elif task_type == _DICT_EXPAND: target_dict, it = target, it_or_key @@ -1172,9 +1214,10 @@ def wait_for_review( errors on unsupported mutable values propagate before on_poll runs. on_poll exceptions and return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter - from returning a classified outcome. Synchronous callbacks must not - return awaitables and must return before a terminal result can be - delivered; the polling deadline cannot interrupt them. + from returning a classified outcome. Synchronous callbacks must return + None (returning an awaitable or any return value other than None raises + TypeError) and must return before a terminal result can be delivered; + the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: @@ -1698,11 +1741,15 @@ async def wait_for_review( if AsyncFuture.done(res): AsyncFuture.result(res) else: + completion_fut = async_get_running_loop().create_future() completed_at: list[float] = [] - AsyncFuture.add_done_callback( - res, - lambda _: completed_at.append(monotonic()), - ) + + def _on_future_done(_: Any) -> None: + completed_at.append(monotonic()) + if not completion_fut.done(): + completion_fut.set_result(None) + + AsyncFuture.add_done_callback(res, _on_future_done) remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: _detach_overdue_future(res) @@ -1710,7 +1757,9 @@ async def wait_for_review( return result break try: - done, _ = await async_wait({res}, timeout=remaining_budget) + done, _ = await async_wait( + {completion_fut}, timeout=remaining_budget + ) except BaseException: _detach_overdue_future(res) raise @@ -1718,7 +1767,7 @@ async def wait_for_review( cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - if cb_finished_in_budget and res in done: + if cb_finished_in_budget and completion_fut in done: AsyncFuture.result(res) else: _detach_overdue_future(res) @@ -1785,7 +1834,7 @@ async def _runner() -> None: deadline_val is None or completed_at[0] <= deadline_val ) if task.done() and cb_finished_in_budget: - task.result() + AsyncTask.result(task) remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: diff --git a/tests/test_http.py b/tests/test_http.py index 1d8f56a2..e40c7ddc 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1295,9 +1295,21 @@ async def test_wait_ends_on_the_read_that_names_another_head( assert len(server.requests) == 3 assert clock.delays == [5, 10] with Server(lambda request, index: Reply(body=responses[index])) as server: + polled_reviews: list[Any] = [] + cb = ( + (lambda r: polled_reviews.append(r)) + if mode == "sync" + else (lambda r: polled_reviews.append(r)) + ) async with session(mode, server.url) as client: result = await call( - client, "wait_for_review", ORG, REVIEW, timeout=100, head_commit_sha=OTHER_HEAD + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + head_commit_sha=OTHER_HEAD, + on_poll=cb, ) assert result.status == "INCOMPLETE" assert result.review.status == "RUNNING" @@ -1306,6 +1318,9 @@ async def test_wait_ends_on_the_read_that_names_another_head( # The second read names the head, so the review that would complete is never read. assert len(server.requests) == 2 assert clock.delays == [5, 10, 5] + assert len(polled_reviews) == 2 + assert polled_reviews[1].status == "RUNNING" + assert polled_reviews[1].head_commit_sha == HEAD @MODES @@ -3182,7 +3197,12 @@ def sync_int_cb(r: Any) -> Any: ) # Unrestricted awaitables returning values (e.g. int) accepted and result discarded + int_cb_completed = False + async def int_returning_callback(r: Any) -> int: + nonlocal int_cb_completed + await asyncio.sleep(0) + int_cb_completed = True return 42 with Server(lambda request, index: Reply(body=responses[1])) as server: @@ -3194,9 +3214,29 @@ async def int_returning_callback(r: Any) -> int: on_poll=int_returning_callback, ) assert res_int.status == "COMPLETED" + assert int_cb_completed is True + + # Unhashable same-loop Future subclass and overridden done() returning False + class UnhashableFuture(asyncio.Future[None]): + __hash__ = None # type: ignore[assignment] + + def done(self) -> bool: + return False + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + unhashable_fut: Any = UnhashableFuture(loop=asyncio.get_running_loop()) + unhashable_fut.set_result(None) + res_unhash = await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: unhashable_fut, + ) + assert res_unhash.status == "COMPLETED" # Case with a waiter whose cancel() raises synchronously: - # assert called and outcome is TIMED_OUT, and no unhandled exception reported + # the waiter returns TIMED_OUT without calling cancel() or reporting an unhandled exception class SyncCancelRaisingFuture(asyncio.Future[None]): def __init__(self, loop: asyncio.AbstractEventLoop) -> None: super().__init__(loop=loop) @@ -3803,17 +3843,22 @@ def __len__(self) -> int: assert type(copied_deceptive_s) is DeceptiveSet assert "member1" in copied_deceptive_s and "member2" in copied_deceptive_s - # Set subclass whose constructor inserts extra member is rejected with TypeError + # Set subclass whose constructor inserts extra member does not reintroduce it class InjectedSet(set[Any]): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.add("injected_shared_member") injected_s = InjectedSet(["orig_member"]) + injected_s.remove("injected_shared_member") detail_injected_s = CustomerReviewDetail.from_dict(responses[1]) detail_injected_s.additional_properties["injected_s"] = injected_s - with pytest.raises(TypeError, match="Unsupported mutable value"): - _snapshot_review(detail_injected_s) + snap_injected_s = _snapshot_review(detail_injected_s) + assert snap_injected_s is not None + copied_injected_s = snap_injected_s.additional_properties["injected_s"] + assert type(copied_injected_s) is InjectedSet + assert "injected_shared_member" not in copied_injected_s + assert "orig_member" in copied_injected_s # Standard built-in set and frozenset properly snapshotted normal_s = {"member1", "member2"} @@ -3841,6 +3886,24 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: assert copied_dq is not dq assert copied_dq[1] is not dq[1] + # Deque subclass preserves subclass type, maxlen, and restores attributes + class CustomDeque(deque[Any]): + pass + + c_dq: CustomDeque = CustomDeque(["d1", "d2"], maxlen=5) + c_dq.custom_dq_attr = ["dq_attr"] # type: ignore[attr-defined] + detail_c_dq = CustomerReviewDetail.from_dict(responses[1]) + detail_c_dq.additional_properties["c_dq"] = c_dq + snap_c_dq = _snapshot_review(detail_c_dq) + assert snap_c_dq is not None + copied_c_dq = snap_c_dq.additional_properties["c_dq"] + assert type(copied_c_dq) is CustomDeque + assert copied_c_dq.maxlen == 5 + assert copied_c_dq == c_dq + assert copied_c_dq is not c_dq + assert copied_c_dq.custom_dq_attr is not c_dq.custom_dq_attr + assert copied_c_dq.custom_dq_attr == ["dq_attr"] + # Deceptive bytearray subclass underreporting len with > 65536 bytes is skipped class DeceptiveByteArray(bytearray): def __len__(self) -> int: @@ -3923,21 +3986,32 @@ def gen_coro_cb(r: Any) -> Any: ) assert inspect.getgeneratorstate(gen_cb_inst) == inspect.GEN_CLOSED - # Detach overdue future retrieves exception from completed failed foreign future + # wait_for_review cleans up already-failed foreign-loop future returned when budget is exhausted foreign_loop_failed = asyncio.new_event_loop() foreign_reports: list[dict[str, Any]] = [] foreign_loop_failed.set_exception_handler(lambda _loop, ctx: foreign_reports.append(ctx)) try: - failed_foreign_fut: Any = foreign_loop_failed.create_future() - failed_foreign_fut.set_exception(RuntimeError("foreign future failed")) - from proofline.client import _detach_overdue_future + foreign_box: list[Any] = [foreign_loop_failed.create_future()] + foreign_box[0].set_exception(RuntimeError("foreign future failed")) + + def foreign_fail_cb(r: Any) -> Any: + clock.now += 150.0 + return foreign_box[0] - _detach_overdue_future(failed_foreign_fut) - del failed_foreign_fut - import gc + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_foreign = await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=foreign_fail_cb, + ) + assert res_foreign.status == "COMPLETED" + foreign_box.clear() + import gc - gc.collect() - assert foreign_reports == [] + gc.collect() + assert foreign_reports == [] finally: foreign_loop_failed.close() From 7e04e4ebe46d02a6bda770120a4c3e6c9cad08d1 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 12:36:34 +0530 Subject: [PATCH 36/75] Address review 35 findings: deferred hash insertion for sets and dicts, defaultdict factory traversal, watchdog cancellation assertions, and unhashable/lying future tests --- README.md | 2 +- proofline/client.py | 255 +++++++++++++++++++++++++++++--------------- tests/test_http.py | 119 +++++++++++++++------ 3 files changed, 256 insertions(+), 120 deletions(-) diff --git a/README.md b/README.md index 21989463..f93d0d43 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 58be1b36..997bfbeb 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -26,7 +26,7 @@ from asyncio import ( wait as async_wait, ) -from collections import deque +from collections import defaultdict, deque from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from inspect import ( CORO_CREATED, @@ -42,7 +42,13 @@ ) from string import hexdigits from time import monotonic, sleep -from types import MemberDescriptorType, TracebackType +from types import ( + BuiltinFunctionType, + FunctionType, + MemberDescriptorType, + MethodType, + TracebackType, +) from typing import Any, Self, TypedDict, TypeVar, Unpack, cast from urllib.parse import quote from uuid import UUID @@ -251,6 +257,8 @@ def _is_immutable(val: Any) -> bool: t = type(val) if t in _IMMUTABLE_TYPES: return True + if isinstance(val, (FunctionType, BuiltinFunctionType, MethodType)): + return not getattr(val, "__dict__", None) if t is datetime.datetime: tz = val.tzinfo return tz is None or type(tz) is datetime.timezone @@ -258,6 +266,8 @@ def _is_immutable(val: Any) -> bool: def _assign_target(target: Any, key: Any, is_attr: bool, val: Any) -> None: + if target is None: + return if is_attr: slot_or_name, is_desc = key if is_desc: @@ -304,7 +314,7 @@ def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: _TUPLE_EXPAND = 5 _TUPLE_FINALIZE = 6 _SET_FINALIZE = 7 -_DICT_ITEM_FINALIZE = 8 +_SET_EXPAND = 8 _EXPAND_BATCH_SIZE = 64 _MAX_SAFE_TUPLE_SIZE = 1000 _MAX_SAFE_BUFFER_SIZE = 65_536 @@ -323,6 +333,9 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non root = object.__new__(type(detail)) memo[id(detail)] = root + deferred_dict_insertions: list[tuple[Any, Any, Any]] = [] + deferred_set_insertions: list[tuple[Any, Any, list[Any]]] = [] + stack: list[Any] = [(_OBJ_EXPAND, root, iter(_get_obj_attrs(detail)))] while stack: @@ -390,10 +403,8 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non f"Unsupported mutable value in review extension data: {type(val).__name__}" ) try: - from collections import defaultdict - if isinstance(val, defaultdict): - new_dict = type(val)(val.default_factory) + new_dict = type(val)(None) else: new_dict = dict.__new__(type(val)) dict.clear(new_dict) @@ -403,9 +414,19 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non ) from exc memo[val_id] = new_dict _assign_target(target, key, is_attr, new_dict) - stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) + if isinstance(val, defaultdict) and val.default_factory is not None: + stack.append( + ( + _ITEM_TASK, + new_dict, + ("default_factory", False), + True, + val.default_factory, + ) + ) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_dict, iter(_get_obj_attrs(val)))) + stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) elif isinstance(val, list): if "__copy__" in type(val).__dict__: raise TypeError( @@ -423,10 +444,13 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_LIST_EXPAND, new_list, iter(val))) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) - elif isinstance(val, (set, frozenset)): - set_len = set.__len__(val) if isinstance(val, set) else frozenset.__len__(val) - set_it = set.__iter__(val) if isinstance(val, set) else frozenset.__iter__(val) - if type(val) is not set and type(val) is not frozenset: + elif isinstance(val, set): + if "__copy__" in type(val).__dict__: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) + set_len = set.__len__(val) + if type(val) is not set: try: if set_len == 0: inspect_signature(type(val).__init__).bind(type(val)) @@ -437,44 +461,68 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non "Unsupported mutable value in review extension data: " f"{type(val).__name__}" ) - if set_len == 0: - if type(val) is set: - res_empty = set() - elif type(val) is frozenset: - res_empty = frozenset() - else: - if isinstance(val, set): - try: - res_empty = set.__new__(type(val)) - set.clear(res_empty) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc + if type(val) is set: + new_set: set[Any] = set() + else: + try: + new_set = set.__new__(type(val)) + set.clear(new_set) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc + if set(new_set): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + memo[val_id] = new_set + _assign_target(target, key, is_attr, new_set) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, new_set, iter(_get_obj_attrs(val)))) + if set_len > 0: + deferred_set_insertions.append((new_set, val, list(val))) + stack.append((_SET_EXPAND, None, iter(val))) + elif isinstance(val, frozenset): + fs_len = frozenset.__len__(val) + if type(val) is not frozenset: + try: + if fs_len == 0: + inspect_signature(type(val).__init__).bind(type(val)) else: - try: - res_empty = frozenset.__new__(type(val), ()) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc - if set(res_empty) if isinstance(val, set) else frozenset(res_empty): + inspect_signature(type(val).__init__).bind(type(val), ()) + except TypeError: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + if fs_len == 0: + if type(val) is frozenset: + res_empty_fs: Any = frozenset() + else: + try: + res_empty_fs = frozenset.__new__(type(val), ()) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc + if frozenset(res_empty_fs): raise TypeError( "Unsupported mutable value in review extension data: " f"{type(val).__name__}" ) - memo[val_id] = res_empty + memo[val_id] = res_empty_fs if hasattr(val, "__dict__") or hasattr(val, "__slots__"): - stack.append((_OBJ_EXPAND, res_empty, iter(_get_obj_attrs(val)))) - _assign_target(target, key, is_attr, res_empty) + stack.append((_OBJ_EXPAND, res_empty_fs, iter(_get_obj_attrs(val)))) + _assign_target(target, key, is_attr, res_empty_fs) else: temp_set_list: list[Any] = [] stack.append((_SET_FINALIZE, target, key, is_attr, val_id, val, temp_set_list)) - stack.append((_LIST_EXPAND, temp_set_list, set_it)) + stack.append((_LIST_EXPAND, temp_set_list, frozenset.__iter__(val))) elif isinstance(val, deque): - if len(val) > _MAX_SAFE_BUFFER_SIZE: + if deque.__len__(val) > _MAX_SAFE_BUFFER_SIZE: return None if type(val) is deque: new_deque: deque[Any] = deque(maxlen=val.maxlen) @@ -625,28 +673,32 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non k, v = next(it) except StopIteration: break - k_done = _is_immutable(k) or id(k) in memo - res_k = k if _is_immutable(k) else memo.get(id(k)) - v_done = _is_immutable(v) or id(v) in memo - res_v = v if _is_immutable(v) else memo.get(id(v)) - - if k_done and v_done: - target_dict[res_k] = res_v - else: - box = [res_k, res_v] + deferred_dict_insertions.append((target_dict, k, v)) + k_needed = not _is_immutable(k) and id(k) not in memo + v_needed = not _is_immutable(v) and id(v) not in memo + if k_needed or v_needed: stack.append((_DICT_EXPAND, target_dict, it)) - stack.append((_DICT_ITEM_FINALIZE, target_dict, box)) - if not v_done: - stack.append((_ITEM_TASK, box, 1, False, v)) - if not k_done: - stack.append((_ITEM_TASK, box, 0, False, k)) + if v_needed: + stack.append((_ITEM_TASK, None, 0, False, v)) + if k_needed: + stack.append((_ITEM_TASK, None, 0, False, k)) break else: stack.append((_DICT_EXPAND, target_dict, it)) - elif task_type == _DICT_ITEM_FINALIZE: - target_dict, box = target, it_or_key - target_dict[box[0]] = box[1] + elif task_type == _SET_EXPAND: + it = it_or_key + for _ in range(_EXPAND_BATCH_SIZE): + try: + m = next(it) + except StopIteration: + break + if not _is_immutable(m) and id(m) not in memo: + stack.append((_SET_EXPAND, None, it)) + stack.append((_ITEM_TASK, None, 0, False, m)) + break + else: + stack.append((_SET_EXPAND, None, it)) elif task_type == _LIST_EXPAND: target_list, it = target, it_or_key @@ -744,20 +796,8 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if val_id in memo: res_set = memo[val_id] else: - if type(orig_val) is set: - res_set = set(temp_set_list) - elif type(orig_val) is frozenset: + if type(orig_val) is frozenset: res_set = frozenset(temp_set_list) - elif isinstance(orig_val, set): - try: - res_set = set.__new__(type(orig_val)) - set.clear(res_set) - set.update(res_set, temp_set_list) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(orig_val).__name__}" - ) from exc else: # frozenset subclass try: res_set = frozenset.__new__(type(orig_val), temp_set_list) @@ -766,10 +806,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non "Unsupported mutable value in review extension data: " f"{type(orig_val).__name__}" ) from exc - expected_members = set(temp_set_list) - if (set(res_set) if isinstance(orig_val, set) else frozenset(res_set)) != ( - expected_members if isinstance(orig_val, set) else frozenset(temp_set_list) - ): + if frozenset(res_set) != frozenset(temp_set_list): raise TypeError( "Unsupported mutable value in review extension data: " f"{type(orig_val).__name__}" @@ -779,9 +816,33 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_OBJ_EXPAND, res_set, iter(_get_obj_attrs(orig_val)))) _assign_target(target, key, is_attr, res_set) + if _deadline_expired(): + return None + + for s, orig_val, orig_members in deferred_set_insertions: + if _deadline_expired(): + return None + resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] + set.update(s, resolved_members) + if set(s) != set(resolved_members): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(orig_val).__name__}" + ) + + for target_dict, orig_k, orig_v in deferred_dict_insertions: + if _deadline_expired(): + return None + k = orig_k if _is_immutable(orig_k) else memo[id(orig_k)] + v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] + target_dict[k] = v + return root +_DETACHED_TASKS: set[Any] = set() +_DETACHED_FUTURES: set[Any] = set() + + def _safe_cancel_target(target: Any) -> None: try: target.cancel() @@ -808,13 +869,20 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: return if loop is not running_loop or loop.is_closed(): return + _DETACHED_FUTURES.add(fut) + + def _on_detached_fut_done(t: Any) -> None: + _DETACHED_FUTURES.discard(t) + try: + if not AsyncFuture.cancelled(t): + AsyncFuture.exception(t) + except BaseException: + pass + try: - AsyncFuture.add_done_callback( - fut, - lambda t: AsyncFuture.exception(t) if not AsyncFuture.cancelled(t) else None, - ) + AsyncFuture.add_done_callback(fut, _on_detached_fut_done) except BaseException: - pass + _DETACHED_FUTURES.discard(fut) except BaseException: pass @@ -824,13 +892,20 @@ def _detach_overdue_task( res: Any, wrapper_started: bool, ) -> None: + _DETACHED_TASKS.add(task) + + def _on_detached_task_done(t: Any) -> None: + _DETACHED_TASKS.discard(t) + try: + if not AsyncFuture.cancelled(t): + AsyncTask.exception(t) + except BaseException: + pass + try: - AsyncFuture.add_done_callback( - task, - lambda t: AsyncTask.exception(t) if not AsyncFuture.cancelled(t) else None, - ) + AsyncFuture.add_done_callback(task, _on_detached_task_done) except BaseException: - pass + _DETACHED_TASKS.discard(task) if not wrapper_started: if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: try: @@ -1829,6 +1904,14 @@ async def _runner() -> None: except BaseException: pass raise + task_completion_fut = async_get_running_loop().create_future() + + def _on_task_done(_: Any) -> None: + if not task_completion_fut.done(): + task_completion_fut.set_result(None) + + AsyncTask.add_done_callback(task, _on_task_done) + deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val @@ -1843,7 +1926,9 @@ async def _runner() -> None: return result break try: - done, _ = await async_wait({task}, timeout=remaining_budget) + done, _ = await async_wait( + {task_completion_fut}, timeout=remaining_budget + ) except BaseException: _detach_overdue_task(task, res, wrapper_started) raise @@ -1851,7 +1936,7 @@ async def _runner() -> None: cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - if cb_finished_in_budget and task in done: + if cb_finished_in_budget and task_completion_fut in done: AsyncTask.result(task) else: _detach_overdue_task(task, res, wrapper_started) diff --git a/tests/test_http.py b/tests/test_http.py index e40c7ddc..f8583cf6 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1318,8 +1318,7 @@ async def test_wait_ends_on_the_read_that_names_another_head( # The second read names the head, so the review that would complete is never read. assert len(server.requests) == 2 assert clock.delays == [5, 10, 5] - assert len(polled_reviews) == 2 - assert polled_reviews[1].status == "RUNNING" + assert [p.status for p in polled_reviews] == ["PENDING", "RUNNING"] assert polled_reviews[1].head_commit_sha == HEAD @@ -2730,8 +2729,12 @@ def cb_consuming_clock(r: Any) -> Any: assert wait_timeouts == [65.0] monkeypatch.setattr(client_module, "async_wait", orig_async_wait) - # Timely pending future failure propagates - timely_fut: asyncio.Future[None] = asyncio.get_running_loop().create_future() + # Timely pending future failure propagates even if done() lies + class LyingDoneFuture(asyncio.Future[None]): + def done(self) -> bool: + return False + + timely_fut: Any = LyingDoneFuture(loop=asyncio.get_running_loop()) async def fail_timely_soon() -> None: await asyncio.sleep(0.01) @@ -2863,10 +2866,11 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: # Case 3: Overdue callback continues running without cancellation on non-terminal review callback_running = asyncio.Event() callback_finished = asyncio.Event() + release_callback = asyncio.Event() async def continuing_coro(r: Any) -> None: callback_running.set() - await asyncio.sleep(0.3) + await release_callback.wait() callback_finished.set() client.get_review = fake_running # type: ignore @@ -2879,19 +2883,21 @@ async def continuing_coro(r: Any) -> None: on_poll=continuing_coro, ) elapsed3 = time.monotonic() - start_t3 - assert 0.18 <= elapsed3 <= 0.60 + assert 0.18 <= elapsed3 assert res.status == "TIMED_OUT" assert callback_running.is_set() assert not callback_finished.is_set() + release_callback.set() await callback_finished.wait() # Case 4: Overdue callback continues running without cancellation on terminal review callback_running_term = asyncio.Event() callback_finished_term = asyncio.Event() + release_callback_term = asyncio.Event() async def continuing_coro_term(r: Any) -> None: callback_running_term.set() - await asyncio.sleep(0.3) + await release_callback_term.wait() callback_finished_term.set() client.get_review = fake_completed # type: ignore @@ -2904,10 +2910,11 @@ async def continuing_coro_term(r: Any) -> None: on_poll=continuing_coro_term, ) elapsed4 = time.monotonic() - start_t4 - assert 0.18 <= elapsed4 <= 0.60 + assert 0.18 <= elapsed4 assert res.status == "COMPLETED" assert callback_running_term.is_set() assert not callback_finished_term.is_set() + release_callback_term.set() await callback_finished_term.wait() # Case 5: Suspending callback that succeeds within budget @@ -2930,38 +2937,78 @@ async def suspending_callback(r: Any) -> None: assert resumed_within_budget # Case 6: Overdue callback failure is observed without leaking to loop handler - detached_task: asyncio.Task[None] | None = None - callback_trigger = asyncio.Event() - - async def failing_overdue_coro(r: Any) -> None: - nonlocal detached_task - detached_task = asyncio.current_task() - await callback_trigger.wait() - raise RuntimeError("error in overdue callback") - + # For both futures and coroutines, cancel the waiter after callback startup, + # assert CancelledError, then release the callback to fail and verify the loop reports + # no unhandled exception. unhandled_exceptions: list[dict[str, Any]] = [] loop = asyncio.get_running_loop() old_handler = loop.get_exception_handler() loop.set_exception_handler(lambda _loop, ctx: unhandled_exceptions.append(ctx)) try: + # 6a: Future callback cancelled after startup + failing_fut: asyncio.Future[None] = loop.create_future() + future_started = asyncio.Event() + + def failing_future_cb(r: Any) -> asyncio.Future[None]: + future_started.set() + return failing_fut + client.get_review = fake_running # type: ignore - res_clean = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=failing_overdue_coro, + waiter_fut_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=failing_future_cb, + ) ) - assert res_clean.status == "TIMED_OUT" - assert detached_task is not None - callback_trigger.set() - done, _ = await asyncio.wait({detached_task}, timeout=2.0) - assert detached_task in done - del done - del detached_task + await future_started.wait() + waiter_fut_task.cancel() + cancelled_fut = False + try: + await waiter_fut_task + except asyncio.CancelledError: + cancelled_fut = True + assert cancelled_fut + + failing_fut.set_exception(RuntimeError("error in cancelled future callback")) + await asyncio.sleep(0.01) + del failing_fut import gc gc.collect() assert unhandled_exceptions == [] + + # 6b: Coroutine callback cancelled after startup + coro_started = asyncio.Event() + coro_trigger = asyncio.Event() + + async def failing_overdue_coro(r: Any) -> None: + coro_started.set() + await coro_trigger.wait() + raise RuntimeError("error in overdue callback") + + waiter_coro_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=failing_overdue_coro, + ) + ) + await coro_started.wait() + waiter_coro_task.cancel() + cancelled_coro = False + try: + await waiter_coro_task + except asyncio.CancelledError: + cancelled_coro = True + assert cancelled_coro + + coro_trigger.set() + await asyncio.sleep(0.01) + gc.collect() + assert unhandled_exceptions == [] finally: loop.set_exception_handler(old_handler) @@ -3216,24 +3263,28 @@ async def int_returning_callback(r: Any) -> int: assert res_int.status == "COMPLETED" assert int_cb_completed is True - # Unhashable same-loop Future subclass and overridden done() returning False + # Unhashable same-loop Future subclass completed after wait starts class UnhashableFuture(asyncio.Future[None]): __hash__ = None # type: ignore[assignment] - def done(self) -> bool: - return False + async def complete_unhashable_soon(fut: Any) -> None: + await asyncio.sleep(0.01) + fut.set_result(None) with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: unhashable_fut: Any = UnhashableFuture(loop=asyncio.get_running_loop()) - unhashable_fut.set_result(None) res_unhash = await client.wait_for_review( ORG, REVIEW, timeout=10, - on_poll=lambda r: unhashable_fut, + on_poll=lambda r: ( + asyncio.create_task(complete_unhashable_soon(unhashable_fut)), + unhashable_fut, + )[1], ) assert res_unhash.status == "COMPLETED" + assert unhashable_fut.done() # Case with a waiter whose cancel() raises synchronously: # the waiter returns TIMED_OUT without calling cancel() or reporting an unhandled exception From 098ec672f5f655b0b60e98c2b9fe15e075b6aa6b Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 12:57:30 +0530 Subject: [PATCH 37/75] Address review 36 findings: identity-keyed detachment dictionaries, hash-dependent dict/set ordering, bound method receiver validation, base container deque operations, and controlled clock watchdog --- proofline/client.py | 63 +++++++++++------ tests/test_http.py | 166 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 173 insertions(+), 56 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 997bfbeb..44c5b39c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -254,6 +254,8 @@ def _export_page_limit(max_pages: int) -> None: def _is_immutable(val: Any) -> bool: if val is None or val is UNSET or isinstance(val, type): return True + if hasattr(val, "__self__") and not _is_immutable(val.__self__): + return False t = type(val) if t in _IMMUTABLE_TYPES: return True @@ -275,7 +277,12 @@ def _assign_target(target: Any, key: Any, is_attr: bool, val: Any) -> None: else: setattr(target, slot_or_name, val) else: - target[key] = val + if isinstance(target, deque): + deque.__setitem__(target, key, val) + elif isinstance(target, list): + list.__setitem__(target, key, val) + else: + target[key] = val def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: @@ -537,7 +544,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non ) from exc memo[val_id] = new_deque _assign_target(target, key, is_attr, new_deque) - stack.append((_LIST_EXPAND, new_deque, iter(val))) + stack.append((_LIST_EXPAND, new_deque, deque.__iter__(val))) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_deque, iter(_get_obj_attrs(val)))) elif isinstance(val, bytearray): @@ -702,18 +709,21 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non elif task_type == _LIST_EXPAND: target_list, it = target, it_or_key + is_dq = isinstance(target_list, deque) + app_fn = deque.append if is_dq else list.append + len_fn = deque.__len__ if is_dq else list.__len__ for _ in range(_EXPAND_BATCH_SIZE): try: v = next(it) except StopIteration: break if _is_immutable(v): - target_list.append(v) + app_fn(target_list, v) elif id(v) in memo: - target_list.append(memo[id(v)]) + app_fn(target_list, memo[id(v)]) else: - idx = len(target_list) - target_list.append(None) + idx = len_fn(target_list) + app_fn(target_list, None) stack.append((_LIST_EXPAND, target_list, it)) stack.append((_ITEM_TASK, target_list, idx, False, v)) break @@ -819,6 +829,16 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if _deadline_expired(): return None + deferred_custom_dict_insertions: list[tuple[Any, Any, Any]] = [] + for target_dict, orig_k, orig_v in deferred_dict_insertions: + if _deadline_expired(): + return None + if _is_immutable(orig_k): + v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] + target_dict[orig_k] = v + else: + deferred_custom_dict_insertions.append((target_dict, orig_k, orig_v)) + for s, orig_val, orig_members in deferred_set_insertions: if _deadline_expired(): return None @@ -829,18 +849,18 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non f"Unsupported mutable value in review extension data: {type(orig_val).__name__}" ) - for target_dict, orig_k, orig_v in deferred_dict_insertions: + for target_dict, orig_k, orig_v in deferred_custom_dict_insertions: if _deadline_expired(): return None - k = orig_k if _is_immutable(orig_k) else memo[id(orig_k)] + k = memo[id(orig_k)] v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] target_dict[k] = v return root -_DETACHED_TASKS: set[Any] = set() -_DETACHED_FUTURES: set[Any] = set() +_DETACHED_TASKS: dict[int, Any] = {} +_DETACHED_FUTURES: dict[int, Any] = {} def _safe_cancel_target(target: Any) -> None: @@ -869,10 +889,11 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: return if loop is not running_loop or loop.is_closed(): return - _DETACHED_FUTURES.add(fut) + fut_id = id(fut) + _DETACHED_FUTURES[fut_id] = fut def _on_detached_fut_done(t: Any) -> None: - _DETACHED_FUTURES.discard(t) + _DETACHED_FUTURES.pop(fut_id, None) try: if not AsyncFuture.cancelled(t): AsyncFuture.exception(t) @@ -882,7 +903,7 @@ def _on_detached_fut_done(t: Any) -> None: try: AsyncFuture.add_done_callback(fut, _on_detached_fut_done) except BaseException: - _DETACHED_FUTURES.discard(fut) + _DETACHED_FUTURES.pop(fut_id, None) except BaseException: pass @@ -892,10 +913,11 @@ def _detach_overdue_task( res: Any, wrapper_started: bool, ) -> None: - _DETACHED_TASKS.add(task) + task_id = id(task) + _DETACHED_TASKS[task_id] = task def _on_detached_task_done(t: Any) -> None: - _DETACHED_TASKS.discard(t) + _DETACHED_TASKS.pop(task_id, None) try: if not AsyncFuture.cancelled(t): AsyncTask.exception(t) @@ -905,7 +927,7 @@ def _on_detached_task_done(t: Any) -> None: try: AsyncFuture.add_done_callback(task, _on_detached_task_done) except BaseException: - _DETACHED_TASKS.discard(task) + _DETACHED_TASKS.pop(task_id, None) if not wrapper_started: if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: try: @@ -1336,7 +1358,7 @@ def wait_for_review( "for async callbacks." ) if res is not None: - raise TypeError(f"Callbacks must return None, got {type(res).__name__}") + raise TypeError("Callbacks must return None.") if result is not None: return result if (_transport.remaining() or 0) <= 0: @@ -1766,10 +1788,7 @@ async def wait_for_review( if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) if res is not None and not isawaitable(res): - raise TypeError( - "Callbacks must return None or an awaitable, " - f"got {type(res).__name__}" - ) + raise TypeError("Callbacks must return None or an awaitable.") if isawaitable(res): if res is async_current_task(): raise ValueError( @@ -1916,7 +1935,7 @@ def _on_task_done(_: Any) -> None: cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - if task.done() and cb_finished_in_budget: + if AsyncFuture.done(task) and cb_finished_in_budget: AsyncTask.result(task) remaining_budget = _transport.remaining() diff --git a/tests/test_http.py b/tests/test_http.py index f8583cf6..9ec0caab 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2801,10 +2801,26 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: import time from typing import Any from proofline import AsyncProoflineClient +import proofline.client as client_module +import proofline._transport as transport_module from proofline._generated.models.customer_review_detail import CustomerReviewDetail from tests.test_http import review, ORG, REVIEW +class ControlledClock: + def __init__(self) -> None: + self.now = 1000.0 + + def time(self) -> float: + return self.now + + def advance(self, dt: float) -> None: + self.now += dt + async def main() -> None: + clock = ControlledClock() + client_module.monotonic = clock.time + transport_module.monotonic = clock.time + running_detail = CustomerReviewDetail.from_dict(review("RUNNING")) completed_detail = CustomerReviewDetail.from_dict(review()) @@ -2818,33 +2834,46 @@ async def fake_completed(org: Any, rev: Any) -> Any: token="test_token", base_url="https://api.proofline.sh" ) as client: # Case 1: Pending same-loop Future that times out is detached without cancelling + # Assert it is still pending before advancing the controlled deadline pending_fut: asyncio.Future[None] | None = None + cb_1_started = asyncio.Event() def pending_future_callback(r: Any) -> asyncio.Future[None]: nonlocal pending_fut loop = asyncio.get_running_loop() pending_fut = loop.create_future() + cb_1_started.set() return pending_fut client.get_review = fake_running # type: ignore - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=pending_future_callback, + waiter_task_1 = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=pending_future_callback, + ) ) - assert res.status == "TIMED_OUT" + await cb_1_started.wait() await asyncio.sleep(0) + assert not waiter_task_1.done() + clock.advance(1.0) + res_1 = await waiter_task_1 + assert res_1.status == "TIMED_OUT" assert pending_fut is not None assert not pending_fut.cancelled() assert not pending_fut.done() + assert id(pending_fut) in client_module._DETACHED_FUTURES + pending_fut.set_result(None) + await asyncio.sleep(0) + assert id(pending_fut) not in client_module._DETACHED_FUTURES # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() async def complete_fut_soon() -> None: - await asyncio.sleep(0.05) + await asyncio.sleep(0.01) completed_fut.set_result(None) def completing_future_callback(r: Any) -> asyncio.Future[None]: @@ -2856,7 +2885,7 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: res = await client.wait_for_review( ORG, REVIEW, - timeout=5.0, + timeout=10.0, on_poll=completing_future_callback, ) assert res.status == "COMPLETED" @@ -2875,16 +2904,19 @@ async def continuing_coro(r: Any) -> None: client.get_review = fake_running # type: ignore - start_t3 = time.monotonic() - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=continuing_coro, + waiter_task_3 = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=continuing_coro, + ) ) - elapsed3 = time.monotonic() - start_t3 - assert 0.18 <= elapsed3 - assert res.status == "TIMED_OUT" + await callback_running.wait() + assert not waiter_task_3.done() + clock.advance(1.0) + res_3 = await waiter_task_3 + assert res_3.status == "TIMED_OUT" assert callback_running.is_set() assert not callback_finished.is_set() release_callback.set() @@ -2902,16 +2934,19 @@ async def continuing_coro_term(r: Any) -> None: client.get_review = fake_completed # type: ignore - start_t4 = time.monotonic() - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=continuing_coro_term, + waiter_task_4 = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=continuing_coro_term, + ) ) - elapsed4 = time.monotonic() - start_t4 - assert 0.18 <= elapsed4 - assert res.status == "COMPLETED" + await callback_running_term.wait() + assert not waiter_task_4.done() + clock.advance(1.0) + res_4 = await waiter_task_4 + assert res_4.status == "COMPLETED" assert callback_running_term.is_set() assert not callback_finished_term.is_set() release_callback_term.set() @@ -2922,7 +2957,7 @@ async def continuing_coro_term(r: Any) -> None: async def suspending_callback(r: Any) -> None: nonlocal resumed_within_budget - await asyncio.sleep(0.2) + await asyncio.sleep(0.01) resumed_within_budget = True client.get_review = fake_completed # type: ignore @@ -2930,16 +2965,13 @@ async def suspending_callback(r: Any) -> None: res = await client.wait_for_review( ORG, REVIEW, - timeout=5.0, + timeout=10.0, on_poll=suspending_callback, ) assert res.status == "COMPLETED" assert resumed_within_budget # Case 6: Overdue callback failure is observed without leaking to loop handler - # For both futures and coroutines, cancel the waiter after callback startup, - # assert CancelledError, then release the callback to fail and verify the loop reports - # no unhandled exception. unhandled_exceptions: list[dict[str, Any]] = [] loop = asyncio.get_running_loop() old_handler = loop.get_exception_handler() @@ -2958,7 +2990,7 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: client.wait_for_review( ORG, REVIEW, - timeout=5.0, + timeout=10.0, on_poll=failing_future_cb, ) ) @@ -2971,8 +3003,10 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: cancelled_fut = True assert cancelled_fut + assert id(failing_fut) in client_module._DETACHED_FUTURES failing_fut.set_exception(RuntimeError("error in cancelled future callback")) - await asyncio.sleep(0.01) + await asyncio.sleep(0) + assert id(failing_fut) not in client_module._DETACHED_FUTURES del failing_fut import gc @@ -2982,17 +3016,19 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: # 6b: Coroutine callback cancelled after startup coro_started = asyncio.Event() coro_trigger = asyncio.Event() + about_to_raise = asyncio.Event() async def failing_overdue_coro(r: Any) -> None: coro_started.set() await coro_trigger.wait() + about_to_raise.set() raise RuntimeError("error in overdue callback") waiter_coro_task = asyncio.create_task( client.wait_for_review( ORG, REVIEW, - timeout=5.0, + timeout=10.0, on_poll=failing_overdue_coro, ) ) @@ -3005,8 +3041,14 @@ async def failing_overdue_coro(r: Any) -> None: cancelled_coro = True assert cancelled_coro + assert len(client_module._DETACHED_TASKS) == 1 + detached_task_id = next(iter(client_module._DETACHED_TASKS.keys())) + coro_trigger.set() + await asyncio.wait_for(about_to_raise.wait(), timeout=1.0) await asyncio.sleep(0.01) + + assert detached_task_id not in client_module._DETACHED_TASKS gc.collect() assert unhandled_exceptions == [] finally: @@ -3015,8 +3057,10 @@ async def failing_overdue_coro(r: Any) -> None: # Case 7: Overdue callback awaiting the polling task is not cancelled polling_waiter_task: asyncio.Task[Any] | None = None callback_completed_7 = asyncio.Event() + cb_7_started = asyncio.Event() async def awaiting_runner_callback(r: Any) -> None: + cb_7_started.set() assert polling_waiter_task is not None outcome_inner = await polling_waiter_task assert outcome_inner.status == "TIMED_OUT" @@ -3031,6 +3075,9 @@ async def awaiting_runner_callback(r: Any) -> None: on_poll=awaiting_runner_callback, ) ) + await cb_7_started.wait() + assert not polling_waiter_task.done() + clock.advance(1.0) res_7 = await polling_waiter_task assert res_7.status == "TIMED_OUT" await asyncio.wait_for(callback_completed_7.wait(), timeout=1.0) @@ -3286,6 +3333,52 @@ async def complete_unhashable_soon(fut: Any) -> None: assert res_unhash.status == "COMPLETED" assert unhashable_fut.done() + # Cancel the waiter while an UnhashableFuture is pending, then fail and release + # the future and assert that the loop reports no unhandled exception. + from proofline.client import _DETACHED_FUTURES + + unhash_cancel_reports: list[dict[str, Any]] = [] + loop = asyncio.get_running_loop() + old_h_unhash = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhash_cancel_reports.append(ctx)) + try: + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + unhash_failing_fut: Any = UnhashableFuture(loop=loop) + cb_started = asyncio.Event() + + def unhash_failing_cb(r: Any) -> Any: + cb_started.set() + return unhash_failing_fut + + waiter_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=unhash_failing_cb, + ) + ) + await cb_started.wait() + waiter_task.cancel() + cancelled = False + try: + await waiter_task + except asyncio.CancelledError: + cancelled = True + assert cancelled + assert id(unhash_failing_fut) in _DETACHED_FUTURES + unhash_failing_fut.set_exception(RuntimeError("unhashable late failure")) + await asyncio.sleep(0) + assert id(unhash_failing_fut) not in _DETACHED_FUTURES + import gc + + del unhash_failing_fut + gc.collect() + assert unhash_cancel_reports == [] + finally: + loop.set_exception_handler(old_h_unhash) + # Case with a waiter whose cancel() raises synchronously: # the waiter returns TIMED_OUT without calling cancel() or reporting an unhandled exception class SyncCancelRaisingFuture(asyncio.Future[None]): @@ -3314,8 +3407,13 @@ def cancel(self, msg: Any = None) -> bool: assert res_sync_cancel.status == "TIMED_OUT" await asyncio.sleep(0) assert fut_sync_cancel.cancel_called is False + assert id(fut_sync_cancel) in _DETACHED_FUTURES assert cancel_reports == [] finally: + if not fut_sync_cancel.done(): + fut_sync_cancel.set_result(None) + await asyncio.sleep(0) + assert id(fut_sync_cancel) not in _DETACHED_FUTURES loop.set_exception_handler(old_h) # Current task cannot be returned by on_poll From 62170965aaf4066c4d623d44d5479e6485fe209a Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 15:22:28 +0530 Subject: [PATCH 38/75] Address review 37 findings: frozenset deferred construction, closure capture validation, task duck-typing, pre-start cancellation timestamping, guarded awaitable inspection, and stubbed clock in SyncCancelRaisingFuture test --- proofline/client.py | 291 ++++++++++++++++++++++++++++++++++---------- tests/test_http.py | 27 +++- 2 files changed, 250 insertions(+), 68 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 44c5b39c..fb9fe8f0 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -251,16 +251,37 @@ def _export_page_limit(max_pages: int) -> None: } -def _is_immutable(val: Any) -> bool: +def _has_mutable_captures(val: Any, seen: set[int] | None = None) -> bool: + closure = getattr(val, "__closure__", None) + if not closure: + return False + if seen is None: + seen = set() + if id(val) in seen: + return False + seen.add(id(val)) + for cell in closure: + try: + contents = cell.cell_contents + except ValueError: + continue + if not _is_immutable(contents, seen): + return True + return False + + +def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if val is None or val is UNSET or isinstance(val, type): return True - if hasattr(val, "__self__") and not _is_immutable(val.__self__): + if hasattr(val, "__self__") and not _is_immutable(val.__self__, seen): return False t = type(val) if t in _IMMUTABLE_TYPES: return True if isinstance(val, (FunctionType, BuiltinFunctionType, MethodType)): - return not getattr(val, "__dict__", None) + if getattr(val, "__dict__", None): + return False + return not _has_mutable_captures(val, seen) if t is datetime.datetime: tz = val.tzinfo return tz is None or type(tz) is datetime.timezone @@ -341,6 +362,8 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non memo[id(detail)] = root deferred_dict_insertions: list[tuple[Any, Any, Any]] = [] + deferred_frozenset_insertions: list[tuple[Any, Any, bool, int, Any, list[Any]]] = [] + deferred_tuple_finalizations: list[tuple[Any, Any, bool, int, Any, list[Any]]] = [] deferred_set_insertions: list[tuple[Any, Any, list[Any]]] = [] stack: list[Any] = [(_OBJ_EXPAND, root, iter(_get_obj_attrs(detail)))] @@ -525,9 +548,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_OBJ_EXPAND, res_empty_fs, iter(_get_obj_attrs(val)))) _assign_target(target, key, is_attr, res_empty_fs) else: - temp_set_list: list[Any] = [] - stack.append((_SET_FINALIZE, target, key, is_attr, val_id, val, temp_set_list)) - stack.append((_LIST_EXPAND, temp_set_list, frozenset.__iter__(val))) + deferred_frozenset_insertions.append( + (target, key, is_attr, val_id, val, list(val)) + ) + stack.append((_SET_EXPAND, None, iter(val))) elif isinstance(val, deque): if deque.__len__(val) > _MAX_SAFE_BUFFER_SIZE: return None @@ -776,6 +800,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non extra[2], extra[3], ) + if any(x is None for x in temp_list): + deferred_tuple_finalizations.append( + (target, key, is_attr, val_id, orig_val, temp_list) + ) + continue if val_id in memo: res_tuple = memo[val_id] elif type(orig_val) is tuple and all(a is b for a, b in zip(orig_val, temp_list)): @@ -795,49 +824,78 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_OBJ_EXPAND, res_tuple, iter(_get_obj_attrs(orig_val)))) _assign_target(target, key, is_attr, res_tuple) - elif task_type == _SET_FINALIZE: - key, is_attr, val_id, orig_val, temp_set_list = ( - it_or_key, - extra[0], - extra[1], - extra[2], - extra[3], - ) - if val_id in memo: - res_set = memo[val_id] + if _deadline_expired(): + return None + + deferred_custom_dict_insertions: list[tuple[Any, Any, Any]] = [] + deferred_later_dict_insertions: list[tuple[Any, Any, Any]] = [] + for target_dict, orig_k, orig_v in deferred_dict_insertions: + if _deadline_expired(): + return None + if _is_immutable(orig_k): + if _is_immutable(orig_v): + target_dict[orig_k] = orig_v + elif id(orig_v) in memo: + target_dict[orig_k] = memo[id(orig_v)] else: - if type(orig_val) is frozenset: - res_set = frozenset(temp_set_list) - else: # frozenset subclass - try: - res_set = frozenset.__new__(type(orig_val), temp_set_list) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(orig_val).__name__}" - ) from exc - if frozenset(res_set) != frozenset(temp_set_list): + deferred_later_dict_insertions.append((target_dict, orig_k, orig_v)) + else: + deferred_custom_dict_insertions.append((target_dict, orig_k, orig_v)) + + for target, key, is_attr, val_id, orig_val, orig_members in deferred_frozenset_insertions: + if _deadline_expired(): + return None + if val_id in memo: + res_set = memo[val_id] + else: + resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] + if type(orig_val) is frozenset: + res_set = frozenset(resolved_members) + else: + try: + res_set = frozenset.__new__(type(orig_val), resolved_members) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) from exc + if frozenset(res_set) != frozenset(resolved_members): raise TypeError( "Unsupported mutable value in review extension data: " f"{type(orig_val).__name__}" ) - memo[val_id] = res_set + memo[val_id] = res_set if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): - stack.append((_OBJ_EXPAND, res_set, iter(_get_obj_attrs(orig_val)))) - _assign_target(target, key, is_attr, res_set) + for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): + val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] + _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) + _assign_target(target, key, is_attr, res_set) - if _deadline_expired(): - return None + for target_dict, orig_k, orig_v in deferred_later_dict_insertions: + if _deadline_expired(): + return None + target_dict[orig_k] = memo[id(orig_v)] - deferred_custom_dict_insertions: list[tuple[Any, Any, Any]] = [] - for target_dict, orig_k, orig_v in deferred_dict_insertions: + for target, key, is_attr, val_id, orig_val, temp_list in deferred_tuple_finalizations: if _deadline_expired(): return None - if _is_immutable(orig_k): - v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] - target_dict[orig_k] = v + if val_id in memo: + res_tuple = memo[val_id] else: - deferred_custom_dict_insertions.append((target_dict, orig_k, orig_v)) + if type(orig_val) is tuple: + res_tuple = tuple(temp_list) + else: + try: + orig_tuple_cls: Any = type(orig_val) + res_tuple = tuple.__new__(orig_tuple_cls, temp_list) + except Exception: + return None + memo[val_id] = res_tuple + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): + val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] + _assign_target(res_tuple, (slot_or_name, is_desc), True, val_to_set) + _assign_target(target, key, is_attr, res_tuple) for s, orig_val, orig_members in deferred_set_insertions: if _deadline_expired(): @@ -870,17 +928,22 @@ def _safe_cancel_target(target: Any) -> None: pass -def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: +def _detach_overdue_future(fut: Any) -> None: try: - if AsyncFuture.done(fut): - if not AsyncFuture.cancelled(fut): + is_done = fut.done() if hasattr(fut, "done") else AsyncFuture.done(fut) + if is_done: + is_canc = fut.cancelled() if hasattr(fut, "cancelled") else AsyncFuture.cancelled(fut) + if not is_canc: try: - AsyncFuture.exception(fut) + if hasattr(fut, "exception"): + fut.exception() + else: + AsyncFuture.exception(fut) except Exception: pass return try: - loop = AsyncFuture.get_loop(fut) + loop = fut.get_loop() if hasattr(fut, "get_loop") else AsyncFuture.get_loop(fut) except Exception: return try: @@ -895,13 +958,18 @@ def _detach_overdue_future(fut: AsyncTask[Any] | AsyncFuture[Any]) -> None: def _on_detached_fut_done(t: Any) -> None: _DETACHED_FUTURES.pop(fut_id, None) try: - if not AsyncFuture.cancelled(t): - AsyncFuture.exception(t) + is_canc = t.cancelled() if hasattr(t, "cancelled") else False + if not is_canc: + if hasattr(t, "exception"): + t.exception() except BaseException: pass try: - AsyncFuture.add_done_callback(fut, _on_detached_fut_done) + if hasattr(fut, "add_done_callback"): + fut.add_done_callback(_on_detached_fut_done) + else: + AsyncFuture.add_done_callback(fut, _on_detached_fut_done) except BaseException: _DETACHED_FUTURES.pop(fut_id, None) except BaseException: @@ -909,7 +977,7 @@ def _on_detached_fut_done(t: Any) -> None: def _detach_overdue_task( - task: AsyncTask[Any], + task: Any, res: Any, wrapper_started: bool, ) -> None: @@ -919,13 +987,18 @@ def _detach_overdue_task( def _on_detached_task_done(t: Any) -> None: _DETACHED_TASKS.pop(task_id, None) try: - if not AsyncFuture.cancelled(t): - AsyncTask.exception(t) + is_canc = t.cancelled() if hasattr(t, "cancelled") else False + if not is_canc: + if hasattr(t, "exception"): + t.exception() except BaseException: pass try: - AsyncFuture.add_done_callback(task, _on_detached_task_done) + if hasattr(task, "add_done_callback"): + task.add_done_callback(_on_detached_task_done) + else: + AsyncFuture.add_done_callback(task, _on_detached_task_done) except BaseException: _DETACHED_TASKS.pop(task_id, None) if not wrapper_started: @@ -1340,7 +1413,11 @@ def wait_for_review( snapshot = _snapshot_review(last) if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) - if isawaitable(res): + try: + res_awaitable = isawaitable(res) + except Exception: + raise TypeError("Callbacks must return None.") from None + if res_awaitable: if iscoroutine(res): try: if getcoroutinestate(res) == CORO_CREATED: @@ -1787,9 +1864,13 @@ async def wait_for_review( snapshot = _snapshot_review(last) if snapshot is not None and (_transport.remaining() or 0) > 0: res = on_poll(snapshot) - if res is not None and not isawaitable(res): + try: + res_awaitable = isawaitable(res) + except Exception: + raise TypeError("Callbacks must return None or an awaitable.") from None + if res is not None and not res_awaitable: raise TypeError("Callbacks must return None or an awaitable.") - if isawaitable(res): + if res_awaitable: if res is async_current_task(): raise ValueError( "Callbacks cannot return the running polling task." @@ -1801,9 +1882,16 @@ async def wait_for_review( raise ValueError("Callbacks must return unstarted coroutines.") if isinstance(res, (AsyncTask, AsyncFuture)): - if not AsyncFuture.done(res): + is_done = ( + res.done() if hasattr(res, "done") else AsyncFuture.done(res) + ) + if not is_done: try: - res_loop = AsyncFuture.get_loop(res) + res_loop = ( + res.get_loop() + if hasattr(res, "get_loop") + else AsyncFuture.get_loop(res) + ) except Exception: res_loop = None running_loop = async_get_running_loop() @@ -1832,8 +1920,14 @@ async def wait_for_review( break if isinstance(res, (AsyncTask, AsyncFuture)): - if AsyncFuture.done(res): - AsyncFuture.result(res) + is_done = ( + res.done() if hasattr(res, "done") else AsyncFuture.done(res) + ) + if is_done: + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) else: completion_fut = async_get_running_loop().create_future() completed_at: list[float] = [] @@ -1843,7 +1937,10 @@ def _on_future_done(_: Any) -> None: if not completion_fut.done(): completion_fut.set_result(None) - AsyncFuture.add_done_callback(res, _on_future_done) + if hasattr(res, "add_done_callback"): + res.add_done_callback(_on_future_done) + else: + AsyncFuture.add_done_callback(res, _on_future_done) remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: _detach_overdue_future(res) @@ -1862,7 +1959,10 @@ def _on_future_done(_: Any) -> None: deadline_val is None or completed_at[0] <= deadline_val ) if cb_finished_in_budget and completion_fut in done: - AsyncFuture.result(res) + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) else: _detach_overdue_future(res) if result is not None: @@ -1896,6 +1996,7 @@ async def _runner() -> None: pass return try: + assert coro is not None await coro finally: completed_at.append(monotonic()) @@ -1925,18 +2026,53 @@ async def _runner() -> None: raise task_completion_fut = async_get_running_loop().create_future() - def _on_task_done(_: Any) -> None: + def _on_task_done(t: Any) -> None: + if not completed_at: + try: + is_canc = ( + t.cancelled() if hasattr(t, "cancelled") else False + ) + if is_canc: + completed_at.append(monotonic()) + except BaseException: + pass if not task_completion_fut.done(): task_completion_fut.set_result(None) - AsyncTask.add_done_callback(task, _on_task_done) + if hasattr(task, "add_done_callback"): + task.add_done_callback(_on_task_done) + else: + AsyncTask.add_done_callback(task, _on_task_done) deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - if AsyncFuture.done(task) and cb_finished_in_budget: - AsyncTask.result(task) + task_is_done = ( + task.done() if hasattr(task, "done") else AsyncFuture.done(task) + ) + if task_is_done and cb_finished_in_budget: + if not wrapper_started: + if ( + iscoroutine(res) + and getcoroutinestate(res) == CORO_CREATED + ): + try: + res.close() + except BaseException: + pass + elif ( + isgenerator(res) + and getgeneratorstate(res) == GEN_CREATED + ): + try: + res.close() + except BaseException: + pass + if hasattr(task, "result"): + task.result() + else: + AsyncTask.result(task) remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: @@ -1955,8 +2091,33 @@ def _on_task_done(_: Any) -> None: cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - if cb_finished_in_budget and task_completion_fut in done: - AsyncTask.result(task) + task_is_done = ( + task.done() if hasattr(task, "done") else AsyncFuture.done(task) + ) + if cb_finished_in_budget and ( + task_completion_fut in done or task_is_done + ): + if not wrapper_started: + if ( + iscoroutine(res) + and getcoroutinestate(res) == CORO_CREATED + ): + try: + res.close() + except BaseException: + pass + elif ( + isgenerator(res) + and getgeneratorstate(res) == GEN_CREATED + ): + try: + res.close() + except BaseException: + pass + if hasattr(task, "result"): + task.result() + else: + AsyncTask.result(task) else: _detach_overdue_task(task, res, wrapper_started) if result is not None: diff --git a/tests/test_http.py b/tests/test_http.py index 9ec0caab..958098a3 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -3396,19 +3396,40 @@ def cancel(self, msg: Any = None) -> bool: loop.set_exception_handler(lambda _loop, ctx: cancel_reports.append(ctx)) try: fut_sync_cancel = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: + clock_now = [1000.0] + orig_client_mono = client_module.monotonic + orig_trans_mono = _transport.monotonic + client_module.monotonic = lambda: clock_now[0] + _transport.monotonic = lambda: clock_now[0] + + def sync_cancel_on_poll(r: Any) -> Any: + clock_now[0] += 0.2 + return fut_sync_cancel + + running_detail = CustomerReviewDetail.from_dict(review("RUNNING")) + + async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: + return running_detail + + try: + async with AsyncProoflineClient( + token="test_token", base_url="https://api.proofline.sh" + ) as client: + client.get_review = fake_sync_cancel_running # type: ignore res_sync_cancel = await client.wait_for_review( ORG, REVIEW, timeout=0.1, - on_poll=lambda r: fut_sync_cancel, + on_poll=sync_cancel_on_poll, ) assert res_sync_cancel.status == "TIMED_OUT" await asyncio.sleep(0) assert fut_sync_cancel.cancel_called is False assert id(fut_sync_cancel) in _DETACHED_FUTURES assert cancel_reports == [] + finally: + client_module.monotonic = orig_client_mono + _transport.monotonic = orig_trans_mono finally: if not fut_sync_cancel.done(): fut_sync_cancel.set_result(None) From 0dcc1b44f6be6efba192400544cfee5dbea0f22d Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 15:38:55 +0530 Subject: [PATCH 39/75] Address review 38 findings: unresolved tuple slot sentinel, defaultdict factory parameter defaults, frozenset iterative dependency construction, deque documentation, isfuture validation, synchronous detached task inspection, pre-close wrapper cancellation, and test quality improvements --- proofline/client.py | 209 +++++++++++++++++++++++++++++++------------- tests/test_http.py | 141 ++++++++++++++++++++++-------- 2 files changed, 254 insertions(+), 96 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index fb9fe8f0..0ff3587f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -20,6 +20,9 @@ from asyncio import ( get_running_loop as async_get_running_loop, ) +from asyncio import ( + isfuture as async_isfuture, +) from asyncio import ( sleep as async_sleep, ) @@ -252,21 +255,34 @@ def _export_page_limit(max_pages: int) -> None: def _has_mutable_captures(val: Any, seen: set[int] | None = None) -> bool: - closure = getattr(val, "__closure__", None) - if not closure: - return False if seen is None: seen = set() if id(val) in seen: return False seen.add(id(val)) - for cell in closure: - try: - contents = cell.cell_contents - except ValueError: - continue - if not _is_immutable(contents, seen): - return True + + closure = getattr(val, "__closure__", None) + if closure: + for cell in closure: + try: + contents = cell.cell_contents + except ValueError: + continue + if not _is_immutable(contents, seen): + return True + + defaults = getattr(val, "__defaults__", None) + if defaults: + for d in defaults: + if not _is_immutable(d, seen): + return True + + kwdefaults = getattr(val, "__kwdefaults__", None) + if kwdefaults and isinstance(kwdefaults, dict): + for d in kwdefaults.values(): + if not _is_immutable(d, seen): + return True + return False @@ -346,6 +362,7 @@ def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: _EXPAND_BATCH_SIZE = 64 _MAX_SAFE_TUPLE_SIZE = 1000 _MAX_SAFE_BUFFER_SIZE = 65_536 +_UNRESOLVED_SLOT = object() def _deadline_expired() -> bool: @@ -785,7 +802,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non temp_list.append(memo[id(v)]) else: idx = len(temp_list) - temp_list.append(None) + temp_list.append(_UNRESOLVED_SLOT) stack.append((_TUPLE_EXPAND, temp_list, it)) stack.append((_ITEM_TASK, temp_list, idx, False, v)) break @@ -800,7 +817,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non extra[2], extra[3], ) - if any(x is None for x in temp_list): + if any(x is _UNRESOLVED_SLOT for x in temp_list): deferred_tuple_finalizations.append( (target, key, is_attr, val_id, orig_val, temp_list) ) @@ -842,34 +859,53 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: deferred_custom_dict_insertions.append((target_dict, orig_k, orig_v)) - for target, key, is_attr, val_id, orig_val, orig_members in deferred_frozenset_insertions: + pending_frozensets = deferred_frozenset_insertions + while pending_frozensets: if _deadline_expired(): return None - if val_id in memo: - res_set = memo[val_id] - else: - resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] - if type(orig_val) is frozenset: - res_set = frozenset(resolved_members) + progress = False + remaining_frozensets = [] + for target, key, is_attr, val_id, orig_val, orig_members in pending_frozensets: + if all(_is_immutable(m) or id(m) in memo for m in orig_members): + resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] + if type(orig_val) is frozenset: + res_set = frozenset(resolved_members) + else: + try: + res_set = frozenset.__new__(type(orig_val), resolved_members) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) from exc + if frozenset(res_set) != frozenset(resolved_members): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) + memo[val_id] = res_set + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): + val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] + _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) + _assign_target(target, key, is_attr, res_set) + progress = True else: - try: - res_set = frozenset.__new__(type(orig_val), resolved_members) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(orig_val).__name__}" - ) from exc - if frozenset(res_set) != frozenset(resolved_members): - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(orig_val).__name__}" - ) - memo[val_id] = res_set - if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): - for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): - val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] - _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) - _assign_target(target, key, is_attr, res_set) + remaining_frozensets.append((target, key, is_attr, val_id, orig_val, orig_members)) + + pending_frozensets = remaining_frozensets + + if progress and deferred_later_dict_insertions: + still_later_dict: list[tuple[Any, Any, Any]] = [] + for target_dict, orig_k, orig_v in deferred_later_dict_insertions: + if id(orig_v) in memo: + target_dict[orig_k] = memo[id(orig_v)] + else: + still_later_dict.append((target_dict, orig_k, orig_v)) + deferred_later_dict_insertions = still_later_dict + + if not progress and pending_frozensets: + raise TypeError("Unsupported cyclic reference in frozenset") for target_dict, orig_k, orig_v in deferred_later_dict_insertions: if _deadline_expired(): @@ -981,6 +1017,35 @@ def _detach_overdue_task( res: Any, wrapper_started: bool, ) -> None: + try: + is_done = task.done() if hasattr(task, "done") else False + except BaseException: + is_done = False + + if is_done: + try: + is_canc = task.cancelled() if hasattr(task, "cancelled") else False + if not is_canc and hasattr(task, "exception"): + task.exception() + except BaseException: + pass + if not wrapper_started: + try: + task.cancel() + except BaseException: + pass + if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: + try: + res.close() + except BaseException: + pass + elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: + try: + res.close() + except BaseException: + pass + return + task_id = id(task) _DETACHED_TASKS[task_id] = task @@ -1001,7 +1066,12 @@ def _on_detached_task_done(t: Any) -> None: AsyncFuture.add_done_callback(task, _on_detached_task_done) except BaseException: _DETACHED_TASKS.pop(task_id, None) + if not wrapper_started: + try: + task.cancel() + except BaseException: + pass if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: try: res.close() @@ -1379,9 +1449,10 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. Oversized tuples or buffers in review extension data skip - on_poll snapshot delivery even with time remaining, and snapshot copy - errors on unsupported mutable values propagate before on_poll runs. + delivery. Oversized tuples, buffers, or deques with more than 65,536 items in + review extension data skip on_poll snapshot delivery even with time + remaining, and snapshot copy errors on unsupported mutable values + propagate before on_poll runs. on_poll exceptions and return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return @@ -1826,10 +1897,10 @@ async def wait_for_review( an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Oversized - tuples or buffers in review extension data skip on_poll snapshot delivery - even with time remaining, and snapshot copy errors on unsupported mutable - values propagate before on_poll runs. Callback return-validation errors - and exceptions propagate even when a terminal outcome has already been + tuples, buffers, or deques with more than 65,536 items in review extension data skip + on_poll snapshot delivery even with time remaining, and snapshot copy errors on + unsupported mutable values propagate before on_poll runs. Callback return-validation + errors and exceptions propagate even when a terminal outcome has already been determined, preventing the waiter from returning a classified outcome. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's @@ -1881,10 +1952,11 @@ async def wait_for_review( if isgenerator(res) and getgeneratorstate(res) != GEN_CREATED: raise ValueError("Callbacks must return unstarted coroutines.") - if isinstance(res, (AsyncTask, AsyncFuture)): - is_done = ( - res.done() if hasattr(res, "done") else AsyncFuture.done(res) - ) + if async_isfuture(res): + try: + is_done = res.done() + except BaseException: + is_done = False if not is_done: try: res_loop = ( @@ -1895,7 +1967,9 @@ async def wait_for_review( except Exception: res_loop = None running_loop = async_get_running_loop() - if res_loop is not running_loop or res_loop.is_closed(): + if res_loop is not running_loop or ( + res_loop is not None and res_loop.is_closed() + ): raise ValueError( "Pending callback futures must belong " "to the running event loop." @@ -1913,16 +1987,17 @@ async def wait_for_review( res.close() except BaseException: pass - elif isinstance(res, (AsyncTask, AsyncFuture)): + elif async_isfuture(res): _detach_overdue_future(res) if result is not None: return result break - if isinstance(res, (AsyncTask, AsyncFuture)): - is_done = ( - res.done() if hasattr(res, "done") else AsyncFuture.done(res) - ) + if async_isfuture(res): + try: + is_done = res.done() + except BaseException: + is_done = False if is_done: if hasattr(res, "result"): res.result() @@ -2048,11 +2123,18 @@ def _on_task_done(t: Any) -> None: cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - task_is_done = ( - task.done() if hasattr(task, "done") else AsyncFuture.done(task) - ) + try: + task_is_done = task.done() if hasattr(task, "done") else False + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise + if task_is_done and cb_finished_in_budget: if not wrapper_started: + try: + task.cancel() + except BaseException: + pass if ( iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED @@ -2091,13 +2173,20 @@ def _on_task_done(t: Any) -> None: cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val ) - task_is_done = ( - task.done() if hasattr(task, "done") else AsyncFuture.done(task) - ) + try: + task_is_done = task.done() if hasattr(task, "done") else False + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise + if cb_finished_in_budget and ( task_completion_fut in done or task_is_done ): if not wrapper_started: + try: + task.cancel() + except BaseException: + pass if ( iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED diff --git a/tests/test_http.py b/tests/test_http.py index 958098a3..f913933a 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2755,17 +2755,31 @@ def timely_fail_cb(r: Any) -> asyncio.Future[None]: ) # Late-observed pending future failure preserves the classified outcome - late_fut: asyncio.Future[None] = asyncio.get_running_loop().create_future() + class TrackedFuture(asyncio.Future[None]): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(loop=loop) + self.exception_retrieved = False + + def exception(self) -> BaseException | None: + self.exception_retrieved = True + return super().exception() + + import weakref + + late_fut: TrackedFuture | None = TrackedFuture(loop=asyncio.get_running_loop()) + late_fut_ref = weakref.ref(late_fut) late_fut.add_done_callback(lambda _: setattr(clock, "now", clock.now + 200.0)) producer_task: asyncio.Task[None] | None = None async def fail_late_soon() -> None: await asyncio.sleep(0) - late_fut.set_exception(ValueError("late failure")) + if late_fut is not None: + late_fut.set_exception(ValueError("late failure")) def late_fail_cb(r: Any) -> asyncio.Future[None]: nonlocal producer_task producer_task = asyncio.create_task(fail_late_soon()) + assert late_fut is not None return late_fut unhandled_reports: list[dict[str, Any]] = [] @@ -2782,14 +2796,19 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: on_poll=late_fail_cb, ) assert res_late.status == "COMPLETED" + assert late_fut is not None assert late_fut.done() assert clock.now >= 200.0 if producer_task is not None: await producer_task + await asyncio.sleep(0) + assert late_fut.exception_retrieved is True + assert id(late_fut) not in client_module._DETACHED_FUTURES del late_fut import gc gc.collect() + assert late_fut_ref() is None assert unhandled_reports == [] finally: loop.set_exception_handler(old_h) @@ -2821,6 +2840,18 @@ async def main() -> None: client_module.monotonic = clock.time transport_module.monotonic = clock.time + sleep_forbidden = False + orig_async_sleep = client_module.async_sleep + + async def guarded_async_sleep(delay: float) -> None: + if sleep_forbidden: + raise AssertionError( + "Ordinary polling sleep occurred before watchdog advanced callback deadline" + ) + await orig_async_sleep(delay) + + client_module.async_sleep = guarded_async_sleep + running_detail = CustomerReviewDetail.from_dict(review("RUNNING")) completed_detail = CustomerReviewDetail.from_dict(review()) @@ -2904,23 +2935,27 @@ async def continuing_coro(r: Any) -> None: client.get_review = fake_running # type: ignore - waiter_task_3 = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=continuing_coro, + sleep_forbidden = True + try: + waiter_task_3 = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=continuing_coro, + ) ) - ) - await callback_running.wait() - assert not waiter_task_3.done() - clock.advance(1.0) - res_3 = await waiter_task_3 - assert res_3.status == "TIMED_OUT" - assert callback_running.is_set() - assert not callback_finished.is_set() - release_callback.set() - await callback_finished.wait() + await callback_running.wait() + assert not waiter_task_3.done() + clock.advance(1.0) + res_3 = await waiter_task_3 + assert res_3.status == "TIMED_OUT" + assert callback_running.is_set() + assert not callback_finished.is_set() + release_callback.set() + await callback_finished.wait() + finally: + sleep_forbidden = False # Case 4: Overdue callback continues running without cancellation on terminal review callback_running_term = asyncio.Event() @@ -3067,20 +3102,24 @@ async def awaiting_runner_callback(r: Any) -> None: callback_completed_7.set() client.get_review = fake_running # type: ignore - polling_waiter_task = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=awaiting_runner_callback, + sleep_forbidden = True + try: + polling_waiter_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=awaiting_runner_callback, + ) ) - ) - await cb_7_started.wait() - assert not polling_waiter_task.done() - clock.advance(1.0) - res_7 = await polling_waiter_task - assert res_7.status == "TIMED_OUT" - await asyncio.wait_for(callback_completed_7.wait(), timeout=1.0) + await cb_7_started.wait() + assert not polling_waiter_task.done() + clock.advance(1.0) + res_7 = await polling_waiter_task + assert res_7.status == "TIMED_OUT" + await asyncio.wait_for(callback_completed_7.wait(), timeout=1.0) + finally: + sleep_forbidden = False asyncio.run(main()) """ @@ -3359,7 +3398,16 @@ def unhash_failing_cb(r: Any) -> Any: on_poll=unhash_failing_cb, ) ) - await cb_started.wait() + cb_wait_task = asyncio.create_task(cb_started.wait()) + done_set, _ = await asyncio.wait( + {cb_wait_task, waiter_task}, + timeout=5.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task in done_set and not cb_started.is_set(): + cb_wait_task.cancel() + await waiter_task + assert cb_wait_task in done_set, "Callback startup timed out" waiter_task.cancel() cancelled = False try: @@ -4030,9 +4078,21 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: assert "injected_shared_member" not in copied_injected_s assert "orig_member" in copied_injected_s - # Standard built-in set and frozenset properly snapshotted - normal_s = {"member1", "member2"} - normal_fs = frozenset(["fs1", "fs2"]) + # Standard built-in set and frozenset properly snapshotted with hashable mutable payload + class HashablePayload: + def __init__(self, key: str, payload: list[str]) -> None: + self.key = key + self.payload = payload + + def __hash__(self) -> int: + return hash(self.key) + + def __eq__(self, other: Any) -> bool: + return isinstance(other, HashablePayload) and self.key == other.key + + member_payload = HashablePayload("test_key", ["original_val"]) + normal_s = {member_payload} + normal_fs = frozenset([member_payload]) detail_sets = CustomerReviewDetail.from_dict(responses[1]) detail_sets.additional_properties["normal_s"] = normal_s detail_sets.additional_properties["normal_fs"] = normal_fs @@ -4040,7 +4100,16 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: assert snap_sets is not None assert snap_sets.additional_properties["normal_s"] == normal_s assert snap_sets.additional_properties["normal_s"] is not normal_s - assert snap_sets.additional_properties["normal_fs"] == normal_fs + copied_fs = snap_sets.additional_properties["normal_fs"] + assert isinstance(copied_fs, frozenset) + assert len(copied_fs) == 1 + cloned_member = next(iter(copied_fs)) + assert cloned_member == member_payload + assert cloned_member is not member_payload + assert cloned_member.payload is not member_payload.payload + assert cloned_member in copied_fs + cloned_member.payload.append("mutated_val") + assert member_payload.payload == ["original_val"] # Deque traversed and snapshotted, and weakref inside deque rejected from collections import deque From 51ec57268b7a8ef04a78457591bc7a57adee9aa1 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 15:57:00 +0530 Subject: [PATCH 40/75] Address review findings: safe builtin class allowlist for defaultdict factory, iterative tuple/dict flushing for frozenset hashes, memoryview byte limit documentation, guarded callback registration, and test quality assertions --- proofline/client.py | 154 +++++++++++++++++++++++++++++--------------- tests/test_http.py | 117 +++++++++++++++++++++++---------- 2 files changed, 186 insertions(+), 85 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 0ff3587f..062fb2bd 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -286,9 +286,31 @@ def _has_mutable_captures(val: Any, seen: set[int] | None = None) -> bool: return False +_SAFE_BUILTIN_CLASSES: set[type] = { + int, + float, + str, + bool, + bytes, + list, + dict, + set, + tuple, + bytearray, + deque, + defaultdict, + datetime.date, + datetime.datetime, + datetime.time, + UUID, +} + + def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: - if val is None or val is UNSET or isinstance(val, type): + if val is None or val is UNSET: return True + if isinstance(val, type): + return val in _SAFE_BUILTIN_CLASSES if hasattr(val, "__self__") and not _is_immutable(val.__self__, seen): return False t = type(val) @@ -859,6 +881,60 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non else: deferred_custom_dict_insertions.append((target_dict, orig_k, orig_v)) + def _flush_pending_structures() -> None: + nonlocal deferred_later_dict_insertions, deferred_tuple_finalizations + changed = True + while changed: + changed = False + if deferred_tuple_finalizations: + still_tuples = [] + for ( + target, + key, + is_attr, + val_id, + orig_val, + temp_list, + ) in deferred_tuple_finalizations: + if not any(x is _UNRESOLVED_SLOT for x in temp_list): + if val_id in memo: + res_tuple = memo[val_id] + else: + if type(orig_val) is tuple: + res_tuple = tuple(temp_list) + else: + try: + orig_tuple_cls: Any = type(orig_val) + res_tuple = tuple.__new__(orig_tuple_cls, temp_list) + except Exception: + continue + memo[val_id] = res_tuple + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): + val_to_set = ( + attr_val + if _is_immutable(attr_val) + else memo.get(id(attr_val), attr_val) + ) + _assign_target(res_tuple, (slot_or_name, is_desc), True, val_to_set) + _assign_target(target, key, is_attr, res_tuple) + changed = True + else: + still_tuples.append((target, key, is_attr, val_id, orig_val, temp_list)) + deferred_tuple_finalizations = still_tuples + + if deferred_later_dict_insertions: + still_dicts = [] + for target_dict, orig_k, orig_v in deferred_later_dict_insertions: + if id(orig_v) in memo: + target_dict[orig_k] = memo[id(orig_v)] + changed = True + else: + still_dicts.append((target_dict, orig_k, orig_v)) + deferred_later_dict_insertions = still_dicts + + _flush_pending_structures() + pending_frozensets = deferred_frozenset_insertions while pending_frozensets: if _deadline_expired(): @@ -890,48 +966,16 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) _assign_target(target, key, is_attr, res_set) progress = True + _flush_pending_structures() else: remaining_frozensets.append((target, key, is_attr, val_id, orig_val, orig_members)) pending_frozensets = remaining_frozensets - if progress and deferred_later_dict_insertions: - still_later_dict: list[tuple[Any, Any, Any]] = [] - for target_dict, orig_k, orig_v in deferred_later_dict_insertions: - if id(orig_v) in memo: - target_dict[orig_k] = memo[id(orig_v)] - else: - still_later_dict.append((target_dict, orig_k, orig_v)) - deferred_later_dict_insertions = still_later_dict - if not progress and pending_frozensets: raise TypeError("Unsupported cyclic reference in frozenset") - for target_dict, orig_k, orig_v in deferred_later_dict_insertions: - if _deadline_expired(): - return None - target_dict[orig_k] = memo[id(orig_v)] - - for target, key, is_attr, val_id, orig_val, temp_list in deferred_tuple_finalizations: - if _deadline_expired(): - return None - if val_id in memo: - res_tuple = memo[val_id] - else: - if type(orig_val) is tuple: - res_tuple = tuple(temp_list) - else: - try: - orig_tuple_cls: Any = type(orig_val) - res_tuple = tuple.__new__(orig_tuple_cls, temp_list) - except Exception: - return None - memo[val_id] = res_tuple - if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): - for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): - val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] - _assign_target(res_tuple, (slot_or_name, is_desc), True, val_to_set) - _assign_target(target, key, is_attr, res_tuple) + _flush_pending_structures() for s, orig_val, orig_members in deferred_set_insertions: if _deadline_expired(): @@ -1449,10 +1493,10 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. Oversized tuples, buffers, or deques with more than 65,536 items in - review extension data skip on_poll snapshot delivery even with time - remaining, and snapshot copy errors on unsupported mutable values - propagate before on_poll runs. + delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or + deques with more than 65,536 items in review extension data skip on_poll snapshot + delivery even with time remaining, and snapshot copy errors on unsupported mutable + values propagate before on_poll runs. on_poll exceptions and return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return @@ -1897,10 +1941,10 @@ async def wait_for_review( an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Oversized - tuples, buffers, or deques with more than 65,536 items in review extension data skip - on_poll snapshot delivery even with time remaining, and snapshot copy errors on - unsupported mutable values propagate before on_poll runs. Callback return-validation - errors and exceptions propagate even when a terminal outcome has already been + tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than + 65,536 items in review extension data skip on_poll snapshot delivery even with time + remaining, and snapshot copy errors on unsupported mutable values propagate before + on_poll runs. Callback return-validation errors and exceptions propagate even when a determined, preventing the waiter from returning a classified outcome. Inline failures and awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's @@ -2012,10 +2056,14 @@ def _on_future_done(_: Any) -> None: if not completion_fut.done(): completion_fut.set_result(None) - if hasattr(res, "add_done_callback"): - res.add_done_callback(_on_future_done) - else: - AsyncFuture.add_done_callback(res, _on_future_done) + try: + if hasattr(res, "add_done_callback"): + res.add_done_callback(_on_future_done) + else: + AsyncFuture.add_done_callback(res, _on_future_done) + except BaseException: + _detach_overdue_future(res) + raise remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: _detach_overdue_future(res) @@ -2114,10 +2162,14 @@ def _on_task_done(t: Any) -> None: if not task_completion_fut.done(): task_completion_fut.set_result(None) - if hasattr(task, "add_done_callback"): - task.add_done_callback(_on_task_done) - else: - AsyncTask.add_done_callback(task, _on_task_done) + try: + if hasattr(task, "add_done_callback"): + task.add_done_callback(_on_task_done) + else: + AsyncTask.add_done_callback(task, _on_task_done) + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( diff --git a/tests/test_http.py b/tests/test_http.py index f913933a..f5dfcf0d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -3181,7 +3181,7 @@ async def async_mutating_callback(r: Any) -> None: detail = CustomerReviewDetail.from_dict(responses[1]) detail.additional_properties["deep"] = deep_container - detail.additional_properties["custom_tuple"] = ({"nested": "val"}, 42) + detail.additional_properties["custom_tuple"] = ({"nested": "val"}, None, 42) from proofline.client import _snapshot_review @@ -3203,12 +3203,15 @@ async def async_mutating_callback(r: Any) -> None: walk_snap["val"] = "mutated_leaf" assert walk_orig["val"] == "deepest" - assert isinstance(snap.additional_properties["custom_tuple"], tuple) - assert ( - snap.additional_properties["custom_tuple"][0] - is not detail.additional_properties["custom_tuple"][0] - ) - assert snap.additional_properties["custom_tuple"][0]["nested"] == "val" + custom_t = snap.additional_properties["custom_tuple"] + orig_t = detail.additional_properties["custom_tuple"] + assert isinstance(custom_t, tuple) + assert custom_t[0] is not orig_t[0] + assert custom_t[0]["nested"] == "val" + assert custom_t[1] is None + assert custom_t[2] == 42 + custom_t[0]["nested"] = "mutated_nested" + assert orig_t[0]["nested"] == "val" # Tuple with deeply nested list must snapshot iteratively without RecursionError deep_nested_list: Any = "leaf" @@ -3399,31 +3402,40 @@ def unhash_failing_cb(r: Any) -> Any: ) ) cb_wait_task = asyncio.create_task(cb_started.wait()) - done_set, _ = await asyncio.wait( - {cb_wait_task, waiter_task}, - timeout=5.0, - return_when=asyncio.FIRST_COMPLETED, - ) - if waiter_task in done_set and not cb_started.is_set(): - cb_wait_task.cancel() - await waiter_task - assert cb_wait_task in done_set, "Callback startup timed out" - waiter_task.cancel() - cancelled = False try: - await waiter_task - except asyncio.CancelledError: - cancelled = True - assert cancelled - assert id(unhash_failing_fut) in _DETACHED_FUTURES - unhash_failing_fut.set_exception(RuntimeError("unhashable late failure")) - await asyncio.sleep(0) - assert id(unhash_failing_fut) not in _DETACHED_FUTURES - import gc + done_set, _ = await asyncio.wait( + {cb_wait_task, waiter_task}, + timeout=5.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task in done_set and not cb_started.is_set(): + cb_wait_task.cancel() + await waiter_task + assert cb_wait_task in done_set, "Callback startup timed out" + waiter_task.cancel() + cancelled = False + try: + await waiter_task + except asyncio.CancelledError: + cancelled = True + assert cancelled + assert id(unhash_failing_fut) in _DETACHED_FUTURES + unhash_failing_fut.set_exception(RuntimeError("unhashable late failure")) + await asyncio.sleep(0) + assert id(unhash_failing_fut) not in _DETACHED_FUTURES + import gc - del unhash_failing_fut - gc.collect() - assert unhash_cancel_reports == [] + del unhash_failing_fut + gc.collect() + assert unhash_cancel_reports == [] + finally: + for t in (cb_wait_task, waiter_task): + if not t.done(): + t.cancel() + try: + await t + except (asyncio.CancelledError, BaseException): + pass finally: loop.set_exception_handler(old_h_unhash) @@ -4090,12 +4102,17 @@ def __hash__(self) -> int: def __eq__(self, other: Any) -> bool: return isinstance(other, HashablePayload) and self.key == other.key + leaf_payload = HashablePayload("leaf_key", ["leaf_original"]) + inner_fs = frozenset([leaf_payload]) + outer_fs = frozenset([inner_fs]) + member_payload = HashablePayload("test_key", ["original_val"]) normal_s = {member_payload} normal_fs = frozenset([member_payload]) detail_sets = CustomerReviewDetail.from_dict(responses[1]) detail_sets.additional_properties["normal_s"] = normal_s detail_sets.additional_properties["normal_fs"] = normal_fs + detail_sets.additional_properties["nested_fs"] = outer_fs snap_sets = _snapshot_review(detail_sets) assert snap_sets is not None assert snap_sets.additional_properties["normal_s"] == normal_s @@ -4111,6 +4128,21 @@ def __eq__(self, other: Any) -> bool: cloned_member.payload.append("mutated_val") assert member_payload.payload == ["original_val"] + copied_outer = snap_sets.additional_properties["nested_fs"] + assert isinstance(copied_outer, frozenset) + assert len(copied_outer) == 1 + copied_inner = next(iter(copied_outer)) + assert isinstance(copied_inner, frozenset) + assert len(copied_inner) == 1 + copied_leaf = next(iter(copied_inner)) + assert copied_leaf == leaf_payload + assert copied_leaf is not leaf_payload + assert copied_leaf.payload is not leaf_payload.payload + assert copied_inner in copied_outer + assert copied_leaf in copied_inner + copied_leaf.payload.append("leaf_mutated") + assert leaf_payload.payload == ["leaf_original"] + # Deque traversed and snapshotted, and weakref inside deque rejected from collections import deque @@ -4226,16 +4258,28 @@ def gen_coro_cb(r: Any) -> Any: assert inspect.getgeneratorstate(gen_cb_inst) == inspect.GEN_CLOSED # wait_for_review cleans up already-failed foreign-loop future returned when budget is exhausted + class TrackedForeignFuture(asyncio.Future[None]): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(loop=loop) + self.exception_retrieved = False + + def exception(self) -> BaseException | None: + self.exception_retrieved = True + return super().exception() + + import weakref + foreign_loop_failed = asyncio.new_event_loop() foreign_reports: list[dict[str, Any]] = [] foreign_loop_failed.set_exception_handler(lambda _loop, ctx: foreign_reports.append(ctx)) try: - foreign_box: list[Any] = [foreign_loop_failed.create_future()] - foreign_box[0].set_exception(RuntimeError("foreign future failed")) + foreign_failed_box: list[Any] = [TrackedForeignFuture(loop=foreign_loop_failed)] + foreign_failed_box[0].set_exception(RuntimeError("foreign future failed")) + foreign_failed_fut_ref = weakref.ref(foreign_failed_box[0]) def foreign_fail_cb(r: Any) -> Any: clock.now += 150.0 - return foreign_box[0] + return foreign_failed_box[0] with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: @@ -4246,10 +4290,15 @@ def foreign_fail_cb(r: Any) -> Any: on_poll=foreign_fail_cb, ) assert res_foreign.status == "COMPLETED" - foreign_box.clear() + tracked_ref = foreign_failed_fut_ref() + assert tracked_ref is not None + assert tracked_ref.exception_retrieved is True + del tracked_ref + foreign_failed_box.clear() import gc gc.collect() + assert foreign_failed_fut_ref() is None assert foreign_reports == [] finally: foreign_loop_failed.close() From b5120d8a06f75ef193aa0edbe0fac1ec3d1446d7 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 20:33:25 +0530 Subject: [PATCH 41/75] Address review run 40 findings: pre-sleep deadline guard for on_poll, allocation guard on create_future, native fallback and observer for callback registration, memoized frozenset reuse and member state population check, deferred tuple subclass attribute traversal, and comprehensive test suite assertions --- README.md | 4 +- proofline/client.py | 204 +++++++++++++++++++++++++++++++++++++------- tests/test_http.py | 204 ++++++++++++++++++++++++++++++-------------- 3 files changed, 316 insertions(+), 96 deletions(-) diff --git a/README.md b/README.md index f93d0d43..46fc750e 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples or buffers in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 062fb2bd..4587e1df 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -843,6 +843,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non deferred_tuple_finalizations.append( (target, key, is_attr, val_id, orig_val, temp_list) ) + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): + if not _is_immutable(attr_val) and id(attr_val) not in memo: + stack.append((_ITEM_TASK, None, None, False, attr_val)) continue if val_id in memo: res_tuple = memo[val_id] @@ -882,7 +886,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non deferred_custom_dict_insertions.append((target_dict, orig_k, orig_v)) def _flush_pending_structures() -> None: - nonlocal deferred_later_dict_insertions, deferred_tuple_finalizations + nonlocal \ + deferred_later_dict_insertions, \ + deferred_custom_dict_insertions, \ + deferred_tuple_finalizations changed = True while changed: changed = False @@ -933,8 +940,62 @@ def _flush_pending_structures() -> None: still_dicts.append((target_dict, orig_k, orig_v)) deferred_later_dict_insertions = still_dicts + if deferred_custom_dict_insertions: + still_custom = [] + for target_dict, orig_k, orig_v in deferred_custom_dict_insertions: + if id(orig_k) in memo: + k = memo[id(orig_k)] + if _is_immutable(orig_v): + target_dict[k] = orig_v + changed = True + elif id(orig_v) in memo: + target_dict[k] = memo[id(orig_v)] + changed = True + else: + still_custom.append((target_dict, orig_k, orig_v)) + else: + still_custom.append((target_dict, orig_k, orig_v)) + deferred_custom_dict_insertions = still_custom + _flush_pending_structures() + def _is_member_state_populated(m_clone: Any) -> bool: + if _is_immutable(m_clone): + return True + visited = set() + stack_nodes = [m_clone] + container_ids: set[int] = set() + while stack_nodes: + cur = stack_nodes.pop() + cid = id(cur) + if cid in visited: + continue + visited.add(cid) + container_ids.add(cid) + if hasattr(cur, "__dict__") and isinstance(cur.__dict__, dict): + stack_nodes.append(cur.__dict__) + if isinstance(cur, dict): + for k, v in cur.items(): + if not _is_immutable(k): + stack_nodes.append(k) + if not _is_immutable(v): + stack_nodes.append(v) + elif isinstance(cur, (list, tuple, set, deque)): + for item in cur: + if not _is_immutable(item): + stack_nodes.append(item) + + for target, _, _, _, _, _ in pending_frozensets: + if id(target) in container_ids: + return False + for target_dict, _, _ in deferred_later_dict_insertions: + if id(target_dict) in container_ids: + return False + for target_dict, _, _ in deferred_custom_dict_insertions: + if id(target_dict) in container_ids: + return False + return True + pending_frozensets = deferred_frozenset_insertions while pending_frozensets: if _deadline_expired(): @@ -942,8 +1003,17 @@ def _flush_pending_structures() -> None: progress = False remaining_frozensets = [] for target, key, is_attr, val_id, orig_val, orig_members in pending_frozensets: + if val_id in memo: + _assign_target(target, key, is_attr, memo[val_id]) + progress = True + continue if all(_is_immutable(m) or id(m) in memo for m in orig_members): resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] + if not all(_is_member_state_populated(rm) for rm in resolved_members): + remaining_frozensets.append( + (target, key, is_attr, val_id, orig_val, orig_members) + ) + continue if type(orig_val) is frozenset: res_set = frozenset(resolved_members) else: @@ -1045,13 +1115,35 @@ def _on_detached_fut_done(t: Any) -> None: except BaseException: pass - try: - if hasattr(fut, "add_done_callback"): + registered = False + if hasattr(fut, "add_done_callback"): + try: fut.add_done_callback(_on_detached_fut_done) - else: + registered = True + except BaseException: + pass + if not registered: + try: AsyncFuture.add_done_callback(fut, _on_detached_fut_done) - except BaseException: - _DETACHED_FUTURES.pop(fut_id, None) + registered = True + except BaseException: + pass + if not registered: + try: + loop = async_get_running_loop() + + async def _observe_fut() -> None: + try: + await fut + except BaseException: + pass + finally: + _DETACHED_FUTURES.pop(fut_id, None) + + obs_fut = loop.create_task(_observe_fut()) + obs_fut.add_done_callback(lambda _: None) + except BaseException: + _DETACHED_FUTURES.pop(fut_id, None) except BaseException: pass @@ -1103,13 +1195,42 @@ def _on_detached_task_done(t: Any) -> None: except BaseException: pass - try: - if hasattr(task, "add_done_callback"): + registered = False + if hasattr(task, "add_done_callback"): + try: task.add_done_callback(_on_detached_task_done) - else: - AsyncFuture.add_done_callback(task, _on_detached_task_done) - except BaseException: - _DETACHED_TASKS.pop(task_id, None) + registered = True + except BaseException: + pass + if not registered: + try: + if isinstance(task, AsyncTask): + AsyncTask.add_done_callback(task, _on_detached_task_done) + registered = True + elif isinstance(task, AsyncFuture): + AsyncFuture.add_done_callback(task, _on_detached_task_done) + registered = True + else: + AsyncFuture.add_done_callback(task, _on_detached_task_done) + registered = True + except BaseException: + pass + if not registered: + try: + loop = async_get_running_loop() + + async def _observe_task() -> None: + try: + await task + except BaseException: + pass + finally: + _DETACHED_TASKS.pop(task_id, None) + + obs = loop.create_task(_observe_task()) + obs.add_done_callback(lambda _: None) + except BaseException: + _DETACHED_TASKS.pop(task_id, None) if not wrapper_started: try: @@ -1521,8 +1642,6 @@ def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if (_transport.remaining() or 0) <= 0: - break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: snapshot = _snapshot_review(last) @@ -1553,7 +1672,7 @@ def wait_for_review( raise TypeError("Callbacks must return None.") if result is not None: return result - if (_transport.remaining() or 0) <= 0: + if on_poll is not None and (_transport.remaining() or 0) <= 0: break sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) @@ -1972,8 +2091,6 @@ async def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if (_transport.remaining() or 0) <= 0: - break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: snapshot = _snapshot_review(last) @@ -2056,14 +2173,20 @@ def _on_future_done(_: Any) -> None: if not completion_fut.done(): completion_fut.set_result(None) - try: - if hasattr(res, "add_done_callback"): + fut_registered = False + if hasattr(res, "add_done_callback"): + try: res.add_done_callback(_on_future_done) - else: + fut_registered = True + except BaseException: + pass + if not fut_registered: + try: AsyncFuture.add_done_callback(res, _on_future_done) - except BaseException: - _detach_overdue_future(res) - raise + fut_registered = True + except BaseException: + _detach_overdue_future(res) + raise remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: _detach_overdue_future(res) @@ -2147,7 +2270,11 @@ async def _runner() -> None: except BaseException: pass raise - task_completion_fut = async_get_running_loop().create_future() + try: + task_completion_fut = async_get_running_loop().create_future() + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise def _on_task_done(t: Any) -> None: if not completed_at: @@ -2162,14 +2289,27 @@ def _on_task_done(t: Any) -> None: if not task_completion_fut.done(): task_completion_fut.set_result(None) - try: - if hasattr(task, "add_done_callback"): + cb_registered = False + if hasattr(task, "add_done_callback"): + try: task.add_done_callback(_on_task_done) - else: - AsyncTask.add_done_callback(task, _on_task_done) - except BaseException: - _detach_overdue_task(task, res, wrapper_started) - raise + cb_registered = True + except BaseException: + pass + if not cb_registered: + try: + if isinstance(task, AsyncTask): + AsyncTask.add_done_callback(task, _on_task_done) + cb_registered = True + elif isinstance(task, AsyncFuture): + AsyncFuture.add_done_callback(task, _on_task_done) + cb_registered = True + else: + AsyncFuture.add_done_callback(task, _on_task_done) + cb_registered = True + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( @@ -2266,7 +2406,7 @@ def _on_task_done(t: Any) -> None: break if result is not None: return result - if (_transport.remaining() or 0) <= 0: + if on_poll is not None and (_transport.remaining() or 0) <= 0: break await async_sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) diff --git a/tests/test_http.py b/tests/test_http.py index f5dfcf0d..5a979d4c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2866,13 +2866,22 @@ async def fake_completed(org: Any, rev: Any) -> Any: ) as client: # Case 1: Pending same-loop Future that times out is detached without cancelling # Assert it is still pending before advancing the controlled deadline - pending_fut: asyncio.Future[None] | None = None + class SignallingFuture(asyncio.Future[None]): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(loop=loop) + self.wait_entered = asyncio.Event() + + def add_done_callback(self, fn: Any, *, context: Any = None) -> None: + super().add_done_callback(fn, context=context) + self.wait_entered.set() + + pending_fut: SignallingFuture | None = None cb_1_started = asyncio.Event() - def pending_future_callback(r: Any) -> asyncio.Future[None]: + def pending_future_callback(r: Any) -> SignallingFuture: nonlocal pending_fut loop = asyncio.get_running_loop() - pending_fut = loop.create_future() + pending_fut = SignallingFuture(loop=loop) cb_1_started.set() return pending_fut @@ -2887,12 +2896,13 @@ def pending_future_callback(r: Any) -> asyncio.Future[None]: ) ) await cb_1_started.wait() - await asyncio.sleep(0) + assert pending_fut is not None + await pending_fut.wait_entered.wait() assert not waiter_task_1.done() + assert id(pending_fut) not in client_module._DETACHED_FUTURES clock.advance(1.0) res_1 = await waiter_task_1 assert res_1.status == "TIMED_OUT" - assert pending_fut is not None assert not pending_fut.cancelled() assert not pending_fut.done() assert id(pending_fut) in client_module._DETACHED_FUTURES @@ -3048,7 +3058,65 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: gc.collect() assert unhandled_exceptions == [] - # 6b: Coroutine callback cancelled after startup + # 6b: Pre-start wrapper cancellation: hold wrapper before entry, + # cancel waiter with budget remaining + import inspect + + hold_wrapper = asyncio.Event() + wrapper_tasks: list[asyncio.Task[Any]] = [] + orig_create_task = client_module.async_create_task + + def holding_create_task(coro_arg: Any, **kwargs: Any) -> asyncio.Task[Any]: + async def held_wrapper() -> Any: + try: + await hold_wrapper.wait() + return await coro_arg + except asyncio.CancelledError: + if hasattr(coro_arg, "close"): + coro_arg.close() + raise + + t = orig_create_task(held_wrapper(), **kwargs) + wrapper_tasks.append(t) + return t + + client_module.async_create_task = holding_create_task + + user_coro_created: list[Any] = [] + + async def dummy_pre_start_coro(r: Any) -> None: + pass + + def pre_start_cb(r: Any) -> Any: + c = dummy_pre_start_coro(r) + user_coro_created.append(c) + return c + + try: + pre_waiter_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=10.0, + on_poll=pre_start_cb, + ) + ) + await asyncio.sleep(0) + assert len(wrapper_tasks) == 1 + assert not wrapper_tasks[0].done() + pre_waiter_task.cancel() + try: + await pre_waiter_task + except asyncio.CancelledError: + pass + assert wrapper_tasks[0].cancelled() + assert len(user_coro_created) == 1 + assert inspect.getcoroutinestate(user_coro_created[0]) == inspect.CORO_CLOSED + finally: + client_module.async_create_task = orig_create_task + hold_wrapper.set() + + # Coroutine callback cancelled after startup coro_started = asyncio.Event() coro_trigger = asyncio.Event() about_to_raise = asyncio.Event() @@ -3182,6 +3250,7 @@ async def async_mutating_callback(r: Any) -> None: detail = CustomerReviewDetail.from_dict(responses[1]) detail.additional_properties["deep"] = deep_container detail.additional_properties["custom_tuple"] = ({"nested": "val"}, None, 42) + detail.additional_properties["none_frozenset_tuple"] = (None, frozenset({1})) from proofline.client import _snapshot_review @@ -3213,6 +3282,13 @@ async def async_mutating_callback(r: Any) -> None: custom_t[0]["nested"] = "mutated_nested" assert orig_t[0]["nested"] == "val" + assert "none_frozenset_tuple" in snap.additional_properties + nft = snap.additional_properties["none_frozenset_tuple"] + assert isinstance(nft, tuple) + assert len(nft) == 2 + assert nft[0] is None + assert nft[1] == frozenset({1}) + # Tuple with deeply nested list must snapshot iteratively without RecursionError deep_nested_list: Any = "leaf" for _ in range(3000): @@ -3296,27 +3372,29 @@ async def dummy_started() -> None: started_c = dummy_started() task_started = asyncio.create_task(started_c) - await asyncio.sleep(0) + try: + await asyncio.sleep(0) - def started_coro_cb(r: Any) -> Any: - clock.now += 100.0 - return started_c + def started_coro_cb(r: Any) -> Any: + clock.now += 100.0 + return started_c - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: - with pytest.raises(ValueError, match="unstarted coroutines"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=5.0, - on_poll=started_coro_cb, - ) - assert inspect.getcoroutinestate(started_c) == inspect.CORO_SUSPENDED - task_started.cancel() - try: - await task_started - except asyncio.CancelledError: - pass + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="unstarted coroutines"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + on_poll=started_coro_cb, + ) + assert inspect.getcoroutinestate(started_c) == inspect.CORO_SUSPENDED + finally: + task_started.cancel() + try: + await task_started + except asyncio.CancelledError: + pass # Non-None, non-awaitable callback return raises TypeError def sync_int_cb(r: Any) -> Any: @@ -3455,46 +3533,48 @@ def cancel(self, msg: Any = None) -> bool: old_h = loop.get_exception_handler() loop.set_exception_handler(lambda _loop, ctx: cancel_reports.append(ctx)) try: - fut_sync_cancel = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) - clock_now = [1000.0] - orig_client_mono = client_module.monotonic - orig_trans_mono = _transport.monotonic - client_module.monotonic = lambda: clock_now[0] - _transport.monotonic = lambda: clock_now[0] - - def sync_cancel_on_poll(r: Any) -> Any: - clock_now[0] += 0.2 - return fut_sync_cancel - - running_detail = CustomerReviewDetail.from_dict(review("RUNNING")) - - async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: - return running_detail - try: - async with AsyncProoflineClient( - token="test_token", base_url="https://api.proofline.sh" - ) as client: - client.get_review = fake_sync_cancel_running # type: ignore - res_sync_cancel = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.1, - on_poll=sync_cancel_on_poll, - ) - assert res_sync_cancel.status == "TIMED_OUT" - await asyncio.sleep(0) - assert fut_sync_cancel.cancel_called is False - assert id(fut_sync_cancel) in _DETACHED_FUTURES - assert cancel_reports == [] + fut_sync_cancel = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) + clock_now = [1000.0] + orig_client_mono = client_module.monotonic + orig_trans_mono = _transport.monotonic + client_module.monotonic = lambda: clock_now[0] + _transport.monotonic = lambda: clock_now[0] + + def sync_cancel_on_poll(r: Any) -> Any: + clock_now[0] += 0.2 + return fut_sync_cancel + + running_detail = CustomerReviewDetail.from_dict(review("RUNNING")) + + async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: + return running_detail + + try: + async with AsyncProoflineClient( + token="test_token", base_url="https://api.proofline.sh" + ) as client: + client.get_review = fake_sync_cancel_running # type: ignore + res_sync_cancel = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.1, + on_poll=sync_cancel_on_poll, + ) + assert res_sync_cancel.status == "TIMED_OUT" + await asyncio.sleep(0) + assert fut_sync_cancel.cancel_called is False + assert id(fut_sync_cancel) in _DETACHED_FUTURES + assert cancel_reports == [] + finally: + client_module.monotonic = orig_client_mono + _transport.monotonic = orig_trans_mono finally: - client_module.monotonic = orig_client_mono - _transport.monotonic = orig_trans_mono + if not fut_sync_cancel.done(): + fut_sync_cancel.set_result(None) + await asyncio.sleep(0) + assert id(fut_sync_cancel) not in _DETACHED_FUTURES finally: - if not fut_sync_cancel.done(): - fut_sync_cancel.set_result(None) - await asyncio.sleep(0) - assert id(fut_sync_cancel) not in _DETACHED_FUTURES loop.set_exception_handler(old_h) # Current task cannot be returned by on_poll From d303cd340a671b120313d9dbcb16dc3acece96bf Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 22:05:25 +0530 Subject: [PATCH 42/75] Address review run 41 findings: restore deadline check after get_review, allocation guard on future create_future, preserve dictionary insertion order, finalize set dependencies before frozensets, defer frozenset/tuple attribute copies, traverse slots in member populated check, and test lifecycle and assertion improvements --- README.md | 2 +- proofline/client.py | 150 ++++++++++++++++++++++++-------------------- tests/test_http.py | 81 ++++++++++++++++++------ 3 files changed, 143 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index 46fc750e..d683f56e 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 4587e1df..b91ac130 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -590,6 +590,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non deferred_frozenset_insertions.append( (target, key, is_attr, val_id, val, list(val)) ) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + for slot_or_name, is_desc, attr_val in _get_obj_attrs(val): + if not _is_immutable(attr_val) and id(attr_val) not in memo: + stack.append((_ITEM_TASK, None, None, False, attr_val)) stack.append((_SET_EXPAND, None, iter(val))) elif isinstance(val, deque): if deque.__len__(val) > _MAX_SAFE_BUFFER_SIZE: @@ -870,26 +874,20 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if _deadline_expired(): return None - deferred_custom_dict_insertions: list[tuple[Any, Any, Any]] = [] - deferred_later_dict_insertions: list[tuple[Any, Any, Any]] = [] + dict_ordered_entries: dict[int, list[tuple[Any, Any]]] = {} + dict_targets: dict[int, Any] = {} + dict_next_index: dict[int, int] = {} + for target_dict, orig_k, orig_v in deferred_dict_insertions: - if _deadline_expired(): - return None - if _is_immutable(orig_k): - if _is_immutable(orig_v): - target_dict[orig_k] = orig_v - elif id(orig_v) in memo: - target_dict[orig_k] = memo[id(orig_v)] - else: - deferred_later_dict_insertions.append((target_dict, orig_k, orig_v)) - else: - deferred_custom_dict_insertions.append((target_dict, orig_k, orig_v)) + td_id = id(target_dict) + if td_id not in dict_ordered_entries: + dict_ordered_entries[td_id] = [] + dict_targets[td_id] = target_dict + dict_next_index[td_id] = 0 + dict_ordered_entries[td_id].append((orig_k, orig_v)) def _flush_pending_structures() -> None: - nonlocal \ - deferred_later_dict_insertions, \ - deferred_custom_dict_insertions, \ - deferred_tuple_finalizations + nonlocal deferred_tuple_finalizations, deferred_set_insertions changed = True while changed: changed = False @@ -903,7 +901,14 @@ def _flush_pending_structures() -> None: orig_val, temp_list, ) in deferred_tuple_finalizations: - if not any(x is _UNRESOLVED_SLOT for x in temp_list): + elements_ready = not any(x is _UNRESOLVED_SLOT for x in temp_list) + attrs_ready = True + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + for _, _, attr_val in _get_obj_attrs(orig_val): + if not _is_immutable(attr_val) and id(attr_val) not in memo: + attrs_ready = False + break + if elements_ready and attrs_ready: if val_id in memo: res_tuple = memo[val_id] else: @@ -919,9 +924,7 @@ def _flush_pending_structures() -> None: if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): val_to_set = ( - attr_val - if _is_immutable(attr_val) - else memo.get(id(attr_val), attr_val) + attr_val if _is_immutable(attr_val) else memo[id(attr_val)] ) _assign_target(res_tuple, (slot_or_name, is_desc), True, val_to_set) _assign_target(target, key, is_attr, res_tuple) @@ -930,39 +933,47 @@ def _flush_pending_structures() -> None: still_tuples.append((target, key, is_attr, val_id, orig_val, temp_list)) deferred_tuple_finalizations = still_tuples - if deferred_later_dict_insertions: - still_dicts = [] - for target_dict, orig_k, orig_v in deferred_later_dict_insertions: - if id(orig_v) in memo: - target_dict[orig_k] = memo[id(orig_v)] + if deferred_set_insertions: + still_sets = [] + for s, orig_val, orig_members in deferred_set_insertions: + if all(_is_immutable(m) or id(m) in memo for m in orig_members): + resolved_members = [ + m if _is_immutable(m) else memo[id(m)] for m in orig_members + ] + set.update(s, resolved_members) + if set(s) != set(resolved_members): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) changed = True else: - still_dicts.append((target_dict, orig_k, orig_v)) - deferred_later_dict_insertions = still_dicts - - if deferred_custom_dict_insertions: - still_custom = [] - for target_dict, orig_k, orig_v in deferred_custom_dict_insertions: - if id(orig_k) in memo: - k = memo[id(orig_k)] - if _is_immutable(orig_v): - target_dict[k] = orig_v - changed = True - elif id(orig_v) in memo: - target_dict[k] = memo[id(orig_v)] - changed = True - else: - still_custom.append((target_dict, orig_k, orig_v)) + still_sets.append((s, orig_val, orig_members)) + deferred_set_insertions = still_sets + + for td_id, entries in dict_ordered_entries.items(): + target_dict = dict_targets[td_id] + idx = dict_next_index[td_id] + while idx < len(entries): + orig_k, orig_v = entries[idx] + k_ready = _is_immutable(orig_k) or id(orig_k) in memo + v_ready = _is_immutable(orig_v) or id(orig_v) in memo + if k_ready and v_ready: + k = orig_k if _is_immutable(orig_k) else memo[id(orig_k)] + v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] + target_dict[k] = v + idx += 1 + changed = True else: - still_custom.append((target_dict, orig_k, orig_v)) - deferred_custom_dict_insertions = still_custom + break + dict_next_index[td_id] = idx _flush_pending_structures() def _is_member_state_populated(m_clone: Any) -> bool: if _is_immutable(m_clone): return True - visited = set() + visited: set[int] = set() stack_nodes = [m_clone] container_ids: set[int] = set() while stack_nodes: @@ -974,6 +985,10 @@ def _is_member_state_populated(m_clone: Any) -> bool: container_ids.add(cid) if hasattr(cur, "__dict__") and isinstance(cur.__dict__, dict): stack_nodes.append(cur.__dict__) + if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): + for _, _, slot_val in _get_obj_attrs(cur): + if not _is_immutable(slot_val): + stack_nodes.append(slot_val) if isinstance(cur, dict): for k, v in cur.items(): if not _is_immutable(k): @@ -988,11 +1003,11 @@ def _is_member_state_populated(m_clone: Any) -> bool: for target, _, _, _, _, _ in pending_frozensets: if id(target) in container_ids: return False - for target_dict, _, _ in deferred_later_dict_insertions: - if id(target_dict) in container_ids: + for s, _, _ in deferred_set_insertions: + if id(s) in container_ids: return False - for target_dict, _, _ in deferred_custom_dict_insertions: - if id(target_dict) in container_ids: + for td_id, entries in dict_ordered_entries.items(): + if td_id in container_ids and dict_next_index[td_id] < len(entries): return False return True @@ -1007,7 +1022,14 @@ def _is_member_state_populated(m_clone: Any) -> bool: _assign_target(target, key, is_attr, memo[val_id]) progress = True continue - if all(_is_immutable(m) or id(m) in memo for m in orig_members): + members_ready = all(_is_immutable(m) or id(m) in memo for m in orig_members) + attrs_ready = True + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + for _, _, attr_val in _get_obj_attrs(orig_val): + if not _is_immutable(attr_val) and id(attr_val) not in memo: + attrs_ready = False + break + if members_ready and attrs_ready: resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] if not all(_is_member_state_populated(rm) for rm in resolved_members): remaining_frozensets.append( @@ -1046,24 +1068,6 @@ def _is_member_state_populated(m_clone: Any) -> bool: raise TypeError("Unsupported cyclic reference in frozenset") _flush_pending_structures() - - for s, orig_val, orig_members in deferred_set_insertions: - if _deadline_expired(): - return None - resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] - set.update(s, resolved_members) - if set(s) != set(resolved_members): - raise TypeError( - f"Unsupported mutable value in review extension data: {type(orig_val).__name__}" - ) - - for target_dict, orig_k, orig_v in deferred_custom_dict_insertions: - if _deadline_expired(): - return None - k = memo[id(orig_k)] - v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] - target_dict[k] = v - return root @@ -1642,6 +1646,8 @@ def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise + if (_transport.remaining() or 0) <= 0: + break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: snapshot = _snapshot_review(last) @@ -2091,6 +2097,8 @@ async def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise + if (_transport.remaining() or 0) <= 0: + break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if on_poll is not None and (_transport.remaining() or 0) > 0: snapshot = _snapshot_review(last) @@ -2165,7 +2173,11 @@ async def wait_for_review( else: AsyncFuture.result(res) else: - completion_fut = async_get_running_loop().create_future() + try: + completion_fut = async_get_running_loop().create_future() + except BaseException: + _detach_overdue_future(res) + raise completed_at: list[float] = [] def _on_future_done(_: Any) -> None: diff --git a/tests/test_http.py b/tests/test_http.py index 5a979d4c..6dae898a 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -3155,6 +3155,21 @@ async def failing_overdue_coro(r: Any) -> None: gc.collect() assert unhandled_exceptions == [] finally: + coro_trigger.set() + if waiter_coro_task is not None and not waiter_coro_task.done(): + waiter_coro_task.cancel() + try: + await waiter_coro_task + except (asyncio.CancelledError, BaseException): + pass + for t in list(client_module._DETACHED_TASKS.values()): + if hasattr(t, "done") and not t.done(): + t.cancel() + try: + await t + except (asyncio.CancelledError, BaseException): + pass + await asyncio.sleep(0.01) loop.set_exception_handler(old_handler) # Case 7: Overdue callback awaiting the polling task is not cancelled @@ -3352,19 +3367,22 @@ async def dummy_coro() -> None: suspended_coro = dummy_coro() try: - suspended_coro.send(None) - except StopIteration: - pass + try: + suspended_coro.send(None) + except StopIteration: + pass - with Server(lambda request, index: Reply(body=responses[1])) as server: - async with session("async", server.url) as client: - with pytest.raises(ValueError, match="unstarted coroutines"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=10, - on_poll=lambda r: suspended_coro, - ) + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="unstarted coroutines"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=lambda r: suspended_coro, + ) + finally: + suspended_coro.close() # Started coroutine raises ValueError even after deadline expiry without closing async def dummy_started() -> None: @@ -3464,12 +3482,12 @@ async def complete_unhashable_soon(fut: Any) -> None: try: with Server(lambda request, index: Reply(body=responses[0])) as server: async with session("async", server.url) as client: - unhash_failing_fut: Any = UnhashableFuture(loop=loop) + unhash_box: list[Any] = [UnhashableFuture(loop=loop)] cb_started = asyncio.Event() def unhash_failing_cb(r: Any) -> Any: cb_started.set() - return unhash_failing_fut + return unhash_box[0] waiter_task = asyncio.create_task( client.wait_for_review( @@ -3497,13 +3515,15 @@ def unhash_failing_cb(r: Any) -> Any: except asyncio.CancelledError: cancelled = True assert cancelled - assert id(unhash_failing_fut) in _DETACHED_FUTURES - unhash_failing_fut.set_exception(RuntimeError("unhashable late failure")) + target_fut = unhash_box[0] + assert id(target_fut) in _DETACHED_FUTURES + target_fut.set_exception(RuntimeError("unhashable late failure")) await asyncio.sleep(0) - assert id(unhash_failing_fut) not in _DETACHED_FUTURES + assert id(target_fut) not in _DETACHED_FUTURES + del target_fut + unhash_box.clear() import gc - del unhash_failing_fut gc.collect() assert unhash_cancel_reports == [] finally: @@ -3514,6 +3534,9 @@ def unhash_failing_cb(r: Any) -> Any: await t except (asyncio.CancelledError, BaseException): pass + if unhash_box and not unhash_box[0].done(): + unhash_box[0].set_result(None) + await asyncio.sleep(0) finally: loop.set_exception_handler(old_h_unhash) @@ -3523,18 +3546,23 @@ class SyncCancelRaisingFuture(asyncio.Future[None]): def __init__(self, loop: asyncio.AbstractEventLoop) -> None: super().__init__(loop=loop) self.cancel_called = False + self.exception_calls = 0 def cancel(self, msg: Any = None) -> bool: self.cancel_called = True raise RuntimeError("synchronous cancel error") + def exception(self) -> BaseException | None: + self.exception_calls += 1 + return super().exception() + cancel_reports: list[dict[str, Any]] = [] loop = asyncio.get_running_loop() old_h = loop.get_exception_handler() loop.set_exception_handler(lambda _loop, ctx: cancel_reports.append(ctx)) try: try: - fut_sync_cancel = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) + fut_sync_cancel: Any = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) clock_now = [1000.0] orig_client_mono = client_module.monotonic orig_trans_mono = _transport.monotonic @@ -3571,9 +3599,18 @@ async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: _transport.monotonic = orig_trans_mono finally: if not fut_sync_cancel.done(): - fut_sync_cancel.set_result(None) + fut_sync_cancel.set_exception(RuntimeError("sync cancel late error")) await asyncio.sleep(0) assert id(fut_sync_cancel) not in _DETACHED_FUTURES + assert fut_sync_cancel.exception_calls > 0 + import weakref + + fut_sync_ref = weakref.ref(fut_sync_cancel) + del fut_sync_cancel + import gc + + gc.collect() + assert fut_sync_ref() is None finally: loop.set_exception_handler(old_h) @@ -4193,6 +4230,7 @@ def __eq__(self, other: Any) -> bool: detail_sets.additional_properties["normal_s"] = normal_s detail_sets.additional_properties["normal_fs"] = normal_fs detail_sets.additional_properties["nested_fs"] = outer_fs + detail_sets.additional_properties["fs_list"] = [normal_fs, normal_fs] snap_sets = _snapshot_review(detail_sets) assert snap_sets is not None assert snap_sets.additional_properties["normal_s"] == normal_s @@ -4200,6 +4238,9 @@ def __eq__(self, other: Any) -> bool: copied_fs = snap_sets.additional_properties["normal_fs"] assert isinstance(copied_fs, frozenset) assert len(copied_fs) == 1 + copied_list = snap_sets.additional_properties["fs_list"] + assert copied_list[0] is copied_list[1] + assert copied_list[0] is copied_fs cloned_member = next(iter(copied_fs)) assert cloned_member == member_payload assert cloned_member is not member_payload From 88894d3574787d34f8ec06f892cb1efb4ac741f1 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 22:18:08 +0530 Subject: [PATCH 43/75] Address review run 42 findings: reject functions with closure cells, weakref dictionary for detached futures, check waiter cancellation before runner callback entry, check member populated state before set update, and test lifecycle and assertion fixes --- proofline/client.py | 129 ++++++++++++++++++++++++++------------------ tests/test_http.py | 17 +++++- 2 files changed, 93 insertions(+), 53 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index b91ac130..ffc626e5 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -263,13 +263,7 @@ def _has_mutable_captures(val: Any, seen: set[int] | None = None) -> bool: closure = getattr(val, "__closure__", None) if closure: - for cell in closure: - try: - contents = cell.cell_contents - except ValueError: - continue - if not _is_immutable(contents, seen): - return True + return True defaults = getattr(val, "__defaults__", None) if defaults: @@ -319,6 +313,8 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if isinstance(val, (FunctionType, BuiltinFunctionType, MethodType)): if getattr(val, "__dict__", None): return False + if getattr(val, "__closure__", None): + return False return not _has_mutable_captures(val, seen) if t is datetime.datetime: tz = val.tzinfo @@ -886,6 +882,49 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non dict_next_index[td_id] = 0 dict_ordered_entries[td_id].append((orig_k, orig_v)) + pending_frozensets: list[Any] = deferred_frozenset_insertions + + def _is_member_state_populated(m_clone: Any) -> bool: + if _is_immutable(m_clone): + return True + visited: set[int] = set() + stack_nodes = [m_clone] + container_ids: set[int] = set() + while stack_nodes: + cur = stack_nodes.pop() + cid = id(cur) + if cid in visited: + continue + visited.add(cid) + container_ids.add(cid) + if hasattr(cur, "__dict__") and isinstance(cur.__dict__, dict): + stack_nodes.append(cur.__dict__) + if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): + for _, _, slot_val in _get_obj_attrs(cur): + if not _is_immutable(slot_val): + stack_nodes.append(slot_val) + if isinstance(cur, dict): + for k, v in cur.items(): + if not _is_immutable(k): + stack_nodes.append(k) + if not _is_immutable(v): + stack_nodes.append(v) + elif isinstance(cur, (list, tuple, set, deque)): + for item in cur: + if not _is_immutable(item): + stack_nodes.append(item) + + for target, _, _, _, _, _ in pending_frozensets: + if id(target) in container_ids: + return False + for s, _, _ in deferred_set_insertions: + if id(s) in container_ids: + return False + for td_id, entries in dict_ordered_entries.items(): + if td_id in container_ids and dict_next_index[td_id] < len(entries): + return False + return True + def _flush_pending_structures() -> None: nonlocal deferred_tuple_finalizations, deferred_set_insertions changed = True @@ -940,6 +979,9 @@ def _flush_pending_structures() -> None: resolved_members = [ m if _is_immutable(m) else memo[id(m)] for m in orig_members ] + if not all(_is_member_state_populated(rm) for rm in resolved_members): + still_sets.append((s, orig_val, orig_members)) + continue set.update(s, resolved_members) if set(s) != set(resolved_members): raise TypeError( @@ -970,47 +1012,6 @@ def _flush_pending_structures() -> None: _flush_pending_structures() - def _is_member_state_populated(m_clone: Any) -> bool: - if _is_immutable(m_clone): - return True - visited: set[int] = set() - stack_nodes = [m_clone] - container_ids: set[int] = set() - while stack_nodes: - cur = stack_nodes.pop() - cid = id(cur) - if cid in visited: - continue - visited.add(cid) - container_ids.add(cid) - if hasattr(cur, "__dict__") and isinstance(cur.__dict__, dict): - stack_nodes.append(cur.__dict__) - if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): - for _, _, slot_val in _get_obj_attrs(cur): - if not _is_immutable(slot_val): - stack_nodes.append(slot_val) - if isinstance(cur, dict): - for k, v in cur.items(): - if not _is_immutable(k): - stack_nodes.append(k) - if not _is_immutable(v): - stack_nodes.append(v) - elif isinstance(cur, (list, tuple, set, deque)): - for item in cur: - if not _is_immutable(item): - stack_nodes.append(item) - - for target, _, _, _, _, _ in pending_frozensets: - if id(target) in container_ids: - return False - for s, _, _ in deferred_set_insertions: - if id(s) in container_ids: - return False - for td_id, entries in dict_ordered_entries.items(): - if td_id in container_ids and dict_next_index[td_id] < len(entries): - return False - return True - pending_frozensets = deferred_frozenset_insertions while pending_frozensets: if _deadline_expired(): @@ -1072,7 +1073,7 @@ def _is_member_state_populated(m_clone: Any) -> bool: _DETACHED_TASKS: dict[int, Any] = {} -_DETACHED_FUTURES: dict[int, Any] = {} +_DETACHED_FUTURES: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() def _safe_cancel_target(target: Any) -> None: @@ -1107,7 +1108,10 @@ def _detach_overdue_future(fut: Any) -> None: if loop is not running_loop or loop.is_closed(): return fut_id = id(fut) - _DETACHED_FUTURES[fut_id] = fut + try: + _DETACHED_FUTURES[fut_id] = fut + except (TypeError, BaseException): + pass def _on_detached_fut_done(t: Any) -> None: _DETACHED_FUTURES.pop(fut_id, None) @@ -2227,15 +2231,35 @@ def _on_future_done(_: Any) -> None: return result break else: + waiter_task = async_current_task() coro = res completed_at = [] wrapper_started = False async def _runner() -> None: nonlocal wrapper_started - wrapper_started = True + waiter_cancelling = False + if waiter_task is not None: + try: + if hasattr(waiter_task, "cancelling"): + waiter_cancelling = waiter_task.cancelling() > 0 + elif hasattr(waiter_task, "cancelled"): + waiter_cancelling = waiter_task.cancelled() + except BaseException: + pass + try: + if hasattr(task, "cancelling") and task.cancelling() > 0: + waiter_cancelling = True + elif hasattr(task, "cancelled") and task.cancelled(): + waiter_cancelling = True + except BaseException: + pass + deadline_val = _transport.DEADLINE.get() - if deadline_val is not None and monotonic() > deadline_val: + deadline_expired = ( + deadline_val is not None and monotonic() > deadline_val + ) + if waiter_cancelling or deadline_expired: if ( iscoroutine(coro) and getcoroutinestate(coro) == CORO_CREATED @@ -2253,6 +2277,7 @@ async def _runner() -> None: except BaseException: pass return + wrapper_started = True try: assert coro is not None await coro diff --git a/tests/test_http.py b/tests/test_http.py index 6dae898a..10016d64 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -3021,6 +3021,8 @@ async def suspending_callback(r: Any) -> None: loop = asyncio.get_running_loop() old_handler = loop.get_exception_handler() loop.set_exception_handler(lambda _loop, ctx: unhandled_exceptions.append(ctx)) + coro_trigger: asyncio.Event | None = None + waiter_coro_task: asyncio.Task[Any] | None = None try: # 6a: Future callback cancelled after startup failing_fut: asyncio.Future[None] = loop.create_future() @@ -3155,7 +3157,8 @@ async def failing_overdue_coro(r: Any) -> None: gc.collect() assert unhandled_exceptions == [] finally: - coro_trigger.set() + if coro_trigger is not None: + coro_trigger.set() if waiter_coro_task is not None and not waiter_coro_task.done(): waiter_coro_task.cancel() try: @@ -3452,6 +3455,14 @@ async def int_returning_callback(r: Any) -> int: class UnhashableFuture(asyncio.Future[None]): __hash__ = None # type: ignore[assignment] + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(loop=loop) + self.exception_calls = 0 + + def exception(self) -> BaseException | None: + self.exception_calls += 1 + return super().exception() + async def complete_unhashable_soon(fut: Any) -> None: await asyncio.sleep(0.01) fut.set_result(None) @@ -3516,15 +3527,18 @@ def unhash_failing_cb(r: Any) -> Any: cancelled = True assert cancelled target_fut = unhash_box[0] + fut_weakref = weakref.ref(target_fut) assert id(target_fut) in _DETACHED_FUTURES target_fut.set_exception(RuntimeError("unhashable late failure")) await asyncio.sleep(0) assert id(target_fut) not in _DETACHED_FUTURES + assert target_fut.exception_calls > 0 del target_fut unhash_box.clear() import gc gc.collect() + assert fut_weakref() is None assert unhash_cancel_reports == [] finally: for t in (cb_wait_task, waiter_task): @@ -4244,6 +4258,7 @@ def __eq__(self, other: Any) -> bool: cloned_member = next(iter(copied_fs)) assert cloned_member == member_payload assert cloned_member is not member_payload + assert next(iter(snap_sets.additional_properties["normal_s"])) is cloned_member assert cloned_member.payload is not member_payload.payload assert cloned_member in copied_fs cloned_member.payload.append("mutated_val") From 74786d2db9f16dde375ab47b298ffc92e898c1b1 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 23:11:59 +0530 Subject: [PATCH 44/75] Address review run 43 findings: reject FunctionType mutable snapshots, weakref detached tasks with loop-scoped ownership, relative cancellation count in runner, bounded batch deadline checks, identity-hashed cyclic set support, and robust test teardown --- proofline/client.py | 112 +++++++++++++++++++++++++++++++++++++++----- tests/test_http.py | 38 +++++++++++++-- 2 files changed, 134 insertions(+), 16 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index ffc626e5..effcff0b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -300,6 +300,13 @@ def _has_mutable_captures(val: Any, seen: set[int] | None = None) -> bool: } +def _is_identity_hashed(obj: Any) -> bool: + try: + return type(obj).__hash__ is object.__hash__ + except Exception: + return False + + def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if val is None or val is UNSET: return True @@ -310,12 +317,10 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: t = type(val) if t in _IMMUTABLE_TYPES: return True - if isinstance(val, (FunctionType, BuiltinFunctionType, MethodType)): - if getattr(val, "__dict__", None): - return False - if getattr(val, "__closure__", None): - return False - return not _has_mutable_captures(val, seen) + if isinstance(val, BuiltinFunctionType): + return not bool(getattr(val, "__dict__", None)) + if isinstance(val, (FunctionType, MethodType)): + return False if t is datetime.datetime: tz = val.tzinfo return tz is None or type(tz) is datetime.timezone @@ -411,7 +416,16 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if task_type == _ITEM_TASK: key, is_attr, val = it_or_key, extra[0], extra[1] - if isinstance(val, (weakref.ref, weakref.ProxyType, weakref.CallableProxyType)): + if isinstance( + val, + ( + FunctionType, + MethodType, + weakref.ref, + weakref.ProxyType, + weakref.CallableProxyType, + ), + ): raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) @@ -874,7 +888,9 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non dict_targets: dict[int, Any] = {} dict_next_index: dict[int, int] = {} - for target_dict, orig_k, orig_v in deferred_dict_insertions: + for count, (target_dict, orig_k, orig_v) in enumerate(deferred_dict_insertions): + if (count & 63) == 0 and _deadline_expired(): + return None td_id = id(target_dict) if td_id not in dict_ordered_entries: dict_ordered_entries[td_id] = [] @@ -884,9 +900,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non pending_frozensets: list[Any] = deferred_frozenset_insertions - def _is_member_state_populated(m_clone: Any) -> bool: + def _is_member_state_populated(m_clone: Any, owner_set_id: int | None = None) -> bool: if _is_immutable(m_clone): return True + if _is_identity_hashed(m_clone) and owner_set_id is None: + return True visited: set[int] = set() stack_nodes = [m_clone] container_ids: set[int] = set() @@ -919,6 +937,12 @@ def _is_member_state_populated(m_clone: Any) -> bool: return False for s, _, _ in deferred_set_insertions: if id(s) in container_ids: + if ( + owner_set_id is not None + and id(s) == owner_set_id + and _is_identity_hashed(m_clone) + ): + continue return False for td_id, entries in dict_ordered_entries.items(): if td_id in container_ids and dict_next_index[td_id] < len(entries): @@ -929,6 +953,8 @@ def _flush_pending_structures() -> None: nonlocal deferred_tuple_finalizations, deferred_set_insertions changed = True while changed: + if _deadline_expired(): + return changed = False if deferred_tuple_finalizations: still_tuples = [] @@ -979,7 +1005,10 @@ def _flush_pending_structures() -> None: resolved_members = [ m if _is_immutable(m) else memo[id(m)] for m in orig_members ] - if not all(_is_member_state_populated(rm) for rm in resolved_members): + if not all( + _is_member_state_populated(rm, owner_set_id=id(s)) + for rm in resolved_members + ): still_sets.append((s, orig_val, orig_members)) continue set.update(s, resolved_members) @@ -993,16 +1022,22 @@ def _flush_pending_structures() -> None: still_sets.append((s, orig_val, orig_members)) deferred_set_insertions = still_sets + op_count = 0 for td_id, entries in dict_ordered_entries.items(): target_dict = dict_targets[td_id] idx = dict_next_index[td_id] while idx < len(entries): + op_count += 1 + if (op_count & 63) == 0 and _deadline_expired(): + return orig_k, orig_v = entries[idx] k_ready = _is_immutable(orig_k) or id(orig_k) in memo v_ready = _is_immutable(orig_v) or id(orig_v) in memo if k_ready and v_ready: k = orig_k if _is_immutable(orig_k) else memo[id(orig_k)] v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] + if not _is_member_state_populated(k, owner_set_id=None): + break target_dict[k] = v idx += 1 changed = True @@ -1011,6 +1046,8 @@ def _flush_pending_structures() -> None: dict_next_index[td_id] = idx _flush_pending_structures() + if _deadline_expired(): + return None pending_frozensets = deferred_frozenset_insertions while pending_frozensets: @@ -1069,10 +1106,19 @@ def _flush_pending_structures() -> None: raise TypeError("Unsupported cyclic reference in frozenset") _flush_pending_structures() + if _deadline_expired(): + return None + if deferred_set_insertions: + raise TypeError("Unsupported cyclic reference in set") + for td_id, entries in dict_ordered_entries.items(): + if dict_next_index[td_id] < len(entries): + raise TypeError("Unsupported cyclic reference in dict") + if deferred_tuple_finalizations: + raise TypeError("Unsupported cyclic reference in tuple") return root -_DETACHED_TASKS: dict[int, Any] = {} +_DETACHED_TASKS: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() _DETACHED_FUTURES: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() @@ -1190,11 +1236,38 @@ def _detach_overdue_task( pass return + try: + loop = task.get_loop() if hasattr(task, "get_loop") else async_get_running_loop() + except Exception: + try: + loop = async_get_running_loop() + except Exception: + loop = None + + if loop is not None and not loop.is_closed(): + loop_tasks = getattr(loop, "_proofline_detached_tasks", None) + if loop_tasks is None: + loop_tasks = set() + try: + setattr(loop, "_proofline_detached_tasks", loop_tasks) + except Exception: + pass + if loop_tasks is not None: + loop_tasks.add(task) + task_id = id(task) - _DETACHED_TASKS[task_id] = task + try: + _DETACHED_TASKS[task_id] = task + except (TypeError, BaseException): + pass def _on_detached_task_done(t: Any) -> None: _DETACHED_TASKS.pop(task_id, None) + if loop is not None: + loop_tasks = getattr(loop, "_proofline_detached_tasks", None) + if loop_tasks is not None: + loop_tasks.discard(t) + loop_tasks.discard(task) try: is_canc = t.cancelled() if hasattr(t, "cancelled") else False if not is_canc: @@ -1234,6 +1307,10 @@ async def _observe_task() -> None: pass finally: _DETACHED_TASKS.pop(task_id, None) + if loop is not None: + loop_tasks = getattr(loop, "_proofline_detached_tasks", None) + if loop_tasks is not None: + loop_tasks.discard(task) obs = loop.create_task(_observe_task()) obs.add_done_callback(lambda _: None) @@ -2232,6 +2309,13 @@ def _on_future_done(_: Any) -> None: break else: waiter_task = async_current_task() + initial_cancelling = 0 + if waiter_task is not None: + try: + if hasattr(waiter_task, "cancelling"): + initial_cancelling = waiter_task.cancelling() + except BaseException: + pass coro = res completed_at = [] wrapper_started = False @@ -2242,7 +2326,9 @@ async def _runner() -> None: if waiter_task is not None: try: if hasattr(waiter_task, "cancelling"): - waiter_cancelling = waiter_task.cancelling() > 0 + waiter_cancelling = ( + waiter_task.cancelling() > initial_cancelling + ) elif hasattr(waiter_task, "cancelled"): waiter_cancelling = waiter_task.cancelled() except BaseException: diff --git a/tests/test_http.py b/tests/test_http.py index 10016d64..78eb9473 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -3023,13 +3023,15 @@ async def suspending_callback(r: Any) -> None: loop.set_exception_handler(lambda _loop, ctx: unhandled_exceptions.append(ctx)) coro_trigger: asyncio.Event | None = None waiter_coro_task: asyncio.Task[Any] | None = None + failing_fut: asyncio.Future[None] | None = None try: # 6a: Future callback cancelled after startup - failing_fut: asyncio.Future[None] = loop.create_future() + failing_fut = loop.create_future() future_started = asyncio.Event() def failing_future_cb(r: Any) -> asyncio.Future[None]: future_started.set() + assert failing_fut is not None return failing_fut client.get_review = fake_running # type: ignore @@ -3054,7 +3056,7 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: failing_fut.set_exception(RuntimeError("error in cancelled future callback")) await asyncio.sleep(0) assert id(failing_fut) not in client_module._DETACHED_FUTURES - del failing_fut + failing_fut = None import gc gc.collect() @@ -3094,6 +3096,7 @@ def pre_start_cb(r: Any) -> Any: user_coro_created.append(c) return c + pre_waiter_task: asyncio.Task[Any] | None = None try: pre_waiter_task = asyncio.create_task( client.wait_for_review( @@ -3116,7 +3119,28 @@ def pre_start_cb(r: Any) -> Any: assert inspect.getcoroutinestate(user_coro_created[0]) == inspect.CORO_CLOSED finally: client_module.async_create_task = orig_create_task - hold_wrapper.set() + if pre_waiter_task is not None and not pre_waiter_task.done(): + pre_waiter_task.cancel() + try: + await pre_waiter_task + except (asyncio.CancelledError, BaseException): + pass + for wt in wrapper_tasks: + if not wt.done(): + wt.cancel() + try: + await wt + except (asyncio.CancelledError, BaseException): + pass + for c in user_coro_created: + try: + if ( + inspect.iscoroutine(c) + and inspect.getcoroutinestate(c) == inspect.CORO_CREATED + ): + c.close() + except BaseException: + pass # Coroutine callback cancelled after startup coro_started = asyncio.Event() @@ -3157,6 +3181,14 @@ async def failing_overdue_coro(r: Any) -> None: gc.collect() assert unhandled_exceptions == [] finally: + if failing_fut is not None: + if not failing_fut.done(): + failing_fut.cancel() + elif not failing_fut.cancelled(): + try: + failing_fut.exception() + except BaseException: + pass if coro_trigger is not None: coro_trigger.set() if waiter_coro_task is not None and not waiter_coro_task.done(): From 72eb91a7c9262e92cac57d0b52ef92241edb2ad5 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 23:32:47 +0530 Subject: [PATCH 45/75] Address review run 44 findings: reject extension classes with mutable attrs, memoize memoryview exporter clone, handle pending tuple assignments in readiness, identity-hash readiness, batched set insertion deadline checks, pre-invocation cancellation capture, docstring refinement, and test lifecycle and timing assertions --- proofline/client.py | 150 ++++++++++++++++++++++++++++++++++---------- tests/test_http.py | 60 ++++++++++++++---- 2 files changed, 165 insertions(+), 45 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index effcff0b..0a23c66b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,6 +5,9 @@ import datetime import math import weakref +from asyncio import ( + CancelledError as AsyncCancelledError, +) from asyncio import ( Future as AsyncFuture, ) @@ -327,6 +330,35 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: return False +def _has_mutable_class_attrs(cls: type) -> bool: + for base in cls.__mro__: + if base in _SAFE_BUILTIN_CLASSES or base is object: + continue + for name, attr in base.__dict__.items(): + if name.startswith("__") and name.endswith("__"): + continue + if isinstance(attr, MemberDescriptorType) or type(attr).__name__ in ( + "member_descriptor", + "getset_descriptor", + ): + continue + if isinstance( + attr, + ( + FunctionType, + MethodType, + classmethod, + staticmethod, + property, + BuiltinFunctionType, + ), + ): + continue + if not _is_immutable(attr): + return True + return False + + def _assign_target(target: Any, key: Any, is_attr: bool, val: Any) -> None: if target is None: return @@ -653,7 +685,35 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non f"{type(val).__name__}" ) from exc else: - resolved_mv = memoryview(bytearray(val)) + exporter = getattr(val, "obj", None) + if isinstance(exporter, bytearray): + exp_id = id(exporter) + if exp_id in memo: + cloned_exporter = memo[exp_id] + else: + if bytearray.__len__(exporter) > _MAX_SAFE_BUFFER_SIZE: + return None + try: + cloned_exporter = bytearray.__new__(type(exporter)) + bytearray.__init__(cloned_exporter, exporter) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(exporter).__name__}" + ) from exc + memo[exp_id] = cloned_exporter + try: + import ctypes + + p_exp = ctypes.c_char.from_buffer(exporter) + p_val = ctypes.c_char.from_buffer(val) + offset = ctypes.addressof(p_val) - ctypes.addressof(p_exp) + base_mv = memoryview(cloned_exporter) + resolved_mv = base_mv[offset : offset + val.nbytes] + except Exception: + resolved_mv = memoryview(cloned_exporter) + else: + resolved_mv = memoryview(bytearray(val)) if val.format != "B" or val.ndim > 1: try: resolved_mv = resolved_mv.cast(val.format, shape=val.shape) @@ -726,6 +786,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_dt, iter(_get_obj_attrs(val)))) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): + if _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) new_obj: Any try: if isinstance(val, str): @@ -900,10 +964,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non pending_frozensets: list[Any] = deferred_frozenset_insertions - def _is_member_state_populated(m_clone: Any, owner_set_id: int | None = None) -> bool: + def _is_member_state_populated(m_clone: Any) -> bool: if _is_immutable(m_clone): return True - if _is_identity_hashed(m_clone) and owner_set_id is None: + if _is_identity_hashed(m_clone): return True visited: set[int] = set() stack_nodes = [m_clone] @@ -932,17 +996,14 @@ def _is_member_state_populated(m_clone: Any, owner_set_id: int | None = None) -> if not _is_immutable(item): stack_nodes.append(item) + for target, _, _, _, _, _ in deferred_tuple_finalizations: + if id(target) in container_ids: + return False for target, _, _, _, _, _ in pending_frozensets: if id(target) in container_ids: return False for s, _, _ in deferred_set_insertions: if id(s) in container_ids: - if ( - owner_set_id is not None - and id(s) == owner_set_id - and _is_identity_hashed(m_clone) - ): - continue return False for td_id, entries in dict_ordered_entries.items(): if td_id in container_ids and dict_next_index[td_id] < len(entries): @@ -1001,17 +1062,22 @@ def _flush_pending_structures() -> None: if deferred_set_insertions: still_sets = [] for s, orig_val, orig_members in deferred_set_insertions: + if _deadline_expired(): + return if all(_is_immutable(m) or id(m) in memo for m in orig_members): - resolved_members = [ - m if _is_immutable(m) else memo[id(m)] for m in orig_members - ] - if not all( - _is_member_state_populated(rm, owner_set_id=id(s)) - for rm in resolved_members - ): + resolved_members = [] + for m_idx, m in enumerate(orig_members): + if (m_idx & 63) == 0 and _deadline_expired(): + return + resolved_members.append(m if _is_immutable(m) else memo[id(m)]) + if not all(_is_member_state_populated(rm) for rm in resolved_members): still_sets.append((s, orig_val, orig_members)) continue - set.update(s, resolved_members) + for ins_idx in range(0, len(resolved_members), 64): + if ins_idx > 0 and _deadline_expired(): + return + chunk = resolved_members[ins_idx : ins_idx + 64] + set.update(s, chunk) if set(s) != set(resolved_members): raise TypeError( "Unsupported mutable value in review extension data: " @@ -1036,7 +1102,7 @@ def _flush_pending_structures() -> None: if k_ready and v_ready: k = orig_k if _is_immutable(orig_k) else memo[id(orig_k)] v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] - if not _is_member_state_populated(k, owner_set_id=None): + if not _is_member_state_populated(k): break target_dict[k] = v idx += 1 @@ -2150,12 +2216,13 @@ async def wait_for_review( tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip on_poll snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before - on_poll runs. Callback return-validation errors and exceptions propagate even when a - determined, preventing the waiter from returning a classified outcome. - Inline failures and awaitable failures observed before the deadline propagate, - but the deadline can suppress awaitable failures (and a pending future's - failure can be suppressed if its done callback runs after the deadline), - including when an outcome is already classified. When the deadline expires, + on_poll runs. Callback return-validation errors and inline exceptions propagate + unconditionally, even when a terminal outcome has already been determined, preventing the + waiter from returning a classified outcome. + Separately, awaitable failures observed before the deadline propagate, but the + deadline suppresses awaitable failures observed after expiry (and a pending future's + failure is suppressed if its done callback runs after the deadline), allowing any + classified outcome to be returned. When the deadline expires, unstarted coroutines returned by on_poll are closed without being scheduled, while already-running callback tasks and futures are detached without cancellation and may continue running. Synchronous @@ -2184,7 +2251,34 @@ async def wait_for_review( if on_poll is not None and (_transport.remaining() or 0) > 0: snapshot = _snapshot_review(last) if snapshot is not None and (_transport.remaining() or 0) > 0: + waiter_task = async_current_task() + initial_cancelling = 0 + if waiter_task is not None: + try: + if hasattr(waiter_task, "cancelling"): + initial_cancelling = waiter_task.cancelling() + except BaseException: + pass res = on_poll(snapshot) + if waiter_task is not None: + current_cancelling = 0 + try: + if hasattr(waiter_task, "cancelling"): + current_cancelling = waiter_task.cancelling() + except BaseException: + pass + if current_cancelling > initial_cancelling: + if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: + try: + res.close() + except BaseException: + pass + elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: + try: + res.close() + except BaseException: + pass + raise AsyncCancelledError() try: res_awaitable = isawaitable(res) except Exception: @@ -2308,14 +2402,6 @@ def _on_future_done(_: Any) -> None: return result break else: - waiter_task = async_current_task() - initial_cancelling = 0 - if waiter_task is not None: - try: - if hasattr(waiter_task, "cancelling"): - initial_cancelling = waiter_task.cancelling() - except BaseException: - pass coro = res completed_at = [] wrapper_started = False diff --git a/tests/test_http.py b/tests/test_http.py index 78eb9473..fd2fc31f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1295,11 +1295,11 @@ async def test_wait_ends_on_the_read_that_names_another_head( assert len(server.requests) == 3 assert clock.delays == [5, 10] with Server(lambda request, index: Reply(body=responses[index])) as server: - polled_reviews: list[Any] = [] + polled_reviews: list[tuple[Any, int]] = [] cb = ( - (lambda r: polled_reviews.append(r)) + (lambda r: polled_reviews.append((r, len(server.requests)))) if mode == "sync" - else (lambda r: polled_reviews.append(r)) + else (lambda r: polled_reviews.append((r, len(server.requests)))) ) async with session(mode, server.url) as client: result = await call( @@ -1318,8 +1318,9 @@ async def test_wait_ends_on_the_read_that_names_another_head( # The second read names the head, so the review that would complete is never read. assert len(server.requests) == 2 assert clock.delays == [5, 10, 5] - assert [p.status for p in polled_reviews] == ["PENDING", "RUNNING"] - assert polled_reviews[1].head_commit_sha == HEAD + assert [p[0].status for p in polled_reviews] == ["PENDING", "RUNNING"] + assert [p[1] for p in polled_reviews] == [1, 2] + assert polled_reviews[1][0].head_commit_sha == HEAD @MODES @@ -2804,13 +2805,27 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: await asyncio.sleep(0) assert late_fut.exception_retrieved is True assert id(late_fut) not in client_module._DETACHED_FUTURES - del late_fut + late_fut = None import gc gc.collect() assert late_fut_ref() is None assert unhandled_reports == [] finally: + if producer_task is not None and not producer_task.done(): + producer_task.cancel() + try: + await producer_task + except (asyncio.CancelledError, BaseException): + pass + if late_fut is not None: + if not late_fut.done(): + late_fut.cancel() + elif not late_fut.cancelled(): + try: + late_fut.exception() + except BaseException: + pass loop.set_exception_handler(old_h) # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant @@ -3063,7 +3078,8 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: assert unhandled_exceptions == [] # 6b: Pre-start wrapper cancellation: hold wrapper before entry, - # cancel waiter with budget remaining + # cancel waiter with budget remaining, run queued runner and + # assert callback body never starts import inspect hold_wrapper = asyncio.Event() @@ -3087,9 +3103,11 @@ async def held_wrapper() -> Any: client_module.async_create_task = holding_create_task user_coro_created: list[Any] = [] + cb_body_started = False async def dummy_pre_start_coro(r: Any) -> None: - pass + nonlocal cb_body_started + cb_body_started = True def pre_start_cb(r: Any) -> Any: c = dummy_pre_start_coro(r) @@ -3109,14 +3127,23 @@ def pre_start_cb(r: Any) -> Any: await asyncio.sleep(0) assert len(wrapper_tasks) == 1 assert not wrapper_tasks[0].done() + + # Cancel waiter with budget remaining pre_waiter_task.cancel() + + # Run the queued runner after cancellation and before waiter cleanup + hold_wrapper.set() + await asyncio.sleep(0) + + assert not cb_body_started + assert len(user_coro_created) == 1 + assert inspect.getcoroutinestate(user_coro_created[0]) == inspect.CORO_CLOSED + assert wrapper_tasks[0].done() + try: await pre_waiter_task except asyncio.CancelledError: pass - assert wrapper_tasks[0].cancelled() - assert len(user_coro_created) == 1 - assert inspect.getcoroutinestate(user_coro_created[0]) == inspect.CORO_CLOSED finally: client_module.async_create_task = orig_create_task if pre_waiter_task is not None and not pre_waiter_task.done(): @@ -3580,8 +3607,15 @@ def unhash_failing_cb(r: Any) -> Any: await t except (asyncio.CancelledError, BaseException): pass - if unhash_box and not unhash_box[0].done(): - unhash_box[0].set_result(None) + if unhash_box: + f = unhash_box[0] + if not f.done(): + f.set_result(None) + elif not f.cancelled(): + try: + f.exception() + except BaseException: + pass await asyncio.sleep(0) finally: loop.set_exception_handler(old_h_unhash) From 59a8a5838ad45d0989faa8f7d4f1bfa90f336ddd Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Sun, 22 Nov 2026 23:54:35 +0530 Subject: [PATCH 46/75] Address review run 45 findings: reconstruct strided/sliced memoryviews preserving layout and readonly state, detach overdue futures/tasks on inline cancellation, loop-own returned detached tasks, identity-only member attribute bypass, bounded set/frozenset readiness scans with deadline checks and native length validation, docstring/README alignment on wrapper tasks, and test lifecycle teardown assertions --- README.md | 2 +- proofline/client.py | 245 ++++++++++++++++++++++++++++++-------------- tests/test_http.py | 140 +++++++++++++++++-------- 3 files changed, 267 insertions(+), 120 deletions(-) diff --git a/README.md b/README.md index d683f56e..00e2dc97 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without being scheduled, while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 0a23c66b..2372200b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,6 +2,7 @@ from __future__ import annotations +import ctypes import datetime import math import weakref @@ -420,6 +421,31 @@ def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: _UNRESOLVED_SLOT = object() +class _Py_buffer(ctypes.Structure): + _fields_ = [ + ("buf", ctypes.c_void_p), + ("obj", ctypes.c_void_p), + ("len", ctypes.c_ssize_t), + ("itemsize", ctypes.c_ssize_t), + ("readonly", ctypes.c_int), + ("ndim", ctypes.c_int), + ("format", ctypes.c_char_p), + ("shape", ctypes.POINTER(ctypes.c_ssize_t)), + ("strides", ctypes.POINTER(ctypes.c_ssize_t)), + ("suboffsets", ctypes.POINTER(ctypes.c_ssize_t)), + ("internal", ctypes.c_void_p), + ] + + +_py_get_buffer = ctypes.pythonapi.PyObject_GetBuffer +_py_get_buffer.restype = ctypes.c_int +_py_get_buffer.argtypes = [ctypes.py_object, ctypes.POINTER(_Py_buffer), ctypes.c_int] + +_py_release_buffer = ctypes.pythonapi.PyBuffer_Release +_py_release_buffer.restype = None +_py_release_buffer.argtypes = [ctypes.POINTER(_Py_buffer)] + + def _deadline_expired() -> bool: budget = _transport.remaining() return budget is not None and budget <= 0 @@ -673,55 +699,86 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non elif isinstance(val, memoryview): if val.nbytes > _MAX_SAFE_BUFFER_SIZE: return None + exporter = getattr(val, "obj", None) resolved_mv: Any - if val.readonly: - resolved_mv = memoryview(bytes(val)) - if val.format != "B" or val.ndim > 1: + if isinstance(exporter, bytearray): + exp_id = id(exporter) + if exp_id in memo: + cloned_exporter = memo[exp_id] + else: + if bytearray.__len__(exporter) > _MAX_SAFE_BUFFER_SIZE: + return None try: - resolved_mv = resolved_mv.cast(val.format, shape=val.shape) + cloned_exporter = bytearray.__new__(type(exporter)) + bytearray.__init__(cloned_exporter, exporter) except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" + f"{type(exporter).__name__}" ) from exc - else: - exporter = getattr(val, "obj", None) - if isinstance(exporter, bytearray): - exp_id = id(exporter) - if exp_id in memo: - cloned_exporter = memo[exp_id] - else: - if bytearray.__len__(exporter) > _MAX_SAFE_BUFFER_SIZE: - return None - try: - cloned_exporter = bytearray.__new__(type(exporter)) - bytearray.__init__(cloned_exporter, exporter) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(exporter).__name__}" - ) from exc - memo[exp_id] = cloned_exporter + memo[exp_id] = cloned_exporter + b_val = _Py_buffer() + b_exp = _Py_buffer() + if _py_get_buffer(val, ctypes.byref(b_val), 0x0118) != 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + try: + if _py_get_buffer(exporter, ctypes.byref(b_exp), 0x0118) != 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(exporter).__name__}" + ) try: - import ctypes - - p_exp = ctypes.c_char.from_buffer(exporter) - p_val = ctypes.c_char.from_buffer(val) - offset = ctypes.addressof(p_val) - ctypes.addressof(p_exp) - base_mv = memoryview(cloned_exporter) - resolved_mv = base_mv[offset : offset + val.nbytes] - except Exception: - resolved_mv = memoryview(cloned_exporter) + offset = b_val.buf - b_exp.buf + finally: + _py_release_buffer(ctypes.byref(b_exp)) + finally: + _py_release_buffer(ctypes.byref(b_val)) + base_mv = memoryview(cloned_exporter) + val_strides = val.strides + val_shape = val.shape + if val.ndim == 1 and val_shape is not None and val_strides is not None: + shape = val_shape[0] + itemsize = val.itemsize + stride = val_strides[0] + step = stride // itemsize + off = offset // itemsize + if shape == 0: + resolved_mv = base_mv[0:0] + elif step > 0: + calc_stop = off + shape * step + resolved_mv = base_mv[off:calc_stop:step] + else: + calc_stop = off + shape * step + if calc_stop < 0: + calc_stop = None + resolved_mv = base_mv[off:calc_stop:step] + elif val.ndim == 0: + resolved_mv = base_mv[offset:offset] + elif val.c_contiguous: + resolved_mv = base_mv[offset : offset + val.nbytes] + else: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + else: + if val.readonly: + resolved_mv = memoryview(bytes(val)) else: resolved_mv = memoryview(bytearray(val)) - if val.format != "B" or val.ndim > 1: - try: - resolved_mv = resolved_mv.cast(val.format, shape=val.shape) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc + if val.format != "B" or (val.ndim > 1 and val.shape != resolved_mv.shape): + try: + resolved_mv = resolved_mv.cast(val.format, shape=val.shape) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc + if val.readonly: + resolved_mv = resolved_mv.toreadonly() memo[val_id] = resolved_mv _assign_target(target, key, is_attr, resolved_mv) elif isinstance(val, datetime.datetime): @@ -974,6 +1031,8 @@ def _is_member_state_populated(m_clone: Any) -> bool: container_ids: set[int] = set() while stack_nodes: cur = stack_nodes.pop() + if _is_immutable(cur) or _is_identity_hashed(cur): + continue cid = id(cur) if cid in visited: continue @@ -983,17 +1042,17 @@ def _is_member_state_populated(m_clone: Any) -> bool: stack_nodes.append(cur.__dict__) if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): for _, _, slot_val in _get_obj_attrs(cur): - if not _is_immutable(slot_val): + if not _is_immutable(slot_val) and not _is_identity_hashed(slot_val): stack_nodes.append(slot_val) if isinstance(cur, dict): for k, v in cur.items(): - if not _is_immutable(k): + if not _is_immutable(k) and not _is_identity_hashed(k): stack_nodes.append(k) - if not _is_immutable(v): + if not _is_immutable(v) and not _is_identity_hashed(v): stack_nodes.append(v) elif isinstance(cur, (list, tuple, set, deque)): for item in cur: - if not _is_immutable(item): + if not _is_immutable(item) and not _is_identity_hashed(item): stack_nodes.append(item) for target, _, _, _, _, _ in deferred_tuple_finalizations: @@ -1064,28 +1123,41 @@ def _flush_pending_structures() -> None: for s, orig_val, orig_members in deferred_set_insertions: if _deadline_expired(): return - if all(_is_immutable(m) or id(m) in memo for m in orig_members): - resolved_members = [] - for m_idx, m in enumerate(orig_members): - if (m_idx & 63) == 0 and _deadline_expired(): - return - resolved_members.append(m if _is_immutable(m) else memo[id(m)]) - if not all(_is_member_state_populated(rm) for rm in resolved_members): - still_sets.append((s, orig_val, orig_members)) - continue - for ins_idx in range(0, len(resolved_members), 64): - if ins_idx > 0 and _deadline_expired(): - return - chunk = resolved_members[ins_idx : ins_idx + 64] - set.update(s, chunk) - if set(s) != set(resolved_members): - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(orig_val).__name__}" - ) - changed = True - else: + members_ready = True + for m_idx, m in enumerate(orig_members): + if (m_idx & 63) == 0 and _deadline_expired(): + return + if not (_is_immutable(m) or id(m) in memo): + members_ready = False + break + if not members_ready: + still_sets.append((s, orig_val, orig_members)) + continue + resolved_members = [] + for m_idx, m in enumerate(orig_members): + if (m_idx & 63) == 0 and _deadline_expired(): + return + rm = m if _is_immutable(m) else memo[id(m)] + resolved_members.append(rm) + if not _is_member_state_populated(rm): + members_ready = False + break + if not members_ready: still_sets.append((s, orig_val, orig_members)) + continue + for ins_idx in range(0, len(resolved_members), 64): + if ins_idx > 0 and _deadline_expired(): + return + chunk = resolved_members[ins_idx : ins_idx + 64] + set.update(s, chunk) + if _deadline_expired(): + return + if set.__len__(s) != len(orig_members): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) + changed = True deferred_set_insertions = still_sets op_count = 0 @@ -1126,7 +1198,13 @@ def _flush_pending_structures() -> None: _assign_target(target, key, is_attr, memo[val_id]) progress = True continue - members_ready = all(_is_immutable(m) or id(m) in memo for m in orig_members) + members_ready = True + for m_idx, m in enumerate(orig_members): + if (m_idx & 63) == 0 and _deadline_expired(): + return None + if not (_is_immutable(m) or id(m) in memo): + members_ready = False + break attrs_ready = True if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for _, _, attr_val in _get_obj_attrs(orig_val): @@ -1134,8 +1212,16 @@ def _flush_pending_structures() -> None: attrs_ready = False break if members_ready and attrs_ready: - resolved_members = [m if _is_immutable(m) else memo[id(m)] for m in orig_members] - if not all(_is_member_state_populated(rm) for rm in resolved_members): + resolved_members = [] + for m_idx, m in enumerate(orig_members): + if (m_idx & 63) == 0 and _deadline_expired(): + return None + rm = m if _is_immutable(m) else memo[id(m)] + resolved_members.append(rm) + if not _is_member_state_populated(rm): + members_ready = False + break + if not members_ready: remaining_frozensets.append( (target, key, is_attr, val_id, orig_val, orig_members) ) @@ -1150,7 +1236,7 @@ def _flush_pending_structures() -> None: "Unsupported mutable value in review extension data: " f"{type(orig_val).__name__}" ) from exc - if frozenset(res_set) != frozenset(resolved_members): + if frozenset.__len__(res_set) != len(orig_members): raise TypeError( "Unsupported mutable value in review extension data: " f"{type(orig_val).__name__}" @@ -1196,6 +1282,9 @@ def _safe_cancel_target(target: Any) -> None: def _detach_overdue_future(fut: Any) -> None: + if hasattr(fut, "get_coro"): + _detach_overdue_task(fut) + return try: is_done = fut.done() if hasattr(fut, "done") else AsyncFuture.done(fut) if is_done: @@ -1270,8 +1359,8 @@ async def _observe_fut() -> None: def _detach_overdue_task( task: Any, - res: Any, - wrapper_started: bool, + res: Any = None, + wrapper_started: bool = True, ) -> None: try: is_done = task.done() if hasattr(task, "done") else False @@ -2222,12 +2311,12 @@ async def wait_for_review( Separately, awaitable failures observed before the deadline propagate, but the deadline suppresses awaitable failures observed after expiry (and a pending future's failure is suppressed if its done callback runs after the deadline), allowing any - classified outcome to be returned. When the deadline expires, - unstarted coroutines returned by on_poll are closed without being scheduled, - while already-running callback tasks and futures are detached without - cancellation and may continue running. Synchronous - callbacks must return before a terminal result can be delivered and the - polling deadline cannot interrupt them. + classified outcome to be returned. When the deadline expires or when the wait is + cancelled, unstarted coroutines returned by on_poll are closed without entering + their body (a wrapper task may already have been scheduled), while already-running + callback tasks and futures are detached without cancellation and may continue + running. Synchronous callbacks must return before a terminal result can be + delivered and the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -2278,6 +2367,8 @@ async def wait_for_review( res.close() except BaseException: pass + elif async_isfuture(res) and res is not waiter_task: + _detach_overdue_future(res) raise AsyncCancelledError() try: res_awaitable = isawaitable(res) diff --git a/tests/test_http.py b/tests/test_http.py index fd2fc31f..ac43861c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2736,24 +2736,41 @@ def done(self) -> bool: return False timely_fut: Any = LyingDoneFuture(loop=asyncio.get_running_loop()) + timely_producer: asyncio.Task[None] | None = None async def fail_timely_soon() -> None: await asyncio.sleep(0.01) timely_fut.set_exception(ValueError("timely failure")) def timely_fail_cb(r: Any) -> asyncio.Future[None]: - asyncio.create_task(fail_timely_soon()) + nonlocal timely_producer + timely_producer = asyncio.create_task(fail_timely_soon()) return timely_fut - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: - with pytest.raises(ValueError, match="timely failure"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=timely_fail_cb, - ) + try: + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="timely failure"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_fail_cb, + ) + finally: + if timely_producer is not None and not timely_producer.done(): + timely_producer.cancel() + try: + await timely_producer + except (asyncio.CancelledError, BaseException): + pass + try: + if not asyncio.Future.done(timely_fut): + timely_fut.cancel() + elif not asyncio.Future.cancelled(timely_fut): + timely_fut.exception() + except BaseException: + pass # Late-observed pending future failure preserves the classified outcome class TrackedFuture(asyncio.Future[None]): @@ -2832,6 +2849,7 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: # tasks cannot stall teardown. watchdog_code = """ import asyncio +import pytest import time from typing import Any from proofline import AsyncProoflineClient @@ -2991,6 +3009,7 @@ async def continuing_coro_term(r: Any) -> None: callback_running_term.set() await release_callback_term.wait() callback_finished_term.set() + raise RuntimeError("overdue coroutine failure") client.get_review = fake_completed # type: ignore @@ -3005,11 +3024,10 @@ async def continuing_coro_term(r: Any) -> None: await callback_running_term.wait() assert not waiter_task_4.done() clock.advance(1.0) + release_callback_term.set() res_4 = await waiter_task_4 assert res_4.status == "COMPLETED" assert callback_running_term.is_set() - assert not callback_finished_term.is_set() - release_callback_term.set() await callback_finished_term.wait() # Case 5: Suspending callback that succeeds within budget @@ -3140,10 +3158,8 @@ def pre_start_cb(r: Any) -> Any: assert inspect.getcoroutinestate(user_coro_created[0]) == inspect.CORO_CLOSED assert wrapper_tasks[0].done() - try: + with pytest.raises(asyncio.CancelledError): await pre_waiter_task - except asyncio.CancelledError: - pass finally: client_module.async_create_task = orig_create_task if pre_waiter_task is not None and not pre_waiter_task.done(): @@ -3522,24 +3538,43 @@ def exception(self) -> BaseException | None: self.exception_calls += 1 return super().exception() + complete_task: asyncio.Task[None] | None = None + async def complete_unhashable_soon(fut: Any) -> None: await asyncio.sleep(0.01) fut.set_result(None) - with Server(lambda request, index: Reply(body=responses[1])) as server: - async with session("async", server.url) as client: - unhashable_fut: Any = UnhashableFuture(loop=asyncio.get_running_loop()) - res_unhash = await client.wait_for_review( - ORG, - REVIEW, - timeout=10, - on_poll=lambda r: ( - asyncio.create_task(complete_unhashable_soon(unhashable_fut)), - unhashable_fut, - )[1], - ) - assert res_unhash.status == "COMPLETED" - assert unhashable_fut.done() + def complete_unhashable_cb(r: Any) -> Any: + nonlocal complete_task + complete_task = asyncio.create_task(complete_unhashable_soon(unhashable_fut)) + return unhashable_fut + + unhashable_fut: Any = UnhashableFuture(loop=asyncio.get_running_loop()) + try: + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_unhash = await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=complete_unhashable_cb, + ) + assert res_unhash.status == "COMPLETED" + assert unhashable_fut.done() + finally: + if complete_task is not None and not complete_task.done(): + complete_task.cancel() + try: + await complete_task + except (asyncio.CancelledError, BaseException): + pass + try: + if not asyncio.Future.done(unhashable_fut): + unhashable_fut.cancel() + elif not asyncio.Future.cancelled(unhashable_fut): + unhashable_fut.exception() + except BaseException: + pass # Cancel the waiter while an UnhashableFuture is pending, then fail and release # the future and assert that the loop reports no unhandled exception. @@ -3640,9 +3675,11 @@ def exception(self) -> BaseException | None: loop = asyncio.get_running_loop() old_h = loop.get_exception_handler() loop.set_exception_handler(lambda _loop, ctx: cancel_reports.append(ctx)) + fut_sync_box: list[Any] = [] try: try: fut_sync_cancel: Any = SyncCancelRaisingFuture(loop=asyncio.get_running_loop()) + fut_sync_box.append(fut_sync_cancel) clock_now = [1000.0] orig_client_mono = client_module.monotonic orig_trans_mono = _transport.monotonic @@ -3678,19 +3715,30 @@ async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: client_module.monotonic = orig_client_mono _transport.monotonic = orig_trans_mono finally: - if not fut_sync_cancel.done(): - fut_sync_cancel.set_exception(RuntimeError("sync cancel late error")) - await asyncio.sleep(0) - assert id(fut_sync_cancel) not in _DETACHED_FUTURES - assert fut_sync_cancel.exception_calls > 0 - import weakref - - fut_sync_ref = weakref.ref(fut_sync_cancel) - del fut_sync_cancel - import gc - - gc.collect() - assert fut_sync_ref() is None + try: + if not fut_sync_cancel.done(): + fut_sync_cancel.set_exception(RuntimeError("sync cancel late error")) + await asyncio.sleep(0) + assert id(fut_sync_cancel) not in _DETACHED_FUTURES + assert fut_sync_cancel.exception_calls > 0 + import weakref + + fut_sync_ref = weakref.ref(fut_sync_cancel) + fut_sync_box.clear() + del fut_sync_cancel + import gc + + gc.collect() + assert fut_sync_ref() is None + finally: + if fut_sync_box: + try: + f = fut_sync_box[0] + if asyncio.Future.done(f) and not asyncio.Future.cancelled(f): + f.exception() + except BaseException: + pass + fut_sync_box.clear() finally: loop.set_exception_handler(old_h) @@ -4503,6 +4551,14 @@ def foreign_fail_cb(r: Any) -> Any: assert foreign_failed_fut_ref() is None assert foreign_reports == [] finally: + if foreign_failed_box: + try: + ff = foreign_failed_box[0] + if not ff.cancelled(): + ff.exception() + except BaseException: + pass + foreign_failed_box.clear() foreign_loop_failed.close() # Datetime subclass whose replace fails and fallback lacks copied_tz raises TypeError From 573ec0dc6712d969b53cba8a2ba8cb57d0d7a984 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 00:08:52 +0530 Subject: [PATCH 47/75] Address review run 46 findings: slice buffer by byte offset and byte length with element format and stride, isolate wrapper context from transport deadline, traverse reachable state through identity-hashed attributes for custom-hashed members, document backing buffer size limit, clarify callback cancellation precedence in docstring, and strengthen watchdog producer/wrapper teardown assertions --- README.md | 4 +- proofline/client.py | 91 ++++++++++++++++++++++++++------------------- tests/test_http.py | 57 ++++++++++++++++++++++------ 3 files changed, 101 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 00e2dc97..1c373a8c 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome. Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 2372200b..5adaa84b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -736,29 +736,36 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non _py_release_buffer(ctypes.byref(b_exp)) finally: _py_release_buffer(ctypes.byref(b_val)) - base_mv = memoryview(cloned_exporter) + base_bytes = memoryview(cloned_exporter) val_strides = val.strides val_shape = val.shape if val.ndim == 1 and val_shape is not None and val_strides is not None: shape = val_shape[0] itemsize = val.itemsize stride = val_strides[0] - step = stride // itemsize - off = offset // itemsize + elem_stride = stride // itemsize if shape == 0: - resolved_mv = base_mv[0:0] - elif step > 0: - calc_stop = off + shape * step - resolved_mv = base_mv[off:calc_stop:step] + resolved_mv = cast(Any, base_bytes[0:0]).cast(val.format) + elif stride >= 0: + byte_len = (shape - 1) * stride + itemsize + byte_slice = base_bytes[offset : offset + byte_len] + casted = cast(Any, byte_slice).cast(val.format) + resolved_mv = casted[::elem_stride] else: - calc_stop = off + shape * step - if calc_stop < 0: - calc_stop = None - resolved_mv = base_mv[off:calc_stop:step] + lowest_byte = offset + (shape - 1) * stride + byte_len = (shape - 1) * abs(stride) + itemsize + byte_slice = base_bytes[lowest_byte : lowest_byte + byte_len] + casted = cast(Any, byte_slice).cast(val.format) + start_elem = (shape - 1) * (-elem_stride) + resolved_mv = casted[start_elem:None:elem_stride] elif val.ndim == 0: - resolved_mv = base_mv[offset:offset] + resolved_mv = cast(Any, base_bytes[offset : offset + val.itemsize]).cast( + val.format + ) elif val.c_contiguous: - resolved_mv = base_mv[offset : offset + val.nbytes] + resolved_mv = cast(Any, base_bytes[offset : offset + val.nbytes]).cast( + val.format, shape=val.shape + ) else: raise TypeError( "Unsupported mutable value in review extension data: " @@ -769,14 +776,14 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non resolved_mv = memoryview(bytes(val)) else: resolved_mv = memoryview(bytearray(val)) - if val.format != "B" or (val.ndim > 1 and val.shape != resolved_mv.shape): - try: - resolved_mv = resolved_mv.cast(val.format, shape=val.shape) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc + if val.format != "B" or (val.ndim > 1 and val.shape != resolved_mv.shape): + try: + resolved_mv = resolved_mv.cast(val.format, shape=val.shape) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc if val.readonly: resolved_mv = resolved_mv.toreadonly() memo[val_id] = resolved_mv @@ -1031,7 +1038,7 @@ def _is_member_state_populated(m_clone: Any) -> bool: container_ids: set[int] = set() while stack_nodes: cur = stack_nodes.pop() - if _is_immutable(cur) or _is_identity_hashed(cur): + if _is_immutable(cur): continue cid = id(cur) if cid in visited: @@ -1042,18 +1049,22 @@ def _is_member_state_populated(m_clone: Any) -> bool: stack_nodes.append(cur.__dict__) if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): for _, _, slot_val in _get_obj_attrs(cur): - if not _is_immutable(slot_val) and not _is_identity_hashed(slot_val): + if not _is_immutable(slot_val): stack_nodes.append(slot_val) if isinstance(cur, dict): for k, v in cur.items(): - if not _is_immutable(k) and not _is_identity_hashed(k): + if not _is_immutable(k): stack_nodes.append(k) - if not _is_immutable(v) and not _is_identity_hashed(v): + if not _is_immutable(v): stack_nodes.append(v) - elif isinstance(cur, (list, tuple, set, deque)): + elif isinstance(cur, tuple): for item in cur: if not _is_immutable(item) and not _is_identity_hashed(item): stack_nodes.append(item) + elif isinstance(cur, (list, set, deque)): + for item in cur: + if not _is_immutable(item): + stack_nodes.append(item) for target, _, _, _, _, _ in deferred_tuple_finalizations: if id(target) in container_ids: @@ -1854,10 +1865,10 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes, or - deques with more than 65,536 items in review extension data skip on_poll snapshot - delivery even with time remaining, and snapshot copy errors on unsupported mutable - values propagate before on_poll runs. + delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or + backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items + in review extension data skip on_poll snapshot delivery even with time remaining, + and snapshot copy errors on unsupported mutable values propagate before on_poll runs. on_poll exceptions and return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return @@ -2302,12 +2313,14 @@ async def wait_for_review( an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Oversized - tuples, buffers, memoryviews with more than 65,536 bytes, or deques with more than - 65,536 items in review extension data skip on_poll snapshot delivery even with time - remaining, and snapshot copy errors on unsupported mutable values propagate before - on_poll runs. Callback return-validation errors and inline exceptions propagate - unconditionally, even when a terminal outcome has already been determined, preventing the - waiter from returning a classified outcome. + tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer + larger than 65,536 bytes), or deques with more than 65,536 items in review extension + data skip on_poll snapshot delivery even with time remaining, and snapshot copy errors + on unsupported mutable values propagate before on_poll runs. Callback + return-validation errors and inline exceptions propagate unconditionally, even when a + terminal outcome has already been determined (cancellation requested during callback + invocation takes precedence over return validation), preventing the waiter from + returning a classified outcome. Separately, awaitable failures observed before the deadline propagate, but the deadline suppresses awaitable failures observed after expiry (and a pending future's failure is suppressed if its done callback runs after the deadline), allowing any @@ -2496,6 +2509,7 @@ def _on_future_done(_: Any) -> None: coro = res completed_at = [] wrapper_started = False + captured_deadline = _transport.DEADLINE.get() async def _runner() -> None: nonlocal wrapper_started @@ -2518,9 +2532,9 @@ async def _runner() -> None: except BaseException: pass - deadline_val = _transport.DEADLINE.get() deadline_expired = ( - deadline_val is not None and monotonic() > deadline_val + captured_deadline is not None + and monotonic() > captured_deadline ) if waiter_cancelling or deadline_expired: if ( @@ -2541,6 +2555,7 @@ async def _runner() -> None: pass return wrapper_started = True + _transport.DEADLINE.set(None) try: assert coro is not None await coro diff --git a/tests/test_http.py b/tests/test_http.py index ac43861c..25588b0c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2945,26 +2945,43 @@ def pending_future_callback(r: Any) -> SignallingFuture: # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() + complete_fut_task: asyncio.Task[None] | None = None async def complete_fut_soon() -> None: await asyncio.sleep(0.01) completed_fut.set_result(None) def completing_future_callback(r: Any) -> asyncio.Future[None]: - asyncio.create_task(complete_fut_soon()) + nonlocal complete_fut_task + complete_fut_task = asyncio.create_task(complete_fut_soon()) return completed_fut client.get_review = fake_completed # type: ignore - res = await client.wait_for_review( - ORG, - REVIEW, - timeout=10.0, - on_poll=completing_future_callback, - ) - assert res.status == "COMPLETED" - assert completed_fut.done() - assert not completed_fut.cancelled() + try: + res = await client.wait_for_review( + ORG, + REVIEW, + timeout=10.0, + on_poll=completing_future_callback, + ) + assert res.status == "COMPLETED" + assert completed_fut.done() + assert not completed_fut.cancelled() + finally: + if complete_fut_task is not None and not complete_fut_task.done(): + complete_fut_task.cancel() + try: + await complete_fut_task + except (asyncio.CancelledError, BaseException): + pass + try: + if not completed_fut.done(): + completed_fut.cancel() + elif not completed_fut.cancelled(): + completed_fut.exception() + except BaseException: + pass # Case 3: Overdue callback continues running without cancellation on non-terminal review callback_running = asyncio.Event() @@ -3024,10 +3041,11 @@ async def continuing_coro_term(r: Any) -> None: await callback_running_term.wait() assert not waiter_task_4.done() clock.advance(1.0) - release_callback_term.set() res_4 = await waiter_task_4 assert res_4.status == "COMPLETED" assert callback_running_term.is_set() + assert not callback_finished_term.is_set() + release_callback_term.set() await callback_finished_term.wait() # Case 5: Suspending callback that succeeds within budget @@ -3189,6 +3207,15 @@ def pre_start_cb(r: Any) -> Any: coro_started = asyncio.Event() coro_trigger = asyncio.Event() about_to_raise = asyncio.Event() + captured_case6_wrappers: list[asyncio.Task[Any]] = [] + orig_create_task_6 = client_module.async_create_task + + def tracked_create_task_6(coro: Any, *args: Any, **kwargs: Any) -> Any: + t = orig_create_task_6(coro, *args, **kwargs) + captured_case6_wrappers.append(t) + return t + + client_module.async_create_task = tracked_create_task_6 async def failing_overdue_coro(r: Any) -> None: coro_started.set() @@ -3224,6 +3251,7 @@ async def failing_overdue_coro(r: Any) -> None: gc.collect() assert unhandled_exceptions == [] finally: + client_module.async_create_task = orig_create_task_6 if failing_fut is not None: if not failing_fut.done(): failing_fut.cancel() @@ -3240,6 +3268,13 @@ async def failing_overdue_coro(r: Any) -> None: await waiter_coro_task except (asyncio.CancelledError, BaseException): pass + for t in captured_case6_wrappers: + if hasattr(t, "done") and not t.done(): + t.cancel() + try: + await t + except (asyncio.CancelledError, BaseException): + pass for t in list(client_module._DETACHED_TASKS.values()): if hasattr(t, "done") and not t.done(): t.cancel() From 1c1911b202a8de436c5edcae3f4e9571e382181a Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 00:21:18 +0530 Subject: [PATCH 48/75] Address review run 47 findings: clear transport deadline around on_poll invocation, support array.array and bytearray subclass exporters with attribute expansion and scalar shape=(), traverse custom hash dependencies through tuple elements, document cancellation during mismatch in README, and harden watchdog teardown and test assertions --- README.md | 2 +- proofline/client.py | 60 +++++++++++++++++++++++++++------- tests/test_http.py | 78 ++++++++++++++++++++++++++++++++++----------- 3 files changed, 109 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 1c373a8c..c883be25 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ if outcome.status != "COMPLETED": With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, or snapshot copy error propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 5adaa84b..3267ad1c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,6 +2,7 @@ from __future__ import annotations +import array import ctypes import datetime import math @@ -696,27 +697,52 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non _assign_target(target, key, is_attr, resolved) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, resolved, iter(_get_obj_attrs(val)))) + elif isinstance(val, array.array): + if val.buffer_info()[1] * val.itemsize > _MAX_SAFE_BUFFER_SIZE: + return None + try: + resolved_arr = array.array(val.typecode, val) + except Exception as exc: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) from exc + memo[val_id] = resolved_arr + _assign_target(target, key, is_attr, resolved_arr) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + stack.append((_OBJ_EXPAND, resolved_arr, iter(_get_obj_attrs(val)))) elif isinstance(val, memoryview): if val.nbytes > _MAX_SAFE_BUFFER_SIZE: return None exporter = getattr(val, "obj", None) resolved_mv: Any - if isinstance(exporter, bytearray): + if isinstance(exporter, (bytearray, array.array)): exp_id = id(exporter) if exp_id in memo: cloned_exporter = memo[exp_id] else: - if bytearray.__len__(exporter) > _MAX_SAFE_BUFFER_SIZE: + exp_bytes_len = ( + bytearray.__len__(exporter) + if isinstance(exporter, bytearray) + else exporter.buffer_info()[1] * exporter.itemsize + ) + if exp_bytes_len > _MAX_SAFE_BUFFER_SIZE: return None try: - cloned_exporter = bytearray.__new__(type(exporter)) - bytearray.__init__(cloned_exporter, exporter) + if isinstance(exporter, bytearray): + cloned_exporter = bytearray.__new__(type(exporter)) + bytearray.__init__(cloned_exporter, exporter) + else: + cloned_exporter = array.array(exporter.typecode, exporter) except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " f"{type(exporter).__name__}" ) from exc memo[exp_id] = cloned_exporter + if hasattr(exporter, "__dict__") or hasattr(exporter, "__slots__"): + stack.append( + (_OBJ_EXPAND, cloned_exporter, iter(_get_obj_attrs(exporter))) + ) b_val = _Py_buffer() b_exp = _Py_buffer() if _py_get_buffer(val, ctypes.byref(b_val), 0x0118) != 0: @@ -760,7 +786,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non resolved_mv = casted[start_elem:None:elem_stride] elif val.ndim == 0: resolved_mv = cast(Any, base_bytes[offset : offset + val.itemsize]).cast( - val.format + val.format, shape=() ) elif val.c_contiguous: resolved_mv = cast(Any, base_bytes[offset : offset + val.nbytes]).cast( @@ -776,9 +802,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non resolved_mv = memoryview(bytes(val)) else: resolved_mv = memoryview(bytearray(val)) - if val.format != "B" or (val.ndim > 1 and val.shape != resolved_mv.shape): + if val.ndim == 0: + resolved_mv = cast(Any, resolved_mv).cast(val.format, shape=()) + elif val.format != "B" or (val.ndim > 1 and val.shape != resolved_mv.shape): try: - resolved_mv = resolved_mv.cast(val.format, shape=val.shape) + resolved_mv = cast(Any, resolved_mv).cast(val.format, shape=val.shape) except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " @@ -1036,6 +1064,7 @@ def _is_member_state_populated(m_clone: Any) -> bool: visited: set[int] = set() stack_nodes = [m_clone] container_ids: set[int] = set() + is_custom_hashed = type(m_clone) is not tuple while stack_nodes: cur = stack_nodes.pop() if _is_immutable(cur): @@ -1059,8 +1088,9 @@ def _is_member_state_populated(m_clone: Any) -> bool: stack_nodes.append(v) elif isinstance(cur, tuple): for item in cur: - if not _is_immutable(item) and not _is_identity_hashed(item): - stack_nodes.append(item) + if not _is_immutable(item): + if is_custom_hashed or not _is_identity_hashed(item): + stack_nodes.append(item) elif isinstance(cur, (list, set, deque)): for item in cur: if not _is_immutable(item): @@ -1899,7 +1929,11 @@ def wait_for_review( if on_poll is not None and (_transport.remaining() or 0) > 0: snapshot = _snapshot_review(last) if snapshot is not None and (_transport.remaining() or 0) > 0: - res = on_poll(snapshot) + deadline_token = _transport.DEADLINE.set(None) + try: + res = on_poll(snapshot) + finally: + _transport.DEADLINE.reset(deadline_token) try: res_awaitable = isawaitable(res) except Exception: @@ -2361,7 +2395,11 @@ async def wait_for_review( initial_cancelling = waiter_task.cancelling() except BaseException: pass - res = on_poll(snapshot) + deadline_token = _transport.DEADLINE.set(None) + try: + res = on_poll(snapshot) + finally: + _transport.DEADLINE.reset(deadline_token) if waiter_task is not None: current_cancelling = 0 try: diff --git a/tests/test_http.py b/tests/test_http.py index 25588b0c..9e5e447c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1294,6 +1294,25 @@ async def test_wait_ends_on_the_read_that_names_another_head( assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) assert len(server.requests) == 3 assert clock.delays == [5, 10] + # Mismatch without on_poll ends on the read that names another head (2 requests) + with Server(lambda request, index: Reply(body=responses[index])) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + head_commit_sha=OTHER_HEAD, + ) + assert result.status == "INCOMPLETE" + assert result.review.status == "RUNNING" + assert gap_facts(result) == [PINNED_ELSEWHERE] + assert result.reason == "The review is pinned to another head commit." + assert len(server.requests) == 2 + assert clock.delays == [5, 10, 5] + + # Mismatch with on_poll also ends on the read that names another head (2 requests) with Server(lambda request, index: Reply(body=responses[index])) as server: polled_reviews: list[tuple[Any, int]] = [] cb = ( @@ -1317,7 +1336,7 @@ async def test_wait_ends_on_the_read_that_names_another_head( assert result.reason == "The review is pinned to another head commit." # The second read names the head, so the review that would complete is never read. assert len(server.requests) == 2 - assert clock.delays == [5, 10, 5] + assert clock.delays == [5, 10, 5, 5] assert [p[0].status for p in polled_reviews] == ["PENDING", "RUNNING"] assert [p[1] for p in polled_reviews] == [1, 2] assert polled_reviews[1][0].head_commit_sha == HEAD @@ -2686,21 +2705,32 @@ async def failing_callback(r: Any) -> None: ) # Assert already-done failed future propagates inline + failed_inline_futs: list[asyncio.Future[None]] = [] + def failed_future_callback(r: Any) -> asyncio.Future[None]: loop = asyncio.get_running_loop() fut: asyncio.Future[None] = loop.create_future() fut.set_exception(ValueError("inline future error")) + failed_inline_futs.append(fut) return fut - with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: - async with session("async", server.url) as client: - with pytest.raises(ValueError, match="inline future error"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=10, - on_poll=failed_future_callback, - ) + try: + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="inline future error"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=failed_future_callback, + ) + finally: + for ff in failed_inline_futs: + try: + if not ff.cancelled(): + ff.exception() + except BaseException: + pass # Assert remaining budget with controlled clock wait_timeouts: list[float | None] = [] @@ -2758,11 +2788,12 @@ def timely_fail_cb(r: Any) -> asyncio.Future[None]: on_poll=timely_fail_cb, ) finally: - if timely_producer is not None and not timely_producer.done(): - timely_producer.cancel() + if timely_producer is not None: + if not timely_producer.done(): + timely_producer.cancel() try: await timely_producer - except (asyncio.CancelledError, BaseException): + except BaseException: pass try: if not asyncio.Future.done(timely_fut): @@ -2969,11 +3000,12 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: assert completed_fut.done() assert not completed_fut.cancelled() finally: - if complete_fut_task is not None and not complete_fut_task.done(): - complete_fut_task.cancel() + if complete_fut_task is not None: + if not complete_fut_task.done(): + complete_fut_task.cancel() try: await complete_fut_task - except (asyncio.CancelledError, BaseException): + except BaseException: pass try: if not completed_fut.done(): @@ -3075,6 +3107,8 @@ async def suspending_callback(r: Any) -> None: coro_trigger: asyncio.Event | None = None waiter_coro_task: asyncio.Task[Any] | None = None failing_fut: asyncio.Future[None] | None = None + orig_create_task_6: Any = None + captured_case6_wrappers: list[asyncio.Task[Any]] = [] try: # 6a: Future callback cancelled after startup failing_fut = loop.create_future() @@ -3207,7 +3241,7 @@ def pre_start_cb(r: Any) -> Any: coro_started = asyncio.Event() coro_trigger = asyncio.Event() about_to_raise = asyncio.Event() - captured_case6_wrappers: list[asyncio.Task[Any]] = [] + captured_case6_wrappers.clear() orig_create_task_6 = client_module.async_create_task def tracked_create_task_6(coro: Any, *args: Any, **kwargs: Any) -> Any: @@ -3242,16 +3276,22 @@ async def failing_overdue_coro(r: Any) -> None: assert len(client_module._DETACHED_TASKS) == 1 detached_task_id = next(iter(client_module._DETACHED_TASKS.keys())) + detached_task = client_module._DETACHED_TASKS[detached_task_id] coro_trigger.set() await asyncio.wait_for(about_to_raise.wait(), timeout=1.0) await asyncio.sleep(0.01) assert detached_task_id not in client_module._DETACHED_TASKS + assert detached_task.done() + assert not detached_task.cancelled() + assert isinstance(detached_task.exception(), RuntimeError) + del detached_task gc.collect() assert unhandled_exceptions == [] finally: - client_module.async_create_task = orig_create_task_6 + if orig_create_task_6 is not None: + client_module.async_create_task = orig_create_task_6 if failing_fut is not None: if not failing_fut.done(): failing_fut.cancel() @@ -3840,7 +3880,7 @@ async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: assert _snapshot_review(detail_buf) is None # Multidimensional memoryview checks nbytes against cap - multi_dim_raw = bytearray(100_000) + multi_dim_raw = b"x" * 100_000 multi_dim_view = memoryview(multi_dim_raw).cast("B", shape=[10, 10_000]) assert len(multi_dim_view) == 10 assert multi_dim_view.nbytes == 100_000 From 2f9987ad301f5b08c83f98c8b2db8ae58d29d188 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 00:48:01 +0530 Subject: [PATCH 49/75] Address review run 48 findings: cast exporter view to B for typed slices, instantiate array.array subclasses via __new__ with args, reject unlisted mutable class attributes, traverse custom-hash members across container graphs, validate loop ownership on detached tasks, document completion-time callback cutoffs, and harden watchdog and fixture teardowns --- README.md | 2 +- proofline/client.py | 129 ++++++++--- tests/test_http.py | 539 ++++++++++++++++++++++++++++++-------------- 3 files changed, 462 insertions(+), 208 deletions(-) diff --git a/README.md b/README.md index c883be25..e404a6ab 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures observed before the deadline propagate, but the deadline can suppress awaitable failures (and a pending future's failure can be suppressed if its done callback runs after the deadline), including when an outcome is already classified. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish after expiry: coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 3267ad1c..9e696605 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -332,16 +332,51 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: return False +_SAFE_SPECIAL_ATTRS: set[str] = { + "__abstractmethods__", + "__annotations__", + "__attrs_attrs__", + "__attrs_own_setattr__", + "__attrs_props__", + "__class__", + "__classcell__", + "__dataclass_fields__", + "__dataclass_params__", + "__dict__", + "__doc__", + "__firstlineno__", + "__hash__", + "__match_args__", + "__module__", + "__mro_entries__", + "__name__", + "__orig_bases__", + "__parameters__", + "__pydantic_decorators__", + "__pydantic_fields__", + "__pydantic_generic_metadata__", + "__qualname__", + "__slots__", + "__static_attributes__", + "__subclasshook__", + "__weakref__", +} + + def _has_mutable_class_attrs(cls: type) -> bool: for base in cls.__mro__: if base in _SAFE_BUILTIN_CLASSES or base is object: continue for name, attr in base.__dict__.items(): - if name.startswith("__") and name.endswith("__"): + if name in _SAFE_SPECIAL_ATTRS: continue if isinstance(attr, MemberDescriptorType) or type(attr).__name__ in ( "member_descriptor", "getset_descriptor", + "wrapper_descriptor", + "method_descriptor", + "slotwrapper", + "classmethod_descriptor", ): continue if isinstance( @@ -701,7 +736,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if val.buffer_info()[1] * val.itemsize > _MAX_SAFE_BUFFER_SIZE: return None try: - resolved_arr = array.array(val.typecode, val) + resolved_arr = cast(Any, array.array).__new__(type(val), val.typecode, val) except Exception as exc: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" @@ -732,7 +767,9 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non cloned_exporter = bytearray.__new__(type(exporter)) bytearray.__init__(cloned_exporter, exporter) else: - cloned_exporter = array.array(exporter.typecode, exporter) + cloned_exporter = cast(Any, array.array).__new__( + type(exporter), exporter.typecode, exporter + ) except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " @@ -762,7 +799,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non _py_release_buffer(ctypes.byref(b_exp)) finally: _py_release_buffer(ctypes.byref(b_val)) - base_bytes = memoryview(cloned_exporter) + base_bytes = cast(Any, memoryview(cloned_exporter)).cast("B") val_strides = val.strides val_shape = val.shape if val.ndim == 1 and val_shape is not None and val_strides is not None: @@ -1062,11 +1099,11 @@ def _is_member_state_populated(m_clone: Any) -> bool: if _is_identity_hashed(m_clone): return True visited: set[int] = set() - stack_nodes = [m_clone] + root_in_custom = not _is_identity_hashed(m_clone) and type(m_clone) is not tuple + stack_nodes: list[tuple[Any, bool]] = [(m_clone, root_in_custom)] container_ids: set[int] = set() - is_custom_hashed = type(m_clone) is not tuple while stack_nodes: - cur = stack_nodes.pop() + cur, in_custom = stack_nodes.pop() if _is_immutable(cur): continue cid = id(cur) @@ -1074,27 +1111,38 @@ def _is_member_state_populated(m_clone: Any) -> bool: continue visited.add(cid) container_ids.add(cid) - if hasattr(cur, "__dict__") and isinstance(cur.__dict__, dict): - stack_nodes.append(cur.__dict__) - if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): - for _, _, slot_val in _get_obj_attrs(cur): - if not _is_immutable(slot_val): - stack_nodes.append(slot_val) - if isinstance(cur, dict): - for k, v in cur.items(): - if not _is_immutable(k): - stack_nodes.append(k) - if not _is_immutable(v): - stack_nodes.append(v) - elif isinstance(cur, tuple): - for item in cur: - if not _is_immutable(item): - if is_custom_hashed or not _is_identity_hashed(item): - stack_nodes.append(item) - elif isinstance(cur, (list, set, deque)): - for item in cur: - if not _is_immutable(item): - stack_nodes.append(item) + if not in_custom and not _is_identity_hashed(cur) and type(cur) is not tuple: + in_custom = True + if in_custom: + if hasattr(cur, "__dict__") and isinstance(cur.__dict__, dict): + stack_nodes.append((cur.__dict__, True)) + if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): + for _, _, slot_val in _get_obj_attrs(cur): + if not _is_immutable(slot_val): + stack_nodes.append((slot_val, True)) + if isinstance(cur, dict): + for k, v in cur.items(): + if not _is_immutable(k): + stack_nodes.append((k, True)) + if not _is_immutable(v): + stack_nodes.append((v, True)) + elif isinstance(cur, tuple): + for item in cur: + if not _is_immutable(item): + stack_nodes.append((item, True)) + elif isinstance(cur, (list, set, deque)): + for item in cur: + if not _is_immutable(item): + stack_nodes.append((item, True)) + else: + if isinstance(cur, tuple): + for item in cur: + if _is_immutable(item): + continue + if _is_identity_hashed(item): + continue + item_is_custom = type(item) is not tuple + stack_nodes.append((item, item_is_custom)) for target, _, _, _, _, _ in deferred_tuple_finalizations: if id(target) in container_ids: @@ -1403,6 +1451,21 @@ def _detach_overdue_task( res: Any = None, wrapper_started: bool = True, ) -> None: + try: + running_loop = async_get_running_loop() + except Exception: + running_loop = None + + try: + loop = task.get_loop() if hasattr(task, "get_loop") else running_loop + except Exception: + loop = running_loop + + if running_loop is not None and loop is not running_loop: + return + if loop is None or loop.is_closed(): + return + try: is_done = task.done() if hasattr(task, "done") else False except BaseException: @@ -2355,10 +2418,12 @@ async def wait_for_review( terminal outcome has already been determined (cancellation requested during callback invocation takes precedence over return validation), preventing the waiter from returning a classified outcome. - Separately, awaitable failures observed before the deadline propagate, but the - deadline suppresses awaitable failures observed after expiry (and a pending future's - failure is suppressed if its done callback runs after the deadline), allowing any - classified outcome to be returned. When the deadline expires or when the wait is + Separately, awaitable failures occurring before the deadline propagate, but the + deadline suppresses failures of awaitables that finish after expiry: coroutine + failures are timed at wrapper completion rather than when the waiter retrieves + them, and pending future failures are cut off at their done-callback execution. + This allows any classified outcome to be returned when a callback finishes after + the deadline. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by on_poll are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and futures are detached without cancellation and may continue diff --git a/tests/test_http.py b/tests/test_http.py index 9e5e447c..6479dbcb 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1,5 +1,6 @@ from __future__ import annotations +import array import asyncio import csv import gzip @@ -14,6 +15,7 @@ import time import tomllib import traceback +import weakref from collections.abc import AsyncIterator from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta @@ -2732,156 +2734,13 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: except BaseException: pass - # Assert remaining budget with controlled clock - wait_timeouts: list[float | None] = [] - orig_async_wait = client_module.async_wait - - async def tracking_wait(fs: Any, *, timeout: float | None = None) -> Any: - wait_timeouts.append(timeout) - return await orig_async_wait(fs, timeout=timeout) - - monkeypatch.setattr(client_module, "async_wait", tracking_wait) - - async def dummy_async_cb(r: Any) -> None: - pass - - def cb_consuming_clock(r: Any) -> Any: - clock.now += 35.0 - return dummy_async_cb(r) - - with Server(lambda request, index: Reply(body=responses[1])) as server: - async with session("async", server.url) as client: - await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=cb_consuming_clock, - ) - assert wait_timeouts == [65.0] - monkeypatch.setattr(client_module, "async_wait", orig_async_wait) - - # Timely pending future failure propagates even if done() lies - class LyingDoneFuture(asyncio.Future[None]): - def done(self) -> bool: - return False - - timely_fut: Any = LyingDoneFuture(loop=asyncio.get_running_loop()) - timely_producer: asyncio.Task[None] | None = None - - async def fail_timely_soon() -> None: - await asyncio.sleep(0.01) - timely_fut.set_exception(ValueError("timely failure")) - - def timely_fail_cb(r: Any) -> asyncio.Future[None]: - nonlocal timely_producer - timely_producer = asyncio.create_task(fail_timely_soon()) - return timely_fut - - try: - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: - with pytest.raises(ValueError, match="timely failure"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=timely_fail_cb, - ) - finally: - if timely_producer is not None: - if not timely_producer.done(): - timely_producer.cancel() - try: - await timely_producer - except BaseException: - pass - try: - if not asyncio.Future.done(timely_fut): - timely_fut.cancel() - elif not asyncio.Future.cancelled(timely_fut): - timely_fut.exception() - except BaseException: - pass - - # Late-observed pending future failure preserves the classified outcome - class TrackedFuture(asyncio.Future[None]): - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - super().__init__(loop=loop) - self.exception_retrieved = False - - def exception(self) -> BaseException | None: - self.exception_retrieved = True - return super().exception() - - import weakref - - late_fut: TrackedFuture | None = TrackedFuture(loop=asyncio.get_running_loop()) - late_fut_ref = weakref.ref(late_fut) - late_fut.add_done_callback(lambda _: setattr(clock, "now", clock.now + 200.0)) - producer_task: asyncio.Task[None] | None = None - - async def fail_late_soon() -> None: - await asyncio.sleep(0) - if late_fut is not None: - late_fut.set_exception(ValueError("late failure")) - - def late_fail_cb(r: Any) -> asyncio.Future[None]: - nonlocal producer_task - producer_task = asyncio.create_task(fail_late_soon()) - assert late_fut is not None - return late_fut - - unhandled_reports: list[dict[str, Any]] = [] - loop = asyncio.get_running_loop() - old_h = loop.get_exception_handler() - loop.set_exception_handler(lambda _loop, ctx: unhandled_reports.append(ctx)) - try: - with Server(lambda request, index: Reply(body=responses[1])) as server: - async with session("async", server.url) as client: - res_late = await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=late_fail_cb, - ) - assert res_late.status == "COMPLETED" - assert late_fut is not None - assert late_fut.done() - assert clock.now >= 200.0 - if producer_task is not None: - await producer_task - await asyncio.sleep(0) - assert late_fut.exception_retrieved is True - assert id(late_fut) not in client_module._DETACHED_FUTURES - late_fut = None - import gc - - gc.collect() - assert late_fut_ref() is None - assert unhandled_reports == [] - finally: - if producer_task is not None and not producer_task.done(): - producer_task.cancel() - try: - await producer_task - except (asyncio.CancelledError, BaseException): - pass - if late_fut is not None: - if not late_fut.done(): - late_fut.cancel() - elif not late_fut.cancelled(): - try: - late_fut.exception() - except BaseException: - pass - loop.set_exception_handler(old_h) - # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. watchdog_code = """ import asyncio import pytest import time +import weakref from typing import Any from proofline import AsyncProoflineClient import proofline.client as client_module @@ -3049,6 +2908,44 @@ async def continuing_coro(r: Any) -> None: finally: sleep_forbidden = False + # Case 3b: Return a Task from a synchronous callback, release it after the polling deadline + # and waiter exit, and assert its client request succeeds. + task_release_3b = asyncio.Event() + task_success_3b = asyncio.Event() + cb_task_3b: asyncio.Task[None] | None = None + + async def task_worker_3b() -> None: + await task_release_3b.wait() + # Client request after polling deadline and waiter exit: + rev_res = await client.get_review(ORG, REVIEW) + assert rev_res.status == "RUNNING" + task_success_3b.set() + + def sync_cb_returning_task(r: Any) -> Any: + nonlocal cb_task_3b + cb_task_3b = asyncio.create_task(task_worker_3b()) + return cb_task_3b + + client.get_review = fake_running # type: ignore + waiter_task_3b = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=sync_cb_returning_task, + ) + ) + await asyncio.sleep(0.01) + assert cb_task_3b is not None + assert not cb_task_3b.done() + clock.advance(1.0) + res_3b = await waiter_task_3b + assert res_3b.status == "TIMED_OUT" + assert not cb_task_3b.done() + task_release_3b.set() + await asyncio.wait_for(task_success_3b.wait(), timeout=1.0) + await cb_task_3b + # Case 4: Overdue callback continues running without cancellation on terminal review callback_running_term = asyncio.Event() callback_finished_term = asyncio.Event() @@ -3195,6 +3092,8 @@ def pre_start_cb(r: Any) -> Any: ) ) await asyncio.sleep(0) + if pre_waiter_task.done(): + await pre_waiter_task assert len(wrapper_tasks) == 1 assert not wrapper_tasks[0].done() @@ -3214,8 +3113,9 @@ def pre_start_cb(r: Any) -> Any: await pre_waiter_task finally: client_module.async_create_task = orig_create_task - if pre_waiter_task is not None and not pre_waiter_task.done(): - pre_waiter_task.cancel() + if pre_waiter_task is not None: + if not pre_waiter_task.done(): + pre_waiter_task.cancel() try: await pre_waiter_task except (asyncio.CancelledError, BaseException): @@ -3246,6 +3146,14 @@ def pre_start_cb(r: Any) -> Any: def tracked_create_task_6(coro: Any, *args: Any, **kwargs: Any) -> Any: t = orig_create_task_6(coro, *args, **kwargs) + t.exception_calls = 0 + orig_exc = t.exception + + def tracked_exc() -> Any: + t.exception_calls += 1 + return orig_exc() + + t.exception = tracked_exc captured_case6_wrappers.append(t) return t @@ -3285,9 +3193,14 @@ async def failing_overdue_coro(r: Any) -> None: assert detached_task_id not in client_module._DETACHED_TASKS assert detached_task.done() assert not detached_task.cancelled() - assert isinstance(detached_task.exception(), RuntimeError) + assert getattr(detached_task, "exception_calls", 0) > 0 + # import weakref (already imported at module level) + + dt_ref = weakref.ref(detached_task) del detached_task + captured_case6_wrappers.clear() gc.collect() + assert dt_ref() is None assert unhandled_exceptions == [] finally: if orig_create_task_6 is not None: @@ -3637,8 +3550,9 @@ def complete_unhashable_cb(r: Any) -> Any: assert res_unhash.status == "COMPLETED" assert unhashable_fut.done() finally: - if complete_task is not None and not complete_task.done(): - complete_task.cancel() + if complete_task is not None: + if not complete_task.done(): + complete_task.cancel() try: await complete_task except (asyncio.CancelledError, BaseException): @@ -3730,7 +3644,7 @@ def unhash_failing_cb(r: Any) -> Any: finally: loop.set_exception_handler(old_h_unhash) - # Case with a waiter whose cancel() raises synchronously: + # Case detaching an overdue callback Future without calling its cancel(): # the waiter returns TIMED_OUT without calling cancel() or reporting an unhandled exception class SyncCancelRaisingFuture(asyncio.Future[None]): def __init__(self, loop: asyncio.AbstractEventLoop) -> None: @@ -3786,34 +3700,35 @@ async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: assert fut_sync_cancel.cancel_called is False assert id(fut_sync_cancel) in _DETACHED_FUTURES assert cancel_reports == [] + + # Late-exception and release checks in test body after detachment verified + fut_sync_cancel.set_exception(RuntimeError("sync cancel late error")) + await asyncio.sleep(0) + assert id(fut_sync_cancel) not in _DETACHED_FUTURES + assert fut_sync_cancel.exception_calls > 0 + # import weakref (already imported at module level) + + fut_sync_ref = weakref.ref(fut_sync_cancel) + fut_sync_box.clear() + del fut_sync_cancel + import gc + + gc.collect() + assert fut_sync_ref() is None finally: client_module.monotonic = orig_client_mono _transport.monotonic = orig_trans_mono finally: - try: - if not fut_sync_cancel.done(): - fut_sync_cancel.set_exception(RuntimeError("sync cancel late error")) - await asyncio.sleep(0) - assert id(fut_sync_cancel) not in _DETACHED_FUTURES - assert fut_sync_cancel.exception_calls > 0 - import weakref - - fut_sync_ref = weakref.ref(fut_sync_cancel) + if fut_sync_box: + try: + f = fut_sync_box[0] + if not asyncio.Future.done(f): + f.cancel() + elif not asyncio.Future.cancelled(f): + f.exception() + except BaseException: + pass fut_sync_box.clear() - del fut_sync_cancel - import gc - - gc.collect() - assert fut_sync_ref() is None - finally: - if fut_sync_box: - try: - f = fut_sync_box[0] - if asyncio.Future.done(f) and not asyncio.Future.cancelled(f): - f.exception() - except BaseException: - pass - fut_sync_box.clear() finally: loop.set_exception_handler(old_h) @@ -4512,7 +4427,7 @@ def __len__(self) -> int: assert _snapshot_review(detail_huge_ba) is None # Weak references in snapshot extension data are rejected with TypeError - import weakref + # import weakref (already imported at module level) class TargetObj: pass @@ -4592,7 +4507,7 @@ def exception(self) -> BaseException | None: self.exception_retrieved = True return super().exception() - import weakref + # import weakref (already imported at module level) foreign_loop_failed = asyncio.new_event_loop() foreign_reports: list[dict[str, Any]] = [] @@ -4654,3 +4569,277 @@ def __copy__(self) -> Any: detail_broken_dt.additional_properties["broken_dt"] = broken_dt with pytest.raises(TypeError, match="Unsupported mutable value"): _snapshot_review(detail_broken_dt) + + # Slotted extension object with class-level mutable list such as __shared__ is rejected + class SlottedSharedAttrObj: + __slots__ = ("instance_attr",) + __shared__ = [1, 2, 3] + + def __init__(self, val: Any) -> None: + self.instance_attr = val + + slotted_shared = SlottedSharedAttrObj("val") + detail_slotted = CustomerReviewDetail.from_dict(responses[1]) + detail_slotted.additional_properties["shared"] = slotted_shared + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_slotted) + + # Set member is a tuple containing an object with a custom hash that reads an inner dict + class CustomHashWithDict: + def __init__(self, d: dict[str, Any]) -> None: + self.d = d + + def __hash__(self) -> int: + return hash(tuple(sorted(self.d.items()))) + + def __eq__(self, other: Any) -> bool: + return isinstance(other, CustomHashWithDict) and self.d == other.d + + inner_dict = {"key": "val"} + custom_obj = CustomHashWithDict(inner_dict) + tuple_with_custom = (custom_obj,) + set_with_tuple = {tuple_with_custom} + detail_tuple_custom = CustomerReviewDetail.from_dict(responses[1]) + detail_tuple_custom.additional_properties["set_tuple"] = set_with_tuple + snap_tc = _snapshot_review(detail_tuple_custom) + assert snap_tc is not None + copied_set = snap_tc.additional_properties["set_tuple"] + copied_tuple = next(iter(copied_set)) + assert copied_tuple[0].d == {"key": "val"} + assert copied_tuple[0].d is not inner_dict + + # Snapshot overlapping views of one subclass exporter, visiting a view first: + # assert shared writes, original isolation, copied attributes, and scalar shape () + class SubclassByteArray(bytearray): + pass + + sub_ba = SubclassByteArray(b"0123456789abcdef") + sub_ba.extra_attr = ["isolated_extra"] # type: ignore[attr-defined] + + sub_mv1 = memoryview(sub_ba)[0:10] + sub_scalar = memoryview(sub_ba)[6:7].cast("B", shape=()) + sub_mv2 = memoryview(sub_ba)[5:15] + + detail_view_first = CustomerReviewDetail.from_dict(responses[1]) + detail_view_first.additional_properties = { + "view1": sub_mv1, + "scalar": sub_scalar, + "view2": sub_mv2, + "exporter": sub_ba, + } + + snap_vf = _snapshot_review(detail_view_first) + assert snap_vf is not None + copied_v1 = snap_vf.additional_properties["view1"] + copied_scalar = snap_vf.additional_properties["scalar"] + copied_v2 = snap_vf.additional_properties["view2"] + copied_exp = snap_vf.additional_properties["exporter"] + + assert copied_scalar.shape == () + assert copied_scalar.ndim == 0 + assert copied_scalar[()] == ord("6") + assert type(copied_exp) is SubclassByteArray + assert copied_exp.extra_attr == ["isolated_extra"] + assert copied_exp.extra_attr is not sub_ba.extra_attr + + copied_v1[6] = ord("X") + assert copied_v2[1] == ord("X") + assert copied_scalar[()] == ord("X") + assert copied_exp[6] == ord("X") + assert sub_ba[6] == ord("6") + assert sub_mv1[6] == ord("6") + assert sub_mv2[1] == ord("6") + assert sub_scalar[()] == ord("6") + copied_exp.extra_attr.append("new_val") + assert "new_val" not in sub_ba.extra_attr + + # Also test with array.array subclass exporter and integer views: + class SubclassIntArray(array.array): + pass + + sub_arr = SubclassIntArray("i", [10, 20, 30, 40, 50, 60, 70, 80]) + sub_arr.custom_dict = {"prop": "val"} # type: ignore[attr-defined] + arr_v1 = memoryview(sub_arr)[1:6] + arr_scalar = memoryview(sub_arr).cast("B")[12:16].cast("i", shape=()) + arr_v2 = memoryview(sub_arr)[2:7] + + detail_arr_vf = CustomerReviewDetail.from_dict(responses[1]) + detail_arr_vf.additional_properties = { + "arr_v1": arr_v1, + "arr_scalar": arr_scalar, + "arr_v2": arr_v2, + "arr_exp": sub_arr, + } + + snap_arr = _snapshot_review(detail_arr_vf) + assert snap_arr is not None + c_arr_v1 = snap_arr.additional_properties["arr_v1"] + c_arr_scalar = snap_arr.additional_properties["arr_scalar"] + c_arr_v2 = snap_arr.additional_properties["arr_v2"] + c_arr_exp = snap_arr.additional_properties["arr_exp"] + + assert c_arr_scalar.shape == () + assert c_arr_scalar.ndim == 0 + assert c_arr_scalar[()] == 40 + assert type(c_arr_exp) is SubclassIntArray + assert c_arr_exp.custom_dict == {"prop": "val"} + assert c_arr_exp.custom_dict is not sub_arr.custom_dict + + c_arr_v1[2] = 999 + assert c_arr_v2[1] == 999 + assert c_arr_scalar[()] == 999 + assert c_arr_exp[3] == 999 + assert sub_arr[3] == 40 + assert arr_v1[2] == 40 + + +async def test_wait_for_review_pending_futures_and_clock( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + responses = [review("RUNNING"), review()] + + # Assert remaining budget with controlled clock + wait_timeouts: list[float | None] = [] + orig_async_wait = client_module.async_wait + + async def tracking_wait(fs: Any, *, timeout: float | None = None) -> Any: + wait_timeouts.append(timeout) + return await orig_async_wait(fs, timeout=timeout) + + monkeypatch.setattr(client_module, "async_wait", tracking_wait) + + async def dummy_async_cb(r: Any) -> None: + pass + + def cb_consuming_clock(r: Any) -> Any: + clock.now += 35.0 + return dummy_async_cb(r) + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=cb_consuming_clock, + ) + assert wait_timeouts == [65.0] + monkeypatch.setattr(client_module, "async_wait", orig_async_wait) + + # Timely pending future failure propagates even if done() lies + class LyingDoneFuture(asyncio.Future[None]): + def done(self) -> bool: + return False + + timely_fut: Any = LyingDoneFuture(loop=asyncio.get_running_loop()) + timely_producer: asyncio.Task[None] | None = None + + async def fail_timely_soon() -> None: + await asyncio.sleep(0.01) + timely_fut.set_exception(ValueError("timely failure")) + + def timely_fail_cb(r: Any) -> asyncio.Future[None]: + nonlocal timely_producer + timely_producer = asyncio.create_task(fail_timely_soon()) + return timely_fut + + try: + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="timely failure"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_fail_cb, + ) + finally: + if timely_producer is not None: + if not timely_producer.done(): + timely_producer.cancel() + try: + await timely_producer + except BaseException: + pass + try: + if not asyncio.Future.done(timely_fut): + timely_fut.cancel() + elif not asyncio.Future.cancelled(timely_fut): + timely_fut.exception() + except BaseException: + pass + + # Late-observed pending future failure preserves the classified outcome + class TrackedFuture(asyncio.Future[None]): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(loop=loop) + self.exception_retrieved = False + + def exception(self) -> BaseException | None: + self.exception_retrieved = True + return super().exception() + + # import weakref (already imported at module level) + + late_fut: TrackedFuture | None = TrackedFuture(loop=asyncio.get_running_loop()) + late_fut_ref = weakref.ref(late_fut) + late_fut.add_done_callback(lambda _: setattr(clock, "now", clock.now + 200.0)) + producer_task: asyncio.Task[None] | None = None + + async def fail_late_soon() -> None: + await asyncio.sleep(0) + if late_fut is not None: + late_fut.set_exception(ValueError("late failure")) + + def late_fail_cb(r: Any) -> asyncio.Future[None]: + nonlocal producer_task + producer_task = asyncio.create_task(fail_late_soon()) + assert late_fut is not None + return late_fut + + unhandled_reports: list[dict[str, Any]] = [] + loop = asyncio.get_running_loop() + old_h = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unhandled_reports.append(ctx)) + try: + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_late = await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=late_fail_cb, + ) + assert res_late.status == "COMPLETED" + assert late_fut is not None + assert late_fut.done() + assert clock.now >= 200.0 + if producer_task is not None: + await producer_task + await asyncio.sleep(0) + assert late_fut.exception_retrieved is True + assert id(late_fut) not in client_module._DETACHED_FUTURES + late_fut = None + import gc + + gc.collect() + assert late_fut_ref() is None + assert unhandled_reports == [] + finally: + if producer_task is not None: + if not producer_task.done(): + producer_task.cancel() + try: + await producer_task + except (asyncio.CancelledError, BaseException): + pass + if late_fut is not None: + if not late_fut.done(): + late_fut.cancel() + elif not late_fut.cancelled(): + try: + late_fut.exception() + except BaseException: + pass + loop.set_exception_handler(old_h) From 3f99b1534313a3758c8f099e826e61eb0cc3bc1f Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 01:05:07 +0530 Subject: [PATCH 50/75] Address review run 49 findings: keep detached tasks in id-keyed dict for unhashable tasks, validate SDK requests in watchdog against test server, test timely future failure with clock advance before waiter resumption, track wrapper exception in case 4, document already-done future return cutoff, close rejected sync on_poll adapters, clear deadline around async_create_task, reject mutable class attrs on buffer and set subclasses, and traverse frozensets in readiness walk --- README.md | 2 +- proofline/client.py | 112 ++++++++++++++++++++++++---- tests/test_http.py | 174 ++++++++++++++++++++++++++++++++------------ 3 files changed, 223 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index e404a6ab..250a1629 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish after expiry: coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish or return after expiry: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 9e696605..0fa6f14e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -571,6 +571,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non ) stack.append((_TUPLE_EXPAND, temp_list, tuple.__iter__(val))) elif isinstance(val, dict): + if type(val) not in (dict, defaultdict) and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if "__copy__" in type(val).__dict__: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" @@ -601,6 +605,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_OBJ_EXPAND, new_dict, iter(_get_obj_attrs(val)))) stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) elif isinstance(val, list): + if type(val) is not list and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if "__copy__" in type(val).__dict__: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" @@ -618,6 +626,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) elif isinstance(val, set): + if type(val) is not set and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if "__copy__" in type(val).__dict__: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" @@ -705,6 +717,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if type(val) is deque: new_deque: deque[Any] = deque(maxlen=val.maxlen) else: + if type(val) is not deque and _has_mutable_class_attrs(type(val)): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) try: new_deque = deque.__new__(type(val)) deque.__init__(new_deque, maxlen=val.maxlen) @@ -719,6 +736,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_deque, iter(_get_obj_attrs(val)))) elif isinstance(val, bytearray): + if type(val) is not bytearray and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if bytearray.__len__(val) > _MAX_SAFE_BUFFER_SIZE: return None try: @@ -733,6 +754,10 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, resolved, iter(_get_obj_attrs(val)))) elif isinstance(val, array.array): + if type(val) is not array.array and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if val.buffer_info()[1] * val.itemsize > _MAX_SAFE_BUFFER_SIZE: return None try: @@ -751,6 +776,13 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non exporter = getattr(val, "obj", None) resolved_mv: Any if isinstance(exporter, (bytearray, array.array)): + if type(exporter) not in (bytearray, array.array) and _has_mutable_class_attrs( + type(exporter) + ): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(exporter).__name__}" + ) exp_id = id(exporter) if exp_id in memo: cloned_exporter = memo[exp_id] @@ -1099,7 +1131,10 @@ def _is_member_state_populated(m_clone: Any) -> bool: if _is_identity_hashed(m_clone): return True visited: set[int] = set() - root_in_custom = not _is_identity_hashed(m_clone) and type(m_clone) is not tuple + root_in_custom = not _is_identity_hashed(m_clone) and type(m_clone) not in ( + tuple, + frozenset, + ) stack_nodes: list[tuple[Any, bool]] = [(m_clone, root_in_custom)] container_ids: set[int] = set() while stack_nodes: @@ -1111,7 +1146,15 @@ def _is_member_state_populated(m_clone: Any) -> bool: continue visited.add(cid) container_ids.add(cid) - if not in_custom and not _is_identity_hashed(cur) and type(cur) is not tuple: + if ( + not in_custom + and not _is_identity_hashed(cur) + and type(cur) + not in ( + tuple, + frozenset, + ) + ): in_custom = True if in_custom: if hasattr(cur, "__dict__") and isinstance(cur.__dict__, dict): @@ -1130,18 +1173,18 @@ def _is_member_state_populated(m_clone: Any) -> bool: for item in cur: if not _is_immutable(item): stack_nodes.append((item, True)) - elif isinstance(cur, (list, set, deque)): + elif isinstance(cur, (list, set, frozenset, deque)): for item in cur: if not _is_immutable(item): stack_nodes.append((item, True)) else: - if isinstance(cur, tuple): + if isinstance(cur, (tuple, frozenset)): for item in cur: if _is_immutable(item): continue if _is_identity_hashed(item): continue - item_is_custom = type(item) is not tuple + item_is_custom = type(item) not in (tuple, frozenset) stack_nodes.append((item, item_is_custom)) for target, _, _, _, _, _ in deferred_tuple_finalizations: @@ -1503,18 +1546,18 @@ def _detach_overdue_task( except Exception: loop = None + task_id = id(task) if loop is not None and not loop.is_closed(): loop_tasks = getattr(loop, "_proofline_detached_tasks", None) if loop_tasks is None: - loop_tasks = set() + loop_tasks = {} try: setattr(loop, "_proofline_detached_tasks", loop_tasks) except Exception: pass if loop_tasks is not None: - loop_tasks.add(task) + loop_tasks[task_id] = task - task_id = id(task) try: _DETACHED_TASKS[task_id] = task except (TypeError, BaseException): @@ -1525,8 +1568,8 @@ def _on_detached_task_done(t: Any) -> None: if loop is not None: loop_tasks = getattr(loop, "_proofline_detached_tasks", None) if loop_tasks is not None: - loop_tasks.discard(t) - loop_tasks.discard(task) + loop_tasks.pop(task_id, None) + loop_tasks.pop(id(t), None) try: is_canc = t.cancelled() if hasattr(t, "cancelled") else False if not is_canc: @@ -1569,7 +1612,7 @@ async def _observe_task() -> None: if loop is not None: loop_tasks = getattr(loop, "_proofline_detached_tasks", None) if loop_tasks is not None: - loop_tasks.discard(task) + loop_tasks.pop(task_id, None) obs = loop.create_task(_observe_task()) obs.add_done_callback(lambda _: None) @@ -2014,11 +2057,24 @@ def wait_for_review( res.close() except Exception: pass + else: + res_close = getattr(res, "close", None) + if callable(res_close): + try: + res_close() + except BaseException: + pass raise TypeError( "on_poll returned an awaitable; use AsyncProoflineClient " "for async callbacks." ) if res is not None: + res_close = getattr(res, "close", None) + if callable(res_close): + try: + res_close() + except BaseException: + pass raise TypeError("Callbacks must return None.") if result is not None: return result @@ -2419,11 +2475,13 @@ async def wait_for_review( invocation takes precedence over return validation), preventing the waiter from returning a classified outcome. Separately, awaitable failures occurring before the deadline propagate, but the - deadline suppresses failures of awaitables that finish after expiry: coroutine + deadline suppresses failures of awaitables that finish or return after expiry: + already-done futures must be returned before the deadline to propagate (failures of + already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution. - This allows any classified outcome to be returned when a callback finishes after - the deadline. When the deadline expires or when the wait is + This allows any classified outcome to be returned when a callback finishes or returns + after the deadline. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by on_poll are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and futures are detached without cancellation and may continue @@ -2483,14 +2541,33 @@ async def wait_for_review( res.close() except BaseException: pass - elif async_isfuture(res) and res is not waiter_task: - _detach_overdue_future(res) + else: + res_close = getattr(res, "close", None) + if callable(res_close): + try: + res_close() + except BaseException: + pass + elif async_isfuture(res) and res is not waiter_task: + _detach_overdue_future(res) raise AsyncCancelledError() try: res_awaitable = isawaitable(res) except Exception: + res_close = getattr(res, "close", None) + if callable(res_close): + try: + res_close() + except BaseException: + pass raise TypeError("Callbacks must return None or an awaitable.") from None if res is not None and not res_awaitable: + res_close = getattr(res, "close", None) + if callable(res_close): + try: + res_close() + except BaseException: + pass raise TypeError("Callbacks must return None or an awaitable.") if res_awaitable: if res is async_current_task(): @@ -2666,6 +2743,7 @@ async def _runner() -> None: completed_at.append(monotonic()) runner_coro = _runner() + deadline_token_task = _transport.DEADLINE.set(None) try: task = async_create_task(runner_coro) except BaseException: @@ -2688,6 +2766,8 @@ async def _runner() -> None: except BaseException: pass raise + finally: + _transport.DEADLINE.reset(deadline_token_task) try: task_completion_fut = async_get_running_loop().create_future() except BaseException: diff --git a/tests/test_http.py b/tests/test_http.py index 6479dbcb..def1034e 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2746,7 +2746,7 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: import proofline.client as client_module import proofline._transport as transport_module from proofline._generated.models.customer_review_detail import CustomerReviewDetail -from tests.test_http import review, ORG, REVIEW +from tests.test_http import review, ORG, REVIEW, Server, Reply class ControlledClock: def __init__(self) -> None: @@ -2909,44 +2909,67 @@ async def continuing_coro(r: Any) -> None: sleep_forbidden = False # Case 3b: Return a Task from a synchronous callback, release it after the polling deadline - # and waiter exit, and assert its client request succeeds. + # and waiter exit, and assert its client request succeeds against the local test server. + task_worker_started = asyncio.Event() task_release_3b = asyncio.Event() task_success_3b = asyncio.Event() cb_task_3b: asyncio.Task[None] | None = None - async def task_worker_3b() -> None: - await task_release_3b.wait() - # Client request after polling deadline and waiter exit: - rev_res = await client.get_review(ORG, REVIEW) - assert rev_res.status == "RUNNING" - task_success_3b.set() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as test_server: + async with AsyncProoflineClient( + token="test_token", base_url=test_server.url + ) as real_client: + async def task_worker_3b() -> None: + task_worker_started.set() + await task_release_3b.wait() + # Real SDK request against the local test server checking deadline: + rev_res = await real_client.get_review(ORG, REVIEW) + assert rev_res.status == "RUNNING" + task_success_3b.set() + + def sync_cb_returning_task(r: Any) -> Any: + nonlocal cb_task_3b + cb_task_3b = asyncio.create_task(task_worker_3b()) + return cb_task_3b + + waiter_task_3b = asyncio.create_task( + real_client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=sync_cb_returning_task, + ) + ) + await task_worker_started.wait() + assert cb_task_3b is not None + assert not cb_task_3b.done() + clock.advance(1.0) + res_3b = await waiter_task_3b + assert res_3b.status == "TIMED_OUT" + assert not cb_task_3b.done() + task_release_3b.set() + await asyncio.wait_for(task_success_3b.wait(), timeout=1.0) + await cb_task_3b - def sync_cb_returning_task(r: Any) -> Any: - nonlocal cb_task_3b - cb_task_3b = asyncio.create_task(task_worker_3b()) - return cb_task_3b + # Case 4: Overdue callback continues running without cancellation on terminal review + orig_create_task_4 = client_module.async_create_task + captured_case4_wrappers: list[Any] = [] - client.get_review = fake_running # type: ignore - waiter_task_3b = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=sync_cb_returning_task, - ) - ) - await asyncio.sleep(0.01) - assert cb_task_3b is not None - assert not cb_task_3b.done() - clock.advance(1.0) - res_3b = await waiter_task_3b - assert res_3b.status == "TIMED_OUT" - assert not cb_task_3b.done() - task_release_3b.set() - await asyncio.wait_for(task_success_3b.wait(), timeout=1.0) - await cb_task_3b + def tracked_create_task_4(coro: Any, *args: Any, **kwargs: Any) -> Any: + t = orig_create_task_4(coro, *args, **kwargs) + t.exception_calls = 0 + orig_exc = t.exception + + def tracked_exc() -> Any: + t.exception_calls += 1 + return orig_exc() + + t.exception = tracked_exc + captured_case4_wrappers.append(t) + return t + + client_module.async_create_task = tracked_create_task_4 - # Case 4: Overdue callback continues running without cancellation on terminal review callback_running_term = asyncio.Event() callback_finished_term = asyncio.Event() release_callback_term = asyncio.Event() @@ -2959,23 +2982,32 @@ async def continuing_coro_term(r: Any) -> None: client.get_review = fake_completed # type: ignore - waiter_task_4 = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=0.2, - on_poll=continuing_coro_term, + try: + waiter_task_4 = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.2, + on_poll=continuing_coro_term, + ) ) - ) - await callback_running_term.wait() - assert not waiter_task_4.done() - clock.advance(1.0) - res_4 = await waiter_task_4 - assert res_4.status == "COMPLETED" - assert callback_running_term.is_set() - assert not callback_finished_term.is_set() - release_callback_term.set() - await callback_finished_term.wait() + await callback_running_term.wait() + assert not waiter_task_4.done() + clock.advance(1.0) + res_4 = await waiter_task_4 + assert res_4.status == "COMPLETED" + assert callback_running_term.is_set() + assert not callback_finished_term.is_set() + release_callback_term.set() + await callback_finished_term.wait() + await asyncio.sleep(0.01) + assert len(captured_case4_wrappers) == 1 + wrapper_4 = captured_case4_wrappers[0] + assert wrapper_4.done() + assert not wrapper_4.cancelled() + assert getattr(wrapper_4, "exception_calls", 0) > 0 + finally: + client_module.async_create_task = orig_create_task_4 # Case 5: Suspending callback that succeeds within budget resumed_within_budget = False @@ -4770,6 +4802,52 @@ def timely_fail_cb(r: Any) -> asyncio.Future[None]: except BaseException: pass + # Timely pending future failure propagates when clock advances after SDK done-callback + # but before waiter resumes + class ClockAdvancingFuture(asyncio.Future[None]): + def add_done_callback(self, fn: Any, *, context: Any = None) -> None: + super().add_done_callback(fn, context=context) + super().add_done_callback(lambda _: setattr(clock, "now", clock.now + 200.0)) + + timely_late_fut: Any = ClockAdvancingFuture(loop=asyncio.get_running_loop()) + timely_late_producer: asyncio.Task[None] | None = None + + async def fail_timely_late_soon() -> None: + await asyncio.sleep(0.01) + timely_late_fut.set_exception(ValueError("timely failure with late resumption")) + + def timely_late_fail_cb(r: Any) -> asyncio.Future[None]: + nonlocal timely_late_producer + timely_late_producer = asyncio.create_task(fail_timely_late_soon()) + return timely_late_fut + + try: + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="timely failure with late resumption"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_late_fail_cb, + ) + assert clock.now >= 200.0 + finally: + if timely_late_producer is not None: + if not timely_late_producer.done(): + timely_late_producer.cancel() + try: + await timely_late_producer + except BaseException: + pass + try: + if not asyncio.Future.done(timely_late_fut): + timely_late_fut.cancel() + elif not asyncio.Future.cancelled(timely_late_fut): + timely_late_fut.exception() + except BaseException: + pass + # Late-observed pending future failure preserves the classified outcome class TrackedFuture(asyncio.Future[None]): def __init__(self, loop: asyncio.AbstractEventLoop) -> None: From c50789f5267b4c675e2f2f9b84979bbcd0d3c91b Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 07:50:26 +0530 Subject: [PATCH 51/75] Address review run 50 findings: guard close lookup and invocation, directly await worker in case 3b, cleanup wrappers in case 4 finally, queue wrapper before cancelling in case 6b, test class-state rejection for set and buffer views, test custom hash reading deferred dict through frozenset, await waiter_coro_task whenever present in case 6, timestamp callback return for already-done futures, close fresh awaitable adapters discarded after deadline, reject frozenset subclasses with mutable class attributes, preserve layout for strided memoryviews over bytes, check backing buffer size, and collect set members in deadline-checked batches --- proofline/client.py | 275 +++++++++++++++++++++++++------------------- tests/test_http.py | 147 ++++++++++++++++++++--- 2 files changed, 288 insertions(+), 134 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 0fa6f14e..d2ba8618 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -500,6 +500,23 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non deferred_tuple_finalizations: list[tuple[Any, Any, bool, int, Any, list[Any]]] = [] deferred_set_insertions: list[tuple[Any, Any, list[Any]]] = [] + def _collect_set_members(val: Any) -> list[Any] | None: + if hasattr(val, "__len__") and len(val) > _MAX_SAFE_BUFFER_SIZE: + return None + members: list[Any] = [] + it = iter(val) + batch_count = 0 + while True: + try: + m = next(it) + except StopIteration: + break + members.append(m) + batch_count += 1 + if (batch_count & 63) == 0 and _deadline_expired(): + return None + return members + stack: list[Any] = [(_OBJ_EXPAND, root, iter(_get_obj_attrs(detail)))] while stack: @@ -667,9 +684,16 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if hasattr(val, "__dict__") or hasattr(val, "__slots__"): stack.append((_OBJ_EXPAND, new_set, iter(_get_obj_attrs(val)))) if set_len > 0: - deferred_set_insertions.append((new_set, val, list(val))) + orig_set_members = _collect_set_members(val) + if orig_set_members is None: + return None + deferred_set_insertions.append((new_set, val, orig_set_members)) stack.append((_SET_EXPAND, None, iter(val))) elif isinstance(val, frozenset): + if type(val) is not frozenset and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) fs_len = frozenset.__len__(val) if type(val) is not frozenset: try: @@ -703,8 +727,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non stack.append((_OBJ_EXPAND, res_empty_fs, iter(_get_obj_attrs(val)))) _assign_target(target, key, is_attr, res_empty_fs) else: + orig_fs_members = _collect_set_members(val) + if orig_fs_members is None: + return None deferred_frozenset_insertions.append( - (target, key, is_attr, val_id, val, list(val)) + (target, key, is_attr, val_id, val, orig_fs_members) ) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(val): @@ -774,11 +801,30 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non if val.nbytes > _MAX_SAFE_BUFFER_SIZE: return None exporter = getattr(val, "obj", None) + if exporter is not None: + try: + b_exp_check = _Py_buffer() + if _py_get_buffer(exporter, ctypes.byref(b_exp_check), 0x0118) == 0: + try: + if b_exp_check.len > _MAX_SAFE_BUFFER_SIZE: + return None + finally: + _py_release_buffer(ctypes.byref(b_exp_check)) + except BaseException: + pass + if hasattr(exporter, "__len__"): + try: + if len(exporter) > _MAX_SAFE_BUFFER_SIZE: + return None + except BaseException: + pass resolved_mv: Any - if isinstance(exporter, (bytearray, array.array)): - if type(exporter) not in (bytearray, array.array) and _has_mutable_class_attrs( - type(exporter) - ): + if isinstance(exporter, (bytearray, array.array, bytes)): + if type(exporter) not in ( + bytearray, + array.array, + bytes, + ) and _has_mutable_class_attrs(type(exporter)): raise TypeError( "Unsupported mutable value in review extension data: " f"{type(exporter).__name__}" @@ -788,14 +834,16 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non cloned_exporter = memo[exp_id] else: exp_bytes_len = ( - bytearray.__len__(exporter) - if isinstance(exporter, bytearray) + len(exporter) + if isinstance(exporter, (bytes, bytearray)) else exporter.buffer_info()[1] * exporter.itemsize ) if exp_bytes_len > _MAX_SAFE_BUFFER_SIZE: return None try: - if isinstance(exporter, bytearray): + if isinstance(exporter, bytes): + cloned_exporter = bytes(exporter) + elif isinstance(exporter, bytearray): cloned_exporter = bytearray.__new__(type(exporter)) bytearray.__init__(cloned_exporter, exporter) else: @@ -867,6 +915,11 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non f"{type(val).__name__}" ) else: + if not val.c_contiguous: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) if val.readonly: resolved_mv = memoryview(bytes(val)) else: @@ -1636,6 +1689,34 @@ async def _observe_task() -> None: pass +def _safe_close(obj: Any) -> None: + try: + closer = getattr(obj, "close", None) + if callable(closer): + closer() + except BaseException: + pass + + +def _cleanup_discarded_awaitable(res: Any, waiter_task: Any = None) -> None: + if iscoroutine(res): + try: + if getcoroutinestate(res) == CORO_CREATED: + res.close() + except BaseException: + pass + elif isgenerator(res): + try: + if getgeneratorstate(res) == GEN_CREATED: + res.close() + except BaseException: + pass + else: + _safe_close(res) + if async_isfuture(res) and (waiter_task is None or res is not waiter_task): + _detach_overdue_future(res) + + def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None: cursor = page.next_cursor if cursor is None: @@ -2043,6 +2124,7 @@ def wait_for_review( try: res_awaitable = isawaitable(res) except Exception: + _safe_close(res) raise TypeError("Callbacks must return None.") from None if res_awaitable: if iscoroutine(res): @@ -2058,23 +2140,13 @@ def wait_for_review( except Exception: pass else: - res_close = getattr(res, "close", None) - if callable(res_close): - try: - res_close() - except BaseException: - pass + _safe_close(res) raise TypeError( "on_poll returned an awaitable; use AsyncProoflineClient " "for async callbacks." ) if res is not None: - res_close = getattr(res, "close", None) - if callable(res_close): - try: - res_close() - except BaseException: - pass + _safe_close(res) raise TypeError("Callbacks must return None.") if result is not None: return result @@ -2523,6 +2595,7 @@ async def wait_for_review( res = on_poll(snapshot) finally: _transport.DEADLINE.reset(deadline_token) + cb_return_time = monotonic() if waiter_task is not None: current_cancelling = 0 try: @@ -2531,43 +2604,15 @@ async def wait_for_review( except BaseException: pass if current_cancelling > initial_cancelling: - if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: - try: - res.close() - except BaseException: - pass - elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: - try: - res.close() - except BaseException: - pass - else: - res_close = getattr(res, "close", None) - if callable(res_close): - try: - res_close() - except BaseException: - pass - elif async_isfuture(res) and res is not waiter_task: - _detach_overdue_future(res) + _cleanup_discarded_awaitable(res, waiter_task=waiter_task) raise AsyncCancelledError() try: res_awaitable = isawaitable(res) except Exception: - res_close = getattr(res, "close", None) - if callable(res_close): - try: - res_close() - except BaseException: - pass + _safe_close(res) raise TypeError("Callbacks must return None or an awaitable.") from None if res is not None and not res_awaitable: - res_close = getattr(res, "close", None) - if callable(res_close): - try: - res_close() - except BaseException: - pass + _safe_close(res) raise TypeError("Callbacks must return None or an awaitable.") if res_awaitable: if res is async_current_task(): @@ -2585,7 +2630,22 @@ async def wait_for_review( is_done = res.done() except BaseException: is_done = False - if not is_done: + if is_done: + deadline_val = _transport.DEADLINE.get() + cb_returned_in_budget = ( + deadline_val is None or cb_return_time <= deadline_val + ) + if cb_returned_in_budget: + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) + else: + _detach_overdue_future(res) + if result is not None: + return result + break + else: try: res_loop = ( res.get_loop() @@ -2605,86 +2665,65 @@ async def wait_for_review( remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: - try: - res.close() - except BaseException: - pass - elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: - try: - res.close() - except BaseException: - pass - elif async_isfuture(res): - _detach_overdue_future(res) + _cleanup_discarded_awaitable(res) if result is not None: return result break if async_isfuture(res): try: - is_done = res.done() + completion_fut = async_get_running_loop().create_future() except BaseException: - is_done = False - if is_done: - if hasattr(res, "result"): - res.result() - else: - AsyncFuture.result(res) - else: - try: - completion_fut = async_get_running_loop().create_future() - except BaseException: - _detach_overdue_future(res) - raise - completed_at: list[float] = [] + _detach_overdue_future(res) + raise + completed_at: list[float] = [] - def _on_future_done(_: Any) -> None: - completed_at.append(monotonic()) - if not completion_fut.done(): - completion_fut.set_result(None) + def _on_future_done(_: Any) -> None: + completed_at.append(monotonic()) + if not completion_fut.done(): + completion_fut.set_result(None) - fut_registered = False - if hasattr(res, "add_done_callback"): - try: - res.add_done_callback(_on_future_done) - fut_registered = True - except BaseException: - pass - if not fut_registered: - try: - AsyncFuture.add_done_callback(res, _on_future_done) - fut_registered = True - except BaseException: - _detach_overdue_future(res) - raise - remaining_budget = _transport.remaining() - if remaining_budget is not None and remaining_budget <= 0: - _detach_overdue_future(res) - if result is not None: - return result - break + fut_registered = False + if hasattr(res, "add_done_callback"): try: - done, _ = await async_wait( - {completion_fut}, timeout=remaining_budget - ) + res.add_done_callback(_on_future_done) + fut_registered = True + except BaseException: + pass + if not fut_registered: + try: + AsyncFuture.add_done_callback(res, _on_future_done) + fut_registered = True except BaseException: _detach_overdue_future(res) raise - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _detach_overdue_future(res) + if result is not None: + return result + break + try: + done, _ = await async_wait( + {completion_fut}, timeout=remaining_budget ) - if cb_finished_in_budget and completion_fut in done: - if hasattr(res, "result"): - res.result() - else: - AsyncFuture.result(res) + except BaseException: + _detach_overdue_future(res) + raise + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + if cb_finished_in_budget and completion_fut in done: + if hasattr(res, "result"): + res.result() else: - _detach_overdue_future(res) - if result is not None: - return result - break + AsyncFuture.result(res) + else: + _detach_overdue_future(res) + if result is not None: + return result + break else: coro = res completed_at = [] diff --git a/tests/test_http.py b/tests/test_http.py index def1034e..8120c5d6 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2940,16 +2940,24 @@ def sync_cb_returning_task(r: Any) -> Any: on_poll=sync_cb_returning_task, ) ) - await task_worker_started.wait() - assert cb_task_3b is not None - assert not cb_task_3b.done() - clock.advance(1.0) - res_3b = await waiter_task_3b - assert res_3b.status == "TIMED_OUT" - assert not cb_task_3b.done() - task_release_3b.set() - await asyncio.wait_for(task_success_3b.wait(), timeout=1.0) - await cb_task_3b + try: + await task_worker_started.wait() + assert cb_task_3b is not None + assert not cb_task_3b.done() + clock.advance(1.0) + res_3b = await waiter_task_3b + assert res_3b.status == "TIMED_OUT" + assert not cb_task_3b.done() + task_release_3b.set() + await asyncio.wait_for(asyncio.shield(cb_task_3b), timeout=1.0) + finally: + if cb_task_3b is not None: + if not cb_task_3b.done(): + cb_task_3b.cancel() + try: + await cb_task_3b + except (asyncio.CancelledError, BaseException): + pass # Case 4: Overdue callback continues running without cancellation on terminal review orig_create_task_4 = client_module.async_create_task @@ -3008,6 +3016,13 @@ async def continuing_coro_term(r: Any) -> None: assert getattr(wrapper_4, "exception_calls", 0) > 0 finally: client_module.async_create_task = orig_create_task_4 + for w in captured_case4_wrappers: + if not w.done(): + w.cancel() + try: + await w + except (asyncio.CancelledError, BaseException): + pass # Case 5: Suspending callback that succeeds within budget resumed_within_budget = False @@ -3085,10 +3100,14 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: wrapper_tasks: list[asyncio.Task[Any]] = [] orig_create_task = client_module.async_create_task + runner_executed = False + def holding_create_task(coro_arg: Any, **kwargs: Any) -> asyncio.Task[Any]: async def held_wrapper() -> Any: + nonlocal runner_executed try: await hold_wrapper.wait() + runner_executed = True return await coro_arg except asyncio.CancelledError: if hasattr(coro_arg, "close"): @@ -3129,13 +3148,13 @@ def pre_start_cb(r: Any) -> Any: assert len(wrapper_tasks) == 1 assert not wrapper_tasks[0].done() - # Cancel waiter with budget remaining - pre_waiter_task.cancel() - - # Run the queued runner after cancellation and before waiter cleanup + # Queue the wrapper before cancelling the waiter in the same loop turn: hold_wrapper.set() + pre_waiter_task.cancel() await asyncio.sleep(0) + assert runner_executed is True + assert not cb_body_started assert len(user_coro_created) == 1 assert inspect.getcoroutinestate(user_coro_created[0]) == inspect.CORO_CLOSED @@ -3247,8 +3266,9 @@ async def failing_overdue_coro(r: Any) -> None: pass if coro_trigger is not None: coro_trigger.set() - if waiter_coro_task is not None and not waiter_coro_task.done(): - waiter_coro_task.cancel() + if waiter_coro_task is not None: + if not waiter_coro_task.done(): + waiter_coro_task.cancel() try: await waiter_coro_task except (asyncio.CancelledError, BaseException): @@ -4724,6 +4744,101 @@ class SubclassIntArray(array.array): assert sub_arr[3] == 40 assert arr_v1[2] == 40 + # Class-state rejection for set subclass and views over bytearray and array.array subclasses + class SetWithClassList(set[Any]): + __shared_list__ = [1, 2] + + detail_set_class_list = CustomerReviewDetail.from_dict(responses[1]) + detail_set_class_list.additional_properties["set_sub"] = SetWithClassList([1, 2]) + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_set_class_list) + + class ByteArrayWithClassList(bytearray): + __shared_list__ = [1, 2] + + ba_sub_shared = ByteArrayWithClassList(b"hello") + detail_ba_view = CustomerReviewDetail.from_dict(responses[1]) + detail_ba_view.additional_properties["ba_view"] = memoryview(ba_sub_shared) + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_ba_view) + + class ArrayWithClassList(array.array): + __shared_list__ = [1, 2] + + arr_sub_shared = ArrayWithClassList("i", [1, 2, 3]) + detail_arr_view = CustomerReviewDetail.from_dict(responses[1]) + detail_arr_view.additional_properties["arr_view"] = memoryview(arr_sub_shared) + with pytest.raises(TypeError, match="Unsupported mutable value"): + _snapshot_review(detail_arr_view) + + # Key whose custom hash reads a deferred dictionary through a frozenset member + class DictHolder: + def __init__(self, d: dict[str, Any]) -> None: + self.d = d + + class CustomHashWithFrozenset: + def __init__(self, f_set: frozenset[Any]) -> None: + self.f_set = f_set + + def __hash__(self) -> int: + for item in self.f_set: + if hasattr(item, "d"): + return hash(tuple(sorted(item.d.items()))) + return 0 + + def __eq__(self, other: Any) -> bool: + return isinstance(other, CustomHashWithFrozenset) and self.f_set == other.f_set + + deferred_dict = {"ready_key": "ready_val"} + f_set = frozenset([DictHolder(deferred_dict)]) + custom_fs_obj = CustomHashWithFrozenset(f_set) + set_with_fs_custom = {custom_fs_obj} + detail_fs_custom = CustomerReviewDetail.from_dict(responses[1]) + detail_fs_custom.additional_properties["fs_custom"] = set_with_fs_custom + snap_fsc = _snapshot_review(detail_fs_custom) + assert snap_fsc is not None + copied_fsc_set = snap_fsc.additional_properties["fs_custom"] + copied_obj = next(iter(copied_fsc_set)) + copied_holder = next(iter(copied_obj.f_set)) + assert copied_holder.d == {"ready_key": "ready_val"} + assert copied_holder.d is not deferred_dict + + # Strided memoryview over immutable bytes preserves strides and c_contiguous + b_data = b"0123456789abcdef" + mv_strided = memoryview(b_data)[::2] + detail_strided = CustomerReviewDetail.from_dict(responses[1]) + detail_strided.additional_properties["strided"] = mv_strided + snap_strided = _snapshot_review(detail_strided) + assert snap_strided is not None + c_strided = snap_strided.additional_properties["strided"] + assert c_strided.strides == mv_strided.strides + assert c_strided.c_contiguous == mv_strided.c_contiguous + assert bytes(c_strided) == bytes(mv_strided) + + # 1-byte view over backing buffer > 65,536 bytes skips delivery (returns None) + big_backing = b"A" * 65537 + mv_1byte = memoryview(big_backing)[0:1] + detail_1byte = CustomerReviewDetail.from_dict(responses[1]) + detail_1byte.additional_properties["mv_1b"] = mv_1byte + assert _snapshot_review(detail_1byte) is None + + # Invalid callback return raising property on close + class RaisingCloseReturn: + @property + def close(self) -> Any: + raise RuntimeError("close property lookup failed") + + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("sync", server.url) as client_sync: + with pytest.raises(TypeError, match="Callbacks must return None"): + await call( + client_sync, + "wait_for_review", + ORG, + REVIEW, + on_poll=lambda r: RaisingCloseReturn(), + ) + async def test_wait_for_review_pending_futures_and_clock( monkeypatch: pytest.MonkeyPatch, From c786c4a6d0410e8312fc5a042816b1002efadc3c Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 08:23:43 +0530 Subject: [PATCH 52/75] Address review run 51 findings: document set/frozenset size limits in docstrings and README, include inline cancellation in mismatch exception list, retrieve completed task exception before loop check in detachment, use shared guard and cleanup discarded awaitables in all unstarted exits, check completion time before taking future timeout branch, resolve self-blocked custom-hash frozenset members, race worker startup against polling task in case 3b, capture and cancel callback task in case 3 finally, settle fixture in SyncCancelRaisingFuture teardown, and assert first snapshot head_commit_sha is UNSET --- README.md | 6 +- proofline/client.py | 261 ++++++++++++++++++++++++-------------------- tests/test_http.py | 45 +++++++- 3 files changed, 185 insertions(+), 127 deletions(-) diff --git a/README.md b/README.md index 250a1629..4d09a9d3 100644 --- a/README.md +++ b/README.md @@ -54,11 +54,11 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish or return after expiry: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish or return after expiry: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, waiter cancellation during inline callback invocation, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index d2ba8618..961726c9 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -1178,7 +1178,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: pending_frozensets: list[Any] = deferred_frozenset_insertions - def _is_member_state_populated(m_clone: Any) -> bool: + def _is_member_state_populated(m_clone: Any, current_target_id: int | None = None) -> bool: if _is_immutable(m_clone): return True if _is_identity_hashed(m_clone): @@ -1242,16 +1242,45 @@ def _is_member_state_populated(m_clone: Any) -> bool: for target, _, _, _, _, _ in deferred_tuple_finalizations: if id(target) in container_ids: + if id(target) == current_target_id: + try: + hash(m_clone) + _ = m_clone == m_clone + continue + except Exception: + return False return False for target, _, _, _, _, _ in pending_frozensets: if id(target) in container_ids: + if id(target) == current_target_id: + try: + hash(m_clone) + _ = m_clone == m_clone + continue + except Exception: + return False return False for s, _, _ in deferred_set_insertions: if id(s) in container_ids: + if id(s) == current_target_id: + try: + hash(m_clone) + _ = m_clone == m_clone + continue + except Exception: + return False return False for td_id, entries in dict_ordered_entries.items(): - if td_id in container_ids and dict_next_index[td_id] < len(entries): - return False + if td_id in container_ids: + if td_id == current_target_id: + try: + hash(m_clone) + _ = m_clone == m_clone + continue + except Exception: + return False + if dict_next_index[td_id] < len(entries): + return False return True def _flush_pending_structures() -> None: @@ -1324,7 +1353,7 @@ def _flush_pending_structures() -> None: return rm = m if _is_immutable(m) else memo[id(m)] resolved_members.append(rm) - if not _is_member_state_populated(rm): + if not _is_member_state_populated(rm, current_target_id=id(s)): members_ready = False break if not members_ready: @@ -1403,7 +1432,7 @@ def _flush_pending_structures() -> None: return None rm = m if _is_immutable(m) else memo[id(m)] resolved_members.append(rm) - if not _is_member_state_populated(rm): + if not _is_member_state_populated(rm, current_target_id=id(target)): members_ready = False break if not members_ready: @@ -1440,6 +1469,41 @@ def _flush_pending_structures() -> None: pending_frozensets = remaining_frozensets if not progress and pending_frozensets: + resolved_any = False + still_pending = [] + for target, key, is_attr, val_id, orig_val, orig_members in pending_frozensets: + can_resolve = True + resolved_members = [] + for m in orig_members: + rm = m if _is_immutable(m) else memo.get(id(m)) + if rm is None: + can_resolve = False + break + try: + hash(rm) + _ = rm == rm + except Exception: + can_resolve = False + break + resolved_members.append(rm) + if can_resolve: + if type(orig_val) is frozenset: + res_set = frozenset(resolved_members) + else: + res_set = frozenset.__new__(type(orig_val), resolved_members) + memo[val_id] = res_set + if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): + val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] + _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) + _assign_target(target, key, is_attr, res_set) + resolved_any = True + else: + still_pending.append((target, key, is_attr, val_id, orig_val, orig_members)) + if resolved_any: + pending_frozensets = still_pending + _flush_pending_structures() + continue raise TypeError("Unsupported cyclic reference in frozenset") _flush_pending_structures() @@ -1542,26 +1606,47 @@ async def _observe_fut() -> None: pass -def _detach_overdue_task( - task: Any, - res: Any = None, - wrapper_started: bool = True, -) -> None: +def _safe_close(obj: Any) -> None: try: - running_loop = async_get_running_loop() - except Exception: - running_loop = None + closer = getattr(obj, "close", None) + if callable(closer): + closer() + except BaseException: + pass - try: - loop = task.get_loop() if hasattr(task, "get_loop") else running_loop - except Exception: - loop = running_loop - if running_loop is not None and loop is not running_loop: +def _cleanup_discarded_awaitable(res: Any, waiter_task: Any = None) -> None: + if res is None: return - if loop is None or loop.is_closed(): + if getattr(res, "_proofline_cleaned_up", False): return + try: + setattr(res, "_proofline_cleaned_up", True) + except BaseException: + pass + if iscoroutine(res): + try: + if getcoroutinestate(res) == CORO_CREATED: + res.close() + except BaseException: + pass + elif isgenerator(res): + try: + if getgeneratorstate(res) == GEN_CREATED: + res.close() + except BaseException: + pass + else: + _safe_close(res) + if async_isfuture(res) and (waiter_task is None or res is not waiter_task): + _detach_overdue_future(res) + +def _detach_overdue_task( + task: Any, + res: Any = None, + wrapper_started: bool = True, +) -> None: try: is_done = task.done() if hasattr(task, "done") else False except BaseException: @@ -1579,16 +1664,22 @@ def _detach_overdue_task( task.cancel() except BaseException: pass - if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: - try: - res.close() - except BaseException: - pass - elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: - try: - res.close() - except BaseException: - pass + _cleanup_discarded_awaitable(res) + return + + try: + running_loop = async_get_running_loop() + except Exception: + running_loop = None + + try: + loop = task.get_loop() if hasattr(task, "get_loop") else running_loop + except Exception: + loop = running_loop + + if running_loop is not None and loop is not running_loop: + return + if loop is None or loop.is_closed(): return try: @@ -1677,44 +1768,7 @@ async def _observe_task() -> None: task.cancel() except BaseException: pass - if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: - try: - res.close() - except BaseException: - pass - elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: - try: - res.close() - except BaseException: - pass - - -def _safe_close(obj: Any) -> None: - try: - closer = getattr(obj, "close", None) - if callable(closer): - closer() - except BaseException: - pass - - -def _cleanup_discarded_awaitable(res: Any, waiter_task: Any = None) -> None: - if iscoroutine(res): - try: - if getcoroutinestate(res) == CORO_CREATED: - res.close() - except BaseException: - pass - elif isgenerator(res): - try: - if getgeneratorstate(res) == GEN_CREATED: - res.close() - except BaseException: - pass - else: - _safe_close(res) - if async_isfuture(res) and (waiter_task is None or res is not waiter_task): - _detach_overdue_future(res) + _cleanup_discarded_awaitable(res) def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None: @@ -2083,9 +2137,10 @@ def wait_for_review( latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or - backed by a buffer larger than 65,536 bytes), or deques with more than 65,536 items - in review extension data skip on_poll snapshot delivery even with time remaining, - and snapshot copy errors on unsupported mutable values propagate before on_poll runs. + backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with + more than 65,536 items in review extension data skip on_poll snapshot delivery even + with time remaining, and snapshot copy errors on unsupported mutable values propagate + before on_poll runs. on_poll exceptions and return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return @@ -2539,9 +2594,9 @@ async def wait_for_review( invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer - larger than 65,536 bytes), or deques with more than 65,536 items in review extension - data skip on_poll snapshot delivery even with time remaining, and snapshot copy errors - on unsupported mutable values propagate before on_poll runs. Callback + larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items + in review extension data skip on_poll snapshot delivery even with time remaining, and + snapshot copy errors on unsupported mutable values propagate before on_poll runs. Callback return-validation errors and inline exceptions propagate unconditionally, even when a terminal outcome has already been determined (cancellation requested during callback invocation takes precedence over return validation), preventing the waiter from @@ -2697,6 +2752,15 @@ def _on_future_done(_: Any) -> None: except BaseException: _detach_overdue_future(res) raise + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + if cb_finished_in_budget: + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: _detach_overdue_future(res) @@ -2756,22 +2820,7 @@ async def _runner() -> None: and monotonic() > captured_deadline ) if waiter_cancelling or deadline_expired: - if ( - iscoroutine(coro) - and getcoroutinestate(coro) == CORO_CREATED - ): - try: - coro.close() - except BaseException: - pass - elif ( - isgenerator(coro) - and getgeneratorstate(coro) == GEN_CREATED - ): - try: - coro.close() - except BaseException: - pass + _cleanup_discarded_awaitable(coro) return wrapper_started = True _transport.DEADLINE.set(None) @@ -2864,22 +2913,7 @@ def _on_task_done(t: Any) -> None: task.cancel() except BaseException: pass - if ( - iscoroutine(res) - and getcoroutinestate(res) == CORO_CREATED - ): - try: - res.close() - except BaseException: - pass - elif ( - isgenerator(res) - and getgeneratorstate(res) == GEN_CREATED - ): - try: - res.close() - except BaseException: - pass + _cleanup_discarded_awaitable(res) if hasattr(task, "result"): task.result() else: @@ -2916,22 +2950,7 @@ def _on_task_done(t: Any) -> None: task.cancel() except BaseException: pass - if ( - iscoroutine(res) - and getcoroutinestate(res) == CORO_CREATED - ): - try: - res.close() - except BaseException: - pass - elif ( - isgenerator(res) - and getgeneratorstate(res) == GEN_CREATED - ): - try: - res.close() - except BaseException: - pass + _cleanup_discarded_awaitable(res) if hasattr(task, "result"): task.result() else: diff --git a/tests/test_http.py b/tests/test_http.py index 8120c5d6..c7f9f90a 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1341,6 +1341,7 @@ async def test_wait_ends_on_the_read_that_names_another_head( assert clock.delays == [5, 10, 5, 5] assert [p[0].status for p in polled_reviews] == ["PENDING", "RUNNING"] assert [p[1] for p in polled_reviews] == [1, 2] + assert polled_reviews[0][0].head_commit_sha is UNSET assert polled_reviews[1][0].head_commit_sha == HEAD @@ -2878,6 +2879,16 @@ def completing_future_callback(r: Any) -> asyncio.Future[None]: callback_running = asyncio.Event() callback_finished = asyncio.Event() release_callback = asyncio.Event() + cb_task_3: asyncio.Task[Any] | None = None + orig_create_task_3 = client_module.async_create_task + + def tracking_create_task_3(coro_arg: Any, **kwargs: Any) -> asyncio.Task[Any]: + nonlocal cb_task_3 + t = orig_create_task_3(coro_arg, **kwargs) + cb_task_3 = t + return t + + client_module.async_create_task = tracking_create_task_3 async def continuing_coro(r: Any) -> None: callback_running.set() @@ -2906,7 +2917,16 @@ async def continuing_coro(r: Any) -> None: release_callback.set() await callback_finished.wait() finally: + client_module.async_create_task = orig_create_task_3 sleep_forbidden = False + release_callback.set() + if cb_task_3 is not None: + if not cb_task_3.done(): + cb_task_3.cancel() + try: + await cb_task_3 + except (asyncio.CancelledError, BaseException): + pass # Case 3b: Return a Task from a synchronous callback, release it after the polling deadline # and waiter exit, and assert its client request succeeds against the local test server. @@ -2940,8 +2960,14 @@ def sync_cb_returning_task(r: Any) -> Any: on_poll=sync_cb_returning_task, ) ) + startup_waiter = asyncio.create_task(task_worker_started.wait()) try: - await task_worker_started.wait() + done, _ = await asyncio.wait( + {startup_waiter, waiter_task_3b}, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task_3b in done: + await waiter_task_3b assert cb_task_3b is not None assert not cb_task_3b.done() clock.advance(1.0) @@ -2951,6 +2977,18 @@ def sync_cb_returning_task(r: Any) -> Any: task_release_3b.set() await asyncio.wait_for(asyncio.shield(cb_task_3b), timeout=1.0) finally: + if not startup_waiter.done(): + startup_waiter.cancel() + try: + await startup_waiter + except (asyncio.CancelledError, BaseException): + pass + if not waiter_task_3b.done(): + waiter_task_3b.cancel() + try: + await waiter_task_3b + except (asyncio.CancelledError, BaseException): + pass if cb_task_3b is not None: if not cb_task_3b.done(): cb_task_3b.cancel() @@ -3772,10 +3810,11 @@ async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: _transport.monotonic = orig_trans_mono finally: if fut_sync_box: + f = fut_sync_box[0] try: - f = fut_sync_box[0] if not asyncio.Future.done(f): - f.cancel() + f.set_result(None) + await asyncio.sleep(0) elif not asyncio.Future.cancelled(f): f.exception() except BaseException: From 26063ffaf1fc9c81744219aa5413951cd88bbe96 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 10:37:50 +0530 Subject: [PATCH 53/75] Address review run 52 findings: race startup wait in case 1, close unentered runner in case 6b teardown, resume normal polling after reading completed on_poll future, cleanup discarded awaitables on task creation error, preserve future close hooks, verify membership of fallback-built frozensets after deferred writes, memoize frozenset clones before attribute assignment, pass current_target_id on dict key readiness check, handle None members in frozenset fallback, reject tuple subclasses with mutable class attrs, and test frozenset custom hash with deferred dict --- proofline/client.py | 217 ++++++++++++++++++++++++++++---------------- tests/test_http.py | 88 ++++++++++++++---- 2 files changed, 209 insertions(+), 96 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 961726c9..2fa62a65 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -360,6 +360,9 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: "__static_attributes__", "__subclasshook__", "__weakref__", + "_fields", + "_field_defaults", + "_field_types", } @@ -377,6 +380,7 @@ def _has_mutable_class_attrs(cls: type) -> bool: "method_descriptor", "slotwrapper", "classmethod_descriptor", + "_tuplegetter", ): continue if isinstance( @@ -455,6 +459,7 @@ def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: _MAX_SAFE_TUPLE_SIZE = 1000 _MAX_SAFE_BUFFER_SIZE = 65_536 _UNRESOLVED_SLOT = object() +_MISSING = object() class _Py_buffer(ctypes.Structure): @@ -499,6 +504,9 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non deferred_frozenset_insertions: list[tuple[Any, Any, bool, int, Any, list[Any]]] = [] deferred_tuple_finalizations: list[tuple[Any, Any, bool, int, Any, list[Any]]] = [] deferred_set_insertions: list[tuple[Any, Any, list[Any]]] = [] + pending_frozenset_ids: set[int] = set() + pending_assignments: dict[int, list[tuple[Any, Any, bool]]] = {} + fallback_built_frozensets: list[tuple[Any, list[Any]]] = [] def _collect_set_members(val: Any) -> list[Any] | None: if hasattr(val, "__len__") and len(val) > _MAX_SAFE_BUFFER_SIZE: @@ -547,6 +555,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: if val_id in memo: _assign_target(target, key, is_attr, memo[val_id]) continue + if val_id in pending_frozenset_ids: + if target is not None: + pending_assignments.setdefault(val_id, []).append((target, key, is_attr)) + continue if type(val) is dict: new_dict: dict[Any, Any] = {} memo[val_id] = new_dict @@ -558,6 +570,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: _assign_target(target, key, is_attr, new_list) stack.append((_LIST_EXPAND, new_list, iter(val))) elif isinstance(val, tuple): + if type(val) is not tuple and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if tuple.__len__(val) > _MAX_SAFE_TUPLE_SIZE: return None if tuple.__len__(val) == 0: @@ -730,12 +746,17 @@ def _collect_set_members(val: Any) -> list[Any] | None: orig_fs_members = _collect_set_members(val) if orig_fs_members is None: return None + pending_frozenset_ids.add(val_id) deferred_frozenset_insertions.append( (target, key, is_attr, val_id, val, orig_fs_members) ) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(val): - if not _is_immutable(attr_val) and id(attr_val) not in memo: + if ( + not _is_immutable(attr_val) + and id(attr_val) not in memo + and id(attr_val) not in pending_frozenset_ids + ): stack.append((_ITEM_TASK, None, None, False, attr_val)) stack.append((_SET_EXPAND, None, iter(val))) elif isinstance(val, deque): @@ -1149,6 +1170,11 @@ def _collect_set_members(val: Any) -> list[Any] | None: if type(orig_val) is tuple: res_tuple = tuple(temp_list) else: + if _has_mutable_class_attrs(type(orig_val)): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) try: orig_cls: Any = type(orig_val) res_tuple = tuple.__new__(orig_cls, temp_list) @@ -1314,6 +1340,11 @@ def _flush_pending_structures() -> None: if type(orig_val) is tuple: res_tuple = tuple(temp_list) else: + if _has_mutable_class_attrs(type(orig_val)): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(orig_val).__name__}" + ) try: orig_tuple_cls: Any = type(orig_val) res_tuple = tuple.__new__(orig_tuple_cls, temp_list) @@ -1388,7 +1419,7 @@ def _flush_pending_structures() -> None: if k_ready and v_ready: k = orig_k if _is_immutable(orig_k) else memo[id(orig_k)] v = orig_v if _is_immutable(orig_v) else memo[id(orig_v)] - if not _is_member_state_populated(k): + if not _is_member_state_populated(k, current_target_id=td_id): break target_dict[k] = v idx += 1 @@ -1422,7 +1453,11 @@ def _flush_pending_structures() -> None: attrs_ready = True if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for _, _, attr_val in _get_obj_attrs(orig_val): - if not _is_immutable(attr_val) and id(attr_val) not in memo: + if ( + not _is_immutable(attr_val) + and id(attr_val) not in memo + and id(attr_val) != val_id + ): attrs_ready = False break if members_ready and attrs_ready: @@ -1456,11 +1491,18 @@ def _flush_pending_structures() -> None: f"{type(orig_val).__name__}" ) memo[val_id] = res_set + pending_frozenset_ids.discard(val_id) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): - val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] + val_to_set = ( + attr_val + if _is_immutable(attr_val) + else memo.get(id(attr_val), attr_val) + ) _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) _assign_target(target, key, is_attr, res_set) + for p_target, p_key, p_is_attr in pending_assignments.pop(val_id, []): + _assign_target(p_target, p_key, p_is_attr, res_set) progress = True _flush_pending_structures() else: @@ -1475,10 +1517,13 @@ def _flush_pending_structures() -> None: can_resolve = True resolved_members = [] for m in orig_members: - rm = m if _is_immutable(m) else memo.get(id(m)) - if rm is None: - can_resolve = False - break + if _is_immutable(m): + rm = m + else: + rm = memo.get(id(m), _MISSING) + if rm is _MISSING: + can_resolve = False + break try: hash(rm) _ = rm == rm @@ -1492,11 +1537,19 @@ def _flush_pending_structures() -> None: else: res_set = frozenset.__new__(type(orig_val), resolved_members) memo[val_id] = res_set + pending_frozenset_ids.discard(val_id) + fallback_built_frozensets.append((res_set, resolved_members)) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): - val_to_set = attr_val if _is_immutable(attr_val) else memo[id(attr_val)] + val_to_set = ( + attr_val + if _is_immutable(attr_val) + else memo.get(id(attr_val), attr_val) + ) _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) _assign_target(target, key, is_attr, res_set) + for p_target, p_key, p_is_attr in pending_assignments.pop(val_id, []): + _assign_target(p_target, p_key, p_is_attr, res_set) resolved_any = True else: still_pending.append((target, key, is_attr, val_id, orig_val, orig_members)) @@ -1509,6 +1562,15 @@ def _flush_pending_structures() -> None: _flush_pending_structures() if _deadline_expired(): return None + for fb_set, fb_members in fallback_built_frozensets: + try: + for rm in fb_members: + if rm not in fb_set: + raise TypeError("Member lookup failed in fallback frozenset") + except TypeError: + raise + except Exception as exc: + raise TypeError("Member lookup failed in fallback frozenset") from exc if deferred_set_insertions: raise TypeError("Unsupported cyclic reference in set") for td_id, entries in dict_ordered_entries.items(): @@ -1636,10 +1698,11 @@ def _cleanup_discarded_awaitable(res: Any, waiter_task: Any = None) -> None: res.close() except BaseException: pass + elif async_isfuture(res): + if waiter_task is None or res is not waiter_task: + _detach_overdue_future(res) else: _safe_close(res) - if async_isfuture(res) and (waiter_task is None or res is not waiter_task): - _detach_overdue_future(res) def _detach_overdue_task( @@ -2718,77 +2781,82 @@ async def wait_for_review( "to the running event loop." ) - remaining_budget = _transport.remaining() - if remaining_budget is not None and remaining_budget <= 0: - _cleanup_discarded_awaitable(res) - if result is not None: - return result - break - - if async_isfuture(res): - try: - completion_fut = async_get_running_loop().create_future() - except BaseException: - _detach_overdue_future(res) - raise - completed_at: list[float] = [] - - def _on_future_done(_: Any) -> None: - completed_at.append(monotonic()) - if not completion_fut.done(): - completion_fut.set_result(None) + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _detach_overdue_future(res) + if result is not None: + return result + break - fut_registered = False - if hasattr(res, "add_done_callback"): try: - res.add_done_callback(_on_future_done) - fut_registered = True + completion_fut = async_get_running_loop().create_future() except BaseException: - pass - if not fut_registered: + _detach_overdue_future(res) + raise + completed_at: list[float] = [] + + def _on_future_done(_: Any) -> None: + completed_at.append(monotonic()) + if not completion_fut.done(): + completion_fut.set_result(None) + + fut_registered = False + if hasattr(res, "add_done_callback"): + try: + res.add_done_callback(_on_future_done) + fut_registered = True + except BaseException: + pass + if not fut_registered: + try: + AsyncFuture.add_done_callback(res, _on_future_done) + fut_registered = True + except BaseException: + _detach_overdue_future(res) + raise + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + if cb_finished_in_budget: + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _detach_overdue_future(res) + if result is not None: + return result + break try: - AsyncFuture.add_done_callback(res, _on_future_done) - fut_registered = True + done, _ = await async_wait( + {completion_fut}, timeout=remaining_budget + ) except BaseException: _detach_overdue_future(res) raise - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val - ) - if cb_finished_in_budget: - if hasattr(res, "result"): - res.result() + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + if cb_finished_in_budget and completion_fut in done: + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) else: - AsyncFuture.result(res) + _detach_overdue_future(res) + if result is not None: + return result + break + else: remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - _detach_overdue_future(res) - if result is not None: - return result - break - try: - done, _ = await async_wait( - {completion_fut}, timeout=remaining_budget - ) - except BaseException: - _detach_overdue_future(res) - raise - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val - ) - if cb_finished_in_budget and completion_fut in done: - if hasattr(res, "result"): - res.result() - else: - AsyncFuture.result(res) - else: - _detach_overdue_future(res) + _cleanup_discarded_awaitable(res) if result is not None: return result break - else: coro = res completed_at = [] wrapper_started = False @@ -2843,16 +2911,7 @@ async def _runner() -> None: runner_coro.close() except BaseException: pass - if iscoroutine(res) and getcoroutinestate(res) == CORO_CREATED: - try: - res.close() - except BaseException: - pass - elif isgenerator(res) and getgeneratorstate(res) == GEN_CREATED: - try: - res.close() - except BaseException: - pass + _cleanup_discarded_awaitable(res) raise finally: _transport.DEADLINE.reset(deadline_token_task) diff --git a/tests/test_http.py b/tests/test_http.py index c7f9f90a..58676a04 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2819,20 +2819,56 @@ def pending_future_callback(r: Any) -> SignallingFuture: on_poll=pending_future_callback, ) ) - await cb_1_started.wait() - assert pending_fut is not None - await pending_fut.wait_entered.wait() - assert not waiter_task_1.done() - assert id(pending_fut) not in client_module._DETACHED_FUTURES - clock.advance(1.0) - res_1 = await waiter_task_1 - assert res_1.status == "TIMED_OUT" - assert not pending_fut.cancelled() - assert not pending_fut.done() - assert id(pending_fut) in client_module._DETACHED_FUTURES - pending_fut.set_result(None) - await asyncio.sleep(0) - assert id(pending_fut) not in client_module._DETACHED_FUTURES + startup_waiter_1 = asyncio.create_task(cb_1_started.wait()) + try: + done_1, _ = await asyncio.wait( + {startup_waiter_1, waiter_task_1}, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task_1 in done_1: + await waiter_task_1 + assert pending_fut is not None + wait_entered_task_1 = asyncio.create_task(pending_fut.wait_entered.wait()) + try: + done_entered, _ = await asyncio.wait( + {wait_entered_task_1, waiter_task_1}, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task_1 in done_entered: + await waiter_task_1 + assert not waiter_task_1.done() + assert id(pending_fut) not in client_module._DETACHED_FUTURES + clock.advance(1.0) + res_1 = await waiter_task_1 + assert res_1.status == "TIMED_OUT" + assert not pending_fut.cancelled() + assert not pending_fut.done() + assert id(pending_fut) in client_module._DETACHED_FUTURES + pending_fut.set_result(None) + await asyncio.sleep(0) + assert id(pending_fut) not in client_module._DETACHED_FUTURES + finally: + if not wait_entered_task_1.done(): + wait_entered_task_1.cancel() + try: + await wait_entered_task_1 + except (asyncio.CancelledError, BaseException): + pass + finally: + if not startup_waiter_1.done(): + startup_waiter_1.cancel() + try: + await startup_waiter_1 + except (asyncio.CancelledError, BaseException): + pass + if not waiter_task_1.done(): + waiter_task_1.cancel() + try: + await waiter_task_1 + except (asyncio.CancelledError, BaseException): + pass + if pending_fut is not None and not pending_fut.done(): + pending_fut.set_result(None) # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() @@ -3139,8 +3175,11 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: orig_create_task = client_module.async_create_task runner_executed = False + captured_runners: list[Any] = [] def holding_create_task(coro_arg: Any, **kwargs: Any) -> asyncio.Task[Any]: + captured_runners.append(coro_arg) + async def held_wrapper() -> Any: nonlocal runner_executed try: @@ -3225,6 +3264,17 @@ def pre_start_cb(r: Any) -> Any: c.close() except BaseException: pass + for cr in captured_runners: + try: + if ( + inspect.iscoroutine(cr) + and inspect.getcoroutinestate(cr) == inspect.CORO_CREATED + ): + cr.close() + elif hasattr(cr, "close"): + cr.close() + except BaseException: + pass # Coroutine callback cancelled after startup coro_started = asyncio.Event() @@ -4822,14 +4872,15 @@ def __init__(self, f_set: frozenset[Any]) -> None: def __hash__(self) -> int: for item in self.f_set: if hasattr(item, "d"): - return hash(tuple(sorted(item.d.items()))) + return hash(tuple(sorted((k, str(type(v))) for k, v in item.d.items()))) return 0 def __eq__(self, other: Any) -> bool: return isinstance(other, CustomHashWithFrozenset) and self.f_set == other.f_set - deferred_dict = {"ready_key": "ready_val"} + deferred_dict: dict[str, Any] = {"ready_key": "ready_val"} f_set = frozenset([DictHolder(deferred_dict)]) + deferred_dict["pending_val"] = f_set custom_fs_obj = CustomHashWithFrozenset(f_set) set_with_fs_custom = {custom_fs_obj} detail_fs_custom = CustomerReviewDetail.from_dict(responses[1]) @@ -4837,9 +4888,12 @@ def __eq__(self, other: Any) -> bool: snap_fsc = _snapshot_review(detail_fs_custom) assert snap_fsc is not None copied_fsc_set = snap_fsc.additional_properties["fs_custom"] + assert len(copied_fsc_set) == 1 copied_obj = next(iter(copied_fsc_set)) + assert copied_obj in copied_fsc_set copied_holder = next(iter(copied_obj.f_set)) - assert copied_holder.d == {"ready_key": "ready_val"} + assert copied_holder.d["ready_key"] == "ready_val" + assert copied_holder.d["pending_val"] is copied_obj.f_set assert copied_holder.d is not deferred_dict # Strided memoryview over immutable bytes preserves strides and c_contiguous From a775d5ebd1c78b77fb70d0547b43a40ced9d9d7d Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 10:52:53 +0530 Subject: [PATCH 54/75] Address review run 53 findings: guard cleanup marker lookup and use external tracking, detach futures before marker check, hold strong references to detached futures, omit close on invalid non-awaitable returns, reject mutable class attrs on datetime subclasses and custom tzinfo, defer unresolved attribute assignments in frozensets, reapply strides to empty memoryviews, preserve bytes exporter subclasses, race startup waits in cases 3 and 7, suspend async mutating callback before edits, and let overdue coroutine fail before waiter processes completion in case 4 --- proofline/client.py | 88 ++++++++++++++++++++++++++++++++------------- tests/test_http.py | 71 ++++++++++++++++++++++++++++-------- 2 files changed, 121 insertions(+), 38 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 2fa62a65..7299e639 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -507,6 +507,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non pending_frozenset_ids: set[int] = set() pending_assignments: dict[int, list[tuple[Any, Any, bool]]] = {} fallback_built_frozensets: list[tuple[Any, list[Any]]] = [] + deferred_attr_assignments: list[tuple[Any, tuple[Any, bool], Any]] = [] def _collect_set_members(val: Any) -> list[Any] | None: if hasattr(val, "__len__") and len(val) > _MAX_SAFE_BUFFER_SIZE: @@ -863,7 +864,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: return None try: if isinstance(exporter, bytes): - cloned_exporter = bytes(exporter) + if type(exporter) is bytes: + cloned_exporter = bytes(exporter) + else: + cloned_exporter = bytes.__new__(type(exporter), exporter) elif isinstance(exporter, bytearray): cloned_exporter = bytearray.__new__(type(exporter)) bytearray.__init__(cloned_exporter, exporter) @@ -909,7 +913,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: stride = val_strides[0] elem_stride = stride // itemsize if shape == 0: - resolved_mv = cast(Any, base_bytes[0:0]).cast(val.format) + casted = cast(Any, base_bytes[0:0]).cast(val.format) + resolved_mv = casted[::elem_stride] elif stride >= 0: byte_len = (shape - 1) * stride + itemsize byte_slice = base_bytes[offset : offset + byte_len] @@ -960,9 +965,18 @@ def _collect_set_members(val: Any) -> list[Any] | None: memo[val_id] = resolved_mv _assign_target(target, key, is_attr, resolved_mv) elif isinstance(val, datetime.datetime): + if type(val) is not datetime.datetime and _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) tz = val.tzinfo copied_tz = tz if tz is not None and type(tz) is not datetime.timezone: + if _has_mutable_class_attrs(type(tz)): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(tz).__name__}" + ) if id(tz) in memo: copied_tz = memo[id(tz)] else: @@ -1310,7 +1324,7 @@ def _is_member_state_populated(m_clone: Any, current_target_id: int | None = Non return True def _flush_pending_structures() -> None: - nonlocal deferred_tuple_finalizations, deferred_set_insertions + nonlocal deferred_tuple_finalizations, deferred_set_insertions, deferred_attr_assignments changed = True while changed: if _deadline_expired(): @@ -1428,6 +1442,17 @@ def _flush_pending_structures() -> None: break dict_next_index[td_id] = idx + if deferred_attr_assignments: + still_attrs = [] + for res_obj, key_desc, orig_attr in deferred_attr_assignments: + if _is_immutable(orig_attr) or id(orig_attr) in memo: + val_to_set = orig_attr if _is_immutable(orig_attr) else memo[id(orig_attr)] + _assign_target(res_obj, key_desc, True, val_to_set) + changed = True + else: + still_attrs.append((res_obj, key_desc, orig_attr)) + deferred_attr_assignments = still_attrs + _flush_pending_structures() if _deadline_expired(): return None @@ -1494,12 +1519,16 @@ def _flush_pending_structures() -> None: pending_frozenset_ids.discard(val_id) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): - val_to_set = ( - attr_val - if _is_immutable(attr_val) - else memo.get(id(attr_val), attr_val) - ) - _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) + if _is_immutable(attr_val): + _assign_target(res_set, (slot_or_name, is_desc), True, attr_val) + elif id(attr_val) in memo: + _assign_target( + res_set, (slot_or_name, is_desc), True, memo[id(attr_val)] + ) + else: + deferred_attr_assignments.append( + (res_set, (slot_or_name, is_desc), attr_val) + ) _assign_target(target, key, is_attr, res_set) for p_target, p_key, p_is_attr in pending_assignments.pop(val_id, []): _assign_target(p_target, p_key, p_is_attr, res_set) @@ -1541,12 +1570,16 @@ def _flush_pending_structures() -> None: fallback_built_frozensets.append((res_set, resolved_members)) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): - val_to_set = ( - attr_val - if _is_immutable(attr_val) - else memo.get(id(attr_val), attr_val) - ) - _assign_target(res_set, (slot_or_name, is_desc), True, val_to_set) + if _is_immutable(attr_val): + _assign_target(res_set, (slot_or_name, is_desc), True, attr_val) + elif id(attr_val) in memo: + _assign_target( + res_set, (slot_or_name, is_desc), True, memo[id(attr_val)] + ) + else: + deferred_attr_assignments.append( + (res_set, (slot_or_name, is_desc), attr_val) + ) _assign_target(target, key, is_attr, res_set) for p_target, p_key, p_is_attr in pending_assignments.pop(val_id, []): _assign_target(p_target, p_key, p_is_attr, res_set) @@ -1578,11 +1611,14 @@ def _flush_pending_structures() -> None: raise TypeError("Unsupported cyclic reference in dict") if deferred_tuple_finalizations: raise TypeError("Unsupported cyclic reference in tuple") + if deferred_attr_assignments: + raise TypeError("Unsupported cyclic reference in attributes") return root _DETACHED_TASKS: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() -_DETACHED_FUTURES: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() +_DETACHED_FUTURES: dict[int, Any] = {} +_CLEANED_UP_AWAITABLES: set[int] = set() def _safe_cancel_target(target: Any) -> None: @@ -1680,8 +1716,19 @@ def _safe_close(obj: Any) -> None: def _cleanup_discarded_awaitable(res: Any, waiter_task: Any = None) -> None: if res is None: return - if getattr(res, "_proofline_cleaned_up", False): + if async_isfuture(res): + if waiter_task is None or res is not waiter_task: + _detach_overdue_future(res) + return + res_id = id(res) + if res_id in _CLEANED_UP_AWAITABLES: return + try: + if getattr(res, "_proofline_cleaned_up", False): + return + except BaseException: + pass + _CLEANED_UP_AWAITABLES.add(res_id) try: setattr(res, "_proofline_cleaned_up", True) except BaseException: @@ -1698,9 +1745,6 @@ def _cleanup_discarded_awaitable(res: Any, waiter_task: Any = None) -> None: res.close() except BaseException: pass - elif async_isfuture(res): - if waiter_task is None or res is not waiter_task: - _detach_overdue_future(res) else: _safe_close(res) @@ -2242,7 +2286,6 @@ def wait_for_review( try: res_awaitable = isawaitable(res) except Exception: - _safe_close(res) raise TypeError("Callbacks must return None.") from None if res_awaitable: if iscoroutine(res): @@ -2264,7 +2307,6 @@ def wait_for_review( "for async callbacks." ) if res is not None: - _safe_close(res) raise TypeError("Callbacks must return None.") if result is not None: return result @@ -2727,10 +2769,8 @@ async def wait_for_review( try: res_awaitable = isawaitable(res) except Exception: - _safe_close(res) raise TypeError("Callbacks must return None or an awaitable.") from None if res is not None and not res_awaitable: - _safe_close(res) raise TypeError("Callbacks must return None or an awaitable.") if res_awaitable: if res is async_current_task(): diff --git a/tests/test_http.py b/tests/test_http.py index 58676a04..d969df09 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2943,15 +2943,29 @@ async def continuing_coro(r: Any) -> None: on_poll=continuing_coro, ) ) - await callback_running.wait() - assert not waiter_task_3.done() - clock.advance(1.0) - res_3 = await waiter_task_3 - assert res_3.status == "TIMED_OUT" - assert callback_running.is_set() - assert not callback_finished.is_set() - release_callback.set() - await callback_finished.wait() + startup_waiter_3 = asyncio.create_task(callback_running.wait()) + try: + done_3, _ = await asyncio.wait( + {startup_waiter_3, waiter_task_3}, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task_3 in done_3: + await waiter_task_3 + assert not waiter_task_3.done() + clock.advance(1.0) + res_3 = await waiter_task_3 + assert res_3.status == "TIMED_OUT" + assert callback_running.is_set() + assert not callback_finished.is_set() + release_callback.set() + await callback_finished.wait() + finally: + if not startup_waiter_3.done(): + startup_waiter_3.cancel() + try: + await startup_waiter_3 + except (asyncio.CancelledError, BaseException): + pass finally: client_module.async_create_task = orig_create_task_3 sleep_forbidden = False @@ -3073,15 +3087,29 @@ async def continuing_coro_term(r: Any) -> None: on_poll=continuing_coro_term, ) ) - await callback_running_term.wait() + startup_waiter_4 = asyncio.create_task(callback_running_term.wait()) + try: + done_4, _ = await asyncio.wait( + {startup_waiter_4, waiter_task_4}, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task_4 in done_4: + await waiter_task_4 + finally: + if not startup_waiter_4.done(): + startup_waiter_4.cancel() + try: + await startup_waiter_4 + except (asyncio.CancelledError, BaseException): + pass assert not waiter_task_4.done() clock.advance(1.0) + release_callback_term.set() + await callback_finished_term.wait() res_4 = await waiter_task_4 assert res_4.status == "COMPLETED" assert callback_running_term.is_set() - assert not callback_finished_term.is_set() - release_callback_term.set() - await callback_finished_term.wait() + assert callback_finished_term.is_set() await asyncio.sleep(0.01) assert len(captured_case4_wrappers) == 1 wrapper_4 = captured_case4_wrappers[0] @@ -3401,7 +3429,21 @@ async def awaiting_runner_callback(r: Any) -> None: on_poll=awaiting_runner_callback, ) ) - await cb_7_started.wait() + startup_waiter_7 = asyncio.create_task(cb_7_started.wait()) + try: + done_7, _ = await asyncio.wait( + {startup_waiter_7, polling_waiter_task}, + return_when=asyncio.FIRST_COMPLETED, + ) + if polling_waiter_task in done_7: + await polling_waiter_task + finally: + if not startup_waiter_7.done(): + startup_waiter_7.cancel() + try: + await startup_waiter_7 + except (asyncio.CancelledError, BaseException): + pass assert not polling_waiter_task.done() clock.advance(1.0) res_7 = await polling_waiter_task @@ -3436,6 +3478,7 @@ def sync_mutating_callback(r: Any) -> None: async def async_mutating_callback(r: Any) -> None: nonlocal mutated_count mutated_count += 1 + await asyncio.sleep(0.01) r.status = "MUTATED" r.actions.publish = True r.additional_properties["mutated"] = "mutated_value" From 47c73c093f66904de8e7746f2c2e053e447e3ed8 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 11:16:19 +0530 Subject: [PATCH 55/75] Address review run 54 findings: fix custom awaitable closing, set length checks, memoryview strides and buffer sharing, and race condition test coverage --- proofline/client.py | 108 ++++++++++++++------ tests/test_http.py | 243 ++++++++++++++++++++++++++++++++------------ 2 files changed, 252 insertions(+), 99 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 7299e639..28238b43 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -510,7 +510,13 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non deferred_attr_assignments: list[tuple[Any, tuple[Any, bool], Any]] = [] def _collect_set_members(val: Any) -> list[Any] | None: - if hasattr(val, "__len__") and len(val) > _MAX_SAFE_BUFFER_SIZE: + if isinstance(val, set): + if set.__len__(val) > _MAX_SAFE_BUFFER_SIZE: + return None + elif isinstance(val, frozenset): + if frozenset.__len__(val) > _MAX_SAFE_BUFFER_SIZE: + return None + elif hasattr(val, "__len__") and len(val) > _MAX_SAFE_BUFFER_SIZE: return None members: list[Any] = [] it = iter(val) @@ -521,6 +527,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: except StopIteration: break members.append(m) + if len(members) > _MAX_SAFE_BUFFER_SIZE: + return None batch_count += 1 if (batch_count & 63) == 0 and _deadline_expired(): return None @@ -946,20 +954,59 @@ def _collect_set_members(val: Any) -> list[Any] | None: "Unsupported mutable value in review extension data: " f"{type(val).__name__}" ) - if val.readonly: - resolved_mv = memoryview(bytes(val)) - else: - resolved_mv = memoryview(bytearray(val)) - if val.ndim == 0: - resolved_mv = cast(Any, resolved_mv).cast(val.format, shape=()) - elif val.format != "B" or (val.ndim > 1 and val.shape != resolved_mv.shape): + if exporter is not None: + exp_id = id(exporter) + if exp_id in memo: + cloned_buf = memo[exp_id] + else: + if val.readonly: + cloned_buf = bytes(exporter) + else: + cloned_buf = bytearray(exporter) + memo[exp_id] = cloned_buf + offset = 0 try: + b_val = _Py_buffer() + b_exp = _Py_buffer() + if _py_get_buffer(val, ctypes.byref(b_val), 0x0118) == 0: + try: + if _py_get_buffer(exporter, ctypes.byref(b_exp), 0x0118) == 0: + try: + offset = b_val.buf - b_exp.buf + finally: + _py_release_buffer(ctypes.byref(b_exp)) + finally: + _py_release_buffer(ctypes.byref(b_val)) + except BaseException: + pass + resolved_mv = memoryview(cloned_buf)[offset : offset + val.nbytes] + else: + if val.readonly: + resolved_mv = memoryview(bytes(val)) + else: + resolved_mv = memoryview(bytearray(val)) + val_strides = val.strides + val_shape = val.shape + try: + if val.ndim == 1 and val_shape is not None and val_strides is not None: + shape = val_shape[0] + itemsize = val.itemsize + stride = val_strides[0] + elem_stride = stride // itemsize if itemsize > 0 else 1 + if shape == 0: + casted = cast(Any, resolved_mv).cast(val.format) + resolved_mv = casted[::elem_stride] + elif val.format != "B": + resolved_mv = cast(Any, resolved_mv).cast(val.format) + elif val.ndim == 0: + resolved_mv = cast(Any, resolved_mv).cast(val.format, shape=()) + elif val.format != "B" or (val.ndim > 1 and val.shape != resolved_mv.shape): resolved_mv = cast(Any, resolved_mv).cast(val.format, shape=val.shape) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc if val.readonly: resolved_mv = resolved_mv.toreadonly() memo[val_id] = resolved_mv @@ -1618,7 +1665,6 @@ def _flush_pending_structures() -> None: _DETACHED_TASKS: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() _DETACHED_FUTURES: dict[int, Any] = {} -_CLEANED_UP_AWAITABLES: set[int] = set() def _safe_cancel_target(target: Any) -> None: @@ -1720,33 +1766,27 @@ def _cleanup_discarded_awaitable(res: Any, waiter_task: Any = None) -> None: if waiter_task is None or res is not waiter_task: _detach_overdue_future(res) return - res_id = id(res) - if res_id in _CLEANED_UP_AWAITABLES: - return - try: - if getattr(res, "_proofline_cleaned_up", False): - return - except BaseException: - pass - _CLEANED_UP_AWAITABLES.add(res_id) - try: - setattr(res, "_proofline_cleaned_up", True) - except BaseException: - pass if iscoroutine(res): try: if getcoroutinestate(res) == CORO_CREATED: res.close() except BaseException: pass - elif isgenerator(res): + return + if isgenerator(res): try: if getgeneratorstate(res) == GEN_CREATED: res.close() except BaseException: pass - else: - _safe_close(res) + return + try: + if getattr(res, "_proofline_cleaned_up", False): + return + setattr(res, "_proofline_cleaned_up", True) + except BaseException: + pass + _safe_close(res) def _detach_overdue_task( @@ -2300,8 +2340,6 @@ def wait_for_review( res.close() except Exception: pass - else: - _safe_close(res) raise TypeError( "on_poll returned an awaitable; use AsyncProoflineClient " "for async callbacks." @@ -2764,7 +2802,11 @@ async def wait_for_review( except BaseException: pass if current_cancelling > initial_cancelling: - _cleanup_discarded_awaitable(res, waiter_task=waiter_task) + try: + if isawaitable(res): + _cleanup_discarded_awaitable(res, waiter_task=waiter_task) + except Exception: + pass raise AsyncCancelledError() try: res_awaitable = isawaitable(res) diff --git a/tests/test_http.py b/tests/test_http.py index d969df09..b541822a 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2967,6 +2967,12 @@ async def continuing_coro(r: Any) -> None: except (asyncio.CancelledError, BaseException): pass finally: + if not waiter_task_3.done(): + waiter_task_3.cancel() + try: + await waiter_task_3 + except (asyncio.CancelledError, BaseException): + pass client_module.async_create_task = orig_create_task_3 sleep_forbidden = False release_callback.set() @@ -3117,6 +3123,12 @@ async def continuing_coro_term(r: Any) -> None: assert not wrapper_4.cancelled() assert getattr(wrapper_4, "exception_calls", 0) > 0 finally: + if not waiter_task_4.done(): + waiter_task_4.cancel() + try: + await waiter_task_4 + except (asyncio.CancelledError, BaseException): + pass client_module.async_create_task = orig_create_task_4 for w in captured_case4_wrappers: if not w.done(): @@ -3156,32 +3168,56 @@ async def suspending_callback(r: Any) -> None: orig_create_task_6: Any = None captured_case6_wrappers: list[asyncio.Task[Any]] = [] try: - # 6a: Future callback cancelled after startup - failing_fut = loop.create_future() - future_started = asyncio.Event() + waiter_fut_task: asyncio.Task[Any] | None = None + try: + # 6a: Future callback cancelled after startup + failing_fut = loop.create_future() + future_started = asyncio.Event() - def failing_future_cb(r: Any) -> asyncio.Future[None]: - future_started.set() - assert failing_fut is not None - return failing_fut + def failing_future_cb(r: Any) -> asyncio.Future[None]: + future_started.set() + assert failing_fut is not None + return failing_fut - client.get_review = fake_running # type: ignore - waiter_fut_task = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=10.0, - on_poll=failing_future_cb, + client.get_review = fake_running # type: ignore + waiter_fut_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=10.0, + on_poll=failing_future_cb, + ) ) - ) - await future_started.wait() - waiter_fut_task.cancel() - cancelled_fut = False - try: - await waiter_fut_task - except asyncio.CancelledError: - cancelled_fut = True - assert cancelled_fut + startup_waiter_6a = asyncio.create_task(future_started.wait()) + try: + done_6a, _ = await asyncio.wait( + {startup_waiter_6a, waiter_fut_task}, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_fut_task in done_6a: + await waiter_fut_task + finally: + if not startup_waiter_6a.done(): + startup_waiter_6a.cancel() + try: + await startup_waiter_6a + except (asyncio.CancelledError, BaseException): + pass + waiter_fut_task.cancel() + cancelled_fut = False + try: + await waiter_fut_task + except asyncio.CancelledError: + cancelled_fut = True + assert cancelled_fut + finally: + if waiter_fut_task is not None and not waiter_fut_task.done(): + waiter_fut_task.cancel() + if waiter_fut_task is not None: + try: + await waiter_fut_task + except (asyncio.CancelledError, BaseException): + pass assert id(failing_fut) in client_module._DETACHED_FUTURES failing_fut.set_exception(RuntimeError("error in cancelled future callback")) @@ -3304,50 +3340,74 @@ def pre_start_cb(r: Any) -> Any: except BaseException: pass - # Coroutine callback cancelled after startup - coro_started = asyncio.Event() - coro_trigger = asyncio.Event() - about_to_raise = asyncio.Event() - captured_case6_wrappers.clear() - orig_create_task_6 = client_module.async_create_task - - def tracked_create_task_6(coro: Any, *args: Any, **kwargs: Any) -> Any: - t = orig_create_task_6(coro, *args, **kwargs) - t.exception_calls = 0 - orig_exc = t.exception - - def tracked_exc() -> Any: - t.exception_calls += 1 - return orig_exc() - - t.exception = tracked_exc - captured_case6_wrappers.append(t) - return t - - client_module.async_create_task = tracked_create_task_6 - - async def failing_overdue_coro(r: Any) -> None: - coro_started.set() - await coro_trigger.wait() - about_to_raise.set() - raise RuntimeError("error in overdue callback") - - waiter_coro_task = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=10.0, - on_poll=failing_overdue_coro, - ) - ) - await coro_started.wait() - waiter_coro_task.cancel() - cancelled_coro = False + waiter_coro_task: asyncio.Task[Any] | None = None try: - await waiter_coro_task - except asyncio.CancelledError: - cancelled_coro = True - assert cancelled_coro + # Coroutine callback cancelled after startup + coro_started = asyncio.Event() + coro_trigger = asyncio.Event() + about_to_raise = asyncio.Event() + captured_case6_wrappers.clear() + orig_create_task_6 = client_module.async_create_task + + def tracked_create_task_6(coro: Any, *args: Any, **kwargs: Any) -> Any: + t = orig_create_task_6(coro, *args, **kwargs) + t.exception_calls = 0 + orig_exc = t.exception + + def tracked_exc() -> Any: + t.exception_calls += 1 + return orig_exc() + + t.exception = tracked_exc + captured_case6_wrappers.append(t) + return t + + client_module.async_create_task = tracked_create_task_6 + + async def failing_overdue_coro(r: Any) -> None: + coro_started.set() + await coro_trigger.wait() + about_to_raise.set() + raise RuntimeError("error in overdue callback") + + waiter_coro_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=10.0, + on_poll=failing_overdue_coro, + ) + ) + startup_waiter_6c = asyncio.create_task(coro_started.wait()) + try: + done_6c, _ = await asyncio.wait( + {startup_waiter_6c, waiter_coro_task}, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_coro_task in done_6c: + await waiter_coro_task + finally: + if not startup_waiter_6c.done(): + startup_waiter_6c.cancel() + try: + await startup_waiter_6c + except (asyncio.CancelledError, BaseException): + pass + waiter_coro_task.cancel() + cancelled_coro = False + try: + await waiter_coro_task + except asyncio.CancelledError: + cancelled_coro = True + assert cancelled_coro + finally: + if waiter_coro_task is not None and not waiter_coro_task.done(): + waiter_coro_task.cancel() + if waiter_coro_task is not None: + try: + await waiter_coro_task + except (asyncio.CancelledError, BaseException): + pass assert len(client_module._DETACHED_TASKS) == 1 detached_task_id = next(iter(client_module._DETACHED_TASKS.keys())) @@ -3451,6 +3511,13 @@ async def awaiting_runner_callback(r: Any) -> None: await asyncio.wait_for(callback_completed_7.wait(), timeout=1.0) finally: sleep_forbidden = False + if polling_waiter_task is not None and not polling_waiter_task.done(): + polling_waiter_task.cancel() + if polling_waiter_task is not None: + try: + await polling_waiter_task + except (asyncio.CancelledError, BaseException): + pass asyncio.run(main()) """ @@ -4951,6 +5018,15 @@ def __eq__(self, other: Any) -> bool: assert c_strided.c_contiguous == mv_strided.c_contiguous assert bytes(c_strided) == bytes(mv_strided) + # Empty strided memoryview over immutable bytes preserves strides + mv_empty_strided = memoryview(b_data)[0:0:2] + detail_empty_strided = CustomerReviewDetail.from_dict(responses[1]) + detail_empty_strided.additional_properties["empty_strided"] = mv_empty_strided + snap_empty_strided = _snapshot_review(detail_empty_strided) + assert snap_empty_strided is not None + c_empty_strided = snap_empty_strided.additional_properties["empty_strided"] + assert c_empty_strided.strides == mv_empty_strided.strides + # 1-byte view over backing buffer > 65,536 bytes skips delivery (returns None) big_backing = b"A" * 65537 mv_1byte = memoryview(big_backing)[0:1] @@ -5099,6 +5175,41 @@ def timely_late_fail_cb(r: Any) -> asyncio.Future[None]: except BaseException: pass + # Timely coroutine failure propagates when clock advances after coroutine raises + # but before wrapper done-callback runs or waiter resumes + orig_create_task_timely = client_module.async_create_task + + def advancing_create_task(coro_arg: Any, **kwargs: Any) -> asyncio.Task[Any]: + t = orig_create_task_timely(coro_arg, **kwargs) + orig_add_done = t.add_done_callback + + def wrapped_add_done(fn: Any, *, context: Any = None) -> None: + def advancing_fn(task_arg: Any) -> None: + clock.now += 200.0 + fn(task_arg) + + orig_add_done(advancing_fn, context=context) + + t.add_done_callback = wrapped_add_done + return t + + monkeypatch.setattr(client_module, "async_create_task", advancing_create_task) + + async def timely_fail_coro(r: Any) -> None: + raise ValueError("timely coroutine failure") + + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(ValueError, match="timely coroutine failure"): + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_fail_coro, + ) + assert clock.now >= 200.0 + monkeypatch.setattr(client_module, "async_create_task", orig_create_task_timely) + # Late-observed pending future failure preserves the classified outcome class TrackedFuture(asyncio.Future[None]): def __init__(self, loop: asyncio.AbstractEventLoop) -> None: From 85e914d32283caf1ef2662cb26c7935497d0c0ba Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 11:35:18 +0530 Subject: [PATCH 56/75] Address review run 55 findings: native array size check, memoryview exporter mutability sharing, loop-scoped detached futures cleanup, and catch late system exceptions in runner --- proofline/client.py | 102 ++++++++++++++++++++++++++++++++---- tests/test_http.py | 125 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 213 insertions(+), 14 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 28238b43..e3feeb2e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -815,8 +815,28 @@ def _collect_set_members(val: Any) -> list[Any] | None: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) - if val.buffer_info()[1] * val.itemsize > _MAX_SAFE_BUFFER_SIZE: - return None + native_len: int | None = None + try: + b_arr = _Py_buffer() + if _py_get_buffer(val, ctypes.byref(b_arr), 0x0118) == 0: + try: + native_len = b_arr.len + finally: + _py_release_buffer(ctypes.byref(b_arr)) + except BaseException: + pass + if native_len is not None: + if native_len > _MAX_SAFE_BUFFER_SIZE: + return None + else: + try: + arr_byte_count = array.array.buffer_info(val)[ + 1 + ] * array.array.itemsize.__get__(val) + except BaseException: + arr_byte_count = val.buffer_info()[1] * val.itemsize + if arr_byte_count > _MAX_SAFE_BUFFER_SIZE: + return None try: resolved_arr = cast(Any, array.array).__new__(type(val), val.typecode, val) except Exception as exc: @@ -959,7 +979,23 @@ def _collect_set_members(val: Any) -> list[Any] | None: if exp_id in memo: cloned_buf = memo[exp_id] else: - if val.readonly: + exp_readonly = False + try: + b_exp_chk = _Py_buffer() + if _py_get_buffer(exporter, ctypes.byref(b_exp_chk), 0x0118) == 0: + try: + exp_readonly = bool(b_exp_chk.readonly) + finally: + _py_release_buffer(ctypes.byref(b_exp_chk)) + else: + exp_readonly = getattr( + exporter, "readonly", False + ) or isinstance(exporter, (bytes, tuple)) + except BaseException: + exp_readonly = getattr(exporter, "readonly", False) or isinstance( + exporter, (bytes, tuple) + ) + if exp_readonly: cloned_buf = bytes(exporter) else: cloned_buf = bytearray(exporter) @@ -1702,13 +1738,53 @@ def _detach_overdue_future(fut: Any) -> None: if loop is not running_loop or loop.is_closed(): return fut_id = id(fut) + loop_futures = getattr(loop, "_proofline_detached_futures", None) + if loop_futures is None: + loop_futures = {} + try: + setattr(loop, "_proofline_detached_futures", loop_futures) + except Exception: + pass + if loop_futures is not None: + loop_futures[fut_id] = fut + try: _DETACHED_FUTURES[fut_id] = fut except (TypeError, BaseException): pass + if not getattr(loop, "_proofline_close_hooked", False): + orig_loop_close = loop.close + + def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: + l_futs = getattr(loop, "_proofline_detached_futures", None) + if l_futs is not None: + for fid in list(l_futs.keys()): + _DETACHED_FUTURES.pop(fid, None) + l_futs.clear() + for fid, f in list(_DETACHED_FUTURES.items()): + f_loop = None + try: + f_loop = f.get_loop() if hasattr(f, "get_loop") else AsyncFuture.get_loop(f) + except BaseException: + f_loop = getattr(f, "_loop", None) + if f_loop is loop: + _DETACHED_FUTURES.pop(fid, None) + return orig_loop_close(*args, **kwargs) + + try: + loop.close = _hooked_loop_close # type: ignore[method-assign] + setattr(loop, "_proofline_close_hooked", True) + except BaseException: + pass + def _on_detached_fut_done(t: Any) -> None: _DETACHED_FUTURES.pop(fut_id, None) + if loop is not None: + l_futs = getattr(loop, "_proofline_detached_futures", None) + if l_futs is not None: + l_futs.pop(fut_id, None) + l_futs.pop(id(t), None) try: is_canc = t.cancelled() if hasattr(t, "cancelled") else False if not is_canc: @@ -2944,7 +3020,7 @@ def _on_future_done(_: Any) -> None: wrapper_started = False captured_deadline = _transport.DEADLINE.get() - async def _runner() -> None: + async def _runner() -> Any: nonlocal wrapper_started waiter_cancelling = False if waiter_task is not None: @@ -2971,14 +3047,18 @@ async def _runner() -> None: ) if waiter_cancelling or deadline_expired: _cleanup_discarded_awaitable(coro) - return + return None wrapper_started = True _transport.DEADLINE.set(None) + handback_exc: BaseException | None = None try: assert coro is not None await coro + except (SystemExit, KeyboardInterrupt) as exc: + handback_exc = exc finally: completed_at.append(monotonic()) + return handback_exc runner_coro = _runner() deadline_token_task = _transport.DEADLINE.set(None) @@ -3056,9 +3136,11 @@ def _on_task_done(t: Any) -> None: pass _cleanup_discarded_awaitable(res) if hasattr(task, "result"): - task.result() + res_val = task.result() else: - AsyncTask.result(task) + res_val = AsyncTask.result(task) + if isinstance(res_val, (SystemExit, KeyboardInterrupt)): + raise res_val remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: @@ -3093,9 +3175,11 @@ def _on_task_done(t: Any) -> None: pass _cleanup_discarded_awaitable(res) if hasattr(task, "result"): - task.result() + res_val = task.result() else: - AsyncTask.result(task) + res_val = AsyncTask.result(task) + if isinstance(res_val, (SystemExit, KeyboardInterrupt)): + raise res_val else: _detach_overdue_task(task, res, wrapper_started) if result is not None: diff --git a/tests/test_http.py b/tests/test_http.py index b541822a..5b403411 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2958,7 +2958,26 @@ async def continuing_coro(r: Any) -> None: assert callback_running.is_set() assert not callback_finished.is_set() release_callback.set() - await callback_finished.wait() + assert cb_task_3 is not None + finish_waiter_3 = asyncio.create_task(callback_finished.wait()) + try: + done_fin_3, _ = await asyncio.wait( + {finish_waiter_3, cb_task_3}, + return_when=asyncio.FIRST_COMPLETED, + ) + if cb_task_3.cancelled(): + pytest.fail("Callback wrapper task was cancelled unexpectedly") + if not callback_finished.is_set(): + if cb_task_3.done() and cb_task_3.exception(): + raise cb_task_3.exception() + pytest.fail("Callback wrapper exited without setting completion event") + finally: + if not finish_waiter_3.done(): + finish_waiter_3.cancel() + try: + await finish_waiter_3 + except (asyncio.CancelledError, BaseException): + pass finally: if not startup_waiter_3.done(): startup_waiter_3.cancel() @@ -3111,14 +3130,32 @@ async def continuing_coro_term(r: Any) -> None: assert not waiter_task_4.done() clock.advance(1.0) release_callback_term.set() - await callback_finished_term.wait() + assert len(captured_case4_wrappers) == 1 + wrapper_4 = captured_case4_wrappers[0] + finish_waiter_4 = asyncio.create_task(callback_finished_term.wait()) + try: + done_fin_4, _ = await asyncio.wait( + {finish_waiter_4, wrapper_4}, + return_when=asyncio.FIRST_COMPLETED, + ) + if wrapper_4.cancelled(): + pytest.fail("Callback wrapper task was cancelled unexpectedly") + if not callback_finished_term.is_set(): + if wrapper_4.done() and wrapper_4.exception(): + raise wrapper_4.exception() + pytest.fail("Callback wrapper exited without setting completion event") + finally: + if not finish_waiter_4.done(): + finish_waiter_4.cancel() + try: + await finish_waiter_4 + except (asyncio.CancelledError, BaseException): + pass res_4 = await waiter_task_4 assert res_4.status == "COMPLETED" assert callback_running_term.is_set() assert callback_finished_term.is_set() await asyncio.sleep(0.01) - assert len(captured_case4_wrappers) == 1 - wrapper_4 = captured_case4_wrappers[0] assert wrapper_4.done() assert not wrapper_4.cancelled() assert getattr(wrapper_4, "exception_calls", 0) > 0 @@ -3523,7 +3560,9 @@ async def awaiting_runner_callback(r: Any) -> None: """ checkout_root = Path(__file__).resolve().parent.parent subprocess.run( - [sys.executable, "-c", watchdog_code], + [sys.executable, "-"], + input=watchdog_code, + text=True, cwd=str(checkout_root), check=True, timeout=10, @@ -5034,6 +5073,33 @@ def __eq__(self, other: Any) -> bool: detail_1byte.additional_properties["mv_1b"] = mv_1byte assert _snapshot_review(detail_1byte) is None + # Array subclass overriding buffer_info to underreport size skips delivery + class UnderreportingArray(array.array): + def buffer_info(self) -> tuple[int, int]: + return (0, 0) + + big_arr = UnderreportingArray("B", [0] * 65537) + detail_arr_underreport = CustomerReviewDetail.from_dict(responses[1]) + detail_arr_underreport.additional_properties["arr_under"] = big_arr + assert _snapshot_review(detail_arr_underreport) is None + + # Read-only view visited first over writable bytearray exporter followed by writable view + shared_exp = bytearray(b"0123456789") + ro_view = memoryview(shared_exp).toreadonly() + rw_view = memoryview(shared_exp) + detail_sibling_views = CustomerReviewDetail.from_dict(responses[1]) + detail_sibling_views.additional_properties["ro_first"] = ro_view + detail_sibling_views.additional_properties["rw_second"] = rw_view + snap_siblings = _snapshot_review(detail_sibling_views) + assert snap_siblings is not None + copied_ro = snap_siblings.additional_properties["ro_first"] + copied_rw = snap_siblings.additional_properties["rw_second"] + assert copied_ro.readonly is True + assert copied_rw.readonly is False + copied_rw[0] = ord(b"Z") + assert copied_ro[0] == ord(b"Z") + assert shared_exp[0] == ord(b"0") + # Invalid callback return raising property on close class RaisingCloseReturn: @property @@ -5283,3 +5349,52 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: except BaseException: pass loop.set_exception_handler(old_h) + + # Late SystemExit inside callback wrapper is suppressed after deadline + async def late_system_exit_coro(r: Any) -> None: + await asyncio.sleep(0.01) + raise SystemExit(42) + + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + res_exit = await client.wait_for_review( + ORG, + REVIEW, + timeout=0.01, + on_poll=late_system_exit_coro, + ) + assert res_exit.status == "TIMED_OUT" + + # In-budget SystemExit inside callback wrapper propagates + async def in_budget_system_exit_coro(r: Any) -> None: + raise SystemExit(42) + + with Server(lambda request, index: Reply(body=responses[0])) as server: + async with session("async", server.url) as client: + with pytest.raises(SystemExit) as exc_info: + await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=in_budget_system_exit_coro, + ) + assert exc_info.value.code == 42 + + # Closing loop releases strong retention from _DETACHED_FUTURES + def test_loop_close_in_thread() -> None: + t_loop = asyncio.new_event_loop() + try: + asyncio.set_event_loop(t_loop) + t_fut = t_loop.create_future() + + async def run_in_t() -> None: + client_module._detach_overdue_future(t_fut) + + t_loop.run_until_complete(run_in_t()) + assert id(t_fut) in client_module._DETACHED_FUTURES + finally: + t_loop.close() + asyncio.set_event_loop(None) + assert id(t_fut) not in client_module._DETACHED_FUTURES + + await asyncio.to_thread(test_loop_close_in_thread) From 25277b85c72a2ed1bff38d0d735d0cade1109266 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 11:48:03 +0530 Subject: [PATCH 57/75] Address review run 56 findings: track seen identities in _is_immutable, check bytes subclass length, use native byte counts for memoryview exporter, loop-scoped detached futures fallback, check cancellation before callback return validation, and improve mismatch and overdue test coverage --- proofline/client.py | 121 +++++++++++++++++++++++++++++--------------- tests/test_http.py | 77 ++++++++++++++++++++++++++-- 2 files changed, 151 insertions(+), 47 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index e3feeb2e..b8faa80f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -317,6 +317,12 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: return True if isinstance(val, type): return val in _SAFE_BUILTIN_CLASSES + if seen is None: + seen = set() + val_id = id(val) + if val_id in seen: + return False + seen.add(val_id) if hasattr(val, "__self__") and not _is_immutable(val.__self__, seen): return False t = type(val) @@ -862,12 +868,6 @@ def _collect_set_members(val: Any) -> list[Any] | None: _py_release_buffer(ctypes.byref(b_exp_check)) except BaseException: pass - if hasattr(exporter, "__len__"): - try: - if len(exporter) > _MAX_SAFE_BUFFER_SIZE: - return None - except BaseException: - pass resolved_mv: Any if isinstance(exporter, (bytearray, array.array, bytes)): if type(exporter) not in ( @@ -883,13 +883,30 @@ def _collect_set_members(val: Any) -> list[Any] | None: if exp_id in memo: cloned_exporter = memo[exp_id] else: - exp_bytes_len = ( - len(exporter) - if isinstance(exporter, (bytes, bytearray)) - else exporter.buffer_info()[1] * exporter.itemsize - ) - if exp_bytes_len > _MAX_SAFE_BUFFER_SIZE: - return None + exp_native_len: int | None = None + try: + b_chk2 = _Py_buffer() + if _py_get_buffer(exporter, ctypes.byref(b_chk2), 0x0118) == 0: + try: + exp_native_len = b_chk2.len + finally: + _py_release_buffer(ctypes.byref(b_chk2)) + except BaseException: + pass + if exp_native_len is not None: + if exp_native_len > _MAX_SAFE_BUFFER_SIZE: + return None + else: + if isinstance(exporter, bytearray): + exp_bytes_len = bytearray.__len__(exporter) + elif isinstance(exporter, bytes): + exp_bytes_len = bytes.__len__(exporter) + else: + exp_bytes_len = array.array.buffer_info(exporter)[ + 1 + ] * array.array.itemsize.__get__(exporter) + if exp_bytes_len > _MAX_SAFE_BUFFER_SIZE: + return None try: if isinstance(exporter, bytes): if type(exporter) is bytes: @@ -1127,6 +1144,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: if isinstance(val, str): new_obj = str.__new__(type(val), val) elif isinstance(val, bytes): + if bytes.__len__(val) > _MAX_SAFE_BUFFER_SIZE: + return None new_obj = bytes.__new__(type(val), val) elif isinstance(val, int): new_obj = int.__new__(type(val), val) @@ -1748,34 +1767,39 @@ def _detach_overdue_future(fut: Any) -> None: if loop_futures is not None: loop_futures[fut_id] = fut - try: - _DETACHED_FUTURES[fut_id] = fut - except (TypeError, BaseException): - pass - - if not getattr(loop, "_proofline_close_hooked", False): - orig_loop_close = loop.close - - def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: - l_futs = getattr(loop, "_proofline_detached_futures", None) - if l_futs is not None: - for fid in list(l_futs.keys()): - _DETACHED_FUTURES.pop(fid, None) - l_futs.clear() - for fid, f in list(_DETACHED_FUTURES.items()): - f_loop = None - try: - f_loop = f.get_loop() if hasattr(f, "get_loop") else AsyncFuture.get_loop(f) - except BaseException: - f_loop = getattr(f, "_loop", None) - if f_loop is loop: - _DETACHED_FUTURES.pop(fid, None) - return orig_loop_close(*args, **kwargs) - + hook_installed = getattr(loop, "_proofline_close_hooked", False) + if not hook_installed: try: + orig_loop_close = loop.close + + def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: + l_futs = getattr(loop, "_proofline_detached_futures", None) + if l_futs is not None: + for fid in list(l_futs.keys()): + _DETACHED_FUTURES.pop(fid, None) + l_futs.clear() + for fid, f in list(_DETACHED_FUTURES.items()): + f_loop = None + try: + f_loop = ( + f.get_loop() if hasattr(f, "get_loop") else AsyncFuture.get_loop(f) + ) + except BaseException: + f_loop = getattr(f, "_loop", None) + if f_loop is loop: + _DETACHED_FUTURES.pop(fid, None) + return orig_loop_close(*args, **kwargs) + loop.close = _hooked_loop_close # type: ignore[method-assign] setattr(loop, "_proofline_close_hooked", True) + hook_installed = True except BaseException: + hook_installed = False + + if hook_installed: + try: + _DETACHED_FUTURES[fut_id] = fut + except (TypeError, BaseException): pass def _on_detached_fut_done(t: Any) -> None: @@ -2831,7 +2855,8 @@ async def wait_for_review( cancelled, unstarted coroutines returned by on_poll are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and futures are detached without cancellation and may continue - running. Synchronous callbacks must return before a terminal result can be + running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not + suppressed). Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: @@ -2871,13 +2896,25 @@ async def wait_for_review( _transport.DEADLINE.reset(deadline_token) cb_return_time = monotonic() if waiter_task is not None: - current_cancelling = 0 + is_task_cancelled = False try: - if hasattr(waiter_task, "cancelling"): - current_cancelling = waiter_task.cancelling() + if ( + hasattr(waiter_task, "cancelling") + and waiter_task.cancelling() > initial_cancelling + ): + is_task_cancelled = True + elif ( + hasattr(waiter_task, "cancelling") + and waiter_task.cancelling() > 0 + ): + is_task_cancelled = True + elif hasattr(waiter_task, "cancelled") and waiter_task.cancelled(): + is_task_cancelled = True + elif getattr(waiter_task, "_must_cancel", False): + is_task_cancelled = True except BaseException: pass - if current_cancelling > initial_cancelling: + if is_task_cancelled: try: if isawaitable(res): _cleanup_discarded_awaitable(res, waiter_task=waiter_task) diff --git a/tests/test_http.py b/tests/test_http.py index 5b403411..e1dbc2d0 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1317,11 +1317,19 @@ async def test_wait_ends_on_the_read_that_names_another_head( # Mismatch with on_poll also ends on the read that names another head (2 requests) with Server(lambda request, index: Reply(body=responses[index])) as server: polled_reviews: list[tuple[Any, int]] = [] - cb = ( - (lambda r: polled_reviews.append((r, len(server.requests)))) - if mode == "sync" - else (lambda r: polled_reviews.append((r, len(server.requests)))) - ) + if mode == "async": + + async def async_mismatch_cb(r: Any) -> None: + await asyncio.sleep(0.01) + polled_reviews.append((r, len(server.requests))) + + cb: Any = async_mismatch_cb + else: + + def sync_mismatch_cb(r: Any) -> None: + polled_reviews.append((r, len(server.requests))) + + cb = sync_mismatch_cb async with session(mode, server.url) as client: result = await call( client, @@ -5350,6 +5358,65 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: pass loop.set_exception_handler(old_h) + # Overdue pending future failure where failure occurs after deadline + late_failing_fut: TrackedFuture | None = TrackedFuture(loop=asyncio.get_running_loop()) + late_failing_fut_ref = weakref.ref(late_failing_fut) + late_failing_producer: asyncio.Task[None] | None = None + + async def fail_after_deadline() -> None: + await asyncio.sleep(0) + clock.now += 200.0 + if late_failing_fut is not None: + late_failing_fut.set_exception(ValueError("failure after deadline")) + + def late_failing_cb(r: Any) -> asyncio.Future[None]: + nonlocal late_failing_producer + late_failing_producer = asyncio.create_task(fail_after_deadline()) + assert late_failing_fut is not None + return late_failing_fut + + unhandled_after_reports: list[dict[str, Any]] = [] + loop.set_exception_handler(lambda _loop, ctx: unhandled_after_reports.append(ctx)) + try: + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_after = await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=late_failing_cb, + ) + assert res_after.status == "COMPLETED" + assert late_failing_fut is not None + assert late_failing_fut.done() + assert clock.now >= 200.0 + if late_failing_producer is not None: + await late_failing_producer + await asyncio.sleep(0) + assert late_failing_fut.exception_retrieved is True + assert id(late_failing_fut) not in client_module._DETACHED_FUTURES + late_failing_fut = None + gc.collect() + assert late_failing_fut_ref() is None + assert unhandled_after_reports == [] + finally: + if late_failing_producer is not None: + if not late_failing_producer.done(): + late_failing_producer.cancel() + try: + await late_failing_producer + except (asyncio.CancelledError, BaseException): + pass + if late_failing_fut is not None: + if not late_failing_fut.done(): + late_failing_fut.cancel() + elif not late_failing_fut.cancelled(): + try: + late_failing_fut.exception() + except BaseException: + pass + loop.set_exception_handler(old_h) + # Late SystemExit inside callback wrapper is suppressed after deadline async def late_system_exit_coro(r: Any) -> None: await asyncio.sleep(0.01) From 32a033bdc94fb2a767401b3710b04955e27e3b86 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 12:06:26 +0530 Subject: [PATCH 58/75] Address review run 57 findings: iterative __self__ walk in _is_immutable, exact bytes size check, unhookable loop test, loop close store clearing order, bytes subclass native buffer reconstruction, baseline cancellation comparison, and documentation clarifications --- README.md | 4 +- proofline/client.py | 104 ++++++++++++++++++++++++++------------------ tests/test_http.py | 59 +++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 4d09a9d3..1c877b52 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish or return after expiry: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish or return after expiry: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not suppressed; waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, waiter cancellation during inline callback invocation, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index b8faa80f..da26000a 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -312,28 +312,42 @@ def _is_identity_hashed(obj: Any) -> bool: return False +def _deadline_expired() -> bool: + budget = _transport.remaining() + return budget is not None and budget <= 0 + + def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: - if val is None or val is UNSET: + curr = val + local_seen = seen if seen is not None else set() + while hasattr(curr, "__self__"): + curr_id = id(curr) + if curr_id in local_seen: + return False + local_seen.add(curr_id) + if _deadline_expired(): + return False + try: + curr = curr.__self__ + except BaseException: + return False + + if curr is None or curr is UNSET: return True - if isinstance(val, type): - return val in _SAFE_BUILTIN_CLASSES - if seen is None: - seen = set() - val_id = id(val) - if val_id in seen: - return False - seen.add(val_id) - if hasattr(val, "__self__") and not _is_immutable(val.__self__, seen): + if isinstance(curr, type): + return curr in _SAFE_BUILTIN_CLASSES + curr_id = id(curr) + if curr_id in local_seen: return False - t = type(val) + t = type(curr) if t in _IMMUTABLE_TYPES: return True - if isinstance(val, BuiltinFunctionType): - return not bool(getattr(val, "__dict__", None)) - if isinstance(val, (FunctionType, MethodType)): + if isinstance(curr, BuiltinFunctionType): + return not bool(getattr(curr, "__dict__", None)) + if isinstance(curr, (FunctionType, MethodType)): return False if t is datetime.datetime: - tz = val.tzinfo + tz = curr.tzinfo return tz is None or type(tz) is datetime.timezone return False @@ -493,11 +507,6 @@ class _Py_buffer(ctypes.Structure): _py_release_buffer.argtypes = [ctypes.POINTER(_Py_buffer)] -def _deadline_expired() -> bool: - budget = _transport.remaining() - return budget is not None and budget <= 0 - - def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | None: if _deadline_expired(): return None @@ -564,6 +573,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: f"Unsupported mutable value in review extension data: {type(val).__name__}" ) if _is_immutable(val): + if type(val) is bytes and len(val) > _MAX_SAFE_BUFFER_SIZE: + return None _assign_target(target, key, is_attr, val) continue val_id = id(val) @@ -1144,9 +1155,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: if isinstance(val, str): new_obj = str.__new__(type(val), val) elif isinstance(val, bytes): - if bytes.__len__(val) > _MAX_SAFE_BUFFER_SIZE: + raw_bytes = bytes(memoryview(val)) + if len(raw_bytes) > _MAX_SAFE_BUFFER_SIZE: return None - new_obj = bytes.__new__(type(val), val) + new_obj = bytes.__new__(type(val), raw_bytes) elif isinstance(val, int): new_obj = int.__new__(type(val), val) elif isinstance(val, float): @@ -1172,6 +1184,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: k, v = next(it) except StopIteration: break + if (type(k) is bytes and len(k) > _MAX_SAFE_BUFFER_SIZE) or ( + type(v) is bytes and len(v) > _MAX_SAFE_BUFFER_SIZE + ): + return None deferred_dict_insertions.append((target_dict, k, v)) k_needed = not _is_immutable(k) and id(k) not in memo v_needed = not _is_immutable(v) and id(v) not in memo @@ -1192,6 +1208,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: m = next(it) except StopIteration: break + if type(m) is bytes and len(m) > _MAX_SAFE_BUFFER_SIZE: + return None if not _is_immutable(m) and id(m) not in memo: stack.append((_SET_EXPAND, None, it)) stack.append((_ITEM_TASK, None, 0, False, m)) @@ -1209,6 +1227,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: v = next(it) except StopIteration: break + if type(v) is bytes and len(v) > _MAX_SAFE_BUFFER_SIZE: + return None if _is_immutable(v): app_fn(target_list, v) elif id(v) in memo: @@ -1229,6 +1249,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: slot_or_name, is_desc, attr_val = next(it) except StopIteration: break + if type(attr_val) is bytes and len(attr_val) > _MAX_SAFE_BUFFER_SIZE: + return None if _is_immutable(attr_val): _assign_target(new_obj, (slot_or_name, is_desc), True, attr_val) elif id(attr_val) in memo: @@ -1773,6 +1795,7 @@ def _detach_overdue_future(fut: Any) -> None: orig_loop_close = loop.close def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: + close_res = orig_loop_close(*args, **kwargs) l_futs = getattr(loop, "_proofline_detached_futures", None) if l_futs is not None: for fid in list(l_futs.keys()): @@ -1788,7 +1811,7 @@ def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: f_loop = getattr(f, "_loop", None) if f_loop is loop: _DETACHED_FUTURES.pop(fid, None) - return orig_loop_close(*args, **kwargs) + return close_res loop.close = _hooked_loop_close # type: ignore[method-assign] setattr(loop, "_proofline_close_hooked", True) @@ -2383,11 +2406,11 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. Oversized tuples, buffers, memoryviews with more than 65,536 bytes (or - backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with - more than 65,536 items in review extension data skip on_poll snapshot delivery even - with time remaining, and snapshot copy errors on unsupported mutable values propagate - before on_poll runs. + delivery. Tuples with more than 1,000 items, mutable buffers or memoryviews with + more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, + frozensets, or deques with more than 65,536 items in review extension data skip + on_poll snapshot delivery even with time remaining, and snapshot copy errors on + unsupported mutable values propagate before on_poll runs. on_poll exceptions and return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return @@ -2835,11 +2858,12 @@ async def wait_for_review( ValueError). Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback - is reached are delivered; deadline expiry can suppress delivery. Oversized - tuples, buffers, memoryviews with more than 65,536 bytes (or backed by a buffer - larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items - in review extension data skip on_poll snapshot delivery even with time remaining, and - snapshot copy errors on unsupported mutable values propagate before on_poll runs. Callback + is reached are delivered; deadline expiry can suppress delivery. Tuples + with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes + (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with + more than 65,536 items in review extension data skip on_poll snapshot delivery even + with time remaining, and snapshot copy errors on unsupported mutable values propagate + before on_poll runs. Callback return-validation errors and inline exceptions propagate unconditionally, even when a terminal outcome has already been determined (cancellation requested during callback invocation takes precedence over return validation), preventing the waiter from @@ -2898,16 +2922,10 @@ async def wait_for_review( if waiter_task is not None: is_task_cancelled = False try: - if ( - hasattr(waiter_task, "cancelling") - and waiter_task.cancelling() > initial_cancelling - ): - is_task_cancelled = True - elif ( - hasattr(waiter_task, "cancelling") - and waiter_task.cancelling() > 0 - ): - is_task_cancelled = True + if hasattr(waiter_task, "cancelling"): + is_task_cancelled = ( + waiter_task.cancelling() > initial_cancelling + ) elif hasattr(waiter_task, "cancelled") and waiter_task.cancelled(): is_task_cancelled = True elif getattr(waiter_task, "_must_cancel", False): diff --git a/tests/test_http.py b/tests/test_http.py index e1dbc2d0..1a93bce4 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -5108,6 +5108,40 @@ def buffer_info(self) -> tuple[int, int]: assert copied_ro[0] == ord(b"Z") assert shared_exp[0] == ord(b"0") + # Exact bytes over 65,536 bytes skips delivery (returns None) + detail_big_bytes = CustomerReviewDetail.from_dict(responses[1]) + detail_big_bytes.additional_properties["big_bytes"] = b"A" * 65537 + assert _snapshot_review(detail_big_bytes) is None + + # Bytes subclass whose __bytes__ tries to expand payload beyond native buffer + class CustomBytesWithExpansion(bytes): + def __bytes__(self) -> bytes: + return b"Z" * 70000 + + small_sub_bytes = CustomBytesWithExpansion(b"small_sub") + small_sub_bytes.custom_tag = "tag" # type: ignore[attr-defined] + detail_sub_bytes = CustomerReviewDetail.from_dict(responses[1]) + detail_sub_bytes.additional_properties["sub_bytes"] = small_sub_bytes + snap_sub_bytes = _snapshot_review(detail_sub_bytes) + assert snap_sub_bytes is not None + copied_sub_bytes = snap_sub_bytes.additional_properties["sub_bytes"] + assert type(copied_sub_bytes) is CustomBytesWithExpansion + assert len(copied_sub_bytes) == len(b"small_sub") + assert memoryview(copied_sub_bytes).tobytes() == b"small_sub" + assert copied_sub_bytes.custom_tag == "tag" + + # Deep __self__ chain (exceeding standard recursion limit) walks iteratively + class DeepSelfChain: + pass + + curr_obj = DeepSelfChain() + for _ in range(1500): + prev = curr_obj + curr_obj = DeepSelfChain() + curr_obj.__self__ = prev # type: ignore[attr-defined] + + assert client_module._is_immutable(curr_obj) is False + # Invalid callback return raising property on close class RaisingCloseReturn: @property @@ -5464,4 +5498,29 @@ async def run_in_t() -> None: asyncio.set_event_loop(None) assert id(t_fut) not in client_module._DETACHED_FUTURES + # Loop that rejects assignment to close: assert future never enters _DETACHED_FUTURES + u_loop = asyncio.new_event_loop() + + class UnhookableLoopType(type(u_loop)): # type: ignore[misc] + @property + def close(self) -> Any: + return super().close + + u_loop.__class__ = UnhookableLoopType + try: + asyncio.set_event_loop(u_loop) + u_fut = u_loop.create_future() + + async def run_in_u() -> None: + client_module._detach_overdue_future(u_fut) + + u_loop.run_until_complete(run_in_u()) + assert id(u_fut) not in client_module._DETACHED_FUTURES + loop_futs = getattr(u_loop, "_proofline_detached_futures", {}) + assert loop_futs.get(id(u_fut)) is u_fut + finally: + UnhookableLoopType.close.fget(u_loop)() # type: ignore[attr-defined] + asyncio.set_event_loop(None) + assert id(u_fut) not in client_module._DETACHED_FUTURES + await asyncio.to_thread(test_loop_close_in_thread) From 6e61d392aa046e9faa374ad4614de7a07971705c Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 12:25:22 +0530 Subject: [PATCH 59/75] Address review run 58 findings: callable-only __self__ inspection, tuple bytes length bound, bytes subclass memoryview exporter fallback, dictionary key lookup validation, natural pending cancellation delivery, and detached task loop close cleanup --- proofline/client.py | 168 ++++++++++++++++++++++++++++---------------- tests/test_http.py | 52 ++++++++++++-- 2 files changed, 153 insertions(+), 67 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index da26000a..35490c46 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -55,6 +55,7 @@ FunctionType, MemberDescriptorType, MethodType, + ModuleType, TracebackType, ) from typing import Any, Self, TypedDict, TypeVar, Unpack, cast @@ -318,37 +319,48 @@ def _deadline_expired() -> bool: def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: - curr = val - local_seen = seen if seen is not None else set() - while hasattr(curr, "__self__"): - curr_id = id(curr) - if curr_id in local_seen: - return False - local_seen.add(curr_id) - if _deadline_expired(): - return False - try: - curr = curr.__self__ - except BaseException: - return False - - if curr is None or curr is UNSET: + if val is None or val is UNSET: return True - if isinstance(curr, type): - return curr in _SAFE_BUILTIN_CLASSES - curr_id = id(curr) - if curr_id in local_seen: - return False - t = type(curr) + if isinstance(val, type): + return val in _SAFE_BUILTIN_CLASSES + t = type(val) if t in _IMMUTABLE_TYPES: return True - if isinstance(curr, BuiltinFunctionType): - return not bool(getattr(curr, "__dict__", None)) - if isinstance(curr, (FunctionType, MethodType)): - return False if t is datetime.datetime: - tz = curr.tzinfo + tz = val.tzinfo return tz is None or type(tz) is datetime.timezone + if isinstance(val, (FunctionType, MethodType)): + return False + if isinstance(val, BuiltinFunctionType): + if bool(getattr(val, "__dict__", None)): + return False + curr = getattr(val, "__self__", None) + if curr is None: + return True + if isinstance(curr, ModuleType): + return True + if isinstance(curr, type): + return curr in _SAFE_BUILTIN_CLASSES or curr is object + local_seen = seen if seen is not None else set() + val_id = id(val) + if val_id in local_seen: + return False + local_seen.add(val_id) + while curr is not None and isinstance(curr, (BuiltinFunctionType, MethodType)): + curr_id = id(curr) + if curr_id in local_seen: + return False + local_seen.add(curr_id) + if _deadline_expired(): + return False + curr = getattr(curr, "__self__", None) + if curr is None: + return True + if isinstance(curr, ModuleType): + return True + if isinstance(curr, type): + return curr in _SAFE_BUILTIN_CLASSES or curr is object + return _is_immutable(curr, local_seen) return False @@ -923,7 +935,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: if type(exporter) is bytes: cloned_exporter = bytes(exporter) else: - cloned_exporter = bytes.__new__(type(exporter), exporter) + raw_exp = bytes(memoryview(exporter)) + if len(raw_exp) > _MAX_SAFE_BUFFER_SIZE: + return None + cloned_exporter = bytes.__new__(type(exporter), raw_exp) elif isinstance(exporter, bytearray): cloned_exporter = bytearray.__new__(type(exporter)) bytearray.__init__(cloned_exporter, exporter) @@ -1269,6 +1284,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: v = next(it) except StopIteration: break + if type(v) is bytes and len(v) > _MAX_SAFE_BUFFER_SIZE: + return None if _is_immutable(v): temp_list.append(v) elif id(v) in memo: @@ -1733,6 +1750,16 @@ def _flush_pending_structures() -> None: for td_id, entries in dict_ordered_entries.items(): if dict_next_index[td_id] < len(entries): raise TypeError("Unsupported cyclic reference in dict") + target_dict = dict_targets[td_id] + for orig_k, _ in entries: + if _deadline_expired(): + return None + k = orig_k if _is_immutable(orig_k) else memo.get(id(orig_k), orig_k) + try: + if k not in target_dict: + return None + except Exception: + return None if deferred_tuple_finalizations: raise TypeError("Unsupported cyclic reference in tuple") if deferred_attr_assignments: @@ -1751,6 +1778,50 @@ def _safe_cancel_target(target: Any) -> None: pass +def _ensure_loop_close_hooked(loop: Any) -> bool: + hook_installed = getattr(loop, "_proofline_close_hooked", False) + if hook_installed: + return True + try: + orig_loop_close = loop.close + + def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: + close_res = orig_loop_close(*args, **kwargs) + l_futs = getattr(loop, "_proofline_detached_futures", None) + if l_futs is not None: + for fid in list(l_futs.keys()): + _DETACHED_FUTURES.pop(fid, None) + l_futs.clear() + l_tasks = getattr(loop, "_proofline_detached_tasks", None) + if l_tasks is not None: + for tid in list(l_tasks.keys()): + _DETACHED_TASKS.pop(tid, None) + l_tasks.clear() + for fid, f in list(_DETACHED_FUTURES.items()): + f_loop = None + try: + f_loop = f.get_loop() if hasattr(f, "get_loop") else AsyncFuture.get_loop(f) + except BaseException: + f_loop = getattr(f, "_loop", None) + if f_loop is loop: + _DETACHED_FUTURES.pop(fid, None) + for tid, t in list(_DETACHED_TASKS.items()): + t_loop = None + try: + t_loop = t.get_loop() if hasattr(t, "get_loop") else AsyncTask.get_loop(t) + except BaseException: + t_loop = getattr(t, "_loop", None) + if t_loop is loop: + _DETACHED_TASKS.pop(tid, None) + return close_res + + loop.close = _hooked_loop_close + setattr(loop, "_proofline_close_hooked", True) + return True + except BaseException: + return False + + def _detach_overdue_future(fut: Any) -> None: if hasattr(fut, "get_coro"): _detach_overdue_task(fut) @@ -1789,35 +1860,7 @@ def _detach_overdue_future(fut: Any) -> None: if loop_futures is not None: loop_futures[fut_id] = fut - hook_installed = getattr(loop, "_proofline_close_hooked", False) - if not hook_installed: - try: - orig_loop_close = loop.close - - def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: - close_res = orig_loop_close(*args, **kwargs) - l_futs = getattr(loop, "_proofline_detached_futures", None) - if l_futs is not None: - for fid in list(l_futs.keys()): - _DETACHED_FUTURES.pop(fid, None) - l_futs.clear() - for fid, f in list(_DETACHED_FUTURES.items()): - f_loop = None - try: - f_loop = ( - f.get_loop() if hasattr(f, "get_loop") else AsyncFuture.get_loop(f) - ) - except BaseException: - f_loop = getattr(f, "_loop", None) - if f_loop is loop: - _DETACHED_FUTURES.pop(fid, None) - return close_res - - loop.close = _hooked_loop_close # type: ignore[method-assign] - setattr(loop, "_proofline_close_hooked", True) - hook_installed = True - except BaseException: - hook_installed = False + hook_installed = _ensure_loop_close_hooked(loop) if hook_installed: try: @@ -1961,6 +2004,7 @@ def _detach_overdue_task( loop = None task_id = id(task) + hook_installed = False if loop is not None and not loop.is_closed(): loop_tasks = getattr(loop, "_proofline_detached_tasks", None) if loop_tasks is None: @@ -1972,10 +2016,13 @@ def _detach_overdue_task( if loop_tasks is not None: loop_tasks[task_id] = task - try: - _DETACHED_TASKS[task_id] = task - except (TypeError, BaseException): - pass + hook_installed = _ensure_loop_close_hooked(loop) + + if hook_installed: + try: + _DETACHED_TASKS[task_id] = task + except (TypeError, BaseException): + pass def _on_detached_task_done(t: Any) -> None: _DETACHED_TASKS.pop(task_id, None) @@ -2938,6 +2985,7 @@ async def wait_for_review( _cleanup_discarded_awaitable(res, waiter_task=waiter_task) except Exception: pass + await async_sleep(0) raise AsyncCancelledError() try: res_awaitable = isawaitable(res) diff --git a/tests/test_http.py b/tests/test_http.py index 1a93bce4..2cc7295e 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1340,6 +1340,10 @@ def sync_mismatch_cb(r: Any) -> None: head_commit_sha=OTHER_HEAD, on_poll=cb, ) + assert [p[0].status for p in polled_reviews] == ["PENDING", "RUNNING"] + assert [p[1] for p in polled_reviews] == [1, 2] + assert polled_reviews[0][0].head_commit_sha is UNSET + assert polled_reviews[1][0].head_commit_sha == HEAD assert result.status == "INCOMPLETE" assert result.review.status == "RUNNING" assert gap_facts(result) == [PINNED_ELSEWHERE] @@ -1347,10 +1351,6 @@ def sync_mismatch_cb(r: Any) -> None: # The second read names the head, so the review that would complete is never read. assert len(server.requests) == 2 assert clock.delays == [5, 10, 5, 5] - assert [p[0].status for p in polled_reviews] == ["PENDING", "RUNNING"] - assert [p[1] for p in polled_reviews] == [1, 2] - assert polled_reviews[0][0].head_commit_sha is UNSET - assert polled_reviews[1][0].head_commit_sha == HEAD @MODES @@ -4905,6 +4905,7 @@ def __eq__(self, other: Any) -> bool: copied_tuple = next(iter(copied_set)) assert copied_tuple[0].d == {"key": "val"} assert copied_tuple[0].d is not inner_dict + assert copied_tuple in copied_set # Snapshot overlapping views of one subclass exporter, visiting a view first: # assert shared writes, original isolation, copied attributes, and scalar shape () @@ -5142,6 +5143,35 @@ class DeepSelfChain: assert client_module._is_immutable(curr_obj) is False + # Non-callable object with immutable __self__ is not classified as immutable + class NonCallableWithSelf: + __self__ = 42 + + nc_inst = NonCallableWithSelf() + assert client_module._is_immutable(nc_inst) is False + detail_nc = CustomerReviewDetail.from_dict(responses[1]) + detail_nc.additional_properties["nc"] = nc_inst + snap_nc = _snapshot_review(detail_nc) + assert snap_nc is not None + copied_nc = snap_nc.additional_properties["nc"] + assert copied_nc is not nc_inst + + # Memoryview over bytes subclass exporter whose __bytes__ tries expansion + mv_sub_bytes = memoryview(small_sub_bytes)[1:5] + detail_mv_sub_bytes = CustomerReviewDetail.from_dict(responses[1]) + detail_mv_sub_bytes.additional_properties["mv_sub_bytes"] = mv_sub_bytes + snap_mv_sub = _snapshot_review(detail_mv_sub_bytes) + assert snap_mv_sub is not None + copied_mv_sub = snap_mv_sub.additional_properties["mv_sub_bytes"] + assert copied_mv_sub.tobytes() == b"mall" + assert type(copied_mv_sub.obj) is CustomBytesWithExpansion + assert memoryview(copied_mv_sub.obj).tobytes() == b"small_sub" + + # Tuple containing oversized bytes (> 65536) returns None + detail_tuple_big_bytes = CustomerReviewDetail.from_dict(responses[1]) + detail_tuple_big_bytes.additional_properties["tuple_big"] = (b"A" * 65537,) + assert _snapshot_review(detail_tuple_big_bytes) is None + # Invalid callback return raising property on close class RaisingCloseReturn: @property @@ -5452,19 +5482,25 @@ def late_failing_cb(r: Any) -> asyncio.Future[None]: loop.set_exception_handler(old_h) # Late SystemExit inside callback wrapper is suppressed after deadline + exit_task_done = asyncio.Event() + async def late_system_exit_coro(r: Any) -> None: - await asyncio.sleep(0.01) - raise SystemExit(42) + try: + clock.now += 200.0 + raise SystemExit(42) + finally: + exit_task_done.set() with Server(lambda request, index: Reply(body=responses[0])) as server: async with session("async", server.url) as client: res_exit = await client.wait_for_review( ORG, REVIEW, - timeout=0.01, + timeout=10.0, on_poll=late_system_exit_coro, ) assert res_exit.status == "TIMED_OUT" + await asyncio.wait_for(exit_task_done.wait(), timeout=1.0) # In-budget SystemExit inside callback wrapper propagates async def in_budget_system_exit_coro(r: Any) -> None: @@ -5493,10 +5529,12 @@ async def run_in_t() -> None: t_loop.run_until_complete(run_in_t()) assert id(t_fut) in client_module._DETACHED_FUTURES + assert getattr(t_loop, "_proofline_detached_futures", {}).get(id(t_fut)) is t_fut finally: t_loop.close() asyncio.set_event_loop(None) assert id(t_fut) not in client_module._DETACHED_FUTURES + assert not getattr(t_loop, "_proofline_detached_futures", {}) # Loop that rejects assignment to close: assert future never enters _DETACHED_FUTURES u_loop = asyncio.new_event_loop() From fd127f71ca1e0d70792ad4ab0e65f980d08df5d8 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 12:42:11 +0530 Subject: [PATCH 60/75] Address review run 59 findings: native array typecode and size check, pre-materialization bytes bounds, mutable set membership validation, independent cancellation check, README awaitable deadline rules, and test improvements --- README.md | 2 +- proofline/client.py | 96 +++++++++++++++++--- tests/test_http.py | 208 ++++++++++++++++++++++++++++---------------- 3 files changed, 217 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index 1c877b52..8d09eeea 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Awaitable failures occurring before the deadline propagate, but the deadline suppresses failures of awaitables that finish or return after expiry: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves them, and pending future failures are cut off at their done-callback execution (allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not suppressed; waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not suppressed; waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, waiter cancellation during inline callback invocation, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 35490c46..0fb920ed 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -535,6 +535,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non pending_assignments: dict[int, list[tuple[Any, Any, bool]]] = {} fallback_built_frozensets: list[tuple[Any, list[Any]]] = [] deferred_attr_assignments: list[tuple[Any, tuple[Any, bool], Any]] = [] + populated_mutable_sets: list[tuple[Any, list[Any]]] = [] def _collect_set_members(val: Any) -> list[Any] | None: if isinstance(val, set): @@ -867,11 +868,37 @@ def _collect_set_members(val: Any) -> list[Any] | None: if arr_byte_count > _MAX_SAFE_BUFFER_SIZE: return None try: - resolved_arr = cast(Any, array.array).__new__(type(val), val.typecode, val) + try: + native_tc = array.array.typecode.__get__(val) + except BaseException: + native_tc = val.typecode + resolved_arr = cast(Any, array.array).__new__(type(val), native_tc, val) except Exception as exc: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) from exc + clone_len: int | None = None + try: + b_chk = _Py_buffer() + if _py_get_buffer(resolved_arr, ctypes.byref(b_chk), 0x0118) == 0: + try: + clone_len = b_chk.len + finally: + _py_release_buffer(ctypes.byref(b_chk)) + except BaseException: + pass + if clone_len is not None: + if clone_len > _MAX_SAFE_BUFFER_SIZE: + return None + else: + try: + arr_clone_bytes = array.array.buffer_info(resolved_arr)[ + 1 + ] * array.array.itemsize.__get__(resolved_arr) + except BaseException: + arr_clone_bytes = resolved_arr.buffer_info()[1] * resolved_arr.itemsize + if arr_clone_bytes > _MAX_SAFE_BUFFER_SIZE: + return None memo[val_id] = resolved_arr _assign_target(target, key, is_attr, resolved_arr) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): @@ -935,17 +962,50 @@ def _collect_set_members(val: Any) -> list[Any] | None: if type(exporter) is bytes: cloned_exporter = bytes(exporter) else: - raw_exp = bytes(memoryview(exporter)) - if len(raw_exp) > _MAX_SAFE_BUFFER_SIZE: + mv_exp = memoryview(exporter) + if mv_exp.nbytes > _MAX_SAFE_BUFFER_SIZE: return None + raw_exp = bytes(mv_exp) cloned_exporter = bytes.__new__(type(exporter), raw_exp) elif isinstance(exporter, bytearray): cloned_exporter = bytearray.__new__(type(exporter)) bytearray.__init__(cloned_exporter, exporter) else: + try: + native_exp_tc = array.array.typecode.__get__(exporter) + except BaseException: + native_exp_tc = exporter.typecode cloned_exporter = cast(Any, array.array).__new__( - type(exporter), exporter.typecode, exporter + type(exporter), native_exp_tc, exporter ) + clone_exp_len: int | None = None + try: + b_chk = _Py_buffer() + if ( + _py_get_buffer(cloned_exporter, ctypes.byref(b_chk), 0x0118) + == 0 + ): + try: + clone_exp_len = b_chk.len + finally: + _py_release_buffer(ctypes.byref(b_chk)) + except BaseException: + pass + if clone_exp_len is not None: + if clone_exp_len > _MAX_SAFE_BUFFER_SIZE: + return None + else: + try: + arr_exp_bytes = array.array.buffer_info(cloned_exporter)[ + 1 + ] * array.array.itemsize.__get__(cloned_exporter) + except BaseException: + arr_exp_bytes = ( + cloned_exporter.buffer_info()[1] + * cloned_exporter.itemsize + ) + if arr_exp_bytes > _MAX_SAFE_BUFFER_SIZE: + return None except Exception as exc: raise TypeError( "Unsupported mutable value in review extension data: " @@ -1170,9 +1230,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: if isinstance(val, str): new_obj = str.__new__(type(val), val) elif isinstance(val, bytes): - raw_bytes = bytes(memoryview(val)) - if len(raw_bytes) > _MAX_SAFE_BUFFER_SIZE: + mv_bytes = memoryview(val) + if mv_bytes.nbytes > _MAX_SAFE_BUFFER_SIZE: return None + raw_bytes = bytes(mv_bytes) new_obj = bytes.__new__(type(val), raw_bytes) elif isinstance(val, int): new_obj = int.__new__(type(val), val) @@ -1557,6 +1618,7 @@ def _flush_pending_structures() -> None: "Unsupported mutable value in review extension data: " f"{type(orig_val).__name__}" ) + populated_mutable_sets.append((s, resolved_members)) changed = True deferred_set_insertions = still_sets @@ -1760,6 +1822,15 @@ def _flush_pending_structures() -> None: return None except Exception: return None + for s, members in populated_mutable_sets: + for rm in members: + if _deadline_expired(): + return None + try: + if rm not in s: + return None + except Exception: + return None if deferred_tuple_finalizations: raise TypeError("Unsupported cyclic reference in tuple") if deferred_attr_assignments: @@ -2969,13 +3040,14 @@ async def wait_for_review( if waiter_task is not None: is_task_cancelled = False try: - if hasattr(waiter_task, "cancelling"): - is_task_cancelled = ( - waiter_task.cancelling() > initial_cancelling - ) - elif hasattr(waiter_task, "cancelled") and waiter_task.cancelled(): + if ( + hasattr(waiter_task, "cancelling") + and waiter_task.cancelling() > initial_cancelling + ): + is_task_cancelled = True + if hasattr(waiter_task, "cancelled") and waiter_task.cancelled(): is_task_cancelled = True - elif getattr(waiter_task, "_must_cancel", False): + if getattr(waiter_task, "_must_cancel", False): is_task_cancelled = True except BaseException: pass diff --git a/tests/test_http.py b/tests/test_http.py index 2cc7295e..b00dfe90 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -3137,6 +3137,10 @@ async def continuing_coro_term(r: Any) -> None: pass assert not waiter_task_4.done() clock.advance(1.0) + res_4 = await asyncio.wait_for(waiter_task_4, timeout=1.0) + assert res_4.status == "COMPLETED" + assert not callback_finished_term.is_set() + release_callback_term.set() assert len(captured_case4_wrappers) == 1 wrapper_4 = captured_case4_wrappers[0] @@ -3159,8 +3163,6 @@ async def continuing_coro_term(r: Any) -> None: await finish_waiter_4 except (asyncio.CancelledError, BaseException): pass - res_4 = await waiter_task_4 - assert res_4.status == "COMPLETED" assert callback_running_term.is_set() assert callback_finished_term.is_set() await asyncio.sleep(0.01) @@ -3864,82 +3866,114 @@ def complete_unhashable_cb(r: Any) -> Any: # Cancel the waiter while an UnhashableFuture is pending, then fail and release # the future and assert that the loop reports no unhandled exception. - from proofline.client import _DETACHED_FUTURES + # Run in a subprocess with a hard timeout, settling the callback future + # before joining the waiter. + unhashable_code = f""" +import asyncio +import sys +import weakref +from pathlib import Path +from uuid import UUID - unhash_cancel_reports: list[dict[str, Any]] = [] - loop = asyncio.get_running_loop() - old_h_unhash = loop.get_exception_handler() - loop.set_exception_handler(lambda _loop, ctx: unhash_cancel_reports.append(ctx)) - try: - with Server(lambda request, index: Reply(body=responses[0])) as server: - async with session("async", server.url) as client: - unhash_box: list[Any] = [UnhashableFuture(loop=loop)] - cb_started = asyncio.Event() +from tests.test_http import Server, Reply, session, review +from proofline.client import _DETACHED_FUTURES - def unhash_failing_cb(r: Any) -> Any: - cb_started.set() - return unhash_box[0] +ORG = UUID("{ORG}") +REVIEW = UUID("{REVIEW}") - waiter_task = asyncio.create_task( - client.wait_for_review( - ORG, - REVIEW, - timeout=10, - on_poll=unhash_failing_cb, - ) - ) - cb_wait_task = asyncio.create_task(cb_started.wait()) - try: - done_set, _ = await asyncio.wait( - {cb_wait_task, waiter_task}, - timeout=5.0, - return_when=asyncio.FIRST_COMPLETED, - ) - if waiter_task in done_set and not cb_started.is_set(): - cb_wait_task.cancel() - await waiter_task - assert cb_wait_task in done_set, "Callback startup timed out" - waiter_task.cancel() - cancelled = False +class UnhashableFuture(asyncio.Future): + __hash__ = None # type: ignore + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.exception_calls = 0 + + def exception(self): + self.exception_calls += 1 + return super().exception() + +async def main(): + unhash_cancel_reports = [] + loop = asyncio.get_running_loop() + loop.set_exception_handler(lambda _loop, ctx: unhash_cancel_reports.append(ctx)) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + unhash_box = [UnhashableFuture(loop=loop)] + cb_started = asyncio.Event() + + def unhash_failing_cb(r): + cb_started.set() + return unhash_box[0] + + waiter_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=unhash_failing_cb, + ) + ) + cb_wait_task = asyncio.create_task(cb_started.wait()) + try: + done_set, _ = await asyncio.wait( + {{cb_wait_task, waiter_task}}, + timeout=5.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task in done_set and not cb_started.is_set(): + cb_wait_task.cancel() + await asyncio.wait_for(waiter_task, timeout=5.0) + assert cb_wait_task in done_set, "Callback startup timed out" + waiter_task.cancel() + cancelled = False + try: + await asyncio.wait_for(waiter_task, timeout=5.0) + except asyncio.CancelledError: + cancelled = True + assert cancelled + target_fut = unhash_box[0] + fut_weakref = weakref.ref(target_fut) + assert id(target_fut) in _DETACHED_FUTURES + target_fut.set_exception(RuntimeError("unhashable late failure")) + await asyncio.sleep(0) + assert id(target_fut) not in _DETACHED_FUTURES + assert target_fut.exception_calls > 0 + del target_fut + unhash_box.clear() + import gc + gc.collect() + assert fut_weakref() is None + assert unhash_cancel_reports == [] + finally: + if unhash_box: + f = unhash_box[0] + if not f.done(): + f.set_result(None) + elif not f.cancelled(): try: - await waiter_task - except asyncio.CancelledError: - cancelled = True - assert cancelled - target_fut = unhash_box[0] - fut_weakref = weakref.ref(target_fut) - assert id(target_fut) in _DETACHED_FUTURES - target_fut.set_exception(RuntimeError("unhashable late failure")) - await asyncio.sleep(0) - assert id(target_fut) not in _DETACHED_FUTURES - assert target_fut.exception_calls > 0 - del target_fut - unhash_box.clear() - import gc + f.exception() + except BaseException: + pass + for t in (cb_wait_task, waiter_task): + if not t.done(): + t.cancel() + try: + await asyncio.wait_for(t, timeout=5.0) + except (asyncio.CancelledError, BaseException): + pass + await asyncio.sleep(0) - gc.collect() - assert fut_weakref() is None - assert unhash_cancel_reports == [] - finally: - for t in (cb_wait_task, waiter_task): - if not t.done(): - t.cancel() - try: - await t - except (asyncio.CancelledError, BaseException): - pass - if unhash_box: - f = unhash_box[0] - if not f.done(): - f.set_result(None) - elif not f.cancelled(): - try: - f.exception() - except BaseException: - pass - await asyncio.sleep(0) - finally: - loop.set_exception_handler(old_h_unhash) +asyncio.run(main()) +""" + checkout_root = Path(__file__).resolve().parent.parent + subprocess.run( + [sys.executable, "-"], + input=unhashable_code, + text=True, + cwd=str(checkout_root), + check=True, + timeout=15, + ) # Case detaching an overdue callback Future without calling its cancel(): # the waiter returns TIMED_OUT without calling cancel() or reporting an unhandled exception @@ -3995,13 +4029,13 @@ async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: assert res_sync_cancel.status == "TIMED_OUT" await asyncio.sleep(0) assert fut_sync_cancel.cancel_called is False - assert id(fut_sync_cancel) in _DETACHED_FUTURES + assert id(fut_sync_cancel) in client_module._DETACHED_FUTURES assert cancel_reports == [] # Late-exception and release checks in test body after detachment verified fut_sync_cancel.set_exception(RuntimeError("sync cancel late error")) await asyncio.sleep(0) - assert id(fut_sync_cancel) not in _DETACHED_FUTURES + assert id(fut_sync_cancel) not in client_module._DETACHED_FUTURES assert fut_sync_cancel.exception_calls > 0 # import weakref (already imported at module level) @@ -5517,24 +5551,46 @@ async def in_budget_system_exit_coro(r: Any) -> None: ) assert exc_info.value.code == 42 - # Closing loop releases strong retention from _DETACHED_FUTURES + # Closing loop releases strong retention from _DETACHED_FUTURES and _DETACHED_TASKS def test_loop_close_in_thread() -> None: t_loop = asyncio.new_event_loop() try: asyncio.set_event_loop(t_loop) t_fut = t_loop.create_future() + t_task: asyncio.Task[Any] | None = None + + async def sleep_forever() -> None: + await asyncio.sleep(3600) async def run_in_t() -> None: + nonlocal t_task + t_task = t_loop.create_task(sleep_forever()) client_module._detach_overdue_future(t_fut) + client_module._detach_overdue_task(t_task) t_loop.run_until_complete(run_in_t()) assert id(t_fut) in client_module._DETACHED_FUTURES assert getattr(t_loop, "_proofline_detached_futures", {}).get(id(t_fut)) is t_fut + assert t_task is not None + assert id(t_task) in client_module._DETACHED_TASKS + assert getattr(t_loop, "_proofline_detached_tasks", {}).get(id(t_task)) is t_task finally: + if t_task is not None: + setattr(t_task, "_log_destroy_pending", False) + try: + if hasattr(t_task, "get_coro"): + coro = t_task.get_coro() + if coro is not None: + coro.close() + except BaseException: + pass t_loop.close() asyncio.set_event_loop(None) assert id(t_fut) not in client_module._DETACHED_FUTURES assert not getattr(t_loop, "_proofline_detached_futures", {}) + assert t_task is not None + assert id(t_task) not in client_module._DETACHED_TASKS + assert not getattr(t_loop, "_proofline_detached_tasks", {}) # Loop that rejects assignment to close: assert future never enters _DETACHED_FUTURES u_loop = asyncio.new_event_loop() From 992d34e65553aedcb094c08e8a995a72eca47873 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 13:38:09 +0530 Subject: [PATCH 61/75] Address review run 60 findings: instance __dict__ memo cloning, pending future observer removal, loop close exception draining, Case 3 bounded wait, and immutable bytes cutoff documentation --- README.md | 4 +- proofline/client.py | 113 +++++++++++++++++++++++++++++++++++++------- tests/test_http.py | 26 ++++++++-- 3 files changed, 119 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 8d09eeea..1f7250fb 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not suppressed; waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not suppressed; waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, waiter cancellation during inline callback invocation, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 0fb920ed..798f2e6e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -472,13 +472,45 @@ def _get_obj_attrs(obj: Any) -> list[tuple[Any, bool, Any]]: except AttributeError: pass - if hasattr(obj, "__dict__") and isinstance(obj.__dict__, dict): - for k, v in obj.__dict__.items(): - items.append((k, False, v)) - return items +def _install_cloned_dict( + val: Any, + new_obj: Any, + memo: dict[int, Any], + stack: list[Any], +) -> None: + if hasattr(val, "__dict__"): + try: + inst_dict = val.__dict__ + if isinstance(inst_dict, dict): + dict_id = id(inst_dict) + if dict_id in memo: + cloned_dict = memo[dict_id] + else: + try: + cloned_dict = dict.__new__(type(inst_dict)) + dict.clear(cloned_dict) + except Exception: + cloned_dict = {} + memo[dict_id] = cloned_dict + for k, v in inst_dict.items(): + if _is_immutable(k) and _is_immutable(v): + if type(k) is bytes and len(k) > _MAX_SAFE_BUFFER_SIZE: + continue + if type(v) is bytes and len(v) > _MAX_SAFE_BUFFER_SIZE: + continue + cloned_dict[k] = v + stack.append((_DICT_EXPAND, cloned_dict, iter(inst_dict.items()))) + try: + new_obj.__dict__ = cloned_dict + except AttributeError: + pass + except Exception: + pass + + _ITEM_TASK = 1 _DICT_EXPAND = 2 _LIST_EXPAND = 3 @@ -563,6 +595,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: return members stack: list[Any] = [(_OBJ_EXPAND, root, iter(_get_obj_attrs(detail)))] + _install_cloned_dict(detail, root, memo, stack) while stack: if _deadline_expired(): @@ -626,6 +659,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: return None memo[val_id] = res_empty if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, res_empty, memo, stack) stack.append((_OBJ_EXPAND, res_empty, iter(_get_obj_attrs(val)))) _assign_target(target, key, is_attr, res_empty) else: @@ -674,6 +708,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: ) ) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, new_dict, memo, stack) stack.append((_OBJ_EXPAND, new_dict, iter(_get_obj_attrs(val)))) stack.append((_DICT_EXPAND, new_dict, iter(val.items()))) elif isinstance(val, list): @@ -696,6 +731,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: _assign_target(target, key, is_attr, new_list) stack.append((_LIST_EXPAND, new_list, iter(val))) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, new_list, memo, stack) stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) elif isinstance(val, set): if type(val) is not set and _has_mutable_class_attrs(type(val)): @@ -737,6 +773,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: memo[val_id] = new_set _assign_target(target, key, is_attr, new_set) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, new_set, memo, stack) stack.append((_OBJ_EXPAND, new_set, iter(_get_obj_attrs(val)))) if set_len > 0: orig_set_members = _collect_set_members(val) @@ -779,6 +816,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: ) memo[val_id] = res_empty_fs if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, res_empty_fs, memo, stack) stack.append((_OBJ_EXPAND, res_empty_fs, iter(_get_obj_attrs(val)))) _assign_target(target, key, is_attr, res_empty_fs) else: @@ -821,6 +859,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: _assign_target(target, key, is_attr, new_deque) stack.append((_LIST_EXPAND, new_deque, deque.__iter__(val))) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, new_deque, memo, stack) stack.append((_OBJ_EXPAND, new_deque, iter(_get_obj_attrs(val)))) elif isinstance(val, bytearray): if type(val) is not bytearray and _has_mutable_class_attrs(type(val)): @@ -839,6 +878,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: memo[val_id] = resolved _assign_target(target, key, is_attr, resolved) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, resolved, memo, stack) stack.append((_OBJ_EXPAND, resolved, iter(_get_obj_attrs(val)))) elif isinstance(val, array.array): if type(val) is not array.array and _has_mutable_class_attrs(type(val)): @@ -902,6 +942,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: memo[val_id] = resolved_arr _assign_target(target, key, is_attr, resolved_arr) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, resolved_arr, memo, stack) stack.append((_OBJ_EXPAND, resolved_arr, iter(_get_obj_attrs(val)))) elif isinstance(val, memoryview): if val.nbytes > _MAX_SAFE_BUFFER_SIZE: @@ -1013,6 +1054,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: ) from exc memo[exp_id] = cloned_exporter if hasattr(exporter, "__dict__") or hasattr(exporter, "__slots__"): + _install_cloned_dict(exporter, cloned_exporter, memo, stack) stack.append( (_OBJ_EXPAND, cloned_exporter, iter(_get_obj_attrs(exporter))) ) @@ -1180,6 +1222,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: ) from exc memo[id(tz)] = copied_tz if hasattr(tz, "__dict__") or hasattr(tz, "__slots__"): + _install_cloned_dict(tz, copied_tz, memo, stack) stack.append((_OBJ_EXPAND, copied_tz, iter(_get_obj_attrs(tz)))) if type(val) is datetime.datetime: @@ -1219,6 +1262,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: memo[val_id] = new_dt _assign_target(target, key, is_attr, new_dt) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, new_dt, memo, stack) stack.append((_OBJ_EXPAND, new_dt, iter(_get_obj_attrs(val)))) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): if _has_mutable_class_attrs(type(val)): @@ -1247,6 +1291,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: ) from exc memo[val_id] = new_obj _assign_target(target, key, is_attr, new_obj) + _install_cloned_dict(val, new_obj, memo, stack) stack.append((_OBJ_EXPAND, new_obj, iter(_get_obj_attrs(val)))) else: raise TypeError( @@ -1398,6 +1443,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: return None memo[val_id] = res_tuple if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): + _install_cloned_dict(orig_val, res_tuple, memo, stack) stack.append((_OBJ_EXPAND, res_tuple, iter(_get_obj_attrs(orig_val)))) _assign_target(target, key, is_attr, res_tuple) @@ -1856,16 +1902,34 @@ def _ensure_loop_close_hooked(loop: Any) -> bool: try: orig_loop_close = loop.close + def _drain_exception(target: Any) -> None: + try: + is_done = target.done() if hasattr(target, "done") else AsyncFuture.done(target) + is_canc = ( + target.cancelled() + if hasattr(target, "cancelled") + else AsyncFuture.cancelled(target) + ) + if is_done and not is_canc: + if hasattr(target, "exception"): + target.exception() + else: + AsyncFuture.exception(target) + except BaseException: + pass + def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: close_res = orig_loop_close(*args, **kwargs) l_futs = getattr(loop, "_proofline_detached_futures", None) if l_futs is not None: - for fid in list(l_futs.keys()): + for fid, f in list(l_futs.items()): + _drain_exception(f) _DETACHED_FUTURES.pop(fid, None) l_futs.clear() l_tasks = getattr(loop, "_proofline_detached_tasks", None) if l_tasks is not None: - for tid in list(l_tasks.keys()): + for tid, t in list(l_tasks.items()): + _drain_exception(t) _DETACHED_TASKS.pop(tid, None) l_tasks.clear() for fid, f in list(_DETACHED_FUTURES.items()): @@ -1875,6 +1939,7 @@ def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: except BaseException: f_loop = getattr(f, "_loop", None) if f_loop is loop: + _drain_exception(f) _DETACHED_FUTURES.pop(fid, None) for tid, t in list(_DETACHED_TASKS.items()): t_loop = None @@ -1883,6 +1948,7 @@ def _hooked_loop_close(*args: Any, **kwargs: Any) -> Any: except BaseException: t_loop = getattr(t, "_loop", None) if t_loop is loop: + _drain_exception(t) _DETACHED_TASKS.pop(tid, None) return close_res @@ -2524,10 +2590,10 @@ def wait_for_review( When on_poll is provided, it is called on each review poll with the latest CustomerReviewDetail. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress - delivery. Tuples with more than 1,000 items, mutable buffers or memoryviews with - more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, - frozensets, or deques with more than 65,536 items in review extension data skip - on_poll snapshot delivery even with time remaining, and snapshot copy errors on + delivery. Tuples with more than 1,000 items, immutable bytes, mutable buffers + or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 + bytes), sets, frozensets, or deques with more than 65,536 items in review extension + data skip on_poll snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before on_poll runs. on_poll exceptions and return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter @@ -2977,21 +3043,22 @@ async def wait_for_review( an awaitable, because the polling deadline cannot interrupt the invocation. Only reviews fetched and validated before the callback is reached are delivered; deadline expiry can suppress delivery. Tuples - with more than 1,000 items, mutable buffers or memoryviews with more than 65,536 bytes - (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with - more than 65,536 items in review extension data skip on_poll snapshot delivery even - with time remaining, and snapshot copy errors on unsupported mutable values propagate - before on_poll runs. Callback + with more than 1,000 items, immutable bytes, mutable buffers or memoryviews + with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), + sets, frozensets, or deques with more than 65,536 items in review extension data + skip on_poll snapshot delivery even with time remaining, and snapshot copy errors + on unsupported mutable values propagate before on_poll runs. Callback return-validation errors and inline exceptions propagate unconditionally, even when a terminal outcome has already been determined (cancellation requested during callback invocation takes precedence over return validation), preventing the waiter from returning a classified outcome. - Separately, awaitable failures occurring before the deadline propagate, but the - deadline suppresses failures of awaitables that finish or return after expiry: + Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine failures are timed at wrapper completion rather than when the waiter retrieves - them, and pending future failures are cut off at their done-callback execution. + them, and pending future failures propagate only if their done callback executes before + the deadline expires (cutting off at done-callback execution and allowing any + classified outcome to be returned). This allows any classified outcome to be returned when a callback finishes or returns after the deadline. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by on_poll are closed without entering @@ -3169,6 +3236,16 @@ def _on_future_done(_: Any) -> None: except BaseException: _detach_overdue_future(res) raise + finally: + try: + if hasattr(res, "remove_done_callback"): + res.remove_done_callback(_on_future_done) + else: + AsyncFuture.remove_done_callback( + res, _on_future_done + ) + except BaseException: + pass deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val diff --git a/tests/test_http.py b/tests/test_http.py index b00dfe90..a313ba87 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2961,7 +2961,7 @@ async def continuing_coro(r: Any) -> None: await waiter_task_3 assert not waiter_task_3.done() clock.advance(1.0) - res_3 = await waiter_task_3 + res_3 = await asyncio.wait_for(asyncio.shield(waiter_task_3), timeout=1.0) assert res_3.status == "TIMED_OUT" assert callback_running.is_set() assert not callback_finished.is_set() @@ -2994,20 +2994,20 @@ async def continuing_coro(r: Any) -> None: except (asyncio.CancelledError, BaseException): pass finally: + release_callback.set() if not waiter_task_3.done(): waiter_task_3.cancel() try: - await waiter_task_3 + await asyncio.wait_for(waiter_task_3, timeout=1.0) except (asyncio.CancelledError, BaseException): pass client_module.async_create_task = orig_create_task_3 sleep_forbidden = False - release_callback.set() if cb_task_3 is not None: if not cb_task_3.done(): cb_task_3.cancel() try: - await cb_task_3 + await asyncio.wait_for(cb_task_3, timeout=1.0) except (asyncio.CancelledError, BaseException): pass @@ -5177,6 +5177,23 @@ class DeepSelfChain: assert client_module._is_immutable(curr_obj) is False + # Explicit reference to instance __dict__ points to the exact same cloned dictionary + class SharedDictOwner: + def __init__(self) -> None: + self.x = 42 + + owner = SharedDictOwner() + detail_dict_ref = CustomerReviewDetail.from_dict(responses[1]) + detail_dict_ref.additional_properties["owner"] = owner + detail_dict_ref.additional_properties["owner_dict"] = owner.__dict__ + snap_dict_ref = _snapshot_review(detail_dict_ref) + assert snap_dict_ref is not None + copied_owner = snap_dict_ref.additional_properties["owner"] + copied_dict = snap_dict_ref.additional_properties["owner_dict"] + assert copied_dict is copied_owner.__dict__ + copied_dict["x"] = 99 + assert copied_owner.x == 99 + # Non-callable object with immutable __self__ is not classified as immutable class NonCallableWithSelf: __self__ = 42 @@ -5574,6 +5591,7 @@ async def run_in_t() -> None: assert t_task is not None assert id(t_task) in client_module._DETACHED_TASKS assert getattr(t_loop, "_proofline_detached_tasks", {}).get(id(t_task)) is t_task + t_fut.set_exception(RuntimeError("failed before close")) finally: if t_task is not None: setattr(t_task, "_log_destroy_pending", False) From ab10a01e5718796c567bb70c7306739946468656 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 14:00:37 +0530 Subject: [PATCH 62/75] Address review run 61 findings: frozenset dict installation, reject module builtins, doc signals and cancellation, bound Case 3b joins, observer removal, exception draining, and test fixtures --- README.md | 2 +- proofline/client.py | 85 +++++++++++++++----------- tests/test_http.py | 144 +++++++++++++++++++++++++++++++++++--------- 3 files changed, 164 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 1f7250fb..4792060c 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not suppressed; waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them, except for wrappers cancelled before their first step which are timed when their done callback runs), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (detached callback coroutines suppress late SystemExit and KeyboardInterrupt signals; waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, waiter cancellation during inline callback invocation, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 798f2e6e..0e1cf96a 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -338,7 +338,7 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if curr is None: return True if isinstance(curr, ModuleType): - return True + return False if isinstance(curr, type): return curr in _SAFE_BUILTIN_CLASSES or curr is object local_seen = seen if seen is not None else set() @@ -357,7 +357,7 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if curr is None: return True if isinstance(curr, ModuleType): - return True + return False if isinstance(curr, type): return curr in _SAFE_BUILTIN_CLASSES or curr is object return _is_immutable(curr, local_seen) @@ -503,10 +503,11 @@ def _install_cloned_dict( continue cloned_dict[k] = v stack.append((_DICT_EXPAND, cloned_dict, iter(inst_dict.items()))) - try: - new_obj.__dict__ = cloned_dict - except AttributeError: - pass + if new_obj is not None: + try: + new_obj.__dict__ = cloned_dict + except AttributeError: + pass except Exception: pass @@ -614,6 +615,9 @@ def _collect_set_members(val: Any) -> list[Any] | None: weakref.ProxyType, weakref.CallableProxyType, ), + ) or ( + isinstance(val, BuiltinFunctionType) + and isinstance(getattr(val, "__self__", None), ModuleType) ): raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" @@ -827,6 +831,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: deferred_frozenset_insertions.append( (target, key, is_attr, val_id, val, orig_fs_members) ) + if hasattr(val, "__dict__"): + _install_cloned_dict(val, None, memo, stack) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(val): if ( @@ -1766,6 +1772,8 @@ def _flush_pending_structures() -> None: ) memo[val_id] = res_set pending_frozenset_ids.discard(val_id) + if hasattr(orig_val, "__dict__"): + _install_cloned_dict(orig_val, res_set, memo, stack) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): if _is_immutable(attr_val): @@ -1817,6 +1825,8 @@ def _flush_pending_structures() -> None: memo[val_id] = res_set pending_frozenset_ids.discard(val_id) fallback_built_frozensets.append((res_set, resolved_members)) + if hasattr(orig_val, "__dict__"): + _install_cloned_dict(orig_val, res_set, memo, stack) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): if _is_immutable(attr_val): @@ -3055,17 +3065,18 @@ async def wait_for_review( Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutine - failures are timed at wrapper completion rather than when the waiter retrieves - them, and pending future failures propagate only if their done callback executes before - the deadline expires (cutting off at done-callback execution and allowing any - classified outcome to be returned). + failures are timed at wrapper completion rather than when the waiter retrieves them + (except for wrappers cancelled before their first step, which are timed when their done + callback runs), and pending future failures propagate only if their done callback + executes before the deadline expires (cutting off at done-callback execution and allowing + any classified outcome to be returned). This allows any classified outcome to be returned when a callback finishes or returns - after the deadline. When the deadline expires or when the wait is - cancelled, unstarted coroutines returned by on_poll are closed without entering - their body (a wrapper task may already have been scheduled), while already-running - callback tasks and futures are detached without cancellation and may continue - running (late SystemExit and KeyboardInterrupt from already-scheduled tasks are not - suppressed). Synchronous callbacks must return before a terminal result can be + after the deadline. When the deadline expires or when the wait is cancelled, unstarted + coroutines returned by on_poll are closed without entering their body (a wrapper task + may already have been scheduled), while already-running callback tasks and futures are + detached without cancellation and may continue running (detached callback coroutines + suppress late SystemExit and KeyboardInterrupt signals, which do not propagate once + detached). Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: @@ -3214,28 +3225,30 @@ def _on_future_done(_: Any) -> None: except BaseException: _detach_overdue_future(res) raise - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val - ) - if cb_finished_in_budget: - if hasattr(res, "result"): - res.result() - else: - AsyncFuture.result(res) - remaining_budget = _transport.remaining() - if remaining_budget is not None and remaining_budget <= 0: - _detach_overdue_future(res) - if result is not None: - return result - break + done: set[Any] = set() try: - done, _ = await async_wait( - {completion_fut}, timeout=remaining_budget + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val ) - except BaseException: - _detach_overdue_future(res) - raise + if cb_finished_in_budget: + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _detach_overdue_future(res) + if result is not None: + return result + break + try: + done, _ = await async_wait( + {completion_fut}, timeout=remaining_budget + ) + except BaseException: + _detach_overdue_future(res) + raise finally: try: if hasattr(res, "remove_done_callback"): diff --git a/tests/test_http.py b/tests/test_http.py index a313ba87..85d1a4ab 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1318,9 +1318,15 @@ async def test_wait_ends_on_the_read_that_names_another_head( with Server(lambda request, index: Reply(body=responses[index])) as server: polled_reviews: list[tuple[Any, int]] = [] if mode == "async": + cb_gate = asyncio.Event() + waiter_task: asyncio.Task[Any] | None = None async def async_mismatch_cb(r: Any) -> None: - await asyncio.sleep(0.01) + if len(polled_reviews) == 1: + assert waiter_task is not None + await asyncio.sleep(0.01) + assert not waiter_task.done() + await cb_gate.wait() polled_reviews.append((r, len(server.requests))) cb: Any = async_mismatch_cb @@ -1331,15 +1337,32 @@ def sync_mismatch_cb(r: Any) -> None: cb = sync_mismatch_cb async with session(mode, server.url) as client: - result = await call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=100, - head_commit_sha=OTHER_HEAD, - on_poll=cb, - ) + if mode == "async": + waiter_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=100, + head_commit_sha=OTHER_HEAD, + on_poll=cb, + ) + ) + while len(polled_reviews) < 1: + await asyncio.sleep(0.01) + await asyncio.sleep(0.05) + assert not waiter_task.done() + cb_gate.set() + result = await waiter_task + else: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + head_commit_sha=OTHER_HEAD, + on_poll=cb, + ) assert [p[0].status for p in polled_reviews] == ["PENDING", "RUNNING"] assert [p[1] for p in polled_reviews] == [1, 2] assert polled_reviews[0][0].head_commit_sha is UNSET @@ -2802,11 +2825,21 @@ class SignallingFuture(asyncio.Future[None]): def __init__(self, loop: asyncio.AbstractEventLoop) -> None: super().__init__(loop=loop) self.wait_entered = asyncio.Event() + self.active_callbacks: list[Any] = [] + self.removed_callbacks: list[Any] = [] def add_done_callback(self, fn: Any, *, context: Any = None) -> None: super().add_done_callback(fn, context=context) + self.active_callbacks.append(fn) self.wait_entered.set() + def remove_done_callback(self, fn: Any) -> int: + count = super().remove_done_callback(fn) + if count > 0: + self.removed_callbacks.append(fn) + self.active_callbacks = [cb for cb in self.active_callbacks if cb != fn] + return count + pending_fut: SignallingFuture | None = None cb_1_started = asyncio.Event() @@ -2852,6 +2885,11 @@ def pending_future_callback(r: Any) -> SignallingFuture: assert not pending_fut.cancelled() assert not pending_fut.done() assert id(pending_fut) in client_module._DETACHED_FUTURES + assert len(pending_fut.removed_callbacks) > 0 + assert any( + "_on_future_done" in getattr(cb, "__name__", "") + for cb in pending_fut.removed_callbacks + ) pending_fut.set_result(None) await asyncio.sleep(0) assert id(pending_fut) not in client_module._DETACHED_FUTURES @@ -3054,29 +3092,30 @@ def sync_cb_returning_task(r: Any) -> Any: assert cb_task_3b is not None assert not cb_task_3b.done() clock.advance(1.0) - res_3b = await waiter_task_3b + res_3b = await asyncio.wait_for(asyncio.shield(waiter_task_3b), timeout=1.0) assert res_3b.status == "TIMED_OUT" assert not cb_task_3b.done() task_release_3b.set() await asyncio.wait_for(asyncio.shield(cb_task_3b), timeout=1.0) finally: + task_release_3b.set() if not startup_waiter.done(): startup_waiter.cancel() try: - await startup_waiter + await asyncio.wait_for(startup_waiter, timeout=0.5) except (asyncio.CancelledError, BaseException): pass if not waiter_task_3b.done(): waiter_task_3b.cancel() try: - await waiter_task_3b + await asyncio.wait_for(waiter_task_3b, timeout=0.5) except (asyncio.CancelledError, BaseException): pass if cb_task_3b is not None: if not cb_task_3b.done(): cb_task_3b.cancel() try: - await cb_task_3b + await asyncio.wait_for(cb_task_3b, timeout=0.5) except (asyncio.CancelledError, BaseException): pass @@ -5088,6 +5127,25 @@ def __eq__(self, other: Any) -> bool: assert copied_holder.d["pending_val"] is copied_obj.f_set assert copied_holder.d is not deferred_dict + # Dictionary fixture whose key hash changes during clone finalization: snapshot is rejected + class MutatingHashKey: + def __init__(self) -> None: + self.val = 1 + + def __hash__(self) -> int: + h = self.val + self.val += 1 + return h + + def __eq__(self, other: Any) -> bool: + return isinstance(other, MutatingHashKey) + + mutating_k = MutatingHashKey() + dict_with_mutating = {mutating_k: "val"} + detail_dict_mutating = CustomerReviewDetail.from_dict(responses[1]) + detail_dict_mutating.additional_properties["mutating_dict"] = dict_with_mutating + assert _snapshot_review(detail_dict_mutating) is None + # Strided memoryview over immutable bytes preserves strides and c_contiguous b_data = b"0123456789abcdef" mv_strided = memoryview(b_data)[::2] @@ -5571,17 +5629,39 @@ async def in_budget_system_exit_coro(r: Any) -> None: # Closing loop releases strong retention from _DETACHED_FUTURES and _DETACHED_TASKS def test_loop_close_in_thread() -> None: t_loop = asyncio.new_event_loop() + + class TrackingFuture(asyncio.Future[Any]): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(loop=loop) + self.exception_retrieved = False + + def exception(self) -> Any: + self.exception_retrieved = True + return super().exception() + + class TrackingTask(asyncio.Task[Any]): + def __init__(self, coro: Any, *, loop: asyncio.AbstractEventLoop) -> None: + super().__init__(coro, loop=loop) + self.exception_retrieved = False + + def exception(self) -> Any: + self.exception_retrieved = True + return super().exception() + try: asyncio.set_event_loop(t_loop) - t_fut = t_loop.create_future() - t_task: asyncio.Task[Any] | None = None + t_fut = TrackingFuture(loop=t_loop) + t_task: TrackingTask | None = None + task_start = asyncio.Event() - async def sleep_forever() -> None: - await asyncio.sleep(3600) + async def fail_task() -> None: + await task_start.wait() + t_loop.stop() + raise RuntimeError("task failed") async def run_in_t() -> None: nonlocal t_task - t_task = t_loop.create_task(sleep_forever()) + t_task = TrackingTask(fail_task(), loop=t_loop) client_module._detach_overdue_future(t_fut) client_module._detach_overdue_task(t_task) @@ -5591,22 +5671,26 @@ async def run_in_t() -> None: assert t_task is not None assert id(t_task) in client_module._DETACHED_TASKS assert getattr(t_loop, "_proofline_detached_tasks", {}).get(id(t_task)) is t_task - t_fut.set_exception(RuntimeError("failed before close")) + + # Fail both targets before their done callbacks run: + task_start.set() + t_loop.run_forever() + t_fut.set_exception(RuntimeError("fut failed before close")) + + assert t_fut.done() + assert t_task.done() + assert not t_fut.exception_retrieved + assert not t_task.exception_retrieved + assert id(t_fut) in client_module._DETACHED_FUTURES + assert id(t_task) in client_module._DETACHED_TASKS finally: - if t_task is not None: - setattr(t_task, "_log_destroy_pending", False) - try: - if hasattr(t_task, "get_coro"): - coro = t_task.get_coro() - if coro is not None: - coro.close() - except BaseException: - pass t_loop.close() asyncio.set_event_loop(None) + assert t_fut.exception_retrieved + assert t_task is not None + assert t_task.exception_retrieved assert id(t_fut) not in client_module._DETACHED_FUTURES assert not getattr(t_loop, "_proofline_detached_futures", {}) - assert t_task is not None assert id(t_task) not in client_module._DETACHED_TASKS assert not getattr(t_loop, "_proofline_detached_tasks", {}) From 372f111c2b785aff377c1a0dcee846c2150e4319 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 14:15:25 +0530 Subject: [PATCH 63/75] Address review run 62 findings: frozenset slot byte limit, task done callback unregistration, Python 3.10 cancellation tracking, frozenset subclass __dict__ alias fixtures, nested state dict lookup fixture, and mismatch callback event synchronization --- proofline/client.py | 99 +++++++++++++++++++++++++++---------------- tests/test_http.py | 101 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 156 insertions(+), 44 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 0e1cf96a..8718b70f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -835,6 +835,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: _install_cloned_dict(val, None, memo, stack) if hasattr(val, "__dict__") or hasattr(val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(val): + if type(attr_val) is bytes and len(attr_val) > _MAX_SAFE_BUFFER_SIZE: + return None if ( not _is_immutable(attr_val) and id(attr_val) not in memo @@ -1777,6 +1779,8 @@ def _flush_pending_structures() -> None: if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): if _is_immutable(attr_val): + if type(attr_val) is bytes and len(attr_val) > _MAX_SAFE_BUFFER_SIZE: + return None _assign_target(res_set, (slot_or_name, is_desc), True, attr_val) elif id(attr_val) in memo: _assign_target( @@ -1830,6 +1834,11 @@ def _flush_pending_structures() -> None: if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): if _is_immutable(attr_val): + if ( + type(attr_val) is bytes + and len(attr_val) > _MAX_SAFE_BUFFER_SIZE + ): + return None _assign_target(res_set, (slot_or_name, is_desc), True, attr_val) elif id(attr_val) in memo: _assign_target( @@ -3296,10 +3305,14 @@ async def _runner() -> Any: ) elif hasattr(waiter_task, "cancelled"): waiter_cancelling = waiter_task.cancelled() + if getattr(waiter_task, "_must_cancel", False): + waiter_cancelling = True except BaseException: pass try: - if hasattr(task, "cancelling") and task.cancelling() > 0: + if getattr(task, "_must_cancel", False): + waiter_cancelling = True + elif hasattr(task, "cancelling") and task.cancelling() > 0: waiter_cancelling = True elif hasattr(task, "cancelled") and task.cancelled(): waiter_cancelling = True @@ -3383,43 +3396,57 @@ def _on_task_done(t: Any) -> None: _detach_overdue_task(task, res, wrapper_started) raise - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val - ) + done_wait: set[Any] = set() try: - task_is_done = task.done() if hasattr(task, "done") else False - except BaseException: - _detach_overdue_task(task, res, wrapper_started) - raise + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None or completed_at[0] <= deadline_val + ) + try: + task_is_done = ( + task.done() if hasattr(task, "done") else False + ) + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise - if task_is_done and cb_finished_in_budget: - if not wrapper_started: - try: - task.cancel() - except BaseException: - pass - _cleanup_discarded_awaitable(res) - if hasattr(task, "result"): - res_val = task.result() - else: - res_val = AsyncTask.result(task) - if isinstance(res_val, (SystemExit, KeyboardInterrupt)): - raise res_val + if task_is_done and cb_finished_in_budget: + if not wrapper_started: + try: + task.cancel() + except BaseException: + pass + _cleanup_discarded_awaitable(res) + if hasattr(task, "result"): + res_val = task.result() + else: + res_val = AsyncTask.result(task) + if isinstance(res_val, (SystemExit, KeyboardInterrupt)): + raise res_val - remaining_budget = _transport.remaining() - if remaining_budget is not None and remaining_budget <= 0: - _detach_overdue_task(task, res, wrapper_started) - if result is not None: - return result - break - try: - done, _ = await async_wait( - {task_completion_fut}, timeout=remaining_budget - ) - except BaseException: - _detach_overdue_task(task, res, wrapper_started) - raise + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _detach_overdue_task(task, res, wrapper_started) + if result is not None: + return result + break + try: + done_wait, _ = await async_wait( + {task_completion_fut}, timeout=remaining_budget + ) + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise + finally: + try: + if hasattr(task, "remove_done_callback"): + task.remove_done_callback(_on_task_done) + elif isinstance(task, AsyncTask): + AsyncTask.remove_done_callback(task, _on_task_done) + else: + AsyncFuture.remove_done_callback(task, _on_task_done) + except BaseException: + pass deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] <= deadline_val @@ -3431,7 +3458,7 @@ def _on_task_done(t: Any) -> None: raise if cb_finished_in_budget and ( - task_completion_fut in done or task_is_done + task_completion_fut in done_wait or task_is_done ): if not wrapper_started: try: diff --git a/tests/test_http.py b/tests/test_http.py index 85d1a4ab..46f51cee 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1318,16 +1318,20 @@ async def test_wait_ends_on_the_read_that_names_another_head( with Server(lambda request, index: Reply(body=responses[index])) as server: polled_reviews: list[tuple[Any, int]] = [] if mode == "async": + first_cb_event = asyncio.Event() + second_cb_reached = asyncio.Event() cb_gate = asyncio.Event() waiter_task: asyncio.Task[Any] | None = None async def async_mismatch_cb(r: Any) -> None: if len(polled_reviews) == 1: assert waiter_task is not None - await asyncio.sleep(0.01) assert not waiter_task.done() + second_cb_reached.set() await cb_gate.wait() polled_reviews.append((r, len(server.requests))) + if len(polled_reviews) == 1: + first_cb_event.set() cb: Any = async_mismatch_cb else: @@ -1347,12 +1351,38 @@ def sync_mismatch_cb(r: Any) -> None: on_poll=cb, ) ) - while len(polled_reviews) < 1: - await asyncio.sleep(0.01) - await asyncio.sleep(0.05) + first_waiter = asyncio.create_task(first_cb_event.wait()) + try: + done_first, _ = await asyncio.wait( + {first_waiter, waiter_task}, + timeout=5.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task in done_first: + await waiter_task + assert first_cb_event.is_set() + finally: + if not first_waiter.done(): + first_waiter.cancel() + + gate_waiter = asyncio.create_task(second_cb_reached.wait()) + try: + done_gate, _ = await asyncio.wait( + {gate_waiter, waiter_task}, + timeout=5.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task in done_gate: + await waiter_task + assert second_cb_reached.is_set() + finally: + if not gate_waiter.done(): + gate_waiter.cancel() + + await asyncio.sleep(0.01) assert not waiter_task.done() cb_gate.set() - result = await waiter_task + result = await asyncio.wait_for(asyncio.shield(waiter_task), timeout=5.0) else: result = await call( client, @@ -4712,12 +4742,19 @@ def __eq__(self, other: Any) -> bool: inner_fs = frozenset([leaf_payload]) outer_fs = frozenset([inner_fs]) + class NonemptySubFrozenset1(frozenset[Any]): + pass + member_payload = HashablePayload("test_key", ["original_val"]) normal_s = {member_payload} - normal_fs = frozenset([member_payload]) + normal_fs = NonemptySubFrozenset1([member_payload]) + normal_fs.custom_attr = "subclass_attr_1" + normal_fs.shared_list = ["shared_val_1"] + alias_dict_1 = normal_fs.__dict__ detail_sets = CustomerReviewDetail.from_dict(responses[1]) detail_sets.additional_properties["normal_s"] = normal_s detail_sets.additional_properties["normal_fs"] = normal_fs + detail_sets.additional_properties["sub_fs_alias"] = alias_dict_1 detail_sets.additional_properties["nested_fs"] = outer_fs detail_sets.additional_properties["fs_list"] = [normal_fs, normal_fs] snap_sets = _snapshot_review(detail_sets) @@ -4725,7 +4762,13 @@ def __eq__(self, other: Any) -> bool: assert snap_sets.additional_properties["normal_s"] == normal_s assert snap_sets.additional_properties["normal_s"] is not normal_s copied_fs = snap_sets.additional_properties["normal_fs"] - assert isinstance(copied_fs, frozenset) + assert isinstance(copied_fs, NonemptySubFrozenset1) + assert copied_fs.custom_attr == "subclass_attr_1" + assert copied_fs.shared_list == ["shared_val_1"] + assert copied_fs.shared_list is not normal_fs.shared_list + copied_alias_dict = snap_sets.additional_properties["sub_fs_alias"] + assert copied_fs.__dict__ is copied_alias_dict + assert copied_fs.__dict__ is not alias_dict_1 assert len(copied_fs) == 1 copied_list = snap_sets.additional_properties["fs_list"] assert copied_list[0] is copied_list[1] @@ -5109,24 +5152,66 @@ def __hash__(self) -> int: def __eq__(self, other: Any) -> bool: return isinstance(other, CustomHashWithFrozenset) and self.f_set == other.f_set + class NonemptySubFrozenset2(frozenset[Any]): + pass + deferred_dict: dict[str, Any] = {"ready_key": "ready_val"} - f_set = frozenset([DictHolder(deferred_dict)]) + f_set = NonemptySubFrozenset2([DictHolder(deferred_dict)]) + f_set.custom_attr = "subclass_attr_2" + f_set.shared_list = ["shared_val_2"] + alias_dict_2 = f_set.__dict__ deferred_dict["pending_val"] = f_set custom_fs_obj = CustomHashWithFrozenset(f_set) set_with_fs_custom = {custom_fs_obj} detail_fs_custom = CustomerReviewDetail.from_dict(responses[1]) detail_fs_custom.additional_properties["fs_custom"] = set_with_fs_custom + detail_fs_custom.additional_properties["sub_fs_2_alias"] = alias_dict_2 snap_fsc = _snapshot_review(detail_fs_custom) assert snap_fsc is not None copied_fsc_set = snap_fsc.additional_properties["fs_custom"] assert len(copied_fsc_set) == 1 copied_obj = next(iter(copied_fsc_set)) assert copied_obj in copied_fsc_set + copied_f_set = copied_obj.f_set + assert isinstance(copied_f_set, NonemptySubFrozenset2) + assert copied_f_set.custom_attr == "subclass_attr_2" + assert copied_f_set.shared_list == ["shared_val_2"] + assert copied_f_set.shared_list is not f_set.shared_list + copied_alias_2 = snap_fsc.additional_properties["sub_fs_2_alias"] + assert copied_f_set.__dict__ is copied_alias_2 + assert copied_f_set.__dict__ is not alias_dict_2 copied_holder = next(iter(copied_obj.f_set)) assert copied_holder.d["ready_key"] == "ready_val" assert copied_holder.d["pending_val"] is copied_obj.f_set assert copied_holder.d is not deferred_dict + # Dictionary key whose hash depends on cloned nested state: snapshot succeeds and lookup works + class NestedStateKey: + def __init__(self, inner: dict[str, Any]) -> None: + self.inner = inner + + def __hash__(self) -> int: + return hash(tuple(sorted((k, str(v)) for k, v in self.inner.items()))) + + def __eq__(self, other: Any) -> bool: + return isinstance(other, NestedStateKey) and self.inner == other.inner + + inner_mapping = {"nested_field": "nested_val"} + nested_key = NestedStateKey(inner_mapping) + dict_with_nested_key = {nested_key: "found_val"} + detail_nested = CustomerReviewDetail.from_dict(responses[1]) + detail_nested.additional_properties["nested_key_dict"] = dict_with_nested_key + + snap_nested = _snapshot_review(detail_nested) + assert snap_nested is not None + copied_nested_dict = snap_nested.additional_properties["nested_key_dict"] + copied_k = next(iter(copied_nested_dict.keys())) + assert copied_k is not nested_key + assert copied_k.inner is not inner_mapping + assert copied_k.inner == {"nested_field": "nested_val"} + assert copied_nested_dict[copied_k] == "found_val" + assert copied_k in copied_nested_dict + # Dictionary fixture whose key hash changes during clone finalization: snapshot is rejected class MutatingHashKey: def __init__(self) -> None: From 22e6ad5a4c8aeff1aa29952fcfed6db84de0ce07 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 15:13:11 +0530 Subject: [PATCH 64/75] Address review run 63 findings: mmap backing buffer isolation, tuple subclass dict finalization, dict source order, wait loop budget recheck, and watchdog assertions --- proofline/client.py | 138 ++++++++++++++++++++++++++------------------ tests/test_http.py | 132 ++++++++++++++++++++++-------------------- 2 files changed, 152 insertions(+), 118 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 8718b70f..5441ed32 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -6,6 +6,7 @@ import ctypes import datetime import math +import mmap import weakref from asyncio import ( CancelledError as AsyncCancelledError, @@ -495,13 +496,6 @@ def _install_cloned_dict( except Exception: cloned_dict = {} memo[dict_id] = cloned_dict - for k, v in inst_dict.items(): - if _is_immutable(k) and _is_immutable(v): - if type(k) is bytes and len(k) > _MAX_SAFE_BUFFER_SIZE: - continue - if type(v) is bytes and len(v) > _MAX_SAFE_BUFFER_SIZE: - continue - cloned_dict[k] = v stack.append((_DICT_EXPAND, cloned_dict, iter(inst_dict.items()))) if new_obj is not None: try: @@ -569,6 +563,7 @@ def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | Non fallback_built_frozensets: list[tuple[Any, list[Any]]] = [] deferred_attr_assignments: list[tuple[Any, tuple[Any, bool], Any]] = [] populated_mutable_sets: list[tuple[Any, list[Any]]] = [] + backing_buffer_memo: dict[int, Any] = {} def _collect_set_members(val: Any) -> list[Any] | None: if isinstance(val, set): @@ -606,18 +601,23 @@ def _collect_set_members(val: Any) -> list[Any] | None: if task_type == _ITEM_TASK: key, is_attr, val = it_or_key, extra[0], extra[1] - if isinstance( - val, - ( - FunctionType, - MethodType, - weakref.ref, - weakref.ProxyType, - weakref.CallableProxyType, - ), - ) or ( - isinstance(val, BuiltinFunctionType) - and isinstance(getattr(val, "__self__", None), ModuleType) + if ( + isinstance( + val, + ( + FunctionType, + MethodType, + weakref.ref, + weakref.ProxyType, + weakref.CallableProxyType, + ), + ) + or ( + isinstance(val, BuiltinFunctionType) + and isinstance(getattr(val, "__self__", None), ModuleType) + ) + or isinstance(val, mmap.mmap) + or type(val).__name__ == "mmap" ): raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" @@ -1128,9 +1128,14 @@ def _collect_set_members(val: Any) -> list[Any] | None: f"{type(val).__name__}" ) if exporter is not None: + if isinstance(exporter, mmap.mmap) or type(exporter).__name__ == "mmap": + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(exporter).__name__}" + ) exp_id = id(exporter) - if exp_id in memo: - cloned_buf = memo[exp_id] + if exp_id in backing_buffer_memo: + cloned_buf = backing_buffer_memo[exp_id] else: exp_readonly = False try: @@ -1152,7 +1157,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: cloned_buf = bytes(exporter) else: cloned_buf = bytearray(exporter) - memo[exp_id] = cloned_buf + backing_buffer_memo[exp_id] = cloned_buf offset = 0 try: b_val = _Py_buffer() @@ -1425,6 +1430,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: deferred_tuple_finalizations.append( (target, key, is_attr, val_id, orig_val, temp_list) ) + if hasattr(orig_val, "__dict__"): + _install_cloned_dict(orig_val, None, memo, stack) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): if not _is_immutable(attr_val) and id(attr_val) not in memo: @@ -1621,6 +1628,8 @@ def _flush_pending_structures() -> None: except Exception: continue memo[val_id] = res_tuple + if hasattr(orig_val, "__dict__"): + _install_cloned_dict(orig_val, res_tuple, memo, stack) if hasattr(orig_val, "__dict__") or hasattr(orig_val, "__slots__"): for slot_or_name, is_desc, attr_val in _get_obj_attrs(orig_val): val_to_set = ( @@ -3236,28 +3245,39 @@ def _on_future_done(_: Any) -> None: raise done: set[Any] = set() try: - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val - ) - if cb_finished_in_budget: - if hasattr(res, "result"): - res.result() - else: - AsyncFuture.result(res) - remaining_budget = _transport.remaining() - if remaining_budget is not None and remaining_budget <= 0: - _detach_overdue_future(res) - if result is not None: - return result - break - try: - done, _ = await async_wait( - {completion_fut}, timeout=remaining_budget + while True: + deadline_val = _transport.DEADLINE.get() + cb_finished_in_budget = bool(completed_at) and ( + deadline_val is None + or completed_at[0] <= deadline_val ) - except BaseException: - _detach_overdue_future(res) - raise + if cb_finished_in_budget: + if hasattr(res, "result"): + res.result() + else: + AsyncFuture.result(res) + break + remaining_budget = _transport.remaining() + if ( + remaining_budget is not None + and remaining_budget <= 0 + ): + _detach_overdue_future(res) + if result is not None: + return result + break + try: + done, _ = await async_wait( + {completion_fut}, timeout=remaining_budget + ) + except BaseException: + _detach_overdue_future(res) + raise + if completion_fut in done: + break + rem_after = _transport.remaining() + if rem_after is not None and rem_after <= 0: + break finally: try: if hasattr(res, "remove_done_callback"): @@ -3424,19 +3444,25 @@ def _on_task_done(t: Any) -> None: if isinstance(res_val, (SystemExit, KeyboardInterrupt)): raise res_val - remaining_budget = _transport.remaining() - if remaining_budget is not None and remaining_budget <= 0: - _detach_overdue_task(task, res, wrapper_started) - if result is not None: - return result - break - try: - done_wait, _ = await async_wait( - {task_completion_fut}, timeout=remaining_budget - ) - except BaseException: - _detach_overdue_task(task, res, wrapper_started) - raise + while True: + remaining_budget = _transport.remaining() + if remaining_budget is not None and remaining_budget <= 0: + _detach_overdue_task(task, res, wrapper_started) + if result is not None: + return result + break + try: + done_wait, _ = await async_wait( + {task_completion_fut}, timeout=remaining_budget + ) + except BaseException: + _detach_overdue_task(task, res, wrapper_started) + raise + if task_completion_fut in done_wait: + break + rem_after = _transport.remaining() + if rem_after is not None and rem_after <= 0: + break finally: try: if hasattr(task, "remove_done_callback"): diff --git a/tests/test_http.py b/tests/test_http.py index 46f51cee..c980d498 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1351,38 +1351,47 @@ def sync_mismatch_cb(r: Any) -> None: on_poll=cb, ) ) - first_waiter = asyncio.create_task(first_cb_event.wait()) try: - done_first, _ = await asyncio.wait( - {first_waiter, waiter_task}, - timeout=5.0, - return_when=asyncio.FIRST_COMPLETED, - ) - if waiter_task in done_first: - await waiter_task - assert first_cb_event.is_set() - finally: - if not first_waiter.done(): - first_waiter.cancel() - - gate_waiter = asyncio.create_task(second_cb_reached.wait()) - try: - done_gate, _ = await asyncio.wait( - {gate_waiter, waiter_task}, - timeout=5.0, - return_when=asyncio.FIRST_COMPLETED, - ) - if waiter_task in done_gate: - await waiter_task - assert second_cb_reached.is_set() + first_waiter = asyncio.create_task(first_cb_event.wait()) + try: + done_first, _ = await asyncio.wait( + {first_waiter, waiter_task}, + timeout=5.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task in done_first: + await waiter_task + assert first_cb_event.is_set() + finally: + if not first_waiter.done(): + first_waiter.cancel() + + gate_waiter = asyncio.create_task(second_cb_reached.wait()) + try: + done_gate, _ = await asyncio.wait( + {gate_waiter, waiter_task}, + timeout=5.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if waiter_task in done_gate: + await waiter_task + assert second_cb_reached.is_set() + finally: + if not gate_waiter.done(): + gate_waiter.cancel() + + await asyncio.sleep(0.01) + assert not waiter_task.done() + cb_gate.set() + result = await asyncio.wait_for(waiter_task, timeout=5.0) finally: - if not gate_waiter.done(): - gate_waiter.cancel() - - await asyncio.sleep(0.01) - assert not waiter_task.done() - cb_gate.set() - result = await asyncio.wait_for(asyncio.shield(waiter_task), timeout=5.0) + if waiter_task is not None and not waiter_task.done(): + waiter_task.cancel() + if waiter_task is not None: + try: + await waiter_task + except (asyncio.CancelledError, BaseException): + pass else: result = await call( client, @@ -2861,6 +2870,8 @@ def __init__(self, loop: asyncio.AbstractEventLoop) -> None: def add_done_callback(self, fn: Any, *, context: Any = None) -> None: super().add_done_callback(fn, context=context) self.active_callbacks.append(fn) + if "_on_future_done" in getattr(fn, "__name__", ""): + clock.advance(1.0) self.wait_entered.set() def remove_done_callback(self, fn: Any) -> int: @@ -2899,37 +2910,23 @@ def pending_future_callback(r: Any) -> SignallingFuture: if waiter_task_1 in done_1: await waiter_task_1 assert pending_fut is not None - wait_entered_task_1 = asyncio.create_task(pending_fut.wait_entered.wait()) - try: - done_entered, _ = await asyncio.wait( - {wait_entered_task_1, waiter_task_1}, - return_when=asyncio.FIRST_COMPLETED, - ) - if waiter_task_1 in done_entered: - await waiter_task_1 - assert not waiter_task_1.done() - assert id(pending_fut) not in client_module._DETACHED_FUTURES - clock.advance(1.0) - res_1 = await waiter_task_1 - assert res_1.status == "TIMED_OUT" - assert not pending_fut.cancelled() - assert not pending_fut.done() - assert id(pending_fut) in client_module._DETACHED_FUTURES - assert len(pending_fut.removed_callbacks) > 0 - assert any( - "_on_future_done" in getattr(cb, "__name__", "") - for cb in pending_fut.removed_callbacks - ) - pending_fut.set_result(None) - await asyncio.sleep(0) - assert id(pending_fut) not in client_module._DETACHED_FUTURES - finally: - if not wait_entered_task_1.done(): - wait_entered_task_1.cancel() - try: - await wait_entered_task_1 - except (asyncio.CancelledError, BaseException): - pass + res_1 = await asyncio.wait_for(waiter_task_1, timeout=1.0) + assert res_1.status == "TIMED_OUT" + assert not pending_fut.cancelled() + assert not pending_fut.done() + assert id(pending_fut) in client_module._DETACHED_FUTURES + assert len(pending_fut.removed_callbacks) > 0 + assert any( + "_on_future_done" in getattr(cb, "__name__", "") + for cb in pending_fut.removed_callbacks + ) + assert not any( + "_on_future_done" in getattr(cb, "__name__", "") + for cb in pending_fut.active_callbacks + ) + pending_fut.set_result(None) + await asyncio.sleep(0) + assert id(pending_fut) not in client_module._DETACHED_FUTURES finally: if not startup_waiter_1.done(): startup_waiter_1.cancel() @@ -3210,9 +3207,15 @@ async def continuing_coro_term(r: Any) -> None: assert res_4.status == "COMPLETED" assert not callback_finished_term.is_set() - release_callback_term.set() assert len(captured_case4_wrappers) == 1 wrapper_4 = captured_case4_wrappers[0] + wrapper_4_cbs = [ + cb[0] if isinstance(cb, tuple) else cb + for cb in (getattr(wrapper_4, "_callbacks", None) or []) + ] + assert not any(getattr(cb, "__name__", "") == "_on_task_done" for cb in wrapper_4_cbs) + + release_callback_term.set() finish_waiter_4 = asyncio.create_task(callback_finished_term.wait()) try: done_fin_4, _ = await asyncio.wait( @@ -3528,6 +3531,11 @@ async def failing_overdue_coro(r: Any) -> None: assert len(client_module._DETACHED_TASKS) == 1 detached_task_id = next(iter(client_module._DETACHED_TASKS.keys())) detached_task = client_module._DETACHED_TASKS[detached_task_id] + detached_cbs = [ + cb[0] if isinstance(cb, tuple) else cb + for cb in (getattr(detached_task, "_callbacks", None) or []) + ] + assert not any(getattr(cb, "__name__", "") == "_on_task_done" for cb in detached_cbs) coro_trigger.set() await asyncio.wait_for(about_to_raise.wait(), timeout=1.0) From b127bd4fb4c9a8a5316951c6a7ff945f166be68c Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 15:28:49 +0530 Subject: [PATCH 65/75] Address review run 64 findings: direct datetime subclass allocation, cancellation qualification and observation, and review head commit assertion --- README.md | 2 +- proofline/client.py | 76 ++++++++++++++++++++++++++++++--------------- tests/test_http.py | 2 ++ 3 files changed, 54 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 4792060c..1be14070 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ if outcome.status != "COMPLETED": `on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them, except for wrappers cancelled before their first step which are timed when their done callback runs), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled), while already-running callback tasks and pending futures are detached without cancellation and may continue running (detached callback coroutines suppress late SystemExit and KeyboardInterrupt signals; waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them, except for wrappers cancelled before their first step which are timed when their done callback runs), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled; cancelling the waiter through an underlying pending future can leave unresumed tasks unflagged until resumption unless observed through the pending future), while already-running callback tasks and pending futures are detached without cancellation and may continue running (detached callback coroutines suppress late SystemExit and KeyboardInterrupt signals; waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, waiter cancellation during inline callback invocation, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index 5441ed32..f072799b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -1210,6 +1210,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) + if type(val) is not datetime.datetime and "__copy__" in type(val).__dict__: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) tz = val.tzinfo copied_tz = tz if tz is not None and type(tz) is not datetime.timezone: @@ -1247,26 +1251,23 @@ def _collect_set_members(val: Any) -> list[Any] | None: _assign_target(target, key, is_attr, new_dt) else: try: - new_dt = val.replace(tzinfo=copied_tz) - except Exception: - try: - new_dt = type(val).__new__( - type(val), - val.year, - val.month, - val.day, - val.hour, - val.minute, - val.second, - val.microsecond, - tzinfo=copied_tz, - fold=val.fold, - ) - except Exception as exc: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) from exc + new_dt = datetime.datetime.__new__( + type(val), + val.year, + val.month, + val.day, + val.hour, + val.minute, + val.second, + val.microsecond, + tzinfo=copied_tz, + fold=val.fold, + ) + except Exception as exc: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) from exc if new_dt is val or new_dt.tzinfo is not copied_tz: raise TypeError( "Unsupported mutable value in review extension data: " @@ -3091,11 +3092,13 @@ async def wait_for_review( This allows any classified outcome to be returned when a callback finishes or returns after the deadline. When the deadline expires or when the wait is cancelled, unstarted coroutines returned by on_poll are closed without entering their body (a wrapper task - may already have been scheduled), while already-running callback tasks and futures are - detached without cancellation and may continue running (detached callback coroutines - suppress late SystemExit and KeyboardInterrupt signals, which do not propagate once - detached). Synchronous callbacks must return before a terminal result can be - delivered and the polling deadline cannot interrupt them. + may already have been scheduled; cancelling the waiter through an underlying pending + future can leave unresumed tasks unflagged until resumption unless observed through the + pending future), while already-running callback tasks and futures are detached without + cancellation and may continue running (detached callback coroutines suppress late + SystemExit and KeyboardInterrupt signals, which do not propagate once detached). + Synchronous callbacks must return before a terminal result can be delivered and the + polling deadline cannot interrupt them. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -3327,6 +3330,24 @@ async def _runner() -> Any: waiter_cancelling = waiter_task.cancelled() if getattr(waiter_task, "_must_cancel", False): waiter_cancelling = True + fw = getattr(waiter_task, "_fut_waiter", None) + while fw is not None: + try: + if ( + hasattr(fw, "cancelling") + and fw.cancelling() > 0 + ): + waiter_cancelling = True + break + if hasattr(fw, "cancelled") and fw.cancelled(): + waiter_cancelling = True + break + if getattr(fw, "_must_cancel", False): + waiter_cancelling = True + break + fw = getattr(fw, "_fut_waiter", None) + except BaseException: + break except BaseException: pass try: @@ -3338,6 +3359,11 @@ async def _runner() -> Any: waiter_cancelling = True except BaseException: pass + try: + if task_completion_fut.cancelled(): + waiter_cancelling = True + except BaseException: + pass deadline_expired = ( captured_deadline is not None diff --git a/tests/test_http.py b/tests/test_http.py index c980d498..beed02a5 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1309,6 +1309,7 @@ async def test_wait_ends_on_the_read_that_names_another_head( ) assert result.status == "INCOMPLETE" assert result.review.status == "RUNNING" + assert result.review.head_commit_sha == HEAD assert gap_facts(result) == [PINNED_ELSEWHERE] assert result.reason == "The review is pinned to another head commit." assert len(server.requests) == 2 @@ -1408,6 +1409,7 @@ def sync_mismatch_cb(r: Any) -> None: assert polled_reviews[1][0].head_commit_sha == HEAD assert result.status == "INCOMPLETE" assert result.review.status == "RUNNING" + assert result.review.head_commit_sha == HEAD assert gap_facts(result) == [PINNED_ELSEWHERE] assert result.reason == "The review is pinned to another head commit." # The second read names the head, so the review that would complete is never read. From c0fa8ebcc6e3b15538563f80ec4c838f17169966 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 16:49:53 +0530 Subject: [PATCH 66/75] Address review run 65 findings: ctypes array and view preservation, wrapper deadline operator, wait loop completion break, and test cleanup settling --- proofline/client.py | 119 ++++++++++++++++++++++++++++++++++++++++---- tests/test_http.py | 12 +++-- 2 files changed, 116 insertions(+), 15 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index f072799b..830537f7 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -968,7 +968,86 @@ def _collect_set_members(val: Any) -> list[Any] | None: except BaseException: pass resolved_mv: Any - if isinstance(exporter, (bytearray, array.array, bytes)): + if isinstance(exporter, ctypes.Array): + if _has_mutable_class_attrs(type(exporter)): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(exporter).__name__}" + ) + exp_id = id(exporter) + if exp_id in memo: + cloned_exporter = memo[exp_id] + else: + if ctypes.sizeof(exporter) > _MAX_SAFE_BUFFER_SIZE: + return None + cloned_exporter = type(exporter).from_buffer_copy(exporter) + memo[exp_id] = cloned_exporter + if hasattr(exporter, "__dict__") or hasattr(exporter, "__slots__"): + _install_cloned_dict(exporter, cloned_exporter, memo, stack) + stack.append( + (_OBJ_EXPAND, cloned_exporter, iter(_get_obj_attrs(exporter))) + ) + b_val = _Py_buffer() + b_exp = _Py_buffer() + offset = 0 + if _py_get_buffer(val, ctypes.byref(b_val), 0x0118) != 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + try: + if _py_get_buffer(exporter, ctypes.byref(b_exp), 0x0118) != 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(exporter).__name__}" + ) + try: + offset = b_val.buf - b_exp.buf + finally: + _py_release_buffer(ctypes.byref(b_exp)) + finally: + _py_release_buffer(ctypes.byref(b_val)) + elem_type = getattr(type(exporter), "_type_", ctypes.c_byte) + val_strides = val.strides + val_shape = val.shape + if val.ndim == 0: + scalar_obj = elem_type.from_buffer(cloned_exporter, offset) + resolved_mv = memoryview(scalar_obj) + elif val.ndim == 1 and val_shape is not None and val_strides is not None: + shape = val_shape[0] + itemsize = val.itemsize + stride = val_strides[0] + elem_stride = stride // itemsize if itemsize > 0 else 1 + if shape == 0: + sub_arr = (elem_type * 0).from_buffer(cloned_exporter, offset) + resolved_mv = memoryview(sub_arr) + elif stride >= 0: + span_items = (shape - 1) * elem_stride + 1 + sub_arr = (elem_type * span_items).from_buffer(cloned_exporter, offset) + resolved_mv = memoryview(sub_arr)[::elem_stride] + else: + lowest_byte = offset + (shape - 1) * stride + span_items = (shape - 1) * abs(elem_stride) + 1 + sub_arr = (elem_type * span_items).from_buffer( + cloned_exporter, lowest_byte + ) + start_elem = (shape - 1) * (-elem_stride) + resolved_mv = memoryview(sub_arr)[start_elem:None:elem_stride] + elif val.c_contiguous: + count = val.nbytes // val.itemsize if val.itemsize > 0 else 0 + sub_arr = (elem_type * count).from_buffer(cloned_exporter, offset) + resolved_mv = memoryview(sub_arr) + else: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{type(val).__name__}" + ) + if val.readonly: + resolved_mv = resolved_mv.toreadonly() + memo[val_id] = resolved_mv + _assign_target(target, key, is_attr, resolved_mv) + continue + elif isinstance(exporter, (bytearray, array.array, bytes)): if type(exporter) not in ( bytearray, array.array, @@ -1278,6 +1357,26 @@ def _collect_set_members(val: Any) -> list[Any] | None: if hasattr(val, "__dict__") or hasattr(val, "__slots__"): _install_cloned_dict(val, new_dt, memo, stack) stack.append((_OBJ_EXPAND, new_dt, iter(_get_obj_attrs(val)))) + elif isinstance(val, ctypes.Array): + arr_nbytes = ctypes.sizeof(val) + if arr_nbytes > _MAX_SAFE_BUFFER_SIZE: + return None + if _has_mutable_class_attrs(type(val)): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) + new_arr: Any + try: + new_arr = type(val).from_buffer_copy(val) + except Exception as exc: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) from exc + memo[val_id] = new_arr + _assign_target(target, key, is_attr, new_arr) + if hasattr(val, "__dict__") or hasattr(val, "__slots__"): + _install_cloned_dict(val, new_arr, memo, stack) + stack.append((_OBJ_EXPAND, new_arr, iter(_get_obj_attrs(val)))) elif hasattr(val, "__dict__") or hasattr(val, "__slots__"): if _has_mutable_class_attrs(type(val)): raise TypeError( @@ -2645,7 +2744,10 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: - if error.status == 0 and (_transport.remaining() or 0) <= 0: + if ( + error.type == "urn:proofline:sdk:timeout" + or (error.status == 0 and (_transport.remaining() or 0) <= 0.05) + ): break raise if (_transport.remaining() or 0) <= 0: @@ -3113,7 +3215,10 @@ async def wait_for_review( try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: - if error.status == 0 and (_transport.remaining() or 0) <= 0: + if ( + error.type == "urn:proofline:sdk:timeout" + or (error.status == 0 and (_transport.remaining() or 0) <= 0.05) + ): break raise if (_transport.remaining() or 0) <= 0: @@ -3265,9 +3370,6 @@ def _on_future_done(_: Any) -> None: remaining_budget is not None and remaining_budget <= 0 ): - _detach_overdue_future(res) - if result is not None: - return result break try: done, _ = await async_wait( @@ -3367,7 +3469,7 @@ async def _runner() -> Any: deadline_expired = ( captured_deadline is not None - and monotonic() > captured_deadline + and monotonic() >= captured_deadline ) if waiter_cancelling or deadline_expired: _cleanup_discarded_awaitable(coro) @@ -3473,9 +3575,6 @@ def _on_task_done(t: Any) -> None: while True: remaining_budget = _transport.remaining() if remaining_budget is not None and remaining_budget <= 0: - _detach_overdue_task(task, res, wrapper_started) - if result is not None: - return result break try: done_wait, _ = await async_wait( diff --git a/tests/test_http.py b/tests/test_http.py index beed02a5..d0fb1abf 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2912,7 +2912,9 @@ def pending_future_callback(r: Any) -> SignallingFuture: if waiter_task_1 in done_1: await waiter_task_1 assert pending_fut is not None - res_1 = await asyncio.wait_for(waiter_task_1, timeout=1.0) + done_waiter_1, _ = await asyncio.wait({waiter_task_1}, timeout=1.0) + assert waiter_task_1 in done_waiter_1 + res_1 = waiter_task_1.result() assert res_1.status == "TIMED_OUT" assert not pending_fut.cancelled() assert not pending_fut.done() @@ -2930,6 +2932,8 @@ def pending_future_callback(r: Any) -> SignallingFuture: await asyncio.sleep(0) assert id(pending_fut) not in client_module._DETACHED_FUTURES finally: + if pending_fut is not None and not pending_fut.done(): + pending_fut.set_result(None) if not startup_waiter_1.done(): startup_waiter_1.cancel() try: @@ -2939,11 +2943,9 @@ def pending_future_callback(r: Any) -> SignallingFuture: if not waiter_task_1.done(): waiter_task_1.cancel() try: - await waiter_task_1 - except (asyncio.CancelledError, BaseException): + done_clean_1, _ = await asyncio.wait({waiter_task_1}, timeout=1.0) + except BaseException: pass - if pending_fut is not None and not pending_fut.done(): - pending_fut.set_result(None) # Case 2: Pending same-loop Future that completes within budget without cancellation completed_fut = asyncio.get_running_loop().create_future() From a212bddcd3966942bbcae51d1f08cadbb127e8ee Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 17:27:24 +0530 Subject: [PATCH 67/75] Address review run 66 findings: ctypes layout validation, byte offset memoryview reconstruction, strict deadline comparison, Case 6c bounded wait, and mismatch review isolation --- proofline/client.py | 155 ++++++++++++++++++++++++++++++-------------- tests/test_http.py | 65 ++++++++++++++----- 2 files changed, 153 insertions(+), 67 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 830537f7..4ccbf5c9 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -323,6 +323,8 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if val is None or val is UNSET: return True if isinstance(val, type): + if issubclass(val, (ctypes._SimpleCData, ctypes.Structure, ctypes.Union, ctypes.Array)): + return True return val in _SAFE_BUILTIN_CLASSES t = type(val) if t in _IMMUTABLE_TYPES: @@ -403,7 +405,17 @@ def _has_mutable_class_attrs(cls: type) -> bool: for base in cls.__mro__: if base in _SAFE_BUILTIN_CLASSES or base is object: continue + is_arr_cls = issubclass(base, ctypes.Array) for name, attr in base.__dict__.items(): + if is_arr_cls and name in ("_type_", "_length_"): + if name == "_length_": + if not isinstance(attr, int) or attr < 0: + return True + continue + if name == "_type_": + if not (isinstance(attr, type) or hasattr(attr, "_type_")): + return True + continue if name in _SAFE_SPECIAL_ATTRS: continue if isinstance(attr, MemberDescriptorType) or type(attr).__name__ in ( @@ -439,7 +451,10 @@ def _assign_target(target: Any, key: Any, is_attr: bool, val: Any) -> None: if is_attr: slot_or_name, is_desc = key if is_desc: - slot_or_name.__set__(target, val) + try: + slot_or_name.__set__(target, val) + except AttributeError: + pass else: setattr(target, slot_or_name, val) else: @@ -969,10 +984,23 @@ def _collect_set_members(val: Any) -> list[Any] | None: pass resolved_mv: Any if isinstance(exporter, ctypes.Array): - if _has_mutable_class_attrs(type(exporter)): + exp_cls = type(exporter) + exp_elem_type = getattr(exp_cls, "_type_", None) + exp_len = getattr(exp_cls, "_length_", None) + if not (isinstance(exp_elem_type, type) or hasattr(exp_elem_type, "_type_")): raise TypeError( "Unsupported mutable value in review extension data: " - f"{type(exporter).__name__}" + f"{exp_cls.__name__}" + ) + if not isinstance(exp_len, int) or exp_len < 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{exp_cls.__name__}" + ) + if _has_mutable_class_attrs(exp_cls): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{exp_cls.__name__}" ) exp_id = id(exporter) if exp_id in memo: @@ -982,11 +1010,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: return None cloned_exporter = type(exporter).from_buffer_copy(exporter) memo[exp_id] = cloned_exporter - if hasattr(exporter, "__dict__") or hasattr(exporter, "__slots__"): + if hasattr(exporter, "__dict__"): _install_cloned_dict(exporter, cloned_exporter, memo, stack) - stack.append( - (_OBJ_EXPAND, cloned_exporter, iter(_get_obj_attrs(exporter))) - ) b_val = _Py_buffer() b_exp = _Py_buffer() offset = 0 @@ -1010,38 +1035,64 @@ def _collect_set_members(val: Any) -> list[Any] | None: elem_type = getattr(type(exporter), "_type_", ctypes.c_byte) val_strides = val.strides val_shape = val.shape - if val.ndim == 0: - scalar_obj = elem_type.from_buffer(cloned_exporter, offset) - resolved_mv = memoryview(scalar_obj) - elif val.ndim == 1 and val_shape is not None and val_strides is not None: - shape = val_shape[0] + full_mv = memoryview(cloned_exporter) + if val.format == full_mv.format: itemsize = val.itemsize - stride = val_strides[0] - elem_stride = stride // itemsize if itemsize > 0 else 1 - if shape == 0: - sub_arr = (elem_type * 0).from_buffer(cloned_exporter, offset) - resolved_mv = memoryview(sub_arr) - elif stride >= 0: - span_items = (shape - 1) * elem_stride + 1 - sub_arr = (elem_type * span_items).from_buffer(cloned_exporter, offset) - resolved_mv = memoryview(sub_arr)[::elem_stride] + item_offset = offset // itemsize if itemsize > 0 else 0 + if val.ndim == 0: + scalar_obj = elem_type.from_buffer(cloned_exporter, offset) + resolved_mv = memoryview(scalar_obj) + elif val.ndim == 1 and val_shape is not None and val_strides is not None: + shape = val_shape[0] + stride = val_strides[0] + elem_stride = stride // itemsize if itemsize > 0 else 1 + if shape == 0: + resolved_mv = full_mv[0:0] + elif elem_stride > 0: + resolved_mv = full_mv[ + item_offset : item_offset + shape * elem_stride : elem_stride + ] + else: + last = item_offset + (shape - 1) * elem_stride + stop = None if last == 0 else (last + elem_stride) + resolved_mv = full_mv[item_offset:stop:elem_stride] + elif val.c_contiguous: + count = val.nbytes // val.itemsize if val.itemsize > 0 else 0 + resolved_mv = full_mv[item_offset : item_offset + count] else: - lowest_byte = offset + (shape - 1) * stride - span_items = (shape - 1) * abs(elem_stride) + 1 - sub_arr = (elem_type * span_items).from_buffer( - cloned_exporter, lowest_byte - ) - start_elem = (shape - 1) * (-elem_stride) - resolved_mv = memoryview(sub_arr)[start_elem:None:elem_stride] - elif val.c_contiguous: - count = val.nbytes // val.itemsize if val.itemsize > 0 else 0 - sub_arr = (elem_type * count).from_buffer(cloned_exporter, offset) - resolved_mv = memoryview(sub_arr) + resolved_mv = full_mv + elif val.format == "B": + full_bytes = full_mv.cast("B") + if val.ndim == 0: + resolved_mv = full_bytes[offset : offset + 1].cast("B", shape=()) + elif val.ndim == 1 and val_shape is not None and val_strides is not None: + shape = val_shape[0] + stride = val_strides[0] + if shape == 0: + resolved_mv = full_bytes[0:0] + elif stride > 0: + resolved_mv = full_bytes[offset : offset + shape * stride : stride] + else: + last = offset + (shape - 1) * stride + stop = None if last == 0 else (last + stride) + resolved_mv = full_bytes[offset:stop:stride] + elif val.c_contiguous: + resolved_mv = full_bytes[offset : offset + val.nbytes] + elif val_shape is not None: + full_bytes_slice: Any = full_bytes[offset : offset + val.nbytes] + resolved_mv = full_bytes_slice.cast("B", shape=val_shape) + else: + resolved_mv = full_bytes[offset : offset + val.nbytes] else: - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{type(val).__name__}" - ) + full_bytes = full_mv.cast("B") + try: + full_bytes_slice = full_bytes[offset : offset + val.nbytes] + if val_shape is not None: + resolved_mv = full_bytes_slice.cast(val.format, shape=val_shape) + else: + resolved_mv = full_bytes_slice.cast(val.format) + except Exception: + resolved_mv = full_mv if val.readonly: resolved_mv = resolved_mv.toreadonly() memo[val_id] = resolved_mv @@ -1140,11 +1191,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: f"{type(exporter).__name__}" ) from exc memo[exp_id] = cloned_exporter - if hasattr(exporter, "__dict__") or hasattr(exporter, "__slots__"): + if hasattr(exporter, "__dict__"): _install_cloned_dict(exporter, cloned_exporter, memo, stack) - stack.append( - (_OBJ_EXPAND, cloned_exporter, iter(_get_obj_attrs(exporter))) - ) b_val = _Py_buffer() b_exp = _Py_buffer() if _py_get_buffer(val, ctypes.byref(b_val), 0x0118) != 0: @@ -1361,9 +1409,20 @@ def _collect_set_members(val: Any) -> list[Any] | None: arr_nbytes = ctypes.sizeof(val) if arr_nbytes > _MAX_SAFE_BUFFER_SIZE: return None - if _has_mutable_class_attrs(type(val)): + val_cls = type(val) + val_elem_type = getattr(val_cls, "_type_", None) + val_len = getattr(val_cls, "_length_", None) + if not (isinstance(val_elem_type, type) or hasattr(val_elem_type, "_type_")): raise TypeError( - f"Unsupported mutable value in review extension data: {type(val).__name__}" + f"Unsupported mutable value in review extension data: {val_cls.__name__}" + ) + if not isinstance(val_len, int) or val_len < 0: + raise TypeError( + f"Unsupported mutable value in review extension data: {val_cls.__name__}" + ) + if _has_mutable_class_attrs(val_cls): + raise TypeError( + f"Unsupported mutable value in review extension data: {val_cls.__name__}" ) new_arr: Any try: @@ -2744,9 +2803,8 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: - if ( - error.type == "urn:proofline:sdk:timeout" - or (error.status == 0 and (_transport.remaining() or 0) <= 0.05) + if error.type == "urn:proofline:sdk:timeout" or ( + error.status == 0 and (_transport.remaining() or 0) <= 0 ): break raise @@ -3215,9 +3273,8 @@ async def wait_for_review( try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: - if ( - error.type == "urn:proofline:sdk:timeout" - or (error.status == 0 and (_transport.remaining() or 0) <= 0.05) + if error.type == "urn:proofline:sdk:timeout" or ( + error.status == 0 and (_transport.remaining() or 0) <= 0 ): break raise @@ -3288,7 +3345,7 @@ async def wait_for_review( if is_done: deadline_val = _transport.DEADLINE.get() cb_returned_in_budget = ( - deadline_val is None or cb_return_time <= deadline_val + deadline_val is None or cb_return_time < deadline_val ) if cb_returned_in_budget: if hasattr(res, "result"): diff --git a/tests/test_http.py b/tests/test_http.py index d0fb1abf..54c865fe 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1331,6 +1331,8 @@ async def async_mismatch_cb(r: Any) -> None: second_cb_reached.set() await cb_gate.wait() polled_reviews.append((r, len(server.requests))) + r.status = "MUTATED" + r.head_commit_sha = "mutated_sha" if len(polled_reviews) == 1: first_cb_event.set() @@ -1339,6 +1341,8 @@ async def async_mismatch_cb(r: Any) -> None: def sync_mismatch_cb(r: Any) -> None: polled_reviews.append((r, len(server.requests))) + r.status = "MUTATED" + r.head_commit_sha = "mutated_sha" cb = sync_mismatch_cb async with session(mode, server.url) as client: @@ -1403,13 +1407,14 @@ def sync_mismatch_cb(r: Any) -> None: head_commit_sha=OTHER_HEAD, on_poll=cb, ) - assert [p[0].status for p in polled_reviews] == ["PENDING", "RUNNING"] + assert [p[0].status for p in polled_reviews] == ["MUTATED", "MUTATED"] assert [p[1] for p in polled_reviews] == [1, 2] - assert polled_reviews[0][0].head_commit_sha is UNSET - assert polled_reviews[1][0].head_commit_sha == HEAD + assert polled_reviews[0][0].head_commit_sha == "mutated_sha" + assert polled_reviews[1][0].head_commit_sha == "mutated_sha" assert result.status == "INCOMPLETE" assert result.review.status == "RUNNING" assert result.review.head_commit_sha == HEAD + assert result.review is not polled_reviews[-1][0] assert gap_facts(result) == [PINNED_ELSEWHERE] assert result.reason == "The review is pinned to another head commit." # The second read names the head, so the review that would complete is never read. @@ -3464,6 +3469,7 @@ def pre_start_cb(r: Any) -> Any: pass waiter_coro_task: asyncio.Task[Any] | None = None + case6c_cancelled = False try: # Coroutine callback cancelled after startup coro_started = asyncio.Event() @@ -3517,20 +3523,25 @@ async def failing_overdue_coro(r: Any) -> None: except (asyncio.CancelledError, BaseException): pass waiter_coro_task.cancel() - cancelled_coro = False + done_c, _ = await asyncio.wait({waiter_coro_task}, timeout=1.0) + assert waiter_coro_task in done_c + assert waiter_coro_task.cancelled() try: await waiter_coro_task - except asyncio.CancelledError: - cancelled_coro = True - assert cancelled_coro + except (asyncio.CancelledError, BaseException): + pass + case6c_cancelled = True finally: - if waiter_coro_task is not None and not waiter_coro_task.done(): - waiter_coro_task.cancel() - if waiter_coro_task is not None: - try: - await waiter_coro_task - except (asyncio.CancelledError, BaseException): - pass + if not case6c_cancelled: + if coro_trigger is not None: + coro_trigger.set() + if waiter_coro_task is not None and not waiter_coro_task.done(): + waiter_coro_task.cancel() + if waiter_coro_task is not None: + try: + await asyncio.wait({waiter_coro_task}, timeout=1.0) + except BaseException: + pass assert len(client_module._DETACHED_TASKS) == 1 detached_task_id = next(iter(client_module._DETACHED_TASKS.keys())) @@ -3574,7 +3585,7 @@ async def failing_overdue_coro(r: Any) -> None: if not waiter_coro_task.done(): waiter_coro_task.cancel() try: - await waiter_coro_task + await asyncio.wait({waiter_coro_task}, timeout=1.0) except (asyncio.CancelledError, BaseException): pass for t in captured_case6_wrappers: @@ -4524,15 +4535,33 @@ def __copy__(self) -> Any: with pytest.raises(TypeError, match="Unsupported mutable value"): _snapshot_review(detail_self_copy) - # Memoryview with invalid destination format for cast raises TypeError + # Ctypes array and memoryview snapshots are preserved import ctypes - c_arr = (ctypes.c_int32 * 4)() + c_arr = (ctypes.c_int32 * 4)(1, 2, 3, 4) mv_ctypes = memoryview(c_arr) + mv_ctypes_bytes = memoryview(c_arr).cast("B") detail_ctypes_mv = CustomerReviewDetail.from_dict(responses[1]) detail_ctypes_mv.additional_properties["ctypes_mv"] = mv_ctypes + detail_ctypes_mv.additional_properties["ctypes_bytes"] = mv_ctypes_bytes + snap_ctypes = _snapshot_review(detail_ctypes_mv) + assert snap_ctypes is not None + copied_mv = snap_ctypes.additional_properties["ctypes_mv"] + copied_bytes = snap_ctypes.additional_properties["ctypes_bytes"] + assert bytes(copied_mv) == bytes(mv_ctypes) + assert bytes(copied_bytes) == bytes(mv_ctypes_bytes) + assert copied_mv.obj is not c_arr + assert copied_bytes.obj is not c_arr + + class MutableArray(ctypes.c_int32 * 4): + pass + + MutableArray.mutable_attr = [1, 2, 3] # application-defined mutable attribute + mut_arr = MutableArray(1, 2, 3, 4) + detail_mut_arr = CustomerReviewDetail.from_dict(responses[1]) + detail_mut_arr.additional_properties["mut_arr"] = memoryview(mut_arr) with pytest.raises(TypeError, match="Unsupported mutable value"): - _snapshot_review(detail_ctypes_mv) + _snapshot_review(detail_mut_arr) # Empty set subclass copies attributes class CustomSet(set[Any]): From 0f80f2cedc57b1321c120ac81de39f369b27620b Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Mon, 23 Nov 2026 17:51:49 +0530 Subject: [PATCH 68/75] Address review run 67 findings: negative slice stop, strict deadline cutoff, Case 6a bounded join, callback removal checks, mismatch field assertions, and ctypes write-through test --- proofline/client.py | 12 ++--- tests/test_http.py | 104 +++++++++++++++++++++++++++++++++++++++----- 2 files changed, 98 insertions(+), 18 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 4ccbf5c9..a9e95147 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -1054,7 +1054,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: ] else: last = item_offset + (shape - 1) * elem_stride - stop = None if last == 0 else (last + elem_stride) + stop = None if (last + elem_stride < 0) else (last + elem_stride) resolved_mv = full_mv[item_offset:stop:elem_stride] elif val.c_contiguous: count = val.nbytes // val.itemsize if val.itemsize > 0 else 0 @@ -1074,7 +1074,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: resolved_mv = full_bytes[offset : offset + shape * stride : stride] else: last = offset + (shape - 1) * stride - stop = None if last == 0 else (last + stride) + stop = None if (last + stride < 0) else (last + stride) resolved_mv = full_bytes[offset:stop:stride] elif val.c_contiguous: resolved_mv = full_bytes[offset : offset + val.nbytes] @@ -3414,7 +3414,7 @@ def _on_future_done(_: Any) -> None: deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( deadline_val is None - or completed_at[0] <= deadline_val + or completed_at[0] < deadline_val ) if cb_finished_in_budget: if hasattr(res, "result"): @@ -3452,7 +3452,7 @@ def _on_future_done(_: Any) -> None: pass deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val + deadline_val is None or completed_at[0] < deadline_val ) if cb_finished_in_budget and completion_fut in done: if hasattr(res, "result"): @@ -3605,7 +3605,7 @@ def _on_task_done(t: Any) -> None: try: deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val + deadline_val is None or completed_at[0] < deadline_val ) try: task_is_done = ( @@ -3657,7 +3657,7 @@ def _on_task_done(t: Any) -> None: pass deadline_val = _transport.DEADLINE.get() cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None or completed_at[0] <= deadline_val + deadline_val is None or completed_at[0] < deadline_val ) try: task_is_done = task.done() if hasattr(task, "done") else False diff --git a/tests/test_http.py b/tests/test_http.py index 54c865fe..f25e0d32 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1318,6 +1318,7 @@ async def test_wait_ends_on_the_read_that_names_another_head( # Mismatch with on_poll also ends on the read that names another head (2 requests) with Server(lambda request, index: Reply(body=responses[index])) as server: polled_reviews: list[tuple[Any, int]] = [] + captured_mismatch_fields: list[tuple[str, Any, int]] = [] if mode == "async": first_cb_event = asyncio.Event() second_cb_reached = asyncio.Event() @@ -1330,6 +1331,7 @@ async def async_mismatch_cb(r: Any) -> None: assert not waiter_task.done() second_cb_reached.set() await cb_gate.wait() + captured_mismatch_fields.append((r.status, r.head_commit_sha, len(server.requests))) polled_reviews.append((r, len(server.requests))) r.status = "MUTATED" r.head_commit_sha = "mutated_sha" @@ -1340,6 +1342,7 @@ async def async_mismatch_cb(r: Any) -> None: else: def sync_mismatch_cb(r: Any) -> None: + captured_mismatch_fields.append((r.status, r.head_commit_sha, len(server.requests))) polled_reviews.append((r, len(server.requests))) r.status = "MUTATED" r.head_commit_sha = "mutated_sha" @@ -1390,11 +1393,12 @@ def sync_mismatch_cb(r: Any) -> None: cb_gate.set() result = await asyncio.wait_for(waiter_task, timeout=5.0) finally: + cb_gate.set() if waiter_task is not None and not waiter_task.done(): waiter_task.cancel() if waiter_task is not None: try: - await waiter_task + await asyncio.wait({waiter_task}, timeout=1.0) except (asyncio.CancelledError, BaseException): pass else: @@ -1407,6 +1411,10 @@ def sync_mismatch_cb(r: Any) -> None: head_commit_sha=OTHER_HEAD, on_poll=cb, ) + assert captured_mismatch_fields == [ + ("PENDING", UNSET, 1), + ("RUNNING", HEAD, 2), + ] assert [p[0].status for p in polled_reviews] == ["MUTATED", "MUTATED"] assert [p[1] for p in polled_reviews] == [1, 2] assert polled_reviews[0][0].head_commit_sha == "mutated_sha" @@ -2812,6 +2820,36 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: except BaseException: pass + # Assert already-failed future returned at deadline is detached and returns outcome + failed_at_deadline_futs: list[asyncio.Future[None]] = [] + call_start = clock.now + + def failed_future_at_deadline_callback(r: Any) -> asyncio.Future[None]: + clock.now = call_start + 10.0 + loop = asyncio.get_running_loop() + fut: asyncio.Future[None] = loop.create_future() + fut.set_exception(ValueError("inline future error exactly at deadline")) + failed_at_deadline_futs.append(fut) + return fut + + try: + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + outcome_at_dl = await client.wait_for_review( + ORG, + REVIEW, + timeout=10, + on_poll=failed_future_at_deadline_callback, + ) + assert outcome_at_dl.status == "TIMED_OUT" + finally: + for ff in failed_at_deadline_futs: + try: + if not ff.cancelled(): + ff.exception() + except BaseException: + pass + # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. watchdog_code = """ @@ -3297,6 +3335,7 @@ async def suspending_callback(r: Any) -> None: captured_case6_wrappers: list[asyncio.Task[Any]] = [] try: waiter_fut_task: asyncio.Task[Any] | None = None + case6a_cancelled = False try: # 6a: Future callback cancelled after startup failing_fut = loop.create_future() @@ -3332,22 +3371,34 @@ def failing_future_cb(r: Any) -> asyncio.Future[None]: except (asyncio.CancelledError, BaseException): pass waiter_fut_task.cancel() - cancelled_fut = False + done_6a_c, _ = await asyncio.wait({waiter_fut_task}, timeout=1.0) + assert waiter_fut_task in done_6a_c + assert waiter_fut_task.cancelled() try: await waiter_fut_task - except asyncio.CancelledError: - cancelled_fut = True - assert cancelled_fut + except (asyncio.CancelledError, BaseException): + pass + case6a_cancelled = True finally: - if waiter_fut_task is not None and not waiter_fut_task.done(): - waiter_fut_task.cancel() - if waiter_fut_task is not None: - try: - await waiter_fut_task - except (asyncio.CancelledError, BaseException): - pass + if not case6a_cancelled: + if failing_fut is not None and not failing_fut.done(): + failing_fut.cancel() + if waiter_fut_task is not None and not waiter_fut_task.done(): + waiter_fut_task.cancel() + if waiter_fut_task is not None: + try: + await asyncio.wait({waiter_fut_task}, timeout=1.0) + except BaseException: + pass assert id(failing_fut) in client_module._DETACHED_FUTURES + failing_fut_cbs = [ + cb[0] if isinstance(cb, tuple) else cb + for cb in (getattr(failing_fut, "_callbacks", None) or []) + ] + assert not any( + getattr(cb, "__name__", "") == "_on_future_done" for cb in failing_fut_cbs + ) failing_fut.set_exception(RuntimeError("error in cancelled future callback")) await asyncio.sleep(0) assert id(failing_fut) not in client_module._DETACHED_FUTURES @@ -3579,6 +3630,13 @@ async def failing_overdue_coro(r: Any) -> None: failing_fut.exception() except BaseException: pass + if waiter_fut_task is not None: + if not waiter_fut_task.done(): + waiter_fut_task.cancel() + try: + await asyncio.wait({waiter_fut_task}, timeout=1.0) + except (asyncio.CancelledError, BaseException): + pass if coro_trigger is not None: coro_trigger.set() if waiter_coro_task is not None: @@ -4026,6 +4084,13 @@ def unhash_failing_cb(r): target_fut = unhash_box[0] fut_weakref = weakref.ref(target_fut) assert id(target_fut) in _DETACHED_FUTURES + target_fut_cbs = [ + cb[0] if isinstance(cb, tuple) else cb + for cb in (getattr(target_fut, "_callbacks", None) or []) + ] + assert not any( + getattr(cb, "__name__", "") == "_on_future_done" for cb in target_fut_cbs + ) target_fut.set_exception(RuntimeError("unhashable late failure")) await asyncio.sleep(0) assert id(target_fut) not in _DETACHED_FUTURES @@ -4541,17 +4606,32 @@ def __copy__(self) -> Any: c_arr = (ctypes.c_int32 * 4)(1, 2, 3, 4) mv_ctypes = memoryview(c_arr) mv_ctypes_bytes = memoryview(c_arr).cast("B") + mv_ctypes_slice = memoryview(c_arr)[1::-2] detail_ctypes_mv = CustomerReviewDetail.from_dict(responses[1]) + detail_ctypes_mv.additional_properties["ctypes_arr"] = c_arr detail_ctypes_mv.additional_properties["ctypes_mv"] = mv_ctypes detail_ctypes_mv.additional_properties["ctypes_bytes"] = mv_ctypes_bytes + detail_ctypes_mv.additional_properties["ctypes_slice"] = mv_ctypes_slice snap_ctypes = _snapshot_review(detail_ctypes_mv) assert snap_ctypes is not None + copied_arr = snap_ctypes.additional_properties["ctypes_arr"] copied_mv = snap_ctypes.additional_properties["ctypes_mv"] copied_bytes = snap_ctypes.additional_properties["ctypes_bytes"] + copied_slice = snap_ctypes.additional_properties["ctypes_slice"] assert bytes(copied_mv) == bytes(mv_ctypes) assert bytes(copied_bytes) == bytes(mv_ctypes_bytes) + assert bytes(copied_slice) == bytes(mv_ctypes_slice) + assert copied_arr is not c_arr assert copied_mv.obj is not c_arr assert copied_bytes.obj is not c_arr + # Write through cloned byte view and verify sibling view and cloned array see the change + # while source bytes stay unchanged: + copied_bytes[0] = 99 + assert copied_arr[0] != 1 + assert bytes(copied_mv)[0] == 99 + assert c_arr[0] == 1 + assert bytes(mv_ctypes)[0] == 1 + assert mv_ctypes_bytes[0] == 1 class MutableArray(ctypes.c_int32 * 4): pass From 9b9475b3d9285bc73c9fe8739e3135d82e882500 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Tue, 24 Nov 2026 08:25:10 +0530 Subject: [PATCH 69/75] Address review run 68 findings: pointer-bearing ctypes rejection, pending future registration completion, fetch timeout propagation, and test join bounds --- proofline/client.py | 144 +++++++++++++++++++++++++++++++++++--------- tests/test_http.py | 132 ++++++++++++++++++++++++++++++++++------ 2 files changed, 231 insertions(+), 45 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index a9e95147..c633ba6e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -323,8 +323,6 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if val is None or val is UNSET: return True if isinstance(val, type): - if issubclass(val, (ctypes._SimpleCData, ctypes.Structure, ctypes.Union, ctypes.Array)): - return True return val in _SAFE_BUILTIN_CLASSES t = type(val) if t in _IMMUTABLE_TYPES: @@ -401,6 +399,28 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: } +def _is_pointer_bearing_ctypes_type(t: Any) -> bool: + if not isinstance(t, type): + return True + if issubclass( + t, + ( + ctypes.py_object, + ctypes._Pointer, + ctypes.c_void_p, + ctypes.c_char_p, + ctypes.c_wchar_p, + ), + ): + return True + code = getattr(t, "_type_", None) + if code in ("O", "P", "z", "Z", "u"): + return True + if issubclass(t, ctypes.Array): + return _is_pointer_bearing_ctypes_type(getattr(t, "_type_", None)) + return False + + def _has_mutable_class_attrs(cls: type) -> bool: for base in cls.__mro__: if base in _SAFE_BUILTIN_CLASSES or base is object: @@ -415,6 +435,8 @@ def _has_mutable_class_attrs(cls: type) -> bool: if name == "_type_": if not (isinstance(attr, type) or hasattr(attr, "_type_")): return True + if _is_pointer_bearing_ctypes_type(attr): + return True continue if name in _SAFE_SPECIAL_ATTRS: continue @@ -561,7 +583,18 @@ class _Py_buffer(ctypes.Structure): _py_release_buffer.argtypes = [ctypes.POINTER(_Py_buffer)] +class _DeadlineAborted(Exception): + pass + + def _snapshot_review(detail: CustomerReviewDetail) -> CustomerReviewDetail | None: + try: + return _snapshot_review_impl(detail) + except _DeadlineAborted: + return None + + +def _snapshot_review_impl(detail: CustomerReviewDetail) -> CustomerReviewDetail | None: if _deadline_expired(): return None @@ -992,6 +1025,11 @@ def _collect_set_members(val: Any) -> list[Any] | None: "Unsupported mutable value in review extension data: " f"{exp_cls.__name__}" ) + if _is_pointer_bearing_ctypes_type(exp_elem_type): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{exp_cls.__name__}" + ) if not isinstance(exp_len, int) or exp_len < 0: raise TypeError( "Unsupported mutable value in review extension data: " @@ -1010,8 +1048,11 @@ def _collect_set_members(val: Any) -> list[Any] | None: return None cloned_exporter = type(exporter).from_buffer_copy(exporter) memo[exp_id] = cloned_exporter - if hasattr(exporter, "__dict__"): + if hasattr(exporter, "__dict__") or hasattr(exporter, "__slots__"): _install_cloned_dict(exporter, cloned_exporter, memo, stack) + stack.append( + (_OBJ_EXPAND, cloned_exporter, iter(_get_obj_attrs(exporter))) + ) b_val = _Py_buffer() b_exp = _Py_buffer() offset = 0 @@ -1086,11 +1127,46 @@ def _collect_set_members(val: Any) -> list[Any] | None: else: full_bytes = full_mv.cast("B") try: - full_bytes_slice = full_bytes[offset : offset + val.nbytes] - if val_shape is not None: - resolved_mv = full_bytes_slice.cast(val.format, shape=val_shape) + if ( + val.ndim == 1 + and val_shape is not None + and val_strides is not None + and val.itemsize > 0 + ): + shape = val_shape[0] + stride = val_strides[0] + itemsize = val.itemsize + elem_stride = stride // itemsize + min_byte = ( + offset if stride >= 0 else (offset + (shape - 1) * stride) + ) + max_byte = ( + (offset + shape * stride) + if stride >= 0 + else (offset + itemsize) + ) + span_bytes: Any = full_bytes[min_byte:max_byte] + span_cast: Any = span_bytes.cast(val.format) + local_offset = (offset - min_byte) // itemsize + if shape == 0: + resolved_mv = span_cast[0:0] + elif elem_stride > 0: + resolved_mv = span_cast[ + local_offset : local_offset + + shape * elem_stride : elem_stride + ] + else: + last = local_offset + (shape - 1) * elem_stride + stop = ( + None if (last + elem_stride < 0) else (last + elem_stride) + ) + resolved_mv = span_cast[local_offset:stop:elem_stride] else: - resolved_mv = full_bytes_slice.cast(val.format) + full_bytes_slice = full_bytes[offset : offset + val.nbytes] + if val_shape is not None: + resolved_mv = full_bytes_slice.cast(val.format, shape=val_shape) + else: + resolved_mv = full_bytes_slice.cast(val.format) except Exception: resolved_mv = full_mv if val.readonly: @@ -1416,6 +1492,10 @@ def _collect_set_members(val: Any) -> list[Any] | None: raise TypeError( f"Unsupported mutable value in review extension data: {val_cls.__name__}" ) + if _is_pointer_bearing_ctypes_type(val_elem_type): + raise TypeError( + f"Unsupported mutable value in review extension data: {val_cls.__name__}" + ) if not isinstance(val_len, int) or val_len < 0: raise TypeError( f"Unsupported mutable value in review extension data: {val_cls.__name__}" @@ -1641,6 +1721,8 @@ def _collect_set_members(val: Any) -> list[Any] | None: pending_frozensets: list[Any] = deferred_frozenset_insertions def _is_member_state_populated(m_clone: Any, current_target_id: int | None = None) -> bool: + if _deadline_expired(): + raise _DeadlineAborted() if _is_immutable(m_clone): return True if _is_identity_hashed(m_clone): @@ -1653,6 +1735,8 @@ def _is_member_state_populated(m_clone: Any, current_target_id: int | None = Non stack_nodes: list[tuple[Any, bool]] = [(m_clone, root_in_custom)] container_ids: set[int] = set() while stack_nodes: + if _deadline_expired(): + raise _DeadlineAborted() cur, in_custom = stack_nodes.pop() if _is_immutable(cur): continue @@ -1676,25 +1760,35 @@ def _is_member_state_populated(m_clone: Any, current_target_id: int | None = Non stack_nodes.append((cur.__dict__, True)) if hasattr(cur, "__slots__") or hasattr(cur, "__dict__"): for _, _, slot_val in _get_obj_attrs(cur): + if _deadline_expired(): + raise _DeadlineAborted() if not _is_immutable(slot_val): stack_nodes.append((slot_val, True)) if isinstance(cur, dict): for k, v in cur.items(): + if _deadline_expired(): + raise _DeadlineAborted() if not _is_immutable(k): stack_nodes.append((k, True)) if not _is_immutable(v): stack_nodes.append((v, True)) elif isinstance(cur, tuple): for item in cur: + if _deadline_expired(): + raise _DeadlineAborted() if not _is_immutable(item): stack_nodes.append((item, True)) elif isinstance(cur, (list, set, frozenset, deque)): for item in cur: + if _deadline_expired(): + raise _DeadlineAborted() if not _is_immutable(item): stack_nodes.append((item, True)) else: if isinstance(cur, (tuple, frozenset)): for item in cur: + if _deadline_expired(): + raise _DeadlineAborted() if _is_immutable(item): continue if _is_identity_hashed(item): @@ -1703,6 +1797,8 @@ def _is_member_state_populated(m_clone: Any, current_target_id: int | None = Non stack_nodes.append((item, item_is_custom)) for target, _, _, _, _, _ in deferred_tuple_finalizations: + if _deadline_expired(): + raise _DeadlineAborted() if id(target) in container_ids: if id(target) == current_target_id: try: @@ -1713,6 +1809,8 @@ def _is_member_state_populated(m_clone: Any, current_target_id: int | None = Non return False return False for target, _, _, _, _, _ in pending_frozensets: + if _deadline_expired(): + raise _DeadlineAborted() if id(target) in container_ids: if id(target) == current_target_id: try: @@ -1723,6 +1821,8 @@ def _is_member_state_populated(m_clone: Any, current_target_id: int | None = Non return False return False for s, _, _ in deferred_set_insertions: + if _deadline_expired(): + raise _DeadlineAborted() if id(s) in container_ids: if id(s) == current_target_id: try: @@ -1733,6 +1833,8 @@ def _is_member_state_populated(m_clone: Any, current_target_id: int | None = Non return False return False for td_id, entries in dict_ordered_entries.items(): + if _deadline_expired(): + raise _DeadlineAborted() if td_id in container_ids: if td_id == current_target_id: try: @@ -2803,8 +2905,8 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: - if error.type == "urn:proofline:sdk:timeout" or ( - error.status == 0 and (_transport.remaining() or 0) <= 0 + if (_transport.remaining() or 0) <= 0 and ( + error.type == "urn:proofline:sdk:timeout" or error.status == 0 ): break raise @@ -3273,8 +3375,8 @@ async def wait_for_review( try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: - if error.type == "urn:proofline:sdk:timeout" or ( - error.status == 0 and (_transport.remaining() or 0) <= 0 + if (_transport.remaining() or 0) <= 0 and ( + error.type == "urn:proofline:sdk:timeout" or error.status == 0 ): break raise @@ -3408,20 +3510,8 @@ def _on_future_done(_: Any) -> None: except BaseException: _detach_overdue_future(res) raise - done: set[Any] = set() try: - while True: - deadline_val = _transport.DEADLINE.get() - cb_finished_in_budget = bool(completed_at) and ( - deadline_val is None - or completed_at[0] < deadline_val - ) - if cb_finished_in_budget: - if hasattr(res, "result"): - res.result() - else: - AsyncFuture.result(res) - break + while not completed_at: remaining_budget = _transport.remaining() if ( remaining_budget is not None @@ -3429,13 +3519,13 @@ def _on_future_done(_: Any) -> None: ): break try: - done, _ = await async_wait( + await async_wait( {completion_fut}, timeout=remaining_budget ) except BaseException: _detach_overdue_future(res) raise - if completion_fut in done: + if completed_at: break rem_after = _transport.remaining() if rem_after is not None and rem_after <= 0: @@ -3454,7 +3544,7 @@ def _on_future_done(_: Any) -> None: cb_finished_in_budget = bool(completed_at) and ( deadline_val is None or completed_at[0] < deadline_val ) - if cb_finished_in_budget and completion_fut in done: + if cb_finished_in_budget: if hasattr(res, "result"): res.result() else: diff --git a/tests/test_http.py b/tests/test_http.py index f25e0d32..5f0916af 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1334,7 +1334,10 @@ async def async_mismatch_cb(r: Any) -> None: captured_mismatch_fields.append((r.status, r.head_commit_sha, len(server.requests))) polled_reviews.append((r, len(server.requests))) r.status = "MUTATED" - r.head_commit_sha = "mutated_sha" + if len(polled_reviews) == 2: + r.head_commit_sha = OTHER_HEAD + else: + r.head_commit_sha = "mutated_sha" if len(polled_reviews) == 1: first_cb_event.set() @@ -1345,7 +1348,10 @@ def sync_mismatch_cb(r: Any) -> None: captured_mismatch_fields.append((r.status, r.head_commit_sha, len(server.requests))) polled_reviews.append((r, len(server.requests))) r.status = "MUTATED" - r.head_commit_sha = "mutated_sha" + if len(polled_reviews) == 2: + r.head_commit_sha = OTHER_HEAD + else: + r.head_commit_sha = "mutated_sha" cb = sync_mismatch_cb async with session(mode, server.url) as client: @@ -1391,7 +1397,10 @@ def sync_mismatch_cb(r: Any) -> None: await asyncio.sleep(0.01) assert not waiter_task.done() cb_gate.set() - result = await asyncio.wait_for(waiter_task, timeout=5.0) + done_w, _ = await asyncio.wait({waiter_task}, timeout=5.0) + if waiter_task not in done_w: + pytest.fail("waiter_task did not complete in 5.0s") + result = waiter_task.result() finally: cb_gate.set() if waiter_task is not None and not waiter_task.done(): @@ -1418,7 +1427,7 @@ def sync_mismatch_cb(r: Any) -> None: assert [p[0].status for p in polled_reviews] == ["MUTATED", "MUTATED"] assert [p[1] for p in polled_reviews] == [1, 2] assert polled_reviews[0][0].head_commit_sha == "mutated_sha" - assert polled_reviews[1][0].head_commit_sha == "mutated_sha" + assert polled_reviews[1][0].head_commit_sha == OTHER_HEAD assert result.status == "INCOMPLETE" assert result.review.status == "RUNNING" assert result.review.head_commit_sha == HEAD @@ -2820,16 +2829,27 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: except BaseException: pass - # Assert already-failed future returned at deadline is detached and returns outcome + # Assert pending future failing at exact deadline is detached and returns outcome failed_at_deadline_futs: list[asyncio.Future[None]] = [] call_start = clock.now + class PendingDeadlineFuture(asyncio.Future[None]): + def add_done_callback(self, fn: Any, *, context: Any = None) -> None: + def wrapped_fn(f: Any) -> None: + clock.now = call_start + 10.0 + fn(f) + + super().add_done_callback(wrapped_fn, context=context) + + async def fail_pending_at_deadline(f: asyncio.Future[None]) -> None: + await asyncio.sleep(0.01) + f.set_exception(ValueError("pending future error exactly at deadline")) + def failed_future_at_deadline_callback(r: Any) -> asyncio.Future[None]: - clock.now = call_start + 10.0 loop = asyncio.get_running_loop() - fut: asyncio.Future[None] = loop.create_future() - fut.set_exception(ValueError("inline future error exactly at deadline")) + fut: asyncio.Future[None] = PendingDeadlineFuture(loop=loop) failed_at_deadline_futs.append(fut) + asyncio.create_task(fail_pending_at_deadline(fut)) return fut try: @@ -3250,7 +3270,9 @@ async def continuing_coro_term(r: Any) -> None: pass assert not waiter_task_4.done() clock.advance(1.0) - res_4 = await asyncio.wait_for(waiter_task_4, timeout=1.0) + done_w4, _ = await asyncio.wait({waiter_task_4}, timeout=1.0) + assert waiter_task_4 in done_w4 + res_4 = waiter_task_4.result() assert res_4.status == "COMPLETED" assert not callback_finished_term.is_set() @@ -3289,10 +3311,11 @@ async def continuing_coro_term(r: Any) -> None: assert not wrapper_4.cancelled() assert getattr(wrapper_4, "exception_calls", 0) > 0 finally: + release_callback_term.set() if not waiter_task_4.done(): waiter_task_4.cancel() try: - await waiter_task_4 + await asyncio.wait({waiter_task_4}, timeout=1.0) except (asyncio.CancelledError, BaseException): pass client_module.async_create_task = orig_create_task_4 @@ -3300,7 +3323,7 @@ async def continuing_coro_term(r: Any) -> None: if not w.done(): w.cancel() try: - await w + await asyncio.wait({w}, timeout=1.0) except (asyncio.CancelledError, BaseException): pass @@ -4017,7 +4040,8 @@ def complete_unhashable_cb(r: Any) -> Any: # Cancel the waiter while an UnhashableFuture is pending, then fail and release # the future and assert that the loop reports no unhandled exception. # Run in a subprocess with a hard timeout, settling the callback future - # before joining the waiter. + # before joining in cleanup and bounding waiter cancellation join with + # asyncio.wait. unhashable_code = f""" import asyncio import sys @@ -4072,15 +4096,16 @@ def unhash_failing_cb(r): ) if waiter_task in done_set and not cb_started.is_set(): cb_wait_task.cancel() - await asyncio.wait_for(waiter_task, timeout=5.0) + await asyncio.wait({{waiter_task}}, timeout=1.0) assert cb_wait_task in done_set, "Callback startup timed out" waiter_task.cancel() - cancelled = False + done_cancel, _ = await asyncio.wait({{waiter_task}}, timeout=1.0) + assert waiter_task in done_cancel + assert waiter_task.cancelled() try: - await asyncio.wait_for(waiter_task, timeout=5.0) + await waiter_task except asyncio.CancelledError: - cancelled = True - assert cancelled + pass target_fut = unhash_box[0] fut_weakref = weakref.ref(target_fut) assert id(target_fut) in _DETACHED_FUTURES @@ -4095,6 +4120,7 @@ def unhash_failing_cb(r): await asyncio.sleep(0) assert id(target_fut) not in _DETACHED_FUTURES assert target_fut.exception_calls > 0 + del target_fut_cbs del target_fut unhash_box.clear() import gc @@ -4115,7 +4141,7 @@ def unhash_failing_cb(r): if not t.done(): t.cancel() try: - await asyncio.wait_for(t, timeout=5.0) + await asyncio.wait({{t}}, timeout=1.0) except (asyncio.CancelledError, BaseException): pass await asyncio.sleep(0) @@ -5796,6 +5822,76 @@ def late_failing_cb(r: Any) -> asyncio.Future[None]: pass loop.set_exception_handler(old_h) + # Pending future failing at exact deadline for completed review preserves COMPLETED + exact_call_start = 0.0 + + class ExactDeadlineCompletedFuture(TrackedFuture): + def add_done_callback(self, fn: Any, *, context: Any = None) -> None: + def wrapped_fn(f: Any) -> None: + clock.now = exact_call_start + 100.0 + fn(f) + + super().add_done_callback(wrapped_fn, context=context) + + exact_dl_fut: ExactDeadlineCompletedFuture | None = ExactDeadlineCompletedFuture( + loop=asyncio.get_running_loop() + ) + exact_dl_ref = weakref.ref(exact_dl_fut) + exact_dl_producer: asyncio.Task[None] | None = None + + async def fail_at_exact_dl() -> None: + await asyncio.sleep(0) + if exact_dl_fut is not None: + exact_dl_fut.set_exception(ValueError("failure at exact deadline")) + + def exact_dl_cb(r: Any) -> asyncio.Future[None]: + nonlocal exact_dl_producer, exact_call_start + exact_call_start = clock.now + exact_dl_producer = asyncio.create_task(fail_at_exact_dl()) + assert exact_dl_fut is not None + return exact_dl_fut + + unhandled_exact_dl_reports: list[dict[str, Any]] = [] + loop.set_exception_handler(lambda _loop, ctx: unhandled_exact_dl_reports.append(ctx)) + try: + with Server(lambda request, index: Reply(body=responses[1])) as server: + async with session("async", server.url) as client: + res_exact_dl = await client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=exact_dl_cb, + ) + assert res_exact_dl.status == "COMPLETED" + assert exact_dl_fut is not None + assert exact_dl_fut.done() + if exact_dl_producer is not None: + await exact_dl_producer + await asyncio.sleep(0) + assert exact_dl_fut.exception_retrieved is True + assert id(exact_dl_fut) not in client_module._DETACHED_FUTURES + exact_dl_fut = None + gc.collect() + assert exact_dl_ref() is None + assert unhandled_exact_dl_reports == [] + finally: + if exact_dl_producer is not None: + if not exact_dl_producer.done(): + exact_dl_producer.cancel() + try: + await exact_dl_producer + except (asyncio.CancelledError, BaseException): + pass + if exact_dl_fut is not None: + if not exact_dl_fut.done(): + exact_dl_fut.cancel() + elif not exact_dl_fut.cancelled(): + try: + exact_dl_fut.exception() + except BaseException: + pass + loop.set_exception_handler(old_h) + # Late SystemExit inside callback wrapper is suppressed after deadline exit_task_done = asyncio.Event() From 766f5778af2905a685e2b64737621c7eaac22c93 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Tue, 24 Nov 2026 08:44:29 +0530 Subject: [PATCH 70/75] Address review run 69 findings: recursive ctypes aggregate checking, covering span byte casting, multidimensional byte view preservation, already-failed exact-deadline assertion, and test quality improvements --- proofline/client.py | 105 +++++++++++++++++++++++++++----------------- tests/test_http.py | 89 ++++++++++++++++++++----------------- 2 files changed, 112 insertions(+), 82 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index c633ba6e..79eef0b9 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -399,9 +399,14 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: } -def _is_pointer_bearing_ctypes_type(t: Any) -> bool: +def _is_pointer_bearing_ctypes_type(t: Any, seen: set[type] | None = None) -> bool: if not isinstance(t, type): return True + if seen is None: + seen = set() + if t in seen: + return False + seen.add(t) if issubclass( t, ( @@ -417,7 +422,17 @@ def _is_pointer_bearing_ctypes_type(t: Any) -> bool: if code in ("O", "P", "z", "Z", "u"): return True if issubclass(t, ctypes.Array): - return _is_pointer_bearing_ctypes_type(getattr(t, "_type_", None)) + elem_t = getattr(t, "_type_", None) + return _is_pointer_bearing_ctypes_type(elem_t, seen) + if issubclass(t, (ctypes.Structure, ctypes.Union)): + for base in t.__mro__: + fields = getattr(base, "_fields_", None) + if fields: + for field_spec in fields: + if len(field_spec) >= 2: + field_type = field_spec[1] + if _is_pointer_bearing_ctypes_type(field_type, seen): + return True return False @@ -1016,25 +1031,28 @@ def _collect_set_members(val: Any) -> list[Any] | None: except BaseException: pass resolved_mv: Any - if isinstance(exporter, ctypes.Array): + if isinstance(exporter, (ctypes.Array, ctypes.Structure, ctypes.Union)): exp_cls = type(exporter) - exp_elem_type = getattr(exp_cls, "_type_", None) - exp_len = getattr(exp_cls, "_length_", None) - if not (isinstance(exp_elem_type, type) or hasattr(exp_elem_type, "_type_")): - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{exp_cls.__name__}" - ) - if _is_pointer_bearing_ctypes_type(exp_elem_type): - raise TypeError( - "Unsupported mutable value in review extension data: " - f"{exp_cls.__name__}" - ) - if not isinstance(exp_len, int) or exp_len < 0: + if _is_pointer_bearing_ctypes_type(exp_cls): raise TypeError( "Unsupported mutable value in review extension data: " f"{exp_cls.__name__}" ) + if isinstance(exporter, ctypes.Array): + exp_elem_type = getattr(exp_cls, "_type_", None) + exp_len = getattr(exp_cls, "_length_", None) + if not ( + isinstance(exp_elem_type, type) or hasattr(exp_elem_type, "_type_") + ): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{exp_cls.__name__}" + ) + if not isinstance(exp_len, int) or exp_len < 0: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{exp_cls.__name__}" + ) if _has_mutable_class_attrs(exp_cls): raise TypeError( "Unsupported mutable value in review extension data: " @@ -1117,10 +1135,13 @@ def _collect_set_members(val: Any) -> list[Any] | None: last = offset + (shape - 1) * stride stop = None if (last + stride < 0) else (last + stride) resolved_mv = full_bytes[offset:stop:stride] + elif val_shape is not None and val.ndim > 1: + full_bytes_slice: Any = full_bytes[offset : offset + val.nbytes] + resolved_mv = full_bytes_slice.cast("B", shape=val_shape) elif val.c_contiguous: resolved_mv = full_bytes[offset : offset + val.nbytes] elif val_shape is not None: - full_bytes_slice: Any = full_bytes[offset : offset + val.nbytes] + full_bytes_slice = full_bytes[offset : offset + val.nbytes] resolved_mv = full_bytes_slice.cast("B", shape=val_shape) else: resolved_mv = full_bytes[offset : offset + val.nbytes] @@ -1136,31 +1157,33 @@ def _collect_set_members(val: Any) -> list[Any] | None: shape = val_shape[0] stride = val_strides[0] itemsize = val.itemsize - elem_stride = stride // itemsize - min_byte = ( - offset if stride >= 0 else (offset + (shape - 1) * stride) - ) - max_byte = ( - (offset + shape * stride) - if stride >= 0 - else (offset + itemsize) - ) - span_bytes: Any = full_bytes[min_byte:max_byte] - span_cast: Any = span_bytes.cast(val.format) - local_offset = (offset - min_byte) // itemsize if shape == 0: - resolved_mv = span_cast[0:0] - elif elem_stride > 0: - resolved_mv = span_cast[ - local_offset : local_offset - + shape * elem_stride : elem_stride - ] + empty_bytes: Any = full_bytes[0:0] + resolved_mv = empty_bytes.cast(val.format) else: - last = local_offset + (shape - 1) * elem_stride - stop = ( - None if (last + elem_stride < 0) else (last + elem_stride) - ) - resolved_mv = span_cast[local_offset:stop:elem_stride] + elem_stride = stride // itemsize + if stride >= 0: + min_byte = offset + max_byte = offset + (shape - 1) * stride + itemsize + else: + min_byte = offset + (shape - 1) * stride + max_byte = offset + itemsize + span_bytes: Any = full_bytes[min_byte:max_byte] + span_cast: Any = span_bytes.cast(val.format) + local_offset = (offset - min_byte) // itemsize + if elem_stride > 0: + resolved_mv = span_cast[ + local_offset : local_offset + + shape * elem_stride : elem_stride + ] + else: + last = local_offset + (shape - 1) * elem_stride + stop = ( + None + if (last + elem_stride < 0) + else (last + elem_stride) + ) + resolved_mv = span_cast[local_offset:stop:elem_stride] else: full_bytes_slice = full_bytes[offset : offset + val.nbytes] if val_shape is not None: @@ -1492,7 +1515,7 @@ def _collect_set_members(val: Any) -> list[Any] | None: raise TypeError( f"Unsupported mutable value in review extension data: {val_cls.__name__}" ) - if _is_pointer_bearing_ctypes_type(val_elem_type): + if _is_pointer_bearing_ctypes_type(val_cls): raise TypeError( f"Unsupported mutable value in review extension data: {val_cls.__name__}" ) diff --git a/tests/test_http.py b/tests/test_http.py index 5f0916af..c47b048c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1323,14 +1323,17 @@ async def test_wait_ends_on_the_read_that_names_another_head( first_cb_event = asyncio.Event() second_cb_reached = asyncio.Event() cb_gate = asyncio.Event() + cb_completed = False waiter_task: asyncio.Task[Any] | None = None async def async_mismatch_cb(r: Any) -> None: + nonlocal cb_completed if len(polled_reviews) == 1: assert waiter_task is not None assert not waiter_task.done() second_cb_reached.set() await cb_gate.wait() + cb_completed = True captured_mismatch_fields.append((r.status, r.head_commit_sha, len(server.requests))) polled_reviews.append((r, len(server.requests))) r.status = "MUTATED" @@ -1394,22 +1397,22 @@ def sync_mismatch_cb(r: Any) -> None: if not gate_waiter.done(): gate_waiter.cancel() - await asyncio.sleep(0.01) + assert not cb_completed assert not waiter_task.done() + assert getattr(waiter_task, "_fut_waiter", None) is not None + assert not waiter_task._fut_waiter.done() cb_gate.set() done_w, _ = await asyncio.wait({waiter_task}, timeout=5.0) if waiter_task not in done_w: pytest.fail("waiter_task did not complete in 5.0s") result = waiter_task.result() + assert cb_completed finally: cb_gate.set() if waiter_task is not None and not waiter_task.done(): waiter_task.cancel() if waiter_task is not None: - try: - await asyncio.wait({waiter_task}, timeout=1.0) - except (asyncio.CancelledError, BaseException): - pass + await asyncio.wait({waiter_task}, timeout=1.0) else: result = await call( client, @@ -2759,7 +2762,10 @@ async def async_poll_callback(review_detail: Any) -> None: # Assert async client also works with regular synchronous callbacks returning None if mode == "async": - with Server(lambda request, index: Reply(body=responses[index])) as server: + async_nested_responses = [dict(responses[0]), dict(responses[1])] + for resp in async_nested_responses: + resp["nested_meta"] = {"key": "original", "tags": ["a", "b"]} + with Server(lambda request, index: Reply(body=async_nested_responses[index])) as server: sync_calls: list[tuple[str, int]] = [] def inline_sync_cb(r: Any) -> None: @@ -2770,6 +2776,8 @@ def inline_sync_cb(r: Any) -> None: assert len(r.assessments) > 0 assert r.assessments[0].checks.receipt_recorded is True r.assessments[0].checks.receipt_recorded = False + r.additional_properties["nested_meta"]["key"] = "mutated" + r.additional_properties["nested_meta"]["tags"].append("c") async with session("async", server.url) as client: result = await call( @@ -2786,6 +2794,8 @@ def inline_sync_cb(r: Any) -> None: assert result.review.actions.publish is False assert "mutated" not in result.review.additional_properties assert result.review.assessments[0].checks.receipt_recorded is True + assert result.review.additional_properties["nested_meta"]["key"] == "original" + assert result.review.additional_properties["nested_meta"]["tags"] == ["a", "b"] # Assert callback TimeoutError before deadline propagates async def failing_callback(r: Any) -> None: @@ -2829,31 +2839,20 @@ def failed_future_callback(r: Any) -> asyncio.Future[None]: except BaseException: pass - # Assert pending future failing at exact deadline is detached and returns outcome + # Assert already-failed future returned at exact fake-clock deadline preserves COMPLETED failed_at_deadline_futs: list[asyncio.Future[None]] = [] call_start = clock.now - class PendingDeadlineFuture(asyncio.Future[None]): - def add_done_callback(self, fn: Any, *, context: Any = None) -> None: - def wrapped_fn(f: Any) -> None: - clock.now = call_start + 10.0 - fn(f) - - super().add_done_callback(wrapped_fn, context=context) - - async def fail_pending_at_deadline(f: asyncio.Future[None]) -> None: - await asyncio.sleep(0.01) - f.set_exception(ValueError("pending future error exactly at deadline")) - def failed_future_at_deadline_callback(r: Any) -> asyncio.Future[None]: + clock.now = call_start + 10.0 loop = asyncio.get_running_loop() - fut: asyncio.Future[None] = PendingDeadlineFuture(loop=loop) + fut: asyncio.Future[None] = loop.create_future() + fut.set_exception(ValueError("already-failed future exactly at deadline")) failed_at_deadline_futs.append(fut) - asyncio.create_task(fail_pending_at_deadline(fut)) return fut try: - with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: outcome_at_dl = await client.wait_for_review( ORG, @@ -2861,7 +2860,7 @@ def failed_future_at_deadline_callback(r: Any) -> asyncio.Future[None]: timeout=10, on_poll=failed_future_at_deadline_callback, ) - assert outcome_at_dl.status == "TIMED_OUT" + assert outcome_at_dl.status == "COMPLETED" finally: for ff in failed_at_deadline_futs: try: @@ -3726,18 +3725,16 @@ async def awaiting_runner_callback(r: Any) -> None: pass assert not polling_waiter_task.done() clock.advance(1.0) - res_7 = await polling_waiter_task + done_7_res, _ = await asyncio.wait({polling_waiter_task}, timeout=1.0) + assert polling_waiter_task in done_7_res, "polling_waiter_task deadlocked on callback" + res_7 = polling_waiter_task.result() assert res_7.status == "TIMED_OUT" - await asyncio.wait_for(callback_completed_7.wait(), timeout=1.0) + done_cb7, _ = await asyncio.wait( + {asyncio.create_task(callback_completed_7.wait())}, timeout=1.0 + ) + assert callback_completed_7.is_set() finally: sleep_forbidden = False - if polling_waiter_task is not None and not polling_waiter_task.done(): - polling_waiter_task.cancel() - if polling_waiter_task is not None: - try: - await polling_waiter_task - except (asyncio.CancelledError, BaseException): - pass asyncio.run(main()) """ @@ -3753,6 +3750,8 @@ async def awaiting_runner_callback(r: Any) -> None: # Assert callback modifying review does not mutate returned review in both sync and async mutated_count = 0 + resp_with_nested = dict(responses[1]) + resp_with_nested["nested_meta"] = {"key": "original", "tags": ["a", "b"]} def sync_mutating_callback(r: Any) -> None: nonlocal mutated_count @@ -3763,6 +3762,8 @@ def sync_mutating_callback(r: Any) -> None: assert len(r.assessments) > 0 assert r.assessments[0].checks.receipt_recorded is True r.assessments[0].checks.receipt_recorded = False + r.additional_properties["nested_meta"]["key"] = "mutated" + r.additional_properties["nested_meta"]["tags"].append("c") async def async_mutating_callback(r: Any) -> None: nonlocal mutated_count @@ -3774,8 +3775,10 @@ async def async_mutating_callback(r: Any) -> None: assert len(r.assessments) > 0 assert r.assessments[0].checks.receipt_recorded is True r.assessments[0].checks.receipt_recorded = False + r.additional_properties["nested_meta"]["key"] = "mutated" + r.additional_properties["nested_meta"]["tags"].append("c") - with Server(lambda request, index: Reply(body=responses[1])) as server: + with Server(lambda request, index: Reply(body=resp_with_nested)) as server: async with session(mode, server.url) as client: mut_cb = async_mutating_callback if mode == "async" else sync_mutating_callback res = await call( @@ -3791,6 +3794,8 @@ async def async_mutating_callback(r: Any) -> None: assert res.review.actions.publish is False assert "mutated" not in res.review.additional_properties assert res.review.assessments[0].checks.receipt_recorded is True + assert res.review.additional_properties["nested_meta"]["key"] == "original" + assert res.review.additional_properties["nested_meta"]["tags"] == ["a", "b"] # Test snapshot directly with an in-memory deep extension and custom tuple to bypass HTTP JSON deep_container: dict[str, Any] = {} @@ -4650,14 +4655,16 @@ def __copy__(self) -> Any: assert copied_arr is not c_arr assert copied_mv.obj is not c_arr assert copied_bytes.obj is not c_arr - # Write through cloned byte view and verify sibling view and cloned array see the change - # while source bytes stay unchanged: - copied_bytes[0] = 99 - assert copied_arr[0] != 1 - assert bytes(copied_mv)[0] == 99 - assert c_arr[0] == 1 - assert bytes(mv_ctypes)[0] == 1 - assert mv_ctypes_bytes[0] == 1 + # Write through cloned byte view at the second element and assert that the reversed slice + # reflects the write while the source stays unchanged: + copied_bytes[4] = 99 + assert copied_arr[1] == 99 + assert bytes(copied_mv)[4] == 99 + assert bytes(copied_slice)[0] == 99 + assert c_arr[1] == 2 + assert bytes(mv_ctypes)[4] == 2 + assert bytes(mv_ctypes_slice)[0] == 2 + assert mv_ctypes_bytes[4] == 2 class MutableArray(ctypes.c_int32 * 4): pass From 9e6c2b9655b1432d0c88515b5f00a70b7308ef9b Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Tue, 24 Nov 2026 09:08:16 +0530 Subject: [PATCH 71/75] Address review run 70 findings: multidimensional ctypes view reconstruction, ctypes._CFuncPtr guard, exporter slot copying, cyclic frozenset deadline checking, and bounded joins --- proofline/client.py | 62 ++++++++++++++++++++++++++++++++++++++++++--- tests/test_http.py | 46 +++++++++++++++++++++++---------- 2 files changed, 91 insertions(+), 17 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 79eef0b9..7c276ccf 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -407,6 +407,7 @@ def _is_pointer_bearing_ctypes_type(t: Any, seen: set[type] | None = None) -> bo if t in seen: return False seen.add(t) + cfuncptr = getattr(ctypes, "_CFuncPtr", None) if issubclass( t, ( @@ -416,7 +417,7 @@ def _is_pointer_bearing_ctypes_type(t: Any, seen: set[type] | None = None) -> bo ctypes.c_char_p, ctypes.c_wchar_p, ), - ): + ) or (cfuncptr is not None and issubclass(t, cfuncptr)): return True code = getattr(t, "_type_", None) if code in ("O", "P", "z", "Z", "u"): @@ -1136,8 +1137,23 @@ def _collect_set_members(val: Any) -> list[Any] | None: stop = None if (last + stride < 0) else (last + stride) resolved_mv = full_bytes[offset:stop:stride] elif val_shape is not None and val.ndim > 1: - full_bytes_slice: Any = full_bytes[offset : offset + val.nbytes] - resolved_mv = full_bytes_slice.cast("B", shape=val_shape) + if val.ndim == 2 and val_strides is not None: + rows, cols = val_shape[0], val_shape[1] + row_stride, col_stride = val_strides[0], val_strides[1] + min_r = 0 if row_stride >= 0 else (rows - 1) + min_c = 0 if col_stride >= 0 else (cols - 1) + min_byte = offset + min_r * row_stride + min_c * col_stride + max_r = (rows - 1) if row_stride >= 0 else 0 + max_c = (cols - 1) if col_stride >= 0 else 0 + max_byte = ( + offset + max_r * row_stride + max_c * col_stride + val.itemsize + ) + span_bytes_2d: Any = full_bytes[min_byte:max_byte] + span_2d: Any = span_bytes_2d.cast("B", shape=(rows, cols)) + resolved_mv = span_2d[::-1] if row_stride < 0 else span_2d + else: + full_bytes_slice: Any = full_bytes[offset : offset + val.nbytes] + resolved_mv = full_bytes_slice.cast("B", shape=val_shape) elif val.c_contiguous: resolved_mv = full_bytes[offset : offset + val.nbytes] elif val_shape is not None: @@ -1184,6 +1200,25 @@ def _collect_set_members(val: Any) -> list[Any] | None: else (last + elem_stride) ) resolved_mv = span_cast[local_offset:stop:elem_stride] + elif ( + val.ndim == 2 + and val_shape is not None + and val_strides is not None + and val.itemsize > 0 + ): + rows, cols = val_shape[0], val_shape[1] + row_stride, col_stride = val_strides[0], val_strides[1] + min_r = 0 if row_stride >= 0 else (rows - 1) + min_c = 0 if col_stride >= 0 else (cols - 1) + min_byte = offset + min_r * row_stride + min_c * col_stride + max_r = (rows - 1) if row_stride >= 0 else 0 + max_c = (cols - 1) if col_stride >= 0 else 0 + max_byte = ( + offset + max_r * row_stride + max_c * col_stride + val.itemsize + ) + span_bytes_2d = full_bytes[min_byte:max_byte] + span_2d = span_bytes_2d.cast(val.format, shape=(rows, cols)) + resolved_mv = span_2d[::-1] if row_stride < 0 else span_2d else: full_bytes_slice = full_bytes[offset : offset + val.nbytes] if val_shape is not None: @@ -1290,8 +1325,11 @@ def _collect_set_members(val: Any) -> list[Any] | None: f"{type(exporter).__name__}" ) from exc memo[exp_id] = cloned_exporter - if hasattr(exporter, "__dict__"): + if hasattr(exporter, "__dict__") or hasattr(exporter, "__slots__"): _install_cloned_dict(exporter, cloned_exporter, memo, stack) + stack.append( + (_OBJ_EXPAND, cloned_exporter, iter(_get_obj_attrs(exporter))) + ) b_val = _Py_buffer() b_exp = _Py_buffer() if _py_get_buffer(val, ctypes.byref(b_val), 0x0118) != 0: @@ -2097,9 +2135,13 @@ def _flush_pending_structures() -> None: resolved_any = False still_pending = [] for target, key, is_attr, val_id, orig_val, orig_members in pending_frozensets: + if _deadline_expired(): + raise _DeadlineAborted() can_resolve = True resolved_members = [] for m in orig_members: + if _deadline_expired(): + raise _DeadlineAborted() if _is_immutable(m): rm = m else: @@ -2108,13 +2150,19 @@ def _flush_pending_structures() -> None: can_resolve = False break try: + if _deadline_expired(): + raise _DeadlineAborted() hash(rm) _ = rm == rm + except _DeadlineAborted: + raise except Exception: can_resolve = False break resolved_members.append(rm) if can_resolve: + if _deadline_expired(): + raise _DeadlineAborted() if type(orig_val) is frozenset: res_set = frozenset(resolved_members) else: @@ -2151,14 +2199,20 @@ def _flush_pending_structures() -> None: pending_frozensets = still_pending _flush_pending_structures() continue + if _deadline_expired(): + raise _DeadlineAborted() raise TypeError("Unsupported cyclic reference in frozenset") _flush_pending_structures() if _deadline_expired(): return None for fb_set, fb_members in fallback_built_frozensets: + if _deadline_expired(): + raise _DeadlineAborted() try: for rm in fb_members: + if _deadline_expired(): + raise _DeadlineAborted() if rm not in fb_set: raise TypeError("Member lookup failed in fallback frozenset") except TypeError: diff --git a/tests/test_http.py b/tests/test_http.py index c47b048c..0482a185 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1398,9 +1398,8 @@ def sync_mismatch_cb(r: Any) -> None: gate_waiter.cancel() assert not cb_completed - assert not waiter_task.done() - assert getattr(waiter_task, "_fut_waiter", None) is not None - assert not waiter_task._fut_waiter.done() + done_blocked, _ = await asyncio.wait({waiter_task}, timeout=0.05) + assert waiter_task not in done_blocked, "waiter completed before callback" cb_gate.set() done_w, _ = await asyncio.wait({waiter_task}, timeout=5.0) if waiter_task not in done_w: @@ -3092,7 +3091,11 @@ async def continuing_coro(r: Any) -> None: await waiter_task_3 assert not waiter_task_3.done() clock.advance(1.0) - res_3 = await asyncio.wait_for(asyncio.shield(waiter_task_3), timeout=1.0) + done_w3, _ = await asyncio.wait({waiter_task_3}, timeout=1.0) + if waiter_task_3 not in done_w3: + print("Pending task: waiter_task_3", file=sys.stderr) + assert waiter_task_3 in done_w3 + res_3 = waiter_task_3.result() assert res_3.status == "TIMED_OUT" assert callback_running.is_set() assert not callback_finished.is_set() @@ -3125,20 +3128,24 @@ async def continuing_coro(r: Any) -> None: except (asyncio.CancelledError, BaseException): pass finally: + client_module.async_create_task = orig_create_task_3 + sleep_forbidden = False release_callback.set() if not waiter_task_3.done(): waiter_task_3.cancel() try: - await asyncio.wait_for(waiter_task_3, timeout=1.0) + done_w3_clean, _ = await asyncio.wait({waiter_task_3}, timeout=1.0) + if waiter_task_3 not in done_w3_clean: + print("Pending task: waiter_task_3", file=sys.stderr) except (asyncio.CancelledError, BaseException): pass - client_module.async_create_task = orig_create_task_3 - sleep_forbidden = False if cb_task_3 is not None: if not cb_task_3.done(): cb_task_3.cancel() try: - await asyncio.wait_for(cb_task_3, timeout=1.0) + done_cb3_clean, _ = await asyncio.wait({cb_task_3}, timeout=1.0) + if cb_task_3 not in done_cb3_clean: + print("Pending task: cb_task_3", file=sys.stderr) except (asyncio.CancelledError, BaseException): pass @@ -3185,30 +3192,43 @@ def sync_cb_returning_task(r: Any) -> Any: assert cb_task_3b is not None assert not cb_task_3b.done() clock.advance(1.0) - res_3b = await asyncio.wait_for(asyncio.shield(waiter_task_3b), timeout=1.0) + done_w3b, _ = await asyncio.wait({waiter_task_3b}, timeout=1.0) + if waiter_task_3b not in done_w3b: + print("Pending task: waiter_task_3b", file=sys.stderr) + assert waiter_task_3b in done_w3b + res_3b = waiter_task_3b.result() assert res_3b.status == "TIMED_OUT" assert not cb_task_3b.done() task_release_3b.set() - await asyncio.wait_for(asyncio.shield(cb_task_3b), timeout=1.0) + done_c3b, _ = await asyncio.wait({cb_task_3b}, timeout=1.0) + if cb_task_3b not in done_c3b: + print("Pending task: cb_task_3b", file=sys.stderr) + assert cb_task_3b in done_c3b finally: task_release_3b.set() if not startup_waiter.done(): startup_waiter.cancel() try: - await asyncio.wait_for(startup_waiter, timeout=0.5) + done_sw, _ = await asyncio.wait({startup_waiter}, timeout=0.5) + if startup_waiter not in done_sw: + print("Pending task: startup_waiter", file=sys.stderr) except (asyncio.CancelledError, BaseException): pass if not waiter_task_3b.done(): waiter_task_3b.cancel() try: - await asyncio.wait_for(waiter_task_3b, timeout=0.5) + done_w3b_clean, _ = await asyncio.wait({waiter_task_3b}, timeout=0.5) + if waiter_task_3b not in done_w3b_clean: + print("Pending task: waiter_task_3b", file=sys.stderr) except (asyncio.CancelledError, BaseException): pass if cb_task_3b is not None: if not cb_task_3b.done(): cb_task_3b.cancel() try: - await asyncio.wait_for(cb_task_3b, timeout=0.5) + done_cb3b_clean, _ = await asyncio.wait({cb_task_3b}, timeout=0.5) + if cb_task_3b not in done_cb3b_clean: + print("Pending task: cb_task_3b", file=sys.stderr) except (asyncio.CancelledError, BaseException): pass From fd2d3f40c6bb8ad04737746d340e5251bc321a11 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Tue, 24 Nov 2026 09:43:44 +0530 Subject: [PATCH 72/75] Address review run 71 findings: UUID cloning and memoization, 2D ctypes span row slicing, subprocess sys import, Case 3b result check, multi-element reverse slice assertions, and controlled mismatch callback synchronization --- proofline/client.py | 17 ++++++-- tests/test_http.py | 101 +++++++++++++++++++++++++++++++++----------- 2 files changed, 90 insertions(+), 28 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 7c276ccf..b0c833b7 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -256,7 +256,6 @@ def _export_page_limit(max_pages: int) -> None: str, bool, bytes, - UUID, datetime.date, } @@ -699,6 +698,11 @@ def _collect_set_members(val: Any) -> list[Any] | None: if target is not None: pending_assignments.setdefault(val_id, []).append((target, key, is_attr)) continue + if isinstance(val, UUID): + cloned_uuid = UUID(int=val.int) + memo[val_id] = cloned_uuid + _assign_target(target, key, is_attr, cloned_uuid) + continue if type(val) is dict: new_dict: dict[Any, Any] = {} memo[val_id] = new_dict @@ -1149,8 +1153,15 @@ def _collect_set_members(val: Any) -> list[Any] | None: offset + max_r * row_stride + max_c * col_stride + val.itemsize ) span_bytes_2d: Any = full_bytes[min_byte:max_byte] - span_2d: Any = span_bytes_2d.cast("B", shape=(rows, cols)) - resolved_mv = span_2d[::-1] if row_stride < 0 else span_2d + row_bytes = cols * val.itemsize + physical_rows = ( + len(span_bytes_2d) // row_bytes if row_bytes > 0 else rows + ) + span_2d: Any = span_bytes_2d.cast("B", shape=(physical_rows, cols)) + abs_step = abs(row_stride) // row_bytes if row_bytes > 0 else 1 + resolved_mv = ( + span_2d[::-abs_step] if row_stride < 0 else span_2d[::abs_step] + ) else: full_bytes_slice: Any = full_bytes[offset : offset + val.nbytes] resolved_mv = full_bytes_slice.cast("B", shape=val_shape) diff --git a/tests/test_http.py b/tests/test_http.py index 0482a185..f023b2aa 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1322,27 +1322,35 @@ async def test_wait_ends_on_the_read_that_names_another_head( if mode == "async": first_cb_event = asyncio.Event() second_cb_reached = asyncio.Event() - cb_gate = asyncio.Event() cb_completed = False waiter_task: asyncio.Task[Any] | None = None - async def async_mismatch_cb(r: Any) -> None: - nonlocal cb_completed - if len(polled_reviews) == 1: - assert waiter_task is not None - assert not waiter_task.done() - second_cb_reached.set() - await cb_gate.wait() - cb_completed = True + class CallbackSignalFuture(asyncio.Future[None]): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.signal_registered = asyncio.Event() + + def add_done_callback(self, fn: Any, *args: Any, **kwargs: Any) -> None: + super().add_done_callback(fn, *args, **kwargs) + self.signal_registered.set() + + loop = asyncio.get_running_loop() + cb_signal_fut = CallbackSignalFuture(loop=loop) + + def async_mismatch_cb(r: Any) -> Any: captured_mismatch_fields.append((r.status, r.head_commit_sha, len(server.requests))) polled_reviews.append((r, len(server.requests))) r.status = "MUTATED" if len(polled_reviews) == 2: r.head_commit_sha = OTHER_HEAD + assert waiter_task is not None + assert not waiter_task.done() + second_cb_reached.set() + return cb_signal_fut else: r.head_commit_sha = "mutated_sha" - if len(polled_reviews) == 1: first_cb_event.set() + return None cb: Any = async_mismatch_cb else: @@ -1383,31 +1391,46 @@ def sync_mismatch_cb(r: Any) -> None: if not first_waiter.done(): first_waiter.cancel() - gate_waiter = asyncio.create_task(second_cb_reached.wait()) + signal_waiter = asyncio.create_task(cb_signal_fut.signal_registered.wait()) try: - done_gate, _ = await asyncio.wait( - {gate_waiter, waiter_task}, + done_sig, _ = await asyncio.wait( + {signal_waiter, waiter_task}, timeout=5.0, return_when=asyncio.FIRST_COMPLETED, ) - if waiter_task in done_gate: + if waiter_task in done_sig: await waiter_task - assert second_cb_reached.is_set() + assert cb_signal_fut.signal_registered.is_set(), ( + "waiter_task did not wait on callback completion signal" + ) finally: - if not gate_waiter.done(): - gate_waiter.cancel() - + if not signal_waiter.done(): + signal_waiter.cancel() + + # Assert that the waiter is awaiting the callback's completion signal + # before opening the gate: + registered_cbs = [ + cb_item[0] if isinstance(cb_item, tuple) else cb_item + for cb_item in (getattr(cb_signal_fut, "_callbacks", None) or []) + ] + assert any( + getattr(cb_item, "__name__", "") == "_on_future_done" + for cb_item in registered_cbs + ) + assert getattr(waiter_task, "_fut_waiter", None) is not None assert not cb_completed - done_blocked, _ = await asyncio.wait({waiter_task}, timeout=0.05) - assert waiter_task not in done_blocked, "waiter completed before callback" - cb_gate.set() + assert not waiter_task.done() + + cb_completed = True + cb_signal_fut.set_result(None) done_w, _ = await asyncio.wait({waiter_task}, timeout=5.0) if waiter_task not in done_w: pytest.fail("waiter_task did not complete in 5.0s") result = waiter_task.result() assert cb_completed finally: - cb_gate.set() + if not cb_signal_fut.done(): + cb_signal_fut.set_result(None) if waiter_task is not None and not waiter_task.done(): waiter_task.cancel() if waiter_task is not None: @@ -2871,6 +2894,7 @@ def failed_future_at_deadline_callback(r: Any) -> asyncio.Future[None]: # Run the watchdog cases in a subprocess with a hard timeout so cancellation-resistant # tasks cannot stall teardown. watchdog_code = """ +import sys import asyncio import pytest import time @@ -3204,6 +3228,8 @@ def sync_cb_returning_task(r: Any) -> Any: if cb_task_3b not in done_c3b: print("Pending task: cb_task_3b", file=sys.stderr) assert cb_task_3b in done_c3b + cb_task_3b.result() + assert task_success_3b.is_set() finally: task_release_3b.set() if not startup_waiter.done(): @@ -4657,7 +4683,7 @@ def __copy__(self) -> Any: c_arr = (ctypes.c_int32 * 4)(1, 2, 3, 4) mv_ctypes = memoryview(c_arr) mv_ctypes_bytes = memoryview(c_arr).cast("B") - mv_ctypes_slice = memoryview(c_arr)[1::-2] + mv_ctypes_slice = memoryview(c_arr)[3::-2] detail_ctypes_mv = CustomerReviewDetail.from_dict(responses[1]) detail_ctypes_mv.additional_properties["ctypes_arr"] = c_arr detail_ctypes_mv.additional_properties["ctypes_mv"] = mv_ctypes @@ -4669,6 +4695,8 @@ def __copy__(self) -> Any: copied_mv = snap_ctypes.additional_properties["ctypes_mv"] copied_bytes = snap_ctypes.additional_properties["ctypes_bytes"] copied_slice = snap_ctypes.additional_properties["ctypes_slice"] + assert copied_slice.shape == mv_ctypes_slice.shape == (2,) + assert copied_slice.strides == mv_ctypes_slice.strides == (-8,) assert bytes(copied_mv) == bytes(mv_ctypes) assert bytes(copied_bytes) == bytes(mv_ctypes_bytes) assert bytes(copied_slice) == bytes(mv_ctypes_slice) @@ -4680,12 +4708,35 @@ def __copy__(self) -> Any: copied_bytes[4] = 99 assert copied_arr[1] == 99 assert bytes(copied_mv)[4] == 99 - assert bytes(copied_slice)[0] == 99 + assert bytes(copied_slice) == b"\x04\x00\x00\x00\x63\x00\x00\x00" assert c_arr[1] == 2 assert bytes(mv_ctypes)[4] == 2 - assert bytes(mv_ctypes_slice)[0] == 2 + assert bytes(mv_ctypes_slice) == b"\x04\x00\x00\x00\x02\x00\x00\x00" assert mv_ctypes_bytes[4] == 2 + # UUID instances are cloned and memoized so mutations cannot alter the original + detail_uuid = CustomerReviewDetail.from_dict(responses[1]) + orig_uuid = detail_uuid.id + snap_uuid = _snapshot_review(detail_uuid) + assert snap_uuid is not None + assert snap_uuid.id is not orig_uuid + assert snap_uuid.id == orig_uuid + object.__setattr__(snap_uuid.id, "int", 999999) + assert snap_uuid.id.int == 999999 + assert orig_uuid.int != 999999 + + # 2D memoryview bounding span cast to physical rows and row sliced + c_arr_2d = (ctypes.c_uint8 * 8)(10, 11, 20, 21, 30, 31, 40, 41) + mv_2d_slice = memoryview(c_arr_2d).cast("B", shape=(4, 2))[::2] + detail_2d = CustomerReviewDetail.from_dict(responses[1]) + detail_2d.additional_properties["ctypes_2d"] = mv_2d_slice + snap_2d = _snapshot_review(detail_2d) + assert snap_2d is not None + copied_2d = snap_2d.additional_properties["ctypes_2d"] + assert copied_2d.shape == mv_2d_slice.shape == (2, 2) + assert copied_2d.strides == mv_2d_slice.strides == (4, 1) + assert copied_2d.tobytes() == mv_2d_slice.tobytes() + class MutableArray(ctypes.c_int32 * 4): pass From 5e0b1ba249fae876a81f061030583f1aef536bd2 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Tue, 24 Nov 2026 10:13:12 +0530 Subject: [PATCH 73/75] Address review run 72 findings: UUID subclass and is_safe cloning, N-D ctypes physical span reconstruction, post-done deadline cutoff, README limit qualification, and test completion tying --- README.md | 4 +- proofline/client.py | 126 +++++++++++++++++++++++++++++++------------- tests/test_http.py | 95 ++++++++++++++++++++++++++++----- 3 files changed, 173 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 1be14070..8dd2f306 100644 --- a/README.md +++ b/README.md @@ -54,9 +54,9 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. +`on_poll` is optional; when supplied to `ProoflineClient`, it must be a synchronous callback and must return `None` (returning an awaitable or any return value other than `None` raises `TypeError`). `on_poll` receives each `CustomerReviewDetail` fetched and validated before the callback is reached; deadline expiry can suppress delivery. Tuples with more than 1,000 items, immutable bytes, mutable buffers, or memoryviews with more than 65,536 bytes (the 65,536-byte limit applies to immutable bytes, mutable buffers, and memoryviews, including any view backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. `on_poll` exceptions and callback return-validation errors propagate even when a terminal outcome has already been determined and can prevent the waiter from returning a classified outcome. Synchronous callbacks must return before a terminal result can be delivered and the polling deadline cannot interrupt them. -With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, immutable bytes, mutable buffers or memoryviews with more than 65,536 bytes (or backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them, except for wrappers cancelled before their first step which are timed when their done callback runs), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled; cancelling the waiter through an underlying pending future can leave unresumed tasks unflagged until resumption unless observed through the pending future), while already-running callback tasks and pending futures are detached without cancellation and may continue running (detached callback coroutines suppress late SystemExit and KeyboardInterrupt signals; waiter cancellation propagates without cancelling detached callback work). +With `AsyncProoflineClient`, `wait_for_review` can be awaited; `on_poll` must be a callable that accepts the review snapshot and returns `None` or an awaitable (such as a coroutine or future). Any coroutines returned by `on_poll` must be unstarted, and any pending futures must belong to the polling event loop. Callbacks cannot return the running polling task (doing so raises `ValueError`). Deadline expiry before invocation (including during snapshot copying) can skip `on_poll` without discarding an already-classified outcome. Tuples with more than 1,000 items, immutable bytes, mutable buffers, or memoryviews with more than 65,536 bytes (the 65,536-byte limit applies to immutable bytes, mutable buffers, and memoryviews, including any view backed by a buffer larger than 65,536 bytes), sets, frozensets, or deques with more than 65,536 items in review extension data skip `on_poll` snapshot delivery even with time remaining, and snapshot copy errors on unsupported mutable values propagate before `on_poll` runs. Callbacks must return promptly even when they return an awaitable, because the polling deadline cannot interrupt the invocation. Return-validation errors and inline failures propagate and can prevent the waiter from returning a classified outcome (cancellation requested during callback invocation takes precedence over return validation). Failure propagation depends on the awaitable type and the polling deadline: already-done futures must be returned before the deadline to propagate (failures of already-done futures returned after expiry are detached and suppressed), coroutines propagate if their wrapper task completes before the deadline (timed at wrapper completion rather than when the waiter retrieves them, except for wrappers cancelled before their first step which are timed when their done callback runs), and pending future failures propagate only if their done callback executes before the deadline expires (cutting off at done-callback execution and allowing any classified outcome to be returned). When the deadline expires or when the wait is cancelled, unstarted coroutines returned by `on_poll` are closed without entering their body (a wrapper task may already have been scheduled; cancelling the waiter through an underlying pending future can leave unresumed tasks unflagged until resumption unless observed through the pending future), while already-running callback tasks and pending futures are detached without cancellation and may continue running (detached callback coroutines suppress late SystemExit and KeyboardInterrupt signals; waiter cancellation propagates without cancelling detached callback work). `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it, and its outcome is `INCOMPLETE` whatever the review's own status (unless a callback exception, callback return-validation error, snapshot copy error, waiter cancellation during inline callback invocation, or waiter cancellation while callback work is pending propagates), its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. diff --git a/proofline/client.py b/proofline/client.py index b0c833b7..36875b65 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -49,6 +49,7 @@ from inspect import ( signature as inspect_signature, ) +from enum import Enum from string import hexdigits from time import monotonic, sleep from types import ( @@ -326,6 +327,8 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: t = type(val) if t in _IMMUTABLE_TYPES: return True + if isinstance(val, Enum): + return True if t is datetime.datetime: tz = val.tzinfo return tz is None or type(tz) is datetime.timezone @@ -490,10 +493,16 @@ def _assign_target(target: Any, key: Any, is_attr: bool, val: Any) -> None: if is_desc: try: slot_or_name.__set__(target, val) - except AttributeError: + except (AttributeError, TypeError): pass else: - setattr(target, slot_or_name, val) + try: + setattr(target, slot_or_name, val) + except (AttributeError, TypeError): + try: + object.__setattr__(target, slot_or_name, val) + except Exception: + pass else: if isinstance(target, deque): deque.__setitem__(target, key, val) @@ -552,8 +561,11 @@ def _install_cloned_dict( if new_obj is not None: try: new_obj.__dict__ = cloned_dict - except AttributeError: - pass + except (AttributeError, TypeError): + try: + object.__setattr__(new_obj, "__dict__", cloned_dict) + except Exception: + pass except Exception: pass @@ -699,9 +711,40 @@ def _collect_set_members(val: Any) -> list[Any] | None: pending_assignments.setdefault(val_id, []).append((target, key, is_attr)) continue if isinstance(val, UUID): - cloned_uuid = UUID(int=val.int) + uuid_cls: Any = type(val) + if uuid_cls is UUID: + cloned_uuid = UUID(int=val.int, is_safe=val.is_safe) + else: + if _has_mutable_class_attrs(uuid_cls): + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{uuid_cls.__name__}" + ) + try: + cloned_uuid = uuid_cls(int=val.int, is_safe=val.is_safe) + except Exception: + try: + cloned_uuid = UUID.__new__(uuid_cls) + object.__setattr__(cloned_uuid, "int", val.int) + object.__setattr__(cloned_uuid, "is_safe", val.is_safe) + except Exception: + raise TypeError( + "Unsupported mutable value in review extension data: " + f"{uuid_cls.__name__}" + ) memo[val_id] = cloned_uuid _assign_target(target, key, is_attr, cloned_uuid) + if uuid_cls is not UUID: + if hasattr(val, "__dict__"): + _install_cloned_dict(val, cloned_uuid, memo, stack) + attrs = list(_get_obj_attrs(val)) + custom_attrs = [ + (desc, is_desc, v) + for (desc, is_desc, v) in attrs + if getattr(desc, "__name__", "") not in ("int", "is_safe") + ] + if custom_attrs: + stack.append((_OBJ_EXPAND, cloned_uuid, iter(custom_attrs))) continue if type(val) is dict: new_dict: dict[Any, Any] = {} @@ -1141,26 +1184,25 @@ def _collect_set_members(val: Any) -> list[Any] | None: stop = None if (last + stride < 0) else (last + stride) resolved_mv = full_bytes[offset:stop:stride] elif val_shape is not None and val.ndim > 1: - if val.ndim == 2 and val_strides is not None: - rows, cols = val_shape[0], val_shape[1] - row_stride, col_stride = val_strides[0], val_strides[1] - min_r = 0 if row_stride >= 0 else (rows - 1) - min_c = 0 if col_stride >= 0 else (cols - 1) - min_byte = offset + min_r * row_stride + min_c * col_stride - max_r = (rows - 1) if row_stride >= 0 else 0 - max_c = (cols - 1) if col_stride >= 0 else 0 - max_byte = ( - offset + max_r * row_stride + max_c * col_stride + val.itemsize - ) - span_bytes_2d: Any = full_bytes[min_byte:max_byte] - row_bytes = cols * val.itemsize - physical_rows = ( - len(span_bytes_2d) // row_bytes if row_bytes > 0 else rows + if val_strides is not None: + d_0 = val_shape[0] + s_0 = val_strides[0] + plane_bytes = val.itemsize + for d in val_shape[1:]: + plane_bytes *= d + min_p = 0 if s_0 >= 0 else (d_0 - 1) + max_p = (d_0 - 1) if s_0 >= 0 else 0 + min_byte = offset + min_p * s_0 + max_byte = offset + max_p * s_0 + plane_bytes + span_bytes_nd: Any = full_bytes[min_byte:max_byte] + physical_planes = ( + len(span_bytes_nd) // plane_bytes if plane_bytes > 0 else d_0 ) - span_2d: Any = span_bytes_2d.cast("B", shape=(physical_rows, cols)) - abs_step = abs(row_stride) // row_bytes if row_bytes > 0 else 1 + physical_shape = (physical_planes,) + val_shape[1:] + span_nd: Any = span_bytes_nd.cast("B", shape=physical_shape) + abs_step = abs(s_0) // plane_bytes if plane_bytes > 0 else 1 resolved_mv = ( - span_2d[::-abs_step] if row_stride < 0 else span_2d[::abs_step] + span_nd[::-abs_step] if s_0 < 0 else span_nd[::abs_step] ) else: full_bytes_slice: Any = full_bytes[offset : offset + val.nbytes] @@ -1212,24 +1254,32 @@ def _collect_set_members(val: Any) -> list[Any] | None: ) resolved_mv = span_cast[local_offset:stop:elem_stride] elif ( - val.ndim == 2 + val.ndim > 1 and val_shape is not None and val_strides is not None and val.itemsize > 0 ): - rows, cols = val_shape[0], val_shape[1] - row_stride, col_stride = val_strides[0], val_strides[1] - min_r = 0 if row_stride >= 0 else (rows - 1) - min_c = 0 if col_stride >= 0 else (cols - 1) - min_byte = offset + min_r * row_stride + min_c * col_stride - max_r = (rows - 1) if row_stride >= 0 else 0 - max_c = (cols - 1) if col_stride >= 0 else 0 - max_byte = ( - offset + max_r * row_stride + max_c * col_stride + val.itemsize + d_0 = val_shape[0] + s_0 = val_strides[0] + plane_bytes = val.itemsize + for d in val_shape[1:]: + plane_bytes *= d + min_p = 0 if s_0 >= 0 else (d_0 - 1) + max_p = (d_0 - 1) if s_0 >= 0 else 0 + min_byte = offset + min_p * s_0 + max_byte = offset + max_p * s_0 + plane_bytes + span_bytes_fmt: Any = full_bytes[min_byte:max_byte] + physical_planes = ( + len(span_bytes_fmt) // plane_bytes if plane_bytes > 0 else d_0 + ) + physical_shape = (physical_planes,) + val_shape[1:] + span_fmt: Any = span_bytes_fmt.cast( + val.format, shape=physical_shape + ) + abs_step = abs(s_0) // plane_bytes if plane_bytes > 0 else 1 + resolved_mv = ( + span_fmt[::-abs_step] if s_0 < 0 else span_fmt[::abs_step] ) - span_bytes_2d = full_bytes[min_byte:max_byte] - span_2d = span_bytes_2d.cast(val.format, shape=(rows, cols)) - resolved_mv = span_2d[::-1] if row_stride < 0 else span_2d else: full_bytes_slice = full_bytes[offset : offset + val.nbytes] if val_shape is not None: @@ -3487,7 +3537,6 @@ async def wait_for_review( res = on_poll(snapshot) finally: _transport.DEADLINE.reset(deadline_token) - cb_return_time = monotonic() if waiter_task is not None: is_task_cancelled = False try: @@ -3533,9 +3582,10 @@ async def wait_for_review( except BaseException: is_done = False if is_done: + done_observed_time = monotonic() deadline_val = _transport.DEADLINE.get() cb_returned_in_budget = ( - deadline_val is None or cb_return_time < deadline_val + deadline_val is None or done_observed_time < deadline_val ) if cb_returned_in_budget: if hasattr(res, "result"): diff --git a/tests/test_http.py b/tests/test_http.py index f023b2aa..70249caa 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1407,17 +1407,45 @@ def sync_mismatch_cb(r: Any) -> None: if not signal_waiter.done(): signal_waiter.cancel() - # Assert that the waiter is awaiting the callback's completion signal - # before opening the gate: + # Assert that the waiter's pending wait is tied to the callback + # completion future before resolving it: registered_cbs = [ cb_item[0] if isinstance(cb_item, tuple) else cb_item for cb_item in (getattr(cb_signal_fut, "_callbacks", None) or []) ] - assert any( - getattr(cb_item, "__name__", "") == "_on_future_done" + done_cbs = [ + cb_item for cb_item in registered_cbs + if getattr(cb_item, "__name__", "") == "_on_future_done" + ] + assert done_cbs, "Callback completion signal _on_future_done not found" + target_cb = done_cbs[0] + closure_vars = { + name: cell.cell_contents + for name, cell in zip( + target_cb.__code__.co_freevars, target_cb.__closure__ or () + ) + } + comp_fut = closure_vars.get("completion_fut") + assert comp_fut is not None, "completion_fut missing from callback closure" + assert not comp_fut.done(), "completion_fut already settled" + on_comp_cbs = [ + c[0] if isinstance(c, tuple) else c + for c in (getattr(comp_fut, "_callbacks", None) or []) + ] + assert on_comp_cbs, "No completion waiter registered on completion_fut" + on_comp_closure = { + name: cell.cell_contents + for name, cell in zip( + on_comp_cbs[0].__code__.co_freevars, + on_comp_cbs[0].__closure__ or (), + ) + } + comp_waiter = on_comp_closure.get("waiter") + assert getattr(waiter_task, "_fut_waiter", None) is comp_waiter, ( + "waiter_task is not awaiting callback completion_fut" ) - assert getattr(waiter_task, "_fut_waiter", None) is not None + assert comp_waiter is not None and not comp_waiter.done() assert not cb_completed assert not waiter_task.done() @@ -4254,12 +4282,24 @@ async def fake_sync_cancel_running(org: Any, rev: Any) -> Any: token="test_token", base_url="https://api.proofline.sh" ) as client: client.get_review = fake_sync_cancel_running # type: ignore - res_sync_cancel = await client.wait_for_review( - ORG, - REVIEW, - timeout=0.1, - on_poll=sync_cancel_on_poll, + poll_task = asyncio.create_task( + client.wait_for_review( + ORG, + REVIEW, + timeout=0.1, + on_poll=sync_cancel_on_poll, + ) ) + done_poll, _ = await asyncio.wait({poll_task}, timeout=5.0) + if poll_task not in done_poll: + if not fut_sync_cancel.done(): + fut_sync_cancel.set_result(None) + poll_task.cancel() + await asyncio.wait({poll_task}, timeout=1.0) + pytest.fail( + "wait_for_review hung on overdue future instead of detaching it" + ) + res_sync_cancel = poll_task.result() assert res_sync_cancel.status == "TIMED_OUT" await asyncio.sleep(0) assert fut_sync_cancel.cancel_called is False @@ -4714,17 +4754,36 @@ def __copy__(self) -> Any: assert bytes(mv_ctypes_slice) == b"\x04\x00\x00\x00\x02\x00\x00\x00" assert mv_ctypes_bytes[4] == 2 - # UUID instances are cloned and memoized so mutations cannot alter the original + # UUID instances are cloned and memoized preserving is_safe and subclass instance state + from uuid import SafeUUID + + class CustomReviewUUID(UUID): + pass + detail_uuid = CustomerReviewDetail.from_dict(responses[1]) - orig_uuid = detail_uuid.id + orig_uuid = UUID(int=detail_uuid.id.int, is_safe=SafeUUID.safe) + detail_uuid.id = orig_uuid + subclass_uuid = CustomReviewUUID(int=orig_uuid.int, is_safe=SafeUUID.safe) + object.__setattr__(subclass_uuid, "custom_tag", "isolated_tag") + detail_uuid.additional_properties["subclass_uuid"] = subclass_uuid + snap_uuid = _snapshot_review(detail_uuid) assert snap_uuid is not None assert snap_uuid.id is not orig_uuid assert snap_uuid.id == orig_uuid + assert snap_uuid.id.is_safe == orig_uuid.is_safe == SafeUUID.safe object.__setattr__(snap_uuid.id, "int", 999999) assert snap_uuid.id.int == 999999 assert orig_uuid.int != 999999 + cloned_subclass = snap_uuid.additional_properties["subclass_uuid"] + assert type(cloned_subclass) is CustomReviewUUID + assert cloned_subclass is not subclass_uuid + assert cloned_subclass.is_safe == SafeUUID.safe + assert cloned_subclass.custom_tag == "isolated_tag" + object.__setattr__(cloned_subclass, "custom_tag", "mutated_tag") + assert subclass_uuid.custom_tag == "isolated_tag" + # 2D memoryview bounding span cast to physical rows and row sliced c_arr_2d = (ctypes.c_uint8 * 8)(10, 11, 20, 21, 30, 31, 40, 41) mv_2d_slice = memoryview(c_arr_2d).cast("B", shape=(4, 2))[::2] @@ -4737,6 +4796,18 @@ def __copy__(self) -> Any: assert copied_2d.strides == mv_2d_slice.strides == (4, 1) assert copied_2d.tobytes() == mv_2d_slice.tobytes() + # 3D memoryview reversed first axis reconstructed from physical span + c_arr_3d = (ctypes.c_uint8 * 24)(*range(24)) + mv_3d_rev = memoryview(c_arr_3d).cast("B", shape=(2, 3, 4))[::-1] + detail_3d = CustomerReviewDetail.from_dict(responses[1]) + detail_3d.additional_properties["ctypes_3d"] = mv_3d_rev + snap_3d = _snapshot_review(detail_3d) + assert snap_3d is not None + copied_3d = snap_3d.additional_properties["ctypes_3d"] + assert copied_3d.shape == mv_3d_rev.shape == (2, 3, 4) + assert copied_3d.strides == mv_3d_rev.strides == (-12, 4, 1) + assert copied_3d.tobytes() == mv_3d_rev.tobytes() + class MutableArray(ctypes.c_int32 * 4): pass From f41b91f28dca157369f7085a370490b0df5ca301 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Tue, 24 Nov 2026 10:37:10 +0530 Subject: [PATCH 74/75] Address review feedback on watchdog clock, wrapper result, and snapshot validations --- proofline/client.py | 66 ++++++++++++++++++++++++++++++++------------- tests/test_http.py | 17 +++++++----- 2 files changed, 58 insertions(+), 25 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 36875b65..fd9c70e6 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -37,6 +37,7 @@ ) from collections import defaultdict, deque from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from enum import Enum from inspect import ( CORO_CREATED, GEN_CREATED, @@ -49,7 +50,6 @@ from inspect import ( signature as inspect_signature, ) -from enum import Enum from string import hexdigits from time import monotonic, sleep from types import ( @@ -319,6 +319,17 @@ def _deadline_expired() -> bool: return budget is not None and budget <= 0 +def _is_immutable_enum(val: Enum, seen: set[int] | None = None) -> bool: + if not _is_immutable(val.value, seen): + return False + inst_dict = getattr(val, "__dict__", None) + if inst_dict: + for v in inst_dict.values(): + if not _is_immutable(v, seen): + return False + return True + + def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if val is None or val is UNSET: return True @@ -328,7 +339,7 @@ def _is_immutable(val: Any, seen: set[int] | None = None) -> bool: if t in _IMMUTABLE_TYPES: return True if isinstance(val, Enum): - return True + return _is_immutable_enum(val, seen) if t is datetime.datetime: tz = val.tzinfo return tz is None or type(tz) is datetime.timezone @@ -697,6 +708,13 @@ def _collect_set_members(val: Any) -> list[Any] | None: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) + if isinstance(val, Enum): + if not _is_immutable(val): + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) + _assign_target(target, key, is_attr, val) + continue if _is_immutable(val): if type(val) is bytes and len(val) > _MAX_SAFE_BUFFER_SIZE: return None @@ -849,6 +867,9 @@ def _collect_set_members(val: Any) -> list[Any] | None: _install_cloned_dict(val, new_list, memo, stack) stack.append((_OBJ_EXPAND, new_list, iter(_get_obj_attrs(val)))) elif isinstance(val, set): + set_len = set.__len__(val) + if set_len > _MAX_SAFE_BUFFER_SIZE: + return None if type(val) is not set and _has_mutable_class_attrs(type(val)): raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" @@ -857,7 +878,6 @@ def _collect_set_members(val: Any) -> list[Any] | None: raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) - set_len = set.__len__(val) if type(val) is not set: try: if set_len == 0: @@ -897,11 +917,17 @@ def _collect_set_members(val: Any) -> list[Any] | None: deferred_set_insertions.append((new_set, val, orig_set_members)) stack.append((_SET_EXPAND, None, iter(val))) elif isinstance(val, frozenset): + fs_len = frozenset.__len__(val) + if fs_len > _MAX_SAFE_BUFFER_SIZE: + return None if type(val) is not frozenset and _has_mutable_class_attrs(type(val)): raise TypeError( f"Unsupported mutable value in review extension data: {type(val).__name__}" ) - fs_len = frozenset.__len__(val) + if "__copy__" in type(val).__dict__: + raise TypeError( + f"Unsupported mutable value in review extension data: {type(val).__name__}" + ) if type(val) is not frozenset: try: if fs_len == 0: @@ -1149,20 +1175,24 @@ def _collect_set_members(val: Any) -> list[Any] | None: if val.ndim == 0: scalar_obj = elem_type.from_buffer(cloned_exporter, offset) resolved_mv = memoryview(scalar_obj) - elif val.ndim == 1 and val_shape is not None and val_strides is not None: - shape = val_shape[0] - stride = val_strides[0] - elem_stride = stride // itemsize if itemsize > 0 else 1 - if shape == 0: + elif ( + full_mv.ndim >= 1 + and full_mv.strides is not None + and val_shape is not None + and val_strides is not None + ): + exp_stride = full_mv.strides[0] + start = offset // exp_stride if exp_stride != 0 else 0 + step = val_strides[0] // exp_stride if exp_stride != 0 else 1 + length = val_shape[0] + if length == 0: resolved_mv = full_mv[0:0] - elif elem_stride > 0: - resolved_mv = full_mv[ - item_offset : item_offset + shape * elem_stride : elem_stride - ] + elif step > 0: + resolved_mv = full_mv[start : start + length * step : step] else: - last = item_offset + (shape - 1) * elem_stride - stop = None if (last + elem_stride < 0) else (last + elem_stride) - resolved_mv = full_mv[item_offset:stop:elem_stride] + last = start + (length - 1) * step + stop = None if (last + step < 0) else (last + step) + resolved_mv = full_mv[start:stop:step] elif val.c_contiguous: count = val.nbytes // val.itemsize if val.itemsize > 0 else 0 resolved_mv = full_mv[item_offset : item_offset + count] @@ -3535,6 +3565,7 @@ async def wait_for_review( deadline_token = _transport.DEADLINE.set(None) try: res = on_poll(snapshot) + cb_return_time = monotonic() finally: _transport.DEADLINE.reset(deadline_token) if waiter_task is not None: @@ -3582,10 +3613,9 @@ async def wait_for_review( except BaseException: is_done = False if is_done: - done_observed_time = monotonic() deadline_val = _transport.DEADLINE.get() cb_returned_in_budget = ( - deadline_val is None or done_observed_time < deadline_val + deadline_val is None or cb_return_time < deadline_val ) if cb_returned_in_budget: if hasattr(res, "result"): diff --git a/tests/test_http.py b/tests/test_http.py index 70249caa..dac841e9 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2985,8 +2985,6 @@ def __init__(self, loop: asyncio.AbstractEventLoop) -> None: def add_done_callback(self, fn: Any, *, context: Any = None) -> None: super().add_done_callback(fn, context=context) self.active_callbacks.append(fn) - if "_on_future_done" in getattr(fn, "__name__", ""): - clock.advance(1.0) self.wait_entered.set() def remove_done_callback(self, fn: Any) -> int: @@ -3025,6 +3023,10 @@ def pending_future_callback(r: Any) -> SignallingFuture: if waiter_task_1 in done_1: await waiter_task_1 assert pending_fut is not None + await pending_fut.wait_entered.wait() + while getattr(waiter_task_1, "_fut_waiter", None) is None: + await asyncio.sleep(0) + clock.advance(1.0) done_waiter_1, _ = await asyncio.wait({waiter_task_1}, timeout=1.0) assert waiter_task_1 in done_waiter_1 res_1 = waiter_task_1.result() @@ -3172,6 +3174,9 @@ async def continuing_coro(r: Any) -> None: await finish_waiter_3 except (asyncio.CancelledError, BaseException): pass + done_cb3_fin, _ = await asyncio.wait({cb_task_3}, timeout=1.0) + assert cb_task_3 in done_cb3_fin + assert cb_task_3.result() is None finally: if not startup_waiter_3.done(): startup_waiter_3.cancel() @@ -3313,7 +3318,6 @@ async def continuing_coro_term(r: Any) -> None: callback_running_term.set() await release_callback_term.wait() callback_finished_term.set() - raise RuntimeError("overdue coroutine failure") client.get_review = fake_completed # type: ignore @@ -3379,10 +3383,9 @@ async def continuing_coro_term(r: Any) -> None: pass assert callback_running_term.is_set() assert callback_finished_term.is_set() - await asyncio.sleep(0.01) - assert wrapper_4.done() - assert not wrapper_4.cancelled() - assert getattr(wrapper_4, "exception_calls", 0) > 0 + done_w4_wrap, _ = await asyncio.wait({wrapper_4}, timeout=1.0) + assert wrapper_4 in done_w4_wrap + assert wrapper_4.result() is None finally: release_callback_term.set() if not waiter_task_4.done(): From 4a7dcf12235e8696e30578c59bf4d812fda31f73 Mon Sep 17 00:00:00 2001 From: abhish12345 Date: Tue, 24 Nov 2026 10:52:29 +0530 Subject: [PATCH 75/75] Address Run 74 findings on enum slots, 0-row view slicing, task factory cancellation, and test quality --- proofline/client.py | 65 +++++++++++++---- tests/test_http.py | 168 +++++++++++++++++++++++++++----------------- 2 files changed, 156 insertions(+), 77 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index fd9c70e6..b2cfa790 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -327,6 +327,22 @@ def _is_immutable_enum(val: Enum, seen: set[int] | None = None) -> bool: for v in inst_dict.values(): if not _is_immutable(v, seen): return False + seen_slots: set[str] = set() + for cls in type(val).__mro__: + slots = getattr(cls, "__slots__", None) + if slots is not None: + if isinstance(slots, str): + slots = (slots,) + for slot_name in slots: + if slot_name in seen_slots or slot_name in ("__dict__", "__weakref__"): + continue + seen_slots.add(slot_name) + try: + slot_val = getattr(val, slot_name) + except AttributeError: + continue + if not _is_immutable(slot_val, seen): + return False return True @@ -1214,7 +1230,22 @@ def _collect_set_members(val: Any) -> list[Any] | None: stop = None if (last + stride < 0) else (last + stride) resolved_mv = full_bytes[offset:stop:stride] elif val_shape is not None and val.ndim > 1: - if val_strides is not None: + if val_shape[0] == 0: + plane_bytes = val.itemsize + for d in val_shape[1:]: + plane_bytes *= d + s_0 = val_strides[0] if val_strides is not None else 1 + if len(full_bytes) >= plane_bytes and plane_bytes > 0: + nonempty_shape = (1,) + val_shape[1:] + base_shaped = full_bytes[:plane_bytes].cast( + "B", shape=nonempty_shape + ) + resolved_mv = ( + base_shaped[::-1][0:0] if s_0 < 0 else base_shaped[0:0] + ) + else: + resolved_mv = full_bytes[0:0] + elif val_strides is not None: d_0 = val_shape[0] s_0 = val_strides[0] plane_bytes = val.itemsize @@ -3733,6 +3764,12 @@ def _on_future_done(_: Any) -> None: completed_at = [] wrapper_started = False captured_deadline = _transport.DEADLINE.get() + wrapper_task: AsyncTask[Any] | None = None + try: + task_completion_fut = async_get_running_loop().create_future() + except BaseException: + _cleanup_discarded_awaitable(res) + raise async def _runner() -> Any: nonlocal wrapper_started @@ -3767,13 +3804,21 @@ async def _runner() -> Any: break except BaseException: pass + curr_task = wrapper_task or async_current_task() try: - if getattr(task, "_must_cancel", False): - waiter_cancelling = True - elif hasattr(task, "cancelling") and task.cancelling() > 0: - waiter_cancelling = True - elif hasattr(task, "cancelled") and task.cancelled(): - waiter_cancelling = True + if curr_task is not None: + if getattr(curr_task, "_must_cancel", False): + waiter_cancelling = True + elif ( + hasattr(curr_task, "cancelling") + and curr_task.cancelling() > 0 + ): + waiter_cancelling = True + elif ( + hasattr(curr_task, "cancelled") + and curr_task.cancelled() + ): + waiter_cancelling = True except BaseException: pass try: @@ -3805,6 +3850,7 @@ async def _runner() -> Any: deadline_token_task = _transport.DEADLINE.set(None) try: task = async_create_task(runner_coro) + wrapper_task = task except BaseException: if ( iscoroutine(runner_coro) @@ -3818,11 +3864,6 @@ async def _runner() -> Any: raise finally: _transport.DEADLINE.reset(deadline_token_task) - try: - task_completion_fut = async_get_running_loop().create_future() - except BaseException: - _detach_overdue_task(task, res, wrapper_started) - raise def _on_task_done(t: Any) -> None: if not completed_at: diff --git a/tests/test_http.py b/tests/test_http.py index dac841e9..382fa582 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2863,10 +2863,16 @@ async def failing_callback(r: Any) -> None: # Assert already-done failed future propagates inline failed_inline_futs: list[asyncio.Future[None]] = [] + call_start_inline = clock.now + + class ClockAdvancingDoneFuture(asyncio.Future[None]): + def done(self) -> bool: + clock.now = call_start_inline + 10.0 + return super().done() def failed_future_callback(r: Any) -> asyncio.Future[None]: loop = asyncio.get_running_loop() - fut: asyncio.Future[None] = loop.create_future() + fut = ClockAdvancingDoneFuture(loop=loop) fut.set_exception(ValueError("inline future error")) failed_inline_futs.append(fut) return fut @@ -2973,6 +2979,16 @@ async def fake_completed(org: Any, rev: Any) -> Any: async with AsyncProoflineClient( token="test_token", base_url="https://api.proofline.sh" ) as client: + async_wait_calls_1 = 0 + orig_async_wait_1 = client_module.async_wait + + async def counting_async_wait_1(*args: Any, **kwargs: Any) -> Any: + nonlocal async_wait_calls_1 + async_wait_calls_1 += 1 + return await orig_async_wait_1(*args, **kwargs) + + client_module.async_wait = counting_async_wait_1 + # Case 1: Pending same-loop Future that times out is detached without cancelling # Assert it is still pending before advancing the controlled deadline class SignallingFuture(asyncio.Future[None]): @@ -2985,6 +3001,8 @@ def __init__(self, loop: asyncio.AbstractEventLoop) -> None: def add_done_callback(self, fn: Any, *, context: Any = None) -> None: super().add_done_callback(fn, context=context) self.active_callbacks.append(fn) + if "_on_future_done" in getattr(fn, "__name__", ""): + clock.advance(1.0) self.wait_entered.set() def remove_done_callback(self, fn: Any) -> int: @@ -3023,16 +3041,13 @@ def pending_future_callback(r: Any) -> SignallingFuture: if waiter_task_1 in done_1: await waiter_task_1 assert pending_fut is not None - await pending_fut.wait_entered.wait() - while getattr(waiter_task_1, "_fut_waiter", None) is None: - await asyncio.sleep(0) - clock.advance(1.0) done_waiter_1, _ = await asyncio.wait({waiter_task_1}, timeout=1.0) assert waiter_task_1 in done_waiter_1 res_1 = waiter_task_1.result() assert res_1.status == "TIMED_OUT" assert not pending_fut.cancelled() assert not pending_fut.done() + assert async_wait_calls_1 == 0 assert id(pending_fut) in client_module._DETACHED_FUTURES assert len(pending_fut.removed_callbacks) > 0 assert any( @@ -3047,6 +3062,7 @@ def pending_future_callback(r: Any) -> SignallingFuture: await asyncio.sleep(0) assert id(pending_fut) not in client_module._DETACHED_FUTURES finally: + client_module.async_wait = orig_async_wait_1 if pending_fut is not None and not pending_fut.done(): pending_fut.set_result(None) if not startup_waiter_1.done(): @@ -4798,6 +4814,10 @@ class CustomReviewUUID(UUID): assert copied_2d.shape == mv_2d_slice.shape == (2, 2) assert copied_2d.strides == mv_2d_slice.strides == (4, 1) assert copied_2d.tobytes() == mv_2d_slice.tobytes() + copied_2d[0, 0] = 99 + assert copied_2d[0, 0] == 99 + assert mv_2d_slice[0, 0] == 10 + assert c_arr_2d[0] == 10 # 3D memoryview reversed first axis reconstructed from physical span c_arr_3d = (ctypes.c_uint8 * 24)(*range(24)) @@ -4810,6 +4830,10 @@ class CustomReviewUUID(UUID): assert copied_3d.shape == mv_3d_rev.shape == (2, 3, 4) assert copied_3d.strides == mv_3d_rev.strides == (-12, 4, 1) assert copied_3d.tobytes() == mv_3d_rev.tobytes() + copied_3d[0, 0, 0] = 99 + assert copied_3d[0, 0, 0] == 99 + assert mv_3d_rev[0, 0, 0] == 12 + assert c_arr_3d[12] == 12 class MutableArray(ctypes.c_int32 * 4): pass @@ -5708,11 +5732,14 @@ def cb_consuming_clock(r: Any) -> Any: with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=cb_consuming_clock, + await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=cb_consuming_clock, + ), + timeout=5.0, ) assert wait_timeouts == [65.0] monkeypatch.setattr(client_module, "async_wait", orig_async_wait) @@ -5738,11 +5765,14 @@ def timely_fail_cb(r: Any) -> asyncio.Future[None]: with Server(lambda request, index: Reply(body=responses[0])) as server: async with session("async", server.url) as client: with pytest.raises(ValueError, match="timely failure"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=timely_fail_cb, + await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_fail_cb, + ), + timeout=5.0, ) finally: if timely_producer is not None: @@ -5783,11 +5813,14 @@ def timely_late_fail_cb(r: Any) -> asyncio.Future[None]: with Server(lambda request, index: Reply(body=responses[0])) as server: async with session("async", server.url) as client: with pytest.raises(ValueError, match="timely failure with late resumption"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=timely_late_fail_cb, + await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_late_fail_cb, + ), + timeout=5.0, ) assert clock.now >= 200.0 finally: @@ -5832,11 +5865,14 @@ async def timely_fail_coro(r: Any) -> None: with Server(lambda request, index: Reply(body=responses[0])) as server: async with session("async", server.url) as client: with pytest.raises(ValueError, match="timely coroutine failure"): - await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=timely_fail_coro, + await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=timely_fail_coro, + ), + timeout=5.0, ) assert clock.now >= 200.0 monkeypatch.setattr(client_module, "async_create_task", orig_create_task_timely) @@ -5876,11 +5912,14 @@ def late_fail_cb(r: Any) -> asyncio.Future[None]: try: with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - res_late = await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=late_fail_cb, + res_late = await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=late_fail_cb, + ), + timeout=5.0, ) assert res_late.status == "COMPLETED" assert late_fut is not None @@ -5937,11 +5976,14 @@ def late_failing_cb(r: Any) -> asyncio.Future[None]: try: with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - res_after = await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=late_failing_cb, + res_after = await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=late_failing_cb, + ), + timeout=5.0, ) assert res_after.status == "COMPLETED" assert late_failing_fut is not None @@ -5976,30 +6018,29 @@ def late_failing_cb(r: Any) -> asyncio.Future[None]: # Pending future failing at exact deadline for completed review preserves COMPLETED exact_call_start = 0.0 + async_wait_calls_exact = 0 + orig_async_wait_exact = client_module.async_wait + + async def counting_async_wait_exact(*args: Any, **kwargs: Any) -> Any: + nonlocal async_wait_calls_exact + async_wait_calls_exact += 1 + return await orig_async_wait_exact(*args, **kwargs) + + monkeypatch.setattr(client_module, "async_wait", counting_async_wait_exact) class ExactDeadlineCompletedFuture(TrackedFuture): def add_done_callback(self, fn: Any, *, context: Any = None) -> None: - def wrapped_fn(f: Any) -> None: - clock.now = exact_call_start + 100.0 - fn(f) - - super().add_done_callback(wrapped_fn, context=context) + super().add_done_callback(fn, context=context) + clock.now = exact_call_start + 100.0 exact_dl_fut: ExactDeadlineCompletedFuture | None = ExactDeadlineCompletedFuture( loop=asyncio.get_running_loop() ) exact_dl_ref = weakref.ref(exact_dl_fut) - exact_dl_producer: asyncio.Task[None] | None = None - - async def fail_at_exact_dl() -> None: - await asyncio.sleep(0) - if exact_dl_fut is not None: - exact_dl_fut.set_exception(ValueError("failure at exact deadline")) def exact_dl_cb(r: Any) -> asyncio.Future[None]: - nonlocal exact_dl_producer, exact_call_start + nonlocal exact_call_start exact_call_start = clock.now - exact_dl_producer = asyncio.create_task(fail_at_exact_dl()) assert exact_dl_fut is not None return exact_dl_fut @@ -6008,32 +6049,29 @@ def exact_dl_cb(r: Any) -> asyncio.Future[None]: try: with Server(lambda request, index: Reply(body=responses[1])) as server: async with session("async", server.url) as client: - res_exact_dl = await client.wait_for_review( - ORG, - REVIEW, - timeout=100.0, - on_poll=exact_dl_cb, + res_exact_dl = await asyncio.wait_for( + client.wait_for_review( + ORG, + REVIEW, + timeout=100.0, + on_poll=exact_dl_cb, + ), + timeout=5.0, ) assert res_exact_dl.status == "COMPLETED" assert exact_dl_fut is not None - assert exact_dl_fut.done() - if exact_dl_producer is not None: - await exact_dl_producer + assert not exact_dl_fut.done() + assert async_wait_calls_exact == 0 + assert id(exact_dl_fut) in client_module._DETACHED_FUTURES + assert exact_dl_fut.exception_retrieved is False + exact_dl_fut.cancel() await asyncio.sleep(0) - assert exact_dl_fut.exception_retrieved is True - assert id(exact_dl_fut) not in client_module._DETACHED_FUTURES exact_dl_fut = None gc.collect() assert exact_dl_ref() is None assert unhandled_exact_dl_reports == [] finally: - if exact_dl_producer is not None: - if not exact_dl_producer.done(): - exact_dl_producer.cancel() - try: - await exact_dl_producer - except (asyncio.CancelledError, BaseException): - pass + monkeypatch.setattr(client_module, "async_wait", orig_async_wait_exact) if exact_dl_fut is not None: if not exact_dl_fut.done(): exact_dl_fut.cancel()