Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -54,6 +54,8 @@
"ExportDataset",
"ExportFormat",
"ExportPage",
"ExportRangePage",
"ExportWindow",
"FileReviewRequest",
"FileReviewResponse",
"KnowledgeResult",
Expand Down
66 changes: 65 additions & 1 deletion proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down
109 changes: 107 additions & 2 deletions proofline/exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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:
Expand Down
9 changes: 8 additions & 1 deletion scripts/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading