diff --git a/README.md b/README.md index 721949da..5efb459f 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,21 @@ with ProoflineClient() as client: 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. +The export API reads a window of at most 31 days. `iter_export_range` reads a longer range, such as a quarter or a year, as consecutive windows and streams every page of each window through `iter_export_pages`. + +```python +with ProoflineClient() as client: + for page in client.iter_export_range( + UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), + "reviews", + from_time="2026-01-01T00:00:00Z", + to_time="2027-01-01T00:00:00Z", + ): + print(page.window.from_time, page.window.to_time, len(page.rows)) +``` + +The range is `[from_time, to_time)`. Every window except the last spans exactly 31 days of elapsed time. The first window starts at `from_time` and the last ends at `to_time`, both exactly as written; each boundary between windows is one UTC timestamp used as one window's `to` and the next window's `from`, so windows neither overlap nor leave gaps. Each yielded `ExportRangePage` is an `ExportPage` with the `window` it was read from, and every window yields at least one page, even with no rows, so a caller can confirm the whole range was read. `max_pages` bounds each window. `max_windows` (default 100, at most 1000) bounds the range. `from_time` and `to_time` must be RFC 3339 date-times with an offset and at most microsecond precision. A malformed time, an empty range, a range that needs more than `max_windows` windows, or the `finding_outcomes` dataset raises `ValueError` before any request. `finding_outcomes` rows are groups counted over one window, so groups from separate windows are not range totals; read it one window at a time with `iter_export_pages`. A cursor is valid only within its own window, so restart an interrupted range from the `window` of the last page you kept. + ## 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/__init__.py b/proofline/__init__.py index 689b454d..392adfad 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -34,7 +34,7 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters -from .exports import ExportDataset, ExportFormat, ExportPage +from .exports import ExportDataset, ExportFormat, ExportPage, ExportRangePage, ExportWindow from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -54,6 +54,8 @@ "ExportDataset", "ExportFormat", "ExportPage", + "ExportRangePage", + "ExportWindow", "FileReviewRequest", "FileReviewResponse", "KnowledgeResult", diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..8d73dc2f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -72,7 +72,15 @@ 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, + ExportRangePage, + decode_export, + export_windows, + range_page, +) from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient from .outcomes import ReviewOutcome, outcome @@ -336,6 +344,34 @@ def iter_export_pages( return raise _pagination_limit("Export") + def iter_export_range( + self, + organization_id: UUID, + dataset: ExportDataset, + *, + from_time: str, + to_time: str, + format: ExportFormat = "ndjson", + max_pages: int = 100, + max_windows: int = 100, + ) -> Iterator[ExportRangePage]: + """Stream every export page of [from_time, to_time), a range of any length. + + The range is read as consecutive windows of at most 31 days, each through + iter_export_pages with max_pages as its bound. Every window yields at least one page. + """ + _export_page_limit(max_pages) + for window in export_windows(dataset, from_time, to_time, max_windows): + for page in self.iter_export_pages( + organization_id, + dataset, + from_time=window.from_time, + to_time=window.to_time, + format=format, + max_pages=max_pages, + ): + yield range_page(page, window) + def list_reviews(self, organization_id: UUID, **filters: Unpack[ReviewFilters]) -> ReviewPage: return self._call(list_reviews.sync_detailed, ReviewPage, organization_id, **filters) @@ -706,6 +742,34 @@ async def iter_export_pages( return raise _pagination_limit("Export") + async def iter_export_range( + self, + organization_id: UUID, + dataset: ExportDataset, + *, + from_time: str, + to_time: str, + format: ExportFormat = "ndjson", + max_pages: int = 100, + max_windows: int = 100, + ) -> AsyncIterator[ExportRangePage]: + """Stream every export page of [from_time, to_time), a range of any length. + + The range is read as consecutive windows of at most 31 days, each through + iter_export_pages with max_pages as its bound. Every window yields at least one page. + """ + _export_page_limit(max_pages) + for window in export_windows(dataset, from_time, to_time, max_windows): + async for page in self.iter_export_pages( + organization_id, + dataset, + from_time=window.from_time, + to_time=window.to_time, + format=format, + max_pages=max_pages, + ): + yield range_page(page, window) + async def list_reviews( self, organization_id: UUID, **filters: Unpack[ReviewFilters] ) -> ReviewPage: diff --git a/proofline/exports.py b/proofline/exports.py index 357db150..bb30f954 100644 --- a/proofline/exports.py +++ b/proofline/exports.py @@ -3,8 +3,9 @@ from __future__ import annotations import json -from dataclasses import dataclass -from datetime import datetime +import re +from dataclasses import dataclass, fields +from datetime import UTC, datetime, timedelta, timezone from typing import Any, Literal import httpx2 @@ -19,6 +20,17 @@ # that have not moved to version 2. _VERSIONS: dict[str, tuple[str, ...]] = {"findings": ("1", "2"), "finding_validations": ("1", "2")} +# The export API reads a window of at most 31 days. +EXPORT_WINDOW = timedelta(days=31) +# RFC 3339 date-time with a required offset. Fractions stop at microseconds so every window +# boundary is exact in datetime arithmetic; the fields are parsed here rather than by +# datetime.fromisoformat, which also accepts ISO 8601 forms the export API does not. +_RFC3339 = re.compile( + r"(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?" + r"(?:([Zz])|([+-])(\d{2}):(\d{2}))", + re.ASCII, +) + @dataclass(frozen=True) class ExportPage: @@ -30,6 +42,99 @@ class ExportPage: next_cursor: str | None +@dataclass(frozen=True) +class ExportWindow: + """One request window [from_time, to_time) of an export range, as sent to the API.""" + + from_time: str + to_time: str + + +@dataclass(frozen=True) +class ExportRangePage(ExportPage): + """An export page and the window of the range it was read from.""" + + window: ExportWindow + + +def _instant(value: object, name: str) -> datetime: + match = _RFC3339.fullmatch(value) if isinstance(value, str) else None + try: + if match is None: + raise ValueError + year, month, day, hour, minute, second = (int(part) for part in match.groups()[:6]) + microsecond = int(match[7].ljust(6, "0")) if match[7] else 0 + offset = timedelta(0) + if not match[8]: + if int(match[11]) > 59: + raise ValueError + offset = timedelta(hours=int(match[10]), minutes=int(match[11])) + if match[9] == "-": + offset = -offset + instant = datetime( + year, month, day, hour, minute, second, microsecond, tzinfo=timezone(offset) + ) + return instant.astimezone(UTC) + except (ValueError, OverflowError): + raise ValueError( + f"{name} must be an RFC 3339 date-time with an offset, such as " + "2026-10-01T00:00:00Z, with at most microsecond precision." + ) from None + + +def _utc_text(instant: datetime) -> str: + timespec = "microseconds" if instant.microsecond else "seconds" + return instant.isoformat(timespec=timespec).replace("+00:00", "Z") + + +def export_windows( + dataset: str, from_time: str, to_time: str, max_windows: int +) -> tuple[ExportWindow, ...]: + """Split [from_time, to_time) into consecutive windows the export API accepts. + + Every window but the last spans exactly 31 days. The first window starts at from_time and + the last ends at to_time, both exactly as written; each boundary between windows is one UTC + string used as one window's end and the next window's start, so no instant is read twice or + skipped. + """ + if dataset == "finding_outcomes": + # Its rows are groups counted over the whole request window, so groups read from + # separate windows are not totals for the range. + raise ValueError( + "finding_outcomes groups rows per window and cannot be split into a range; " + "read one window of at most 31 days with iter_export_pages." + ) + if ( + isinstance(max_windows, bool) + or not isinstance(max_windows, int) + or not 1 <= max_windows <= 1_000 + ): + raise ValueError("Export ranges require max_windows 1..1000.") + start = _instant(from_time, "from_time") + end = _instant(to_time, "to_time") + if end <= start: + raise ValueError("to_time must be later than from_time.") + needed = -((start - end) // EXPORT_WINDOW) + if needed > max_windows: + raise ValueError( + f"The export range needs {needed} windows of 31 days, more than " + f"max_windows={max_windows}." + ) + windows: list[ExportWindow] = [] + window_from = from_time + for index in range(1, needed): + boundary = _utc_text(start + index * EXPORT_WINDOW) + windows.append(ExportWindow(window_from, boundary)) + window_from = boundary + windows.append(ExportWindow(window_from, to_time)) + return tuple(windows) + + +def range_page(page: ExportPage, window: ExportWindow) -> ExportRangePage: + values = {field.name: getattr(page, field.name) for field in fields(ExportPage)} + return ExportRangePage(**values, window=window) + + def decode_export( response: httpx2.Response, format: ExportFormat, dataset: ExportDataset ) -> ExportPage: diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..102c6b9c 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -42,7 +42,14 @@ def main() -> None: raise SystemExit("ReviewFilters differs from the list_reviews query parameters.") for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "iter_export_pages", + "iter_export_range", + "iter_reviews", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/test_exports.py b/tests/test_exports.py index ccb5f704..318a5791 100644 --- a/tests/test_exports.py +++ b/tests/test_exports.py @@ -3,6 +3,7 @@ import csv import io from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime, timedelta from itertools import product import httpx2 @@ -10,7 +11,7 @@ from proofline import ProoflineError from proofline._transport import MAX_RESPONSE_BYTES -from proofline.exports import decode_export +from proofline.exports import EXPORT_WINDOW, ExportWindow, decode_export, export_windows def response(text: str) -> httpx2.Response: @@ -103,3 +104,148 @@ def decode(index: int) -> str: with ThreadPoolExecutor(max_workers=4) as pool: assert set(pool.map(decode, range(12))) == {str(before)} assert csv.field_size_limit() == before + + +def instant(value: str) -> datetime: + return datetime.fromisoformat(value.replace("Z", "+00:00")) + + +def test_export_windows_split_a_range_without_gaps_or_overlaps() -> None: + windows = export_windows("reviews", "2026-01-01T00:00:00Z", "2026-04-01T00:00:00Z", 100) + assert windows == ( + ExportWindow("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z"), + ExportWindow("2026-02-01T00:00:00Z", "2026-03-04T00:00:00Z"), + ExportWindow("2026-03-04T00:00:00Z", "2026-04-01T00:00:00Z"), + ) + + +@pytest.mark.parametrize( + ("from_time", "to_time", "expected"), + [ + # A range of exactly 31 days is one request, and one microsecond more is two. + ("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z", ["2026-02-01T00:00:00Z"]), + ( + "2026-01-01T00:00:00Z", + "2026-02-01T00:00:00.000001Z", + ["2026-02-01T00:00:00Z", "2026-02-01T00:00:00.000001Z"], + ), + ("2026-01-01T00:00:00Z", "2026-01-01T00:00:00.000001Z", ["2026-01-01T00:00:00.000001Z"]), + # Caller offsets and fractions stay as written; inner boundaries are UTC. + ( + "2026-01-01T05:30:00.25+05:30", + "2026-03-01t00:00:00-08:00", + ["2026-02-01T00:00:00.250000Z", "2026-03-01t00:00:00-08:00"], + ), + # Days are elapsed time, so a range across a leap day still steps by 31 x 24 hours. + ( + "2028-02-01T00:00:00Z", + "2028-04-01T00:00:00Z", + ["2028-03-03T00:00:00Z", "2028-04-01T00:00:00Z"], + ), + ], +) +def test_export_windows_keep_caller_bounds_and_exact_spans( + from_time: str, to_time: str, expected: list[str] +) -> None: + windows = export_windows("findings", from_time, to_time, 100) + assert [window.to_time for window in windows] == expected + assert windows[0].from_time == from_time + assert windows[-1].to_time == to_time + for previous, current in zip(windows, windows[1:], strict=False): + assert previous.to_time == current.from_time + spans = [instant(w.to_time) - instant(w.from_time) for w in windows] + assert all(timedelta(0) < span <= EXPORT_WINDOW for span in spans) + assert all(span == EXPORT_WINDOW for span in spans[:-1]) + assert sum(spans, timedelta(0)) == instant(to_time) - instant(from_time) + + +def test_export_windows_cover_long_ranges_exactly() -> None: + start = datetime(2024, 2, 29, 23, 59, 59, 999_999, tzinfo=UTC) + for days in (1, 30, 31, 32, 62, 365, 366, 3_100): + for extra in (timedelta(0), timedelta(microseconds=1), timedelta(hours=7)): + end = start + timedelta(days=days) + extra + from_time = start.isoformat().replace("+00:00", "Z") + to_time = end.isoformat().replace("+00:00", "Z") + windows = export_windows("spend", from_time, to_time, 1_000) + spans = [instant(w.to_time) - instant(w.from_time) for w in windows] + assert len(windows) == -(-(end - start) // EXPORT_WINDOW) + assert all(span == EXPORT_WINDOW for span in spans[:-1]) + assert timedelta(0) < spans[-1] <= EXPORT_WINDOW + assert sum(spans, timedelta(0)) == end - start + + +@pytest.mark.parametrize( + "value", + [ + "2026-01-01", + "2026-01-01T00:00:00", + "2026-01-01T00:00Z", + "2026-01-01 00:00:00Z", + "20260101T000000Z", + "2026-W01-1T00:00:00Z", + "2026-02-30T00:00:00Z", + "2026-13-01T00:00:00Z", + "2026-01-01T24:00:00Z", + "2026-01-01T23:60:00Z", + "2026-01-01T23:59:60Z", + "2026-01-01T00:00:00.Z", + "2026-01-01T00:00:00.1234567Z", + "2026-01-01T00:00:00+24:00", + "2026-01-01T00:00:00+05:60", + "2026-01-01T00:00:00+0530", + "0000-01-01T00:00:00Z", + "0001-01-01T00:00:00+01:00", + "\uff12026-01-01T00:00:00Z", + " 2026-01-01T00:00:00Z", + "2026-01-01T00:00:00Z\n", + "", + None, + 1767225600, + datetime(2026, 1, 1, tzinfo=UTC), + ], +) +def test_export_windows_refuse_times_that_are_not_rfc3339(value: object) -> None: + for from_time, to_time, name in ( + (value, "2027-01-01T00:00:00Z", "from_time"), + ("2025-01-01T00:00:00Z", value, "to_time"), + ): + with pytest.raises(ValueError, match=f"^{name} must be an RFC 3339"): + export_windows("reviews", from_time, to_time, 100) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + ("from_time", "to_time"), + [ + ("2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"), + ("2026-01-01T05:30:00+05:30", "2026-01-01T00:00:00Z"), + ("2026-02-01T00:00:00Z", "2026-01-01T00:00:00Z"), + ], +) +def test_export_windows_refuse_empty_ranges(from_time: str, to_time: str) -> None: + with pytest.raises(ValueError, match="later than from_time"): + export_windows("reviews", from_time, to_time, 100) + + +@pytest.mark.parametrize("bound", [0, -1, 1001, True, 1.5, "2", None]) +def test_export_windows_validate_the_window_bound(bound: object) -> None: + with pytest.raises(ValueError, match="max_windows 1..1000"): + export_windows( + "reviews", + "2026-01-01T00:00:00Z", + "2026-02-01T00:00:00Z", + bound, # type: ignore[arg-type] + ) + + +def test_export_windows_refuse_a_range_beyond_the_window_bound() -> None: + assert len(export_windows("reviews", "2026-01-01T00:00:00Z", "2026-03-04T00:00:00Z", 2)) == 2 + with pytest.raises(ValueError, match="needs 3 windows of 31 days, more than max_windows=2"): + export_windows("reviews", "2026-01-01T00:00:00Z", "2026-03-04T00:00:00.000001Z", 2) + # The bound is checked before any window is built, even for an extreme range. + with pytest.raises(ValueError, match="more than max_windows=1000"): + export_windows("reviews", "0001-01-01T00:00:00Z", "9999-12-31T23:59:59Z", 1_000) + + +def test_export_windows_refuse_finding_outcomes() -> None: + with pytest.raises(ValueError, match="finding_outcomes groups rows per window"): + export_windows("finding_outcomes", "2026-01-01T00:00:00Z", "2026-01-02T00:00:00Z", 100) diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..4606e3da 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -35,6 +35,7 @@ CustomerAssessmentDetail, CustomerFinding, CustomerReviewDetail, + ExportPage, FileReviewRequest, FileReviewResponse, PatchReviewRequest, @@ -2035,6 +2036,147 @@ def respond(request: Request, index: int) -> Reply: assert len(server.requests) == yielded + 1 +def export_reply(format: str, rows: list[dict[str, Any]], cursor: str | None = None) -> Reply: + if format == "csv": + body = "dataset_version,claim\r\n" + "".join( + f"{row['dataset_version']},{row['claim']}\r\n" for row in rows + ) + else: + body = "".join(json.dumps(row) + "\n" for row in rows) + headers = { + "Content-Type": "text/csv" if format == "csv" else "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-11-16T00:00:00Z", + } + if cursor is not None: + headers["X-Proofline-Export-Next-Cursor"] = cursor + return Reply(body=body.encode(), headers=headers) + + +@MODES +@pytest.mark.parametrize("format", ["csv", "ndjson"]) +async def test_export_range_reads_each_window_through_its_cursors(mode: str, format: str) -> None: + from_time = "2026-01-01T05:30:00+05:30" + to_time = "2026-03-20T00:00:00Z" + windows = [ + (from_time, "2026-02-01T00:00:00Z"), + ("2026-02-01T00:00:00Z", "2026-03-04T00:00:00Z"), + ("2026-03-04T00:00:00Z", to_time), + ] + # The first window continues once; the second has no rows; the third has one page. + script = [ + (0, None, [{"dataset_version": 1, "claim": "a"}], "w0/+next"), + (0, "w0/+next", [{"dataset_version": 1, "claim": "b"}], None), + (1, None, [], None), + (2, None, [{"dataset_version": 1, "claim": "c"}], None), + ] + + def respond(request: Request, index: int) -> Reply: + assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/findings?") + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + window, cursor, rows, next_cursor = script[index] + expected = { + "from": [windows[window][0]], + "to": [windows[window][1]], + "format": [format], + } + if cursor is not None: + expected["cursor"] = [cursor] + assert parse_qs(urlsplit(request.path).query) == expected + return export_reply(format, rows, next_cursor) + + with Server(respond) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_range( + ORG, "findings", from_time=from_time, to_time=to_time, format=format + ) + assert not server.requests + if hasattr(iterator, "__aiter__"): + pages = [page async for page in iterator] + else: + pages = list(iterator) + assert len(server.requests) == len(script) + assert [(page.window.from_time, page.window.to_time) for page in pages] == [ + windows[0], + windows[0], + windows[1], + windows[2], + ] + assert [[row["claim"] for row in page.rows] for page in pages] == [["a"], ["b"], [], ["c"]] + assert [page.next_cursor for page in pages] == ["w0/+next", None, None, None] + assert all(isinstance(page, ExportPage) and page.format == format for page in pages) + assert all(page.version == 1 for page in pages) + assert all(page.settled_until == "2026-11-16T00:00:00Z" for page in pages) + + +@MODES +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"dataset": "finding_outcomes"}, "finding_outcomes groups rows per window"), + ({"from_time": "2026-01-01"}, "from_time must be an RFC 3339"), + ({"to_time": "2026-04-01T00:00:00"}, "to_time must be an RFC 3339"), + ({"to_time": "2026-01-01T00:00:00Z"}, "later than from_time"), + ({"max_windows": 2}, "needs 3 windows"), + ({"max_windows": True}, "max_windows 1..1000"), + ({"max_pages": 0}, "max_pages"), + ], +) +async def test_export_range_validates_before_requests( + mode: str, kwargs: dict[str, Any], message: str +) -> None: + arguments: dict[str, Any] = { + "dataset": "reviews", + "from_time": "2026-01-01T00:00:00Z", + "to_time": "2026-04-01T00:00:00Z", + **kwargs, + } + dataset = arguments.pop("dataset") + with Server(lambda request, index: Reply(body={})) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_range(ORG, dataset, **arguments) + with pytest.raises(ValueError, match=message): + await next_export(iterator) + assert not server.requests + + +@MODES +@pytest.mark.parametrize("failure", ["refused", "bound"]) +async def test_export_range_stops_at_the_first_failed_window(mode: str, failure: str) -> None: + def respond(request: Request, index: int) -> Reply: + if index == 0: + return export_reply("ndjson", [{"dataset_version": 1, "claim": "kept"}]) + if failure == "refused": + return Reply(status=404, body={"detail": "not found"}) + return export_reply("ndjson", [{"dataset_version": 1}], f"cursor-{index}") + + pages: list[Any] = [] + with Server(respond) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_range( + ORG, + "reviews", + from_time="2026-01-01T00:00:00Z", + to_time="2026-04-01T00:00:00Z", + max_pages=2, + ) + with pytest.raises(ProoflineError) as raised: + while True: + pages.append(await next_export(iterator)) + if failure == "refused": + assert raised.value.status == 404 + assert len(server.requests) == 2 + else: + assert raised.value.type == "urn:proofline:sdk:pagination-limit" + assert len(server.requests) == 3 + # The window after the failed one is never requested. + assert [parse_qs(urlsplit(request.path).query)["from"] for request in server.requests][ + 1: + ] == [["2026-02-01T00:00:00Z"]] * (len(server.requests) - 1) + assert pages[0].rows == [{"dataset_version": 1, "claim": "kept"}] + assert pages[0].window.to_time == "2026-02-01T00:00:00Z" + + @MODES @pytest.mark.parametrize( ("format", "content_type"),