From c22ce1c6cd052b8fa4554313673908c1883ca09a Mon Sep 17 00:00:00 2001 From: Darius Date: Sat, 5 Dec 2026 00:07:13 -0600 Subject: [PATCH 1/2] Reject duplicate object keys in NDJSON export pages --- README.md | 2 +- proofline/exports.py | 14 +++++++++++++- tests/test_exports.py | 33 +++++++++++++++++++++++++++++++++ tests/test_http.py | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 250fb32e..f727564f 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ with ProoflineClient() as client: # Continue with cursor=page.next_cursor when it is not None. ``` -Each response returns the original text, decoded rows, dataset version, settled horizon, and an optional next cursor. Each CSV page includes its own header and keeps cells as strings, including nested JSON cells. NDJSON pages retain JSON values. To read additional pages, repeat the call with the returned cursor and the same dataset, window, format, and grouping. A missing next cursor marks the last page. +Each response returns the original text, decoded rows, dataset version, settled horizon, and an optional next cursor. Each CSV page includes its own header and keeps cells as strings, including nested JSON cells. NDJSON pages retain JSON values. If an object repeats a key, even inside a nested object, the SDK rejects the entire page with `urn:proofline:sdk:invalid-response` to avoid silently losing a value. To read additional pages, repeat the call with the returned cursor and the same dataset, window, format, and grouping. A missing next cursor marks the last page. `iter_export_pages` follows continuation cursors lazily while keeping the same organization, dataset, window, format, and grouping on every request. diff --git a/proofline/exports.py b/proofline/exports.py index 357db150..6837b1d2 100644 --- a/proofline/exports.py +++ b/proofline/exports.py @@ -30,6 +30,14 @@ class ExportPage: next_cursor: str | None +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + # Check before a duplicate can silently replace a field such as dataset_version. + obj = dict(pairs) + if len(obj) != len(pairs): + raise ValueError("Duplicate NDJSON object key.") + return obj + + def decode_export( response: httpx2.Response, format: ExportFormat, dataset: ExportDataset ) -> ExportPage: @@ -55,7 +63,11 @@ def decode_export( raise ValueError rows = [dict(zip(columns, row, strict=True)) for row in records] else: - rows = [json.loads(line) for line in text.split("\n") if line.strip()] + rows = [ + json.loads(line, object_pairs_hook=_unique_object) + for line in text.split("\n") + if line.strip() + ] if any( not isinstance(row, dict) or str(row.get("dataset_version")) != version for row in rows ): diff --git a/tests/test_exports.py b/tests/test_exports.py index ccb5f704..78ce0410 100644 --- a/tests/test_exports.py +++ b/tests/test_exports.py @@ -103,3 +103,36 @@ 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 + + +@pytest.mark.parametrize( + "line", + [ + '{"dataset_version":2,"dataset_version":1}', + '{"dataset_version":1,"claim":"first","claim":"second"}', + r'{"dataset_version":1,"items":[{"claim":null,"cl\u0061im":false}]}', + ], + ids=["masked-version", "overwritten-field", "escaped-nested-key"], +) +def test_ndjson_rejects_duplicate_keys(line: str) -> None: + reply = response(line) + reply.headers["Content-Type"] = "application/x-ndjson" + with pytest.raises(ProoflineError) as caught: + decode_export(reply, "ndjson", "reviews") + assert caught.value.type == "urn:proofline:sdk:invalid-response" + assert caught.value.status == 200 + + +def test_ndjson_allows_reused_keys_in_distinct_objects() -> None: + text = ( + '{"dataset_version":1,"items":[{"id":1},{"id":2,"ID":3}]}\r\n' + '{"dataset_version":1,"items":[]}\n' + ) + reply = response(text) + reply.headers["Content-Type"] = "application/x-ndjson" + page = decode_export(reply, "ndjson", "reviews") + assert page.text == text + assert page.rows == [ + {"dataset_version": 1, "items": [{"id": 1}, {"id": 2, "ID": 3}]}, + {"dataset_version": 1, "items": []}, + ] diff --git a/tests/test_http.py b/tests/test_http.py index 37aa2b4f..3af8fe49 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2057,6 +2057,40 @@ async def next_export(iterator: Any) -> Any: return await anext(iterator) if hasattr(iterator, "__anext__") else next(iterator) +@MODES +async def test_export_iterator_rejects_ambiguous_ndjson_page(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + body = b'{"dataset_version":1,"claim":"ok"}\n' + if index: + body += b'{"dataset_version":1,"claim":"first","claim":"second"}\n' + return Reply( + body=body, + headers={ + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": f"next-{index}", + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + pages = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + format="ndjson", + ) + first = await next_export(pages) + assert first.rows == [{"dataset_version": 1, "claim": "ok"}] + with pytest.raises(ProoflineError) as raised: + await next_export(pages) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + assert raised.value.status == 200 + assert len(server.requests) == 2 + + @MODES @pytest.mark.parametrize("format", ["csv", "ndjson"]) async def test_export_iterator_preserves_filters_and_streams_empty_pages( From bd0061827245dab49f63019f20a04202e015ad59 Mon Sep 17 00:00:00 2001 From: Darius Date: Sat, 5 Dec 2026 00:09:30 -0600 Subject: [PATCH 2/2] Reuse the NDJSON decoder across rows in each export page --- proofline/exports.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/proofline/exports.py b/proofline/exports.py index 6837b1d2..8017e44f 100644 --- a/proofline/exports.py +++ b/proofline/exports.py @@ -63,11 +63,8 @@ def decode_export( raise ValueError rows = [dict(zip(columns, row, strict=True)) for row in records] else: - rows = [ - json.loads(line, object_pairs_hook=_unique_object) - for line in text.split("\n") - if line.strip() - ] + decoder = json.JSONDecoder(object_pairs_hook=_unique_object) + rows = [decoder.decode(line) for line in text.split("\n") if line.strip()] if any( not isinstance(row, dict) or str(row.get("dataset_version")) != version for row in rows ):