Skip to content

Commit 960b70d

Browse files
committed
Add sync and async export page iteration
1 parent 768f971 commit 960b70d

4 files changed

Lines changed: 212 additions & 3 deletions

File tree

‎README.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,29 @@ with ProoflineClient() as client:
5151
# Continue with cursor=page.next_cursor when it is not None.
5252
```
5353

54+
`iter_export_pages` runs that loop for one window and yields every page while it
55+
follows the signed cursors, keeping the dataset, window, format and grouping fixed.
56+
It stops at the last page, refuses a cursor it has already received and raises
57+
`ProoflineError` when `max_pages` (100 by default, at most 1000) is reached.
58+
`AsyncProoflineClient` exposes the same helper for `async for`.
59+
60+
```python
61+
import os
62+
from uuid import UUID
63+
64+
with ProoflineClient() as client:
65+
rows = [
66+
row
67+
for export in client.iter_export_pages(
68+
UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]),
69+
"findings",
70+
from_time="2026-10-01T00:00:00Z",
71+
to_time="2026-10-25T00:00:00Z",
72+
)
73+
for row in export.rows
74+
]
75+
```
76+
5477
## Coverage uploads
5578

5679
Use a repository-restricted token with `coverage:write` and current repository write

‎proofline/client.py‎

Lines changed: 100 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,12 +180,34 @@ def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None:
180180
return cursor
181181

182182

183-
def _pagination_limit() -> ProoflineError:
183+
def _pagination_limit(subject: str = "Review") -> ProoflineError:
184184
return ProoflineError(
185-
0, "urn:proofline:sdk:pagination-limit", "Review pagination reached the configured bound."
185+
0,
186+
"urn:proofline:sdk:pagination-limit",
187+
f"{subject} pagination reached the configured bound.",
186188
)
187189

188190

191+
def _export_limits(max_pages: int) -> None:
192+
if not 1 <= max_pages <= 1_000:
193+
raise ValueError("Export iteration requires max_pages 1..1000.")
194+
195+
196+
def _export_cursor(page: ExportPage, seen: set[str]) -> str | None:
197+
"""A missing continuation ends the window; a repeated one is refused."""
198+
cursor = page.next_cursor
199+
if not cursor:
200+
return None
201+
if cursor in seen:
202+
raise ProoflineError(
203+
0,
204+
"urn:proofline:sdk:invalid-pagination",
205+
"The export page has no new continuation cursor.",
206+
)
207+
seen.add(cursor)
208+
return cursor
209+
210+
189211
class ProoflineClient:
190212
"""Synchronous typed HTTP operations.
191213
@@ -491,6 +513,44 @@ def iter_reviews(
491513
params["cursor"] = cursor
492514
raise _pagination_limit()
493515

516+
def iter_export_pages(
517+
self,
518+
organization_id: UUID,
519+
dataset: ExportDataset,
520+
*,
521+
from_time: str,
522+
to_time: str,
523+
format: ExportFormat = "ndjson",
524+
group_by: str | None = None,
525+
cursor: str | None = None,
526+
max_pages: int = 100,
527+
) -> Iterator[ExportPage]:
528+
"""Read every export page of one window by following signed cursors.
529+
530+
The window, format and grouping stay fixed across the requests, so a
531+
continuation only changes the cursor. Iteration stops at the last page,
532+
refuses a repeated cursor and stops at the configured page bound.
533+
"""
534+
_export_limits(max_pages)
535+
seen: set[str] = set()
536+
if cursor:
537+
seen.add(cursor)
538+
for _ in range(max_pages):
539+
page = self.export_reviews(
540+
organization_id,
541+
dataset,
542+
from_time=from_time,
543+
to_time=to_time,
544+
format=format,
545+
cursor=cursor,
546+
group_by=group_by,
547+
)
548+
yield page
549+
cursor = _export_cursor(page, seen)
550+
if cursor is None:
551+
return
552+
raise _pagination_limit("Export")
553+
494554
def wait_for_review(
495555
self, organization_id: UUID, review_id: UUID, *, timeout: float = 300
496556
) -> ReviewOutcome:
@@ -850,6 +910,44 @@ async def iter_reviews(
850910
params["cursor"] = cursor
851911
raise _pagination_limit()
852912

913+
async def iter_export_pages(
914+
self,
915+
organization_id: UUID,
916+
dataset: ExportDataset,
917+
*,
918+
from_time: str,
919+
to_time: str,
920+
format: ExportFormat = "ndjson",
921+
group_by: str | None = None,
922+
cursor: str | None = None,
923+
max_pages: int = 100,
924+
) -> AsyncIterator[ExportPage]:
925+
"""Read every export page of one window by following signed cursors.
926+
927+
The window, format and grouping stay fixed across the requests, so a
928+
continuation only changes the cursor. Iteration stops at the last page,
929+
refuses a repeated cursor and stops at the configured page bound.
930+
"""
931+
_export_limits(max_pages)
932+
seen: set[str] = set()
933+
if cursor:
934+
seen.add(cursor)
935+
for _ in range(max_pages):
936+
page = await self.export_reviews(
937+
organization_id,
938+
dataset,
939+
from_time=from_time,
940+
to_time=to_time,
941+
format=format,
942+
cursor=cursor,
943+
group_by=group_by,
944+
)
945+
yield page
946+
cursor = _export_cursor(page, seen)
947+
if cursor is None:
948+
return
949+
raise _pagination_limit("Export")
950+
853951
async def wait_for_review(
854952
self, organization_id: UUID, review_id: UUID, *, timeout: float = 300
855953
) -> ReviewOutcome:

‎scripts/contracts.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def main() -> None:
2929
"The generated JSON operations must match the twenty-one public JSON token routes."
3030
)
3131
tree = ast.parse((ROOT / "proofline/client.py").read_text())
32-
helpers = {"close", "aclose", "iter_reviews", "wait_for_review"}
32+
helpers = {"close", "aclose", "iter_reviews", "iter_export_pages", "wait_for_review"}
3333
clients = {
3434
node.name: {
3535
member.name

‎tests/test_http.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
CustomerAssessmentDetail,
2929
CustomerFinding,
3030
CustomerReviewDetail,
31+
ExportPage,
3132
FileReviewRequest,
3233
FileReviewResponse,
3334
PatchReviewRequest,
@@ -95,6 +96,13 @@ async def collect(client: Client, **kwargs: Any) -> list[Any]:
9596
return list(iterator)
9697

9798

99+
async def collect_pages(client: Client, dataset: str, **kwargs: Any) -> list[ExportPage]:
100+
iterator = client.iter_export_pages(ORG, dataset, **kwargs)
101+
if hasattr(iterator, "__aiter__"):
102+
return [export async for export in iterator]
103+
return list(iterator)
104+
105+
98106
class Clock:
99107
def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:
100108
self.now = 100.0
@@ -1392,6 +1400,86 @@ def respond(request: Request, index: int) -> Reply:
13921400
assert caught.value.status == 404
13931401

13941402

1403+
@MODES
1404+
async def test_export_iteration_keeps_the_window_and_refuses_cycles_or_bounds(mode: str) -> None:
1405+
kwargs = {
1406+
"from_time": "2026-10-01T00:00:00Z",
1407+
"to_time": "2026-10-25T00:00:00Z",
1408+
"format": "csv",
1409+
"group_by": "severity",
1410+
}
1411+
1412+
def csv_reply(cursor: str | None) -> Reply:
1413+
headers = {
1414+
"Content-Type": "text/csv",
1415+
"X-Proofline-Export-Version": "1",
1416+
"X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z",
1417+
}
1418+
if cursor is not None:
1419+
headers["X-Proofline-Export-Next-Cursor"] = cursor
1420+
return Reply(body=b"dataset_version,severity\r\n1,high\r\n", headers=headers)
1421+
1422+
def respond(request: Request, index: int) -> Reply:
1423+
query = parse_qs(urlsplit(request.path).query)
1424+
assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/finding_outcomes?")
1425+
assert query["from"] == ["2026-10-01T00:00:00Z"]
1426+
assert query["to"] == ["2026-10-25T00:00:00Z"]
1427+
assert query["format"] == ["csv"]
1428+
assert query["group_by"] == ["severity"]
1429+
assert query.get("cursor") == ([f"cursor-{index - 1}"] if index else None)
1430+
headers = {
1431+
"Content-Type": "text/csv",
1432+
"X-Proofline-Export-Version": "1",
1433+
"X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z",
1434+
}
1435+
if index < 2:
1436+
headers["X-Proofline-Export-Next-Cursor"] = f"cursor-{index}"
1437+
return Reply(
1438+
body=f"dataset_version,severity\r\n1,page-{index}\r\n".encode(), headers=headers
1439+
)
1440+
1441+
with Server(respond) as server:
1442+
async with session(mode, server.url) as client:
1443+
exports = await collect_pages(client, "finding_outcomes", **kwargs)
1444+
assert [export.rows[0]["severity"] for export in exports] == [
1445+
"page-0",
1446+
"page-1",
1447+
"page-2",
1448+
]
1449+
assert exports[0].text.startswith("dataset_version,severity\r\n")
1450+
assert [export.next_cursor for export in exports] == ["cursor-0", "cursor-1", None]
1451+
assert exports[-1].settled_until == "2026-10-25T00:00:00Z"
1452+
assert len(server.requests) == 3
1453+
1454+
with Server(lambda request, index: csv_reply("repeated")) as server:
1455+
async with session(mode, server.url) as client:
1456+
with pytest.raises(ProoflineError) as raised:
1457+
await collect_pages(client, "finding_outcomes", **kwargs)
1458+
assert raised.value.type == "urn:proofline:sdk:invalid-pagination"
1459+
assert len(server.requests) == 2
1460+
1461+
with Server(lambda request, index: csv_reply("seeded")) as server:
1462+
async with session(mode, server.url) as client:
1463+
with pytest.raises(ProoflineError) as raised:
1464+
await collect_pages(client, "finding_outcomes", cursor="seeded", **kwargs)
1465+
assert raised.value.type == "urn:proofline:sdk:invalid-pagination"
1466+
assert len(server.requests) == 1
1467+
1468+
with Server(lambda request, index: csv_reply(f"cursor-{index}")) as server:
1469+
async with session(mode, server.url) as client:
1470+
with pytest.raises(ProoflineError) as raised:
1471+
await collect_pages(client, "finding_outcomes", max_pages=2, **kwargs)
1472+
assert raised.value.detail == "Export pagination reached the configured bound."
1473+
assert len(server.requests) == 2
1474+
1475+
with Server(lambda request, index: csv_reply(None)) as server:
1476+
async with session(mode, server.url) as client:
1477+
for bound in (0, 1_001):
1478+
with pytest.raises(ValueError):
1479+
await collect_pages(client, "finding_outcomes", max_pages=bound, **kwargs)
1480+
assert server.requests == []
1481+
1482+
13951483
@MODES
13961484
async def test_knowledge_negotiation_scope_and_no_retry(mode: str) -> None:
13971485
refusal = False

0 commit comments

Comments
 (0)