diff --git a/README.md b/README.md index 721949da..afb1d940 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ with ProoflineClient() as client: 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. +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, or a page whose settled horizon differs from the first page read by the iterator, raise `ProoflineError` with type `urn:proofline:sdk:invalid-pagination`, and the invalid page 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 diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..3dc50793 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -72,7 +72,7 @@ from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError -from .exports import ExportDataset, ExportFormat, ExportPage, decode_export +from .exports import ExportDataset, ExportFormat, ExportPage, checked_export_horizon, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient from .outcomes import ReviewOutcome, outcome @@ -317,9 +317,10 @@ def iter_export_pages( group_by: str | None = None, max_pages: int = 100, ) -> Iterator[ExportPage]: - """Stream export pages, refusing cursor cycles and incomplete bounded traversals.""" + """Stream export pages while checking cursors, the settled horizon, and page bounds.""" _export_page_limit(max_pages) seen = {cursor} if cursor is not None else set() + horizon: str | None = None for _ in range(max_pages): page = self.export_reviews( organization_id, @@ -331,6 +332,7 @@ def iter_export_pages( group_by=group_by, ) cursor = _export_next_cursor(page, seen) + horizon = checked_export_horizon(page.settled_until, horizon) yield page if cursor is None: return @@ -687,9 +689,10 @@ async def iter_export_pages( group_by: str | None = None, max_pages: int = 100, ) -> AsyncIterator[ExportPage]: - """Stream export pages, refusing cursor cycles and incomplete bounded traversals.""" + """Stream export pages while checking cursors, the settled horizon, and page bounds.""" _export_page_limit(max_pages) seen = {cursor} if cursor is not None else set() + horizon: str | None = None for _ in range(max_pages): page = await self.export_reviews( organization_id, @@ -701,6 +704,7 @@ async def iter_export_pages( group_by=group_by, ) cursor = _export_next_cursor(page, seen) + horizon = checked_export_horizon(page.settled_until, horizon) yield page if cursor is None: return diff --git a/proofline/exports.py b/proofline/exports.py index 357db150..2a16e145 100644 --- a/proofline/exports.py +++ b/proofline/exports.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import re from dataclasses import dataclass from datetime import datetime from typing import Any, Literal @@ -30,6 +31,25 @@ class ExportPage: next_cursor: str | None +def _settled_instant(horizon: str) -> tuple[datetime, str]: + # datetime handles offsets, but truncates fractional seconds after six digits. + fraction = re.search(r"[.,]([0-9]{7,})(?=Z$|[+-][0-9]{2}:[0-9]{2}$)", horizon) + remainder = fraction[1][6:].rstrip("0") if fraction else "" + return datetime.fromisoformat(horizon), remainder + + +def checked_export_horizon(horizon: str, first: str | None) -> str: + if first is None: + return horizon + if horizon != first and _settled_instant(horizon) != _settled_instant(first): + raise ProoflineError( + 0, + "urn:proofline:sdk:invalid-pagination", + "The export settled horizon changed between pages.", + ) + return first + + def decode_export( response: httpx2.Response, format: ExportFormat, dataset: ExportDataset ) -> ExportPage: diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..689b8468 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1921,6 +1921,56 @@ def respond(request: Request, index: int) -> Reply: assert len(server.requests) == 2 +@MODES +@pytest.mark.parametrize( + ("first_horizon", "next_horizon", "empty", "valid"), + [ + ("2026-10-25T00:00:00Z", "2026-10-24T20:00:00-04:00", False, True), + ("2026-10-25T00:00:00Z", "2026-10-25T00:00:01Z", False, False), + ("2026-10-25T00:00:00Z", "2026-10-25T00:00:01Z", True, False), + ("2026-10-25T00:00:00.1234567Z", "2026-10-25T00:00:00.1234568Z", False, False), + ("2026-10-25T00:00:00.1234567Z", "2026-10-25T00:00:00.123456700Z", False, True), + ], + ids=["equivalent-offset", "changed", "changed-empty", "submicrosecond", "trailing-zeroes"], +) +async def test_export_iterator_requires_frozen_horizon( + mode: str, first_horizon: str, next_horizon: str, empty: bool, valid: bool +) -> None: + def respond(request: Request, index: int) -> Reply: + query = parse_qs(urlsplit(request.path).query) + assert query.get("cursor") == (["resume"] if index == 0 else ["next"]) + headers = { + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": first_horizon if index == 0 else next_horizon, + } + if index == 0: + headers["X-Proofline-Export-Next-Cursor"] = "next" + return Reply( + body=b"" if index == 1 and empty else b'{"dataset_version":1}\n', + headers=headers, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + cursor="resume", + ) + assert (await next_export(iterator)).settled_until == first_horizon + if valid: + assert (await next_export(iterator)).settled_until == next_horizon + else: + with pytest.raises(ProoflineError) as raised: + await next_export(iterator) + assert raised.value.type == "urn:proofline:sdk:invalid-pagination" + assert raised.value.detail == "The export settled horizon changed between pages." + assert len(server.requests) == 2 + + @MODES @pytest.mark.parametrize("failure", ["empty", "repeat", "resume", "cycle", "bound", "refused"]) async def test_export_iterator_refuses_invalid_continuations_and_bounds(