Skip to content
Merged
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
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,28 @@ coroutines. The [SDK guide](https://proofline.sh/docs/sdks/) and
Licensed under the Apache License, Version 2.0. The generated models under
`proofline/_generated` carry the MIT license of the generator templates.

## Exports

`export_reviews` reads one CSV or NDJSON page through the existing bounded transport.
It returns the original text, decoded rows, dataset version, settled horizon and
optional next cursor. CSV cells remain strings, including nested JSON cells;
NDJSON retains JSON values. Export tokens need `analytics:read`.
Repeat with the returned cursor and the same dataset, window, format and grouping.
A missing next cursor marks the last page. Each CSV page includes its own header.

```python
from uuid import UUID

with ProoflineClient() as client:
page = client.export_reviews(
UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), "reviews",
from_time="2026-10-01T00:00:00Z", to_time="2026-10-25T00:00:00Z",
format="csv",
)
print(page.text, end="")
# Continue with cursor=page.next_cursor when it is not None.
```

## Coverage uploads

Use a repository-restricted token with `coverage:write` and current repository write
Expand Down
4 changes: 4 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from ._transport import VERSION as __version__
from ._transport import ProoflineError
from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters
from .exports import ExportDataset, ExportFormat, ExportPage
from .outcomes import AssessmentGap, CheckGap, ReviewOutcome

__all__ = [
Expand All @@ -47,6 +48,9 @@
"CustomerAssessmentDetail",
"CustomerFinding",
"CustomerReviewDetail",
"ExportDataset",
"ExportFormat",
"ExportPage",
"FileReviewRequest",
"FileReviewResponse",
"PatchReviewRequest",
Expand Down
2 changes: 1 addition & 1 deletion proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from ._sync_http import IO_DEADLINE
from ._sync_http import Transport as SyncHTTPTransport

VERSION = "1.0.0"
VERSION = "1.0.1"
MAX_RESPONSE_BYTES = 8 * 1024 * 1024
WEEKDAY = r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)"
FULL_WEEKDAY = r"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)"
Expand Down
75 changes: 75 additions & 0 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
from ._generated.models.stop_response import StopResponse
from ._generated.types import UNSET, Response, Unset
from ._transport import ProoflineError
from .exports import ExportDataset, ExportFormat, ExportPage, decode_export
from .outcomes import ReviewOutcome, outcome

T = TypeVar("T")
Expand Down Expand Up @@ -246,6 +247,43 @@ def _call(
except Exception:
raise _malformed() from None

def export_reviews(
self,
organization_id: UUID,
dataset: ExportDataset,
*,
from_time: str,
to_time: str,
format: ExportFormat = "ndjson",
cursor: str | None = None,
group_by: str | None = None,
) -> ExportPage:
"""Read one export page. Repeat with next_cursor and the same filters."""
if dataset not in (
"reviews",
"finding_outcomes",
"finding_validations",
"spend",
"findings",
):
raise ValueError("Unknown export dataset.")
if format not in ("csv", "ndjson"):
raise ValueError("Export format must be csv or ndjson.")
params = {"from": from_time, "to": to_time, "format": format}
if cursor is not None:
params["cursor"] = cursor
if group_by is not None:
params["group_by"] = group_by
try:
response = self._http.get(
f"/api/v1/organizations/{organization_id}/exports/{dataset}",
params=params,
headers={"Accept": "text/csv" if format == "csv" else "application/x-ndjson"},
)
return decode_export(response, format)
except httpx.HTTPError as error:
raise _network(error) from None

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 @@ -541,6 +579,43 @@ async def _call(
except Exception:
raise _malformed() from None

async def export_reviews(
self,
organization_id: UUID,
dataset: ExportDataset,
*,
from_time: str,
to_time: str,
format: ExportFormat = "ndjson",
cursor: str | None = None,
group_by: str | None = None,
) -> ExportPage:
"""Read one export page. Repeat with next_cursor and the same filters."""
if dataset not in (
"reviews",
"finding_outcomes",
"finding_validations",
"spend",
"findings",
):
raise ValueError("Unknown export dataset.")
if format not in ("csv", "ndjson"):
raise ValueError("Export format must be csv or ndjson.")
params = {"from": from_time, "to": to_time, "format": format}
if cursor is not None:
params["cursor"] = cursor
if group_by is not None:
params["group_by"] = group_by
try:
response = await self._http.get(
f"/api/v1/organizations/{organization_id}/exports/{dataset}",
params=params,
headers={"Accept": "text/csv" if format == "csv" else "application/x-ndjson"},
)
return decode_export(response, format)
except httpx.HTTPError as error:
raise _network(error) from None

async def list_reviews(
self, organization_id: UUID, **filters: Unpack[ReviewFilters]
) -> ReviewPage:
Expand Down
62 changes: 62 additions & 0 deletions proofline/exports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Bounded export pages, with their original text and continuation metadata."""

from __future__ import annotations

import csv
import io
import json
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal

import httpx

from ._transport import ProoflineError

ExportDataset = Literal["reviews", "finding_outcomes", "finding_validations", "spend", "findings"]
ExportFormat = Literal["csv", "ndjson"]


@dataclass(frozen=True)
class ExportPage:
format: ExportFormat
text: str
rows: list[dict[str, Any]]
version: int
settled_until: str
next_cursor: str | None


def decode_export(response: httpx.Response, format: ExportFormat) -> ExportPage:
try:
media = "text/csv" if format == "csv" else "application/x-ndjson"
if (
response.headers.get("content-type", "").split(";")[0].strip() != media
or response.headers.get("x-proofline-export-version") != "1"
):
raise ValueError
horizon = response.headers["x-proofline-export-settled-until"]
if datetime.fromisoformat(horizon.replace("Z", "+00:00")).tzinfo is None:
raise ValueError
text = response.content.decode("utf-8")
if format == "csv":
records = list(csv.reader(io.StringIO(text, newline=""), strict=True))
columns = records.pop(0)
if len(set(columns)) != len(columns) or any(
len(row) != len(columns) for row in records
):
raise ValueError
rows = [dict(zip(columns, row, strict=True)) for row in records]
else:
rows = [json.loads(line) for line in text.splitlines() if line.strip()]
if any(not isinstance(row, dict) or str(row.get("dataset_version")) != "1" for row in rows):
raise ValueError
return ExportPage(
format, text, rows, 1, horizon, response.headers.get("x-proofline-export-next-cursor")
)
except (ValueError, KeyError, IndexError, UnicodeError, csv.Error):
raise ProoflineError(
response.status_code,
"urn:proofline:sdk:invalid-response",
"The export body or metadata is invalid.",
) from None
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "proofline-sdk"
version = "1.0.0"
version = "1.0.1"
description = "Typed synchronous and asynchronous clients for the Proofline review API"
readme = "README.md"
license = "Apache-2.0 AND MIT"
Expand Down
5 changes: 3 additions & 2 deletions scripts/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ def main() -> None:
if isinstance(node, ast.ClassDef)
and node.name in {"ProoflineClient", "AsyncProoflineClient"}
}
if clients != {"ProoflineClient": declared, "AsyncProoflineClient": declared}:
raise SystemExit("Both client facades must expose exactly the generated public operations.")
public = declared | {"export_reviews"}
if clients != {"ProoflineClient": public, "AsyncProoflineClient": public}:
raise SystemExit("Both client facades must expose the JSON operations and metadata export.")
prohibited = {"safe", "passed", "clean"}
for path in (ROOT / "proofline").rglob("*.py"):
for node in ast.walk(ast.parse(path.read_text())):
Expand Down
8 changes: 6 additions & 2 deletions scripts/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,12 @@ def generate(destination: Path) -> None:
raise SystemExit(f"Generation requires ruff=={RUFF_VERSION}.")
version = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]["version"]
document = json.loads(DOCUMENT.read_text())
if document["info"]["version"] != version:
raise SystemExit("The SDK version must match the public API version.")
package_version = tuple(map(int, version.split(".")))
api_version = tuple(map(int, document["info"]["version"].split(".")))
if package_version[:2] != api_version[:2] or package_version[2] < api_version[2]:
raise SystemExit(
"The SDK must follow the public API major/minor and not precede its patch."
)
env = dict(os.environ)
env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env.get("PATH", "")
with tempfile.TemporaryDirectory(prefix="proofline-json-contract-") as temporary:
Expand Down
6 changes: 3 additions & 3 deletions scripts/install_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
def main() -> None:
if not Path(proofline.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()):
raise SystemExit("The smoke test must import the installed artifact, not checkout source.")
assert importlib.metadata.version("proofline-sdk") == "1.0.0"
assert proofline.__version__ == "1.0.0"
assert importlib.metadata.version("proofline-sdk") == "1.0.1"
assert proofline.__version__ == "1.0.1"
calls: list[str] = []
finding = {
"id": str(FINDING),
Expand Down Expand Up @@ -79,7 +79,7 @@ def log_message(self, format: str, *args: object) -> None:

def do_GET(self) -> None:
assert self.headers["Authorization"] == f"Bearer {TOKEN}"
assert self.headers["User-Agent"] == "proofline-python/1.0.0"
assert self.headers["User-Agent"] == "proofline-python/1.0.1"
calls.append(self.path)
body = finding if "/findings/" in self.path else review
payload = json.dumps(body).encode()
Expand Down
3 changes: 2 additions & 1 deletion tests/http_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ def dispatch(self) -> None:
)
time.sleep(reply.header_pause)
self.send_response(reply.status)
self.send_header("Content-Type", "application/json")
if "Content-Type" not in reply.headers:
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
for key, value in reply.headers.items():
self.send_header(key, value)
Expand Down
41 changes: 40 additions & 1 deletion tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ def respond(request: Request, index: int) -> Reply:
assert len({request.peer_port for request in server.requests}) == 1
for request in server.requests:
assert request.headers["Authorization"] == f"Bearer {TOKEN}"
assert request.headers["User-Agent"] == "proofline-python/1.0.0"
assert request.headers["User-Agent"] == "proofline-python/1.0.1"
assert request.headers["Accept-Encoding"] == "identity"
assert "Cookie" not in request.headers
assert "Content-Type" not in request.headers
Expand Down Expand Up @@ -1332,3 +1332,42 @@ def test_token_environment_and_https_origin_rejection(monkeypatch: pytest.Monkey
ProoflineClient(TOKEN, base_url=origin)
with ProoflineClient(TOKEN, base_url="http://[::1]:8080"):
pass


@MODES
async def test_export_pages_preserve_csv_and_refuse_foreign_cursor(mode: str) -> 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/findings?")
assert request.headers["Authorization"] == f"Bearer {TOKEN}"
if query.get("cursor") == ["refused"]:
return Reply(status=404, body={"detail": "not found"})
is_csv = query.get("format") == ["csv"]
return Reply(
body=(
b'dataset_version,claim\r\n1,"comma, quote "" and\nnewline"\r\n'
if is_csv
else b'{"dataset_version":1,"claim":"hello"}\n'
),
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",
"X-Proofline-Export-Next-Cursor": "opaque/+cursor",
},
)

with Server(respond) as server:
async with session(mode, server.url) as client:
kwargs = {"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-25T00:00:00Z"}
exported = await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs)
assert exported.rows[0]["claim"] == 'comma, quote " and\nnewline'
assert exported.next_cursor == "opaque/+cursor"
exported = await call(
client, "export_reviews", ORG, "findings", cursor=exported.next_cursor, **kwargs
)
assert exported.rows[0]["dataset_version"] == 1
assert "cursor=opaque%2F%2Bcursor" in server.requests[1].path
with pytest.raises(ProoflineError) as caught:
await call(client, "export_reviews", ORG, "findings", cursor="refused", **kwargs)
assert caught.value.status == 404
Loading