From ba68d03801e6780e1b915ed4d1386e56f3eef1ca Mon Sep 17 00:00:00 2001 From: Bruno Albrecht Bardales Date: Sun, 15 Nov 2026 22:02:02 +0000 Subject: [PATCH 1/3] Add iter_export_pages to follow export cursors Yields each export page in order on the sync and async clients, sending the same dataset, window, format and grouping on every request, and stops after the page without a next cursor. Same guardrails as iter_reviews: max_pages bound, repeated or empty cursor raises invalid-pagination. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01V9GvJaWFKxjgK1vyZ27mhr --- README.md | 15 ++++++ proofline/client.py | 95 +++++++++++++++++++++++++++++++++++- tests/test_http.py | 114 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 222 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cba574d8..1a08d678 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,21 @@ with ProoflineClient() as client: Each response returns the original text, decoded rows, dataset version, settled horizon, and an optional next cursor. Each CSV page includes its own header and keeps cells as strings, including nested JSON cells. NDJSON pages retain JSON values. To read additional pages, repeat the call with the returned cursor and the same dataset, window, format, and grouping. A missing next cursor marks the last page. +`iter_export_pages` follows the cursor for you. It sends the same dataset, window, format, and grouping on every request, yields each page in order, and stops after the page without a next cursor. Pass `cursor` to resume from a saved position. A repeated or empty cursor raises `ProoflineError` with the type `urn:proofline:sdk:invalid-pagination`, and reading more than `max_pages` pages (default 100, at most 1000) raises `urn:proofline:sdk:pagination-limit`. The async client yields the same pages with `async for`. + +```python +with ProoflineClient() as client: + for page in client.iter_export_pages( + UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), + "spend", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + group_by="repository", + ): + for row in page.rows: + print(row) +``` + ## Coverage uploads To upload coverage reports from CI, use a repository-restricted token with `coverage:write` and current repository write access. Name the full commit SHA that the tests ran on. Send 1 to 50 LCOV, Cobertura XML, JaCoCo XML, or Go cover reports in a JSON body of at most 30 MiB. diff --git a/proofline/client.py b/proofline/client.py index 57114842..f04ca410 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -180,12 +180,33 @@ def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None: return cursor -def _pagination_limit() -> ProoflineError: +def _pagination_limit(subject: str = "Review") -> ProoflineError: return ProoflineError( - 0, "urn:proofline:sdk:pagination-limit", "Review pagination reached the configured bound." + 0, + "urn:proofline:sdk:pagination-limit", + f"{subject} pagination reached the configured bound.", ) +def _export_page_limit(max_pages: int) -> None: + if not 1 <= max_pages <= 1_000: + raise ValueError("Export pagination requires max_pages 1..1000.") + + +def _next_export_cursor(page: ExportPage, seen: set[str]) -> str | None: + cursor = page.next_cursor + if cursor is None: + return None + if not cursor or cursor in seen: + raise ProoflineError( + 0, + "urn:proofline:sdk:invalid-pagination", + "The export page has no new continuation cursor.", + ) + seen.add(cursor) + return cursor + + class ProoflineClient(Operations): """Synchronous typed HTTP operations. @@ -283,6 +304,41 @@ def export_reviews( except httpx.HTTPError as error: raise _transport.network_error(error) from None + def iter_export_pages( + self, + organization_id: UUID, + dataset: ExportDataset, + *, + from_time: str, + to_time: str, + format: ExportFormat = "ndjson", + cursor: str | None = None, + group_by: str | None = None, + max_pages: int = 100, + ) -> Iterator[ExportPage]: + """Yield every export page in order, following next_cursor with the same filters. + + Stops after the page without a next cursor. A repeated or empty cursor raises + ``invalid-pagination``; more than ``max_pages`` pages raises ``pagination-limit``. + """ + _export_page_limit(max_pages) + seen: set[str] = {cursor} if cursor else set() + for _ in range(max_pages): + page = self.export_reviews( + organization_id, + dataset, + from_time=from_time, + to_time=to_time, + format=format, + cursor=cursor, + group_by=group_by, + ) + yield page + cursor = _next_export_cursor(page, seen) + if cursor is None: + return + raise _pagination_limit("Export") + def list_reviews(self, organization_id: UUID, **filters: Unpack[ReviewFilters]) -> ReviewPage: return self._call(list_reviews.sync_detailed, ReviewPage, organization_id, **filters) @@ -622,6 +678,41 @@ async def export_reviews( except httpx.HTTPError as error: raise _transport.network_error(error) from None + async def iter_export_pages( + self, + organization_id: UUID, + dataset: ExportDataset, + *, + from_time: str, + to_time: str, + format: ExportFormat = "ndjson", + cursor: str | None = None, + group_by: str | None = None, + max_pages: int = 100, + ) -> AsyncIterator[ExportPage]: + """Yield every export page in order, following next_cursor with the same filters. + + Stops after the page without a next cursor. A repeated or empty cursor raises + ``invalid-pagination``; more than ``max_pages`` pages raises ``pagination-limit``. + """ + _export_page_limit(max_pages) + seen: set[str] = {cursor} if cursor else set() + for _ in range(max_pages): + page = await self.export_reviews( + organization_id, + dataset, + from_time=from_time, + to_time=to_time, + format=format, + cursor=cursor, + group_by=group_by, + ) + yield page + cursor = _next_export_cursor(page, seen) + if cursor is None: + return + raise _pagination_limit("Export") + async def list_reviews( self, organization_id: UUID, **filters: Unpack[ReviewFilters] ) -> ReviewPage: diff --git a/tests/test_http.py b/tests/test_http.py index fd0494b0..097692ca 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1845,6 +1845,120 @@ def respond(request: Request, index: int) -> Reply: assert caught.value.status == 404 +EXPORT_WINDOW: dict[str, Any] = { + "from_time": "2026-10-01T00:00:00Z", + "to_time": "2026-10-25T00:00:00Z", +} + + +def export_reply(body: bytes, next_cursor: str | None, *, is_csv: bool = False) -> Reply: + headers = { + "Content-Type": "text/csv" if is_csv else "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + } + if next_cursor is not None: + headers["X-Proofline-Export-Next-Cursor"] = next_cursor + return Reply(body=body, headers=headers) + + +async def collect_exports(client: Client, *args: Any, **kwargs: Any) -> list[Any]: + iterator = client.iter_export_pages(ORG, *args, **kwargs) + if hasattr(iterator, "__aiter__"): + return [page async for page in iterator] + return list(iterator) + + +@MODES +async def test_iter_export_pages_follows_cursors_with_the_same_filters(mode: str) -> None: + cursors = {None: "first/+page", "first/+page": "second", "second": None} + + def respond(request: Request, index: int) -> Reply: + query = parse_qs(urlsplit(request.path).query) + assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/spend?") + assert query["from"] == [EXPORT_WINDOW["from_time"]] + assert query["to"] == [EXPORT_WINDOW["to_time"]] + assert query["format"] == ["csv"] + assert query["group_by"] == ["repository"] + cursor = query.get("cursor", [None])[0] + return export_reply( + f"dataset_version,page\r\n1,{index}\r\n".encode(), cursors[cursor], is_csv=True + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + pages = await collect_exports( + client, "spend", format="csv", group_by="repository", **EXPORT_WINDOW + ) + assert [page.rows[0]["page"] for page in pages] == ["0", "1", "2"] + assert [page.next_cursor for page in pages] == ["first/+page", "second", None] + assert "cursor" not in server.requests[0].path + assert "cursor=first%2F%2Bpage" in server.requests[1].path + assert "cursor=second" in server.requests[2].path + + +@MODES +async def test_iter_export_pages_resumes_from_a_cursor(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + assert parse_qs(urlsplit(request.path).query)["cursor"] == ["saved"] + return export_reply(b'{"dataset_version":1,"id":"last"}\n', None) + + with Server(respond) as server: + async with session(mode, server.url) as client: + pages = await collect_exports(client, "reviews", cursor="saved", **EXPORT_WINDOW) + assert [page.rows[0]["id"] for page in pages] == ["last"] + assert len(server.requests) == 1 + + +@MODES +@pytest.mark.parametrize("repeated", ["loop", "", "saved"]) +async def test_iter_export_pages_refuses_a_repeated_or_empty_cursor( + mode: str, repeated: str +) -> None: + def respond(request: Request, index: int) -> Reply: + return export_reply(b'{"dataset_version":1}\n', repeated) + + kwargs = {"cursor": "saved"} if repeated == "saved" else {} + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await collect_exports(client, "findings", **kwargs, **EXPORT_WINDOW) + assert raised.value.type == "urn:proofline:sdk:invalid-pagination" + assert len(server.requests) == (1 if repeated != "loop" else 2) + + +@MODES +async def test_iter_export_pages_stops_at_max_pages(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + return export_reply(b'{"dataset_version":1}\n', f"next-{index}") + + with Server(respond) as server: + async with session(mode, server.url) as client: + seen: list[Any] = [] + with pytest.raises(ProoflineError) as raised: + iterator = client.iter_export_pages(ORG, "reviews", max_pages=2, **EXPORT_WINDOW) + if hasattr(iterator, "__aiter__"): + async for page in iterator: + seen.append(page) + else: + for page in iterator: + seen.append(page) + assert raised.value.type == "urn:proofline:sdk:pagination-limit" + assert raised.value.detail == "Export pagination reached the configured bound." + assert len(seen) == 2 + assert len(server.requests) == 2 + + +@MODES +@pytest.mark.parametrize("max_pages", [0, 1_001]) +async def test_iter_export_pages_validates_max_pages(mode: str, max_pages: int) -> None: + with Server(lambda request, index: Reply()) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError): + await collect_exports(client, "reviews", max_pages=max_pages, **EXPORT_WINDOW) + assert server.requests == [] + + @MODES @pytest.mark.parametrize( ("format", "content_type"), From 07afcf8f8b9691346916106f6e1fabde8e6aec41 Mon Sep 17 00:00:00 2001 From: Bruno Albrecht Bardales Date: Tue, 17 Nov 2026 13:22:01 +0000 Subject: [PATCH 2/3] Register iter_export_pages as a client helper in the contract check Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01V9GvJaWFKxjgK1vyZ27mhr --- scripts/contracts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/contracts.py b/scripts/contracts.py index d34ba64a..e8e4e73a 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -31,7 +31,7 @@ def main() -> None: from proofline import AsyncProoflineClient, ProoflineClient for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_reviews", "wait_for_review"} + helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} exposed = { name for name in dir(client) From e6fa89125f49cfe98500196e5358fec8125102ad Mon Sep 17 00:00:00 2001 From: Bruno Albrecht Bardales Date: Tue, 17 Nov 2026 14:35:36 +0000 Subject: [PATCH 3/3] Consolidate on #27's export iterator; never yield a page with an invalid cursor Adopt the bounded export iterator from #27 unchanged, rebased on current main: the continuation cursor is validated before its page is yielded, and max_pages rejects booleans and non-integers. Take #27's tests in place of this branch's. Add a regression for sync and async clients asserting that the page carrying an empty, resumed, repeated or cyclic cursor is never yielded. Co-authored-by: AI1120 <133474218+AI1120@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01V9GvJaWFKxjgK1vyZ27mhr --- README.md | 7 +- proofline/client.py | 28 ++---- tests/test_http.py | 236 ++++++++++++++++++++++++++++---------------- 3 files changed, 167 insertions(+), 104 deletions(-) diff --git a/README.md b/README.md index 1a08d678..3c7a6ca9 100644 --- a/README.md +++ b/README.md @@ -76,21 +76,22 @@ with ProoflineClient() as client: Each response returns the original text, decoded rows, dataset version, settled horizon, and an optional next cursor. Each CSV page includes its own header and keeps cells as strings, including nested JSON cells. NDJSON pages retain JSON values. To read additional pages, repeat the call with the returned cursor and the same dataset, window, format, and grouping. A missing next cursor marks the last page. -`iter_export_pages` follows the cursor for you. It sends the same dataset, window, format, and grouping on every request, yields each page in order, and stops after the page without a next cursor. Pass `cursor` to resume from a saved position. A repeated or empty cursor raises `ProoflineError` with the type `urn:proofline:sdk:invalid-pagination`, and reading more than `max_pages` pages (default 100, at most 1000) raises `urn:proofline:sdk:pagination-limit`. The async client yields the same pages with `async for`. +`iter_export_pages` follows continuation cursors lazily while keeping the same organization, dataset, window, format, and grouping on every request. ```python with ProoflineClient() as client: for page in client.iter_export_pages( UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), - "spend", + "reviews", from_time="2026-10-01T00:00:00Z", to_time="2026-10-25T00:00:00Z", - group_by="repository", ): for row in page.rows: print(row) ``` +Use `async for` with `AsyncProoflineClient`. Each yielded page retains its raw text, decoded rows, and metadata; CSV pages retain their individual headers. Pass `cursor=` to resume an export. Iteration stops only when the server omits the next cursor, including when an intermediate page has no rows. Empty or repeated continuation cursors raise `ProoflineError` with type `urn:proofline:sdk:invalid-pagination`, and the page that carries such a cursor is never yielded. The default bound is 100 pages; set `max_pages` to an integer from 1 to 1000. Exhausting that bound while a cursor remains raises `urn:proofline:sdk:pagination-limit`, so a partial export cannot silently appear complete. Stop iteration early when only a prefix is needed. + ## Coverage uploads To upload coverage reports from CI, use a repository-restricted token with `coverage:write` and current repository write access. Name the full commit SHA that the tests ran on. Send 1 to 50 LCOV, Cobertura XML, JaCoCo XML, or Go cover reports in a JSON body of at most 30 MiB. diff --git a/proofline/client.py b/proofline/client.py index f04ca410..dd5106f6 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -180,20 +180,20 @@ def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None: return cursor -def _pagination_limit(subject: str = "Review") -> ProoflineError: +def _pagination_limit(resource: str = "Review") -> ProoflineError: return ProoflineError( 0, "urn:proofline:sdk:pagination-limit", - f"{subject} pagination reached the configured bound.", + f"{resource} pagination reached the configured bound.", ) def _export_page_limit(max_pages: int) -> None: - if not 1 <= max_pages <= 1_000: + if isinstance(max_pages, bool) or not isinstance(max_pages, int) or not 1 <= max_pages <= 1_000: raise ValueError("Export pagination requires max_pages 1..1000.") -def _next_export_cursor(page: ExportPage, seen: set[str]) -> str | None: +def _export_next_cursor(page: ExportPage, seen: set[str]) -> str | None: cursor = page.next_cursor if cursor is None: return None @@ -316,13 +316,9 @@ def iter_export_pages( group_by: str | None = None, max_pages: int = 100, ) -> Iterator[ExportPage]: - """Yield every export page in order, following next_cursor with the same filters. - - Stops after the page without a next cursor. A repeated or empty cursor raises - ``invalid-pagination``; more than ``max_pages`` pages raises ``pagination-limit``. - """ + """Stream export pages, refusing cursor cycles and incomplete bounded traversals.""" _export_page_limit(max_pages) - seen: set[str] = {cursor} if cursor else set() + seen = {cursor} if cursor is not None else set() for _ in range(max_pages): page = self.export_reviews( organization_id, @@ -333,8 +329,8 @@ def iter_export_pages( cursor=cursor, group_by=group_by, ) + cursor = _export_next_cursor(page, seen) yield page - cursor = _next_export_cursor(page, seen) if cursor is None: return raise _pagination_limit("Export") @@ -690,13 +686,9 @@ async def iter_export_pages( group_by: str | None = None, max_pages: int = 100, ) -> AsyncIterator[ExportPage]: - """Yield every export page in order, following next_cursor with the same filters. - - Stops after the page without a next cursor. A repeated or empty cursor raises - ``invalid-pagination``; more than ``max_pages`` pages raises ``pagination-limit``. - """ + """Stream export pages, refusing cursor cycles and incomplete bounded traversals.""" _export_page_limit(max_pages) - seen: set[str] = {cursor} if cursor else set() + seen = {cursor} if cursor is not None else set() for _ in range(max_pages): page = await self.export_reviews( organization_id, @@ -707,8 +699,8 @@ async def iter_export_pages( cursor=cursor, group_by=group_by, ) + cursor = _export_next_cursor(page, seen) yield page - cursor = _next_export_cursor(page, seen) if cursor is None: return raise _pagination_limit("Export") diff --git a/tests/test_http.py b/tests/test_http.py index 097692ca..7b922c34 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1845,118 +1845,188 @@ def respond(request: Request, index: int) -> Reply: assert caught.value.status == 404 -EXPORT_WINDOW: dict[str, Any] = { - "from_time": "2026-10-01T00:00:00Z", - "to_time": "2026-10-25T00:00:00Z", -} - - -def export_reply(body: bytes, next_cursor: str | None, *, is_csv: bool = False) -> Reply: - headers = { - "Content-Type": "text/csv" if is_csv else "application/x-ndjson", - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - } - if next_cursor is not None: - headers["X-Proofline-Export-Next-Cursor"] = next_cursor - return Reply(body=body, headers=headers) - - -async def collect_exports(client: Client, *args: Any, **kwargs: Any) -> list[Any]: - iterator = client.iter_export_pages(ORG, *args, **kwargs) - if hasattr(iterator, "__aiter__"): - return [page async for page in iterator] - return list(iterator) +async def next_export(iterator: Any) -> Any: + return await anext(iterator) if hasattr(iterator, "__anext__") else next(iterator) @MODES -async def test_iter_export_pages_follows_cursors_with_the_same_filters(mode: str) -> None: - cursors = {None: "first/+page", "first/+page": "second", "second": None} - +@pytest.mark.parametrize("format", ["csv", "ndjson"]) +async def test_export_iterator_preserves_filters_and_streams_empty_pages( + mode: str, format: str +) -> None: def respond(request: Request, index: int) -> Reply: + assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/finding_outcomes?") + assert request.headers["Authorization"] == f"Bearer {TOKEN}" query = parse_qs(urlsplit(request.path).query) - assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/spend?") - assert query["from"] == [EXPORT_WINDOW["from_time"]] - assert query["to"] == [EXPORT_WINDOW["to_time"]] - assert query["format"] == ["csv"] - assert query["group_by"] == ["repository"] - cursor = query.get("cursor", [None])[0] - return export_reply( - f"dataset_version,page\r\n1,{index}\r\n".encode(), cursors[cursor], is_csv=True + assert query == { + "from": ["2026-10-01T00:00:00Z"], + "to": ["2026-10-25T00:00:00Z"], + "format": [format], + "group_by": ["repository"], + "cursor": ["resume/+cursor" if index == 0 else "next/+cursor"], + } + headers = { + "Content-Type": "text/csv" if format == "csv" else "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + } + if index == 0: + headers["X-Proofline-Export-Next-Cursor"] = "next/+cursor" + body = ( + ( + b"dataset_version,claim\r\n" + if index == 0 + else b"dataset_version,claim\r\n1,hello\r\n" + ) + if format == "csv" + else (b"" if index == 0 else b'{"dataset_version":1,"claim":"hello"}\n') ) + return Reply(body=body, headers=headers) with Server(respond) as server: async with session(mode, server.url) as client: - pages = await collect_exports( - client, "spend", format="csv", group_by="repository", **EXPORT_WINDOW + iterator = client.iter_export_pages( + ORG, + "finding_outcomes", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + format=format, + cursor="resume/+cursor", + group_by="repository", + max_pages=2, ) - assert [page.rows[0]["page"] for page in pages] == ["0", "1", "2"] - assert [page.next_cursor for page in pages] == ["first/+page", "second", None] - assert "cursor" not in server.requests[0].path - assert "cursor=first%2F%2Bpage" in server.requests[1].path - assert "cursor=second" in server.requests[2].path + assert not server.requests + first = await next_export(iterator) + assert first.rows == [] + assert first.next_cursor == "next/+cursor" + assert first.version == 1 + assert first.settled_until == "2026-10-25T00:00:00Z" + assert len(server.requests) == 1 + second = await next_export(iterator) + assert second.rows[0]["claim"] == "hello" + assert second.next_cursor is None + assert second.text.endswith("\n") + if mode == "sync": + with pytest.raises(StopIteration): + next(iterator) + else: + with pytest.raises(StopAsyncIteration): + await anext(iterator) + assert len(server.requests) == 2 @MODES -async def test_iter_export_pages_resumes_from_a_cursor(mode: str) -> None: +@pytest.mark.parametrize("failure", ["empty", "repeat", "resume", "cycle", "bound", "refused"]) +async def test_export_iterator_refuses_invalid_continuations_and_bounds( + mode: str, failure: str +) -> None: def respond(request: Request, index: int) -> Reply: - assert parse_qs(urlsplit(request.path).query)["cursor"] == ["saved"] - return export_reply(b'{"dataset_version":1,"id":"last"}\n', None) + if failure == "refused": + return Reply(status=404, body={"detail": "not found"}) + cursor = { + "empty": "", + "repeat": "next", + "resume": "initial", + "cycle": "a" if index % 2 == 0 else "b", + "bound": str(index), + }[failure] + return Reply( + body=b'{"dataset_version":1}\n', + headers={ + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": cursor, + }, + ) with Server(respond) as server: async with session(mode, server.url) as client: - pages = await collect_exports(client, "reviews", cursor="saved", **EXPORT_WINDOW) - assert [page.rows[0]["id"] for page in pages] == ["last"] - assert len(server.requests) == 1 + iterator = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + max_pages=3, + cursor="initial" if failure == "resume" else None, + ) + with pytest.raises(ProoflineError) as raised: + for _ in range(4): + await next_export(iterator) + if failure == "refused": + assert raised.value.status == 404 + else: + suffix = "pagination-limit" if failure == "bound" else "invalid-pagination" + assert raised.value.type == f"urn:proofline:sdk:{suffix}" + expected_requests = { + "empty": 1, + "repeat": 2, + "resume": 1, + "cycle": 3, + "bound": 3, + "refused": 1, + } + assert len(server.requests) == expected_requests[failure] @MODES -@pytest.mark.parametrize("repeated", ["loop", "", "saved"]) -async def test_iter_export_pages_refuses_a_repeated_or_empty_cursor( - mode: str, repeated: str -) -> None: - def respond(request: Request, index: int) -> Reply: - return export_reply(b'{"dataset_version":1}\n', repeated) - - kwargs = {"cursor": "saved"} if repeated == "saved" else {} - with Server(respond) as server: +@pytest.mark.parametrize("bound", [0, -1, 1001, True, 1.5]) +async def test_export_iterator_validates_bound_before_requests(mode: str, bound: Any) -> None: + with Server(lambda request, index: Reply(body={})) as server: async with session(mode, server.url) as client: - with pytest.raises(ProoflineError) as raised: - await collect_exports(client, "findings", **kwargs, **EXPORT_WINDOW) - assert raised.value.type == "urn:proofline:sdk:invalid-pagination" - assert len(server.requests) == (1 if repeated != "loop" else 2) + iterator = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + max_pages=bound, + ) + with pytest.raises(ValueError, match="max_pages"): + await next_export(iterator) + assert not server.requests @MODES -async def test_iter_export_pages_stops_at_max_pages(mode: str) -> None: +@pytest.mark.parametrize( + ("cursors", "resume", "yielded"), + [ + ([""], None, 0), + (["initial"], "initial", 0), + (["a", "a"], None, 1), + (["a", "b", "a"], None, 2), + ], + ids=["empty", "resume", "repeat", "cycle"], +) +async def test_export_iterator_never_yields_the_page_with_an_invalid_cursor( + mode: str, cursors: list[str], resume: str | None, yielded: int +) -> None: def respond(request: Request, index: int) -> Reply: - return export_reply(b'{"dataset_version":1}\n', f"next-{index}") + return Reply( + body=f'{{"dataset_version":1,"page":{index}}}\n'.encode(), + headers={ + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": cursors[index], + }, + ) + pages: list[Any] = [] with Server(respond) as server: async with session(mode, server.url) as client: - seen: list[Any] = [] + iterator = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + cursor=resume, + ) with pytest.raises(ProoflineError) as raised: - iterator = client.iter_export_pages(ORG, "reviews", max_pages=2, **EXPORT_WINDOW) - if hasattr(iterator, "__aiter__"): - async for page in iterator: - seen.append(page) - else: - for page in iterator: - seen.append(page) - assert raised.value.type == "urn:proofline:sdk:pagination-limit" - assert raised.value.detail == "Export pagination reached the configured bound." - assert len(seen) == 2 - assert len(server.requests) == 2 - - -@MODES -@pytest.mark.parametrize("max_pages", [0, 1_001]) -async def test_iter_export_pages_validates_max_pages(mode: str, max_pages: int) -> None: - with Server(lambda request, index: Reply()) as server: - async with session(mode, server.url) as client: - with pytest.raises(ValueError): - await collect_exports(client, "reviews", max_pages=max_pages, **EXPORT_WINDOW) - assert server.requests == [] + while True: + pages.append(await next_export(iterator)) + assert raised.value.type == "urn:proofline:sdk:invalid-pagination" + assert [page.rows[0]["page"] for page in pages] == list(range(yielded)) + assert len(server.requests) == yielded + 1 @MODES