Skip to content

Commit ba3e7f4

Browse files
badGarnetclaude
andcommitted
fix: validate the JSON fallback, key NDJSON off the sent Accept header
Four review findings on the elements-file path, all reproduced first. The JSON-to-NDJSON conversion iterated `http_res.json()` directly, bypassing the response schema. A `null` body raised TypeError from iterating None, and a non-array body was worse than that: iterating a dict yields its keys, so `{"detail": "oops"}` was written out as a one-element document reading `"detail"`. It now goes through `unmarshal_json_response`, so a malformed 200 fails exactly as it does on the `elements` path, and `null` yields an empty file. NDJSON detection keyed off `accept_header_override` alone, but `http_headers` can replace Accept too -- and the split-PDF hook already keys off the request header. So one caller passing `http_headers={"Accept": "application/x-ndjson"}` got `elements_file` for a multi-page PDF and `elements` for a two-page one. Detection now reads the header off the built request, which is the same source the hook uses. The async path ran the parse-and-write inline, blocking the event loop for exactly the large bodies this mode exists for. Offloaded with `asyncio.to_thread`. Test `finally` blocks used a bare `os.unlink`, which masks an assertion failure above it with FileNotFoundError -- the same defect flagged in the README two rounds ago, reintroduced in the tests. Now `Path(...).unlink(missing_ok=True)`. Also removes a duplicated "The" left in `_combine_chunks_to_ndjson`'s docstring by the earlier trim. Four tests added, each confirmed to fail against the pre-fix source. The async one originally asserted `asyncio.to_thread` was called, which passed even with the offload removed because other SDK internals use it during the same call; it now records the thread the conversion ran on and compares it to the event-loop thread. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 358e21a commit ba3e7f4

3 files changed

Lines changed: 137 additions & 11 deletions

File tree

‎_test_unstructured_client/unit/test_ndjson_elements_file.py‎

Lines changed: 109 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import json
1414
import os
1515
import tempfile
16+
import threading
1617
from pathlib import Path
1718
from unittest import mock
1819

@@ -35,7 +36,7 @@
3536
_ndjson_elements_file,
3637
_ndjson_elements_file_async,
3738
)
38-
from unstructured_client.models import operations, shared
39+
from unstructured_client.models import errors, operations, shared
3940

4041

4142
def _elements(prefix, count):
@@ -606,7 +607,8 @@ def handler(_request):
606607
try:
607608
assert _read_ndjson(res.elements_file) == elements
608609
finally:
609-
os.unlink(res.elements_file)
610+
# missing_ok so a failed assertion above is not masked by the cleanup.
611+
Path(res.elements_file).unlink(missing_ok=True)
610612

611613

612614
def test_partition_sets_elements_file_when_server_returns_ndjson():
@@ -629,7 +631,8 @@ def handler(_request):
629631
try:
630632
assert _read_ndjson(res.elements_file) == elements
631633
finally:
632-
os.unlink(res.elements_file)
634+
# missing_ok so a failed assertion above is not masked by the cleanup.
635+
Path(res.elements_file).unlink(missing_ok=True)
633636

634637

635638
def test_partition_without_the_override_still_returns_elements():
@@ -646,3 +649,106 @@ def handler(_request):
646649

647650
assert res.elements == elements
648651
assert res.elements_file is None
652+
653+
654+
def test_partition_sets_elements_file_when_accept_set_via_http_headers():
655+
"""`http_headers` can replace Accept too, and must behave the same as the override.
656+
657+
Regression guard: this used to key off `accept_header_override` alone, so the split
658+
hook (which reads the request header) and the unsplit path disagreed for one caller.
659+
"""
660+
elements = [{"type": "Table", "text": "t0"}]
661+
662+
def handler(_request):
663+
return httpx.Response(
664+
200, headers={"Content-Type": "application/json"}, json=elements
665+
)
666+
667+
client = _mock_client(handler)
668+
res = client.general.partition(
669+
request=_text_request(),
670+
http_headers={"Accept": "application/x-ndjson"},
671+
)
672+
673+
assert res.elements is None
674+
try:
675+
assert _read_ndjson(res.elements_file) == elements
676+
finally:
677+
Path(res.elements_file).unlink(missing_ok=True)
678+
679+
680+
def test_partition_ndjson_rejects_a_non_list_json_body():
681+
"""A malformed 200 must fail the same way it would on the `elements` path.
682+
683+
Iterating the raw JSON would write a dict's *keys* out as elements, so a
684+
`{"detail": ...}` body became a one-element document reading `"detail"`.
685+
"""
686+
def handler(_request):
687+
return httpx.Response(
688+
200, headers={"Content-Type": "application/json"}, json={"detail": "oops"}
689+
)
690+
691+
client = _mock_client(handler)
692+
with pytest.raises(errors.ResponseValidationError):
693+
client.general.partition(
694+
request=_text_request(),
695+
accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON,
696+
)
697+
698+
699+
def test_partition_ndjson_handles_a_null_json_body():
700+
"""`null` used to raise TypeError from iterating None; it now yields an empty file."""
701+
def handler(_request):
702+
return httpx.Response(
703+
200, headers={"Content-Type": "application/json"}, content=b"null"
704+
)
705+
706+
client = _mock_client(handler)
707+
res = client.general.partition(
708+
request=_text_request(),
709+
accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON,
710+
)
711+
712+
try:
713+
assert _read_ndjson(res.elements_file) == []
714+
finally:
715+
Path(res.elements_file).unlink(missing_ok=True)
716+
717+
718+
@pytest.mark.asyncio
719+
async def test_partition_async_ndjson_does_not_block_on_conversion():
720+
"""The async path must offload the parse-and-write, not run it on the event loop."""
721+
elements = [{"type": "Table", "text": "t0"}]
722+
723+
def handler(_request):
724+
return httpx.Response(
725+
200, headers={"Content-Type": "application/json"}, json=elements
726+
)
727+
728+
client = UnstructuredClient(
729+
api_key_auth="x",
730+
server_url="http://localhost:8000",
731+
async_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
732+
)
733+
# Assert on the thread the conversion actually ran on. Patching `asyncio.to_thread`
734+
# and checking `.called` proves nothing -- other SDK internals use it during the same
735+
# call, so that assertion passes even with the offload removed.
736+
event_loop_thread = threading.get_ident()
737+
ran_on = {}
738+
real_convert = general._json_body_to_elements_file
739+
740+
def _spy(http_res):
741+
ran_on["thread"] = threading.get_ident()
742+
return real_convert(http_res)
743+
744+
with mock.patch.object(general, "_json_body_to_elements_file", _spy):
745+
res = await client.general.partition_async(
746+
request=_text_request(),
747+
accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON,
748+
)
749+
750+
assert ran_on["thread"] != event_loop_thread, "conversion ran on the event loop"
751+
try:
752+
assert _read_ndjson(res.elements_file) == elements
753+
finally:
754+
Path(res.elements_file).unlink(missing_ok=True)

‎src/unstructured_client/_hooks/custom/split_pdf_hook.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1509,7 +1509,7 @@ def _combine_chunks_to_ndjson(self, operation_id: str, chunk_paths: list[str]) -
15091509
"""Concatenate the per-chunk files into one NDJSON file and record its path.
15101510
15111511
`_build_after_success_response` turns the recorded path into the response. The
1512-
The combined file goes in the cache *parent* directory rather than the operation's
1512+
combined file goes in the cache *parent* directory rather than the operation's
15131513
TemporaryDirectory, which `_clear_operation` removes as soon as after_success
15141514
returns. It therefore outlives the operation and the caller owns deleting it (see
15151515
`PartitionResponse.elements_file`).

‎src/unstructured_client/general.py‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
22

33
from .basesdk import BaseSDK
4+
import asyncio
45
from enum import Enum
56
import httpx
67
import json
@@ -12,7 +13,10 @@
1213
from unstructured_client.models import errors, operations, shared
1314
from unstructured_client.types import BaseModel, OptionalNullable, UNSET
1415
from unstructured_client._hooks.custom.clean_server_url_hook import clean_server_url
15-
from unstructured_client._hooks.custom.request_utils import ELEMENTS_FILE_EXTENSION_KEY
16+
from unstructured_client._hooks.custom.request_utils import (
17+
ELEMENTS_FILE_EXTENSION_KEY,
18+
NDJSON_MEDIA_TYPE,
19+
)
1620
from unstructured_client.utils.unmarshal_json_response import unmarshal_json_response
1721

1822

@@ -33,8 +37,16 @@ def _new_elements_file():
3337
)
3438

3539

36-
def _ndjson_requested(accept_header_override: Optional[PartitionAcceptEnum]) -> bool:
37-
return accept_header_override == PartitionAcceptEnum.APPLICATION_X_NDJSON
40+
def _ndjson_requested(request: httpx.Request) -> bool:
41+
"""Whether NDJSON was asked for, read off the Accept header actually sent.
42+
43+
Keyed off the request rather than `accept_header_override` because `http_headers` can
44+
replace Accept as well, and the split-PDF hook already keys off this same header.
45+
Reading only the override would let the split and unsplit paths disagree for the same
46+
caller: a multi-page PDF would come back as `elements_file` while a two-page one came
47+
back as `elements`.
48+
"""
49+
return NDJSON_MEDIA_TYPE in request.headers.get("Accept", "")
3850

3951

4052
def _json_body_to_elements_file(http_res: httpx.Response) -> str:
@@ -50,11 +62,17 @@ def _json_body_to_elements_file(http_res: httpx.Response) -> str:
5062
and parsing it adds the element list on top. It exists to keep the contract uniform.
5163
The memory win comes from the split-PDF path, where the hook concatenates chunk files
5264
on disk and this function is never reached.
65+
66+
The body goes through `unmarshal_json_response` rather than a bare `json()` so that a
67+
payload which is not a list of objects fails the same way it would on the `elements`
68+
path. Iterating raw JSON would crash on `null` and, worse, silently write a dict's
69+
keys out as elements.
5370
"""
71+
elements = unmarshal_json_response(Optional[List[Dict[str, Any]]], http_res)
5472
out = _new_elements_file()
5573
try:
5674
with out:
57-
for element in http_res.json():
75+
for element in elements or []:
5876
out.write(json.dumps(element, ensure_ascii=False).encode())
5977
out.write(b"\n")
6078
except BaseException:
@@ -222,7 +240,7 @@ def partition(
222240
raw_response=http_res,
223241
)
224242
if utils.match_response(http_res, "200", "application/json"):
225-
if _ndjson_requested(accept_header_override):
243+
if _ndjson_requested(req):
226244
return operations.PartitionResponse(
227245
elements_file=_json_body_to_elements_file(http_res),
228246
status_code=http_res.status_code,
@@ -361,9 +379,11 @@ async def partition_async(
361379
raw_response=http_res,
362380
)
363381
if utils.match_response(http_res, "200", "application/json"):
364-
if _ndjson_requested(accept_header_override):
382+
if _ndjson_requested(req):
365383
return operations.PartitionResponse(
366-
elements_file=_json_body_to_elements_file(http_res),
384+
elements_file=await asyncio.to_thread(
385+
_json_body_to_elements_file, http_res
386+
),
367387
status_code=http_res.status_code,
368388
content_type=http_res.headers.get("Content-Type") or "",
369389
raw_response=http_res,

0 commit comments

Comments
 (0)