Skip to content

Commit 358e21a

Browse files
badGarnetclaude
andcommitted
fix: set elements_file even when the server returns JSON
The deployed API does not offer application/x-ndjson -- its spec (v1.5.69) declares only application/json and text/csv, and the string "ndjson" appears nowhere in the document. So any request that bypasses the split-PDF hook came back as JSON, the application/json branch matched first and won, and elements_file stayed None while elements was populated. The opt-in was silently ignored. That path is much wider than "non-PDF". _before_request_unlocked short-circuits when split_size >= page_count, and get_optimal_split_size floors at MIN_PAGES_PER_SPLIT=2, so one- and two-page PDFs are sent whole -- it would have read as intermittent to anyone hitting it on small inputs. The x-ndjson branch is now checked first, and a JSON body is written out as NDJSON when NDJSON was requested. elements_file is therefore set for every input and callers need one code path rather than two. This does not bound memory on the unsplit path -- the body is already read and parsing adds the element list on top -- it makes the contract uniform. The memory win remains the split-PDF path, where the hook concatenates chunk files on disk and this conversion is never reached. Also fixes the README example, which raised TypeError from open(None) and then raised the same TypeError again out of Path(None) in the finally, masking the first. Adds the end-to-end coverage whose absence let this through: all 24 existing tests were helper- or hook-level, so nothing exercised the media-type dispatch in general.py. Three tests now drive partition() over a mock transport -- server returns JSON, server returns NDJSON, and no override at all. The first fails against the old dispatch. They hold the client for the call rather than chaining off a temporary, since sdk.py registers a weakref.finalize that closes the transport. Smaller review notes: log a warning per skipped empty chunk so element_count can be reconciled against chunk_count; document that the non-"[" sniff assumes one JSON value per line rather than checking; trim the _combine_chunks_to_ndjson docstring. The regeneration comments no longer claim a daily workflow is about to drop the field -- generation is blocked at the Speakeasy account level and gen.lock has not moved since 2026-01. Whether that scaffolding is worth keeping is left open. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 1ec2e25 commit 358e21a

8 files changed

Lines changed: 193 additions & 37 deletions

File tree

‎.genignore‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ src/unstructured_client/utils/retries.py
3131
# See test_regeneration_guards.py::test_partition_response_keeps_elements_file.
3232
src/unstructured_client/models/operations/partition.py
3333

34-
# Docs for that same custom elements_file field. This file is generated from the spec
35-
# and the daily generation workflow would otherwise drop the row on its next run.
34+
# Docs for that same custom elements_file field. Generated from the spec, so a
35+
# regeneration would drop the row.
36+
#
37+
# Note: SDK generation is currently blocked at the Speakeasy account level
38+
# ("generation access blocked"), so nothing can regenerate today and gen.lock has not
39+
# moved since 2026-01. These entries are insurance for when that is restored, not a
40+
# defence against an imminent run.
3641
docs/models/operations/partitionresponse.md

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
## 0.46.0
22

33
### Features
4-
* Add an NDJSON elements-file mode to `partition()`. Pass `accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON` to get `PartitionResponse.elements_file` — a path to an NDJSON file with one element per line — instead of `PartitionResponse.elements`. On the split-PDF path the per-chunk temp files are concatenated on disk rather than parsed, flattened, re-serialized with `json.dumps` and re-parsed by the SDK, which held four copies of the document in memory at once. Peak memory becomes roughly one chunk instead of the whole document. **The caller owns the returned file and is responsible for deleting it.** Requesting `application/json` (the default) is unchanged.
4+
* Add an NDJSON elements-file mode to `partition()`. Pass `accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON` to get `PartitionResponse.elements_file` — a path to an NDJSON file with one element per line — instead of `PartitionResponse.elements`. On the split-PDF path the per-chunk temp files are concatenated on disk rather than parsed, flattened, re-serialized with `json.dumps` and re-parsed by the SDK, which held four copies of the document in memory at once; peak memory becomes roughly one chunk instead of the whole document. `elements_file` is set for every input, including ones that are not split and responses from a server that ignores the `Accept` header, so callers need only one code path — but the memory saving itself applies only to split PDFs (a PDF of more than two pages, with `split_pdf_page=True`). **The caller owns the returned file and is responsible for deleting it.** Requesting `application/json` (the default) is unchanged.
55

66
## 0.45.0
77

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,7 @@ For very large documents, the parsed element list can dominate the client's memo
434434
**You own the returned file and are responsible for deleting it.**
435435

436436
> [!NOTE]
437-
> The memory saving applies to the split-PDF path, i.e. a PDF with `split_pdf_page=True` (the default). For unsplit inputs — a non-PDF file, or `split_pdf_page=False` — the response body is still read fully into memory before being written to disk, so peak memory can reach roughly twice the body size. You still get `elements_file` either way.
437+
> `elements_file` is always set when you pass this header, but the **memory saving** only applies to the split-PDF path. An input is only split when it is a PDF, `split_pdf_page=True` (the default), and it has more than two pages — `split_size` is floored at 2, so one- and two-page PDFs are sent whole. For those, and for non-PDFs, the response body is read fully into memory before being written to disk, so peak memory can reach roughly twice the body size.
438438
439439
Example:
440440
```python

‎_test_unstructured_client/unit/test_ndjson_elements_file.py‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,13 @@
2929
write_chunk_body_to_temp,
3030
)
3131
from unstructured_client._hooks.custom.split_pdf_hook import SplitPdfHook
32+
from unstructured_client import UnstructuredClient
3233
from unstructured_client.general import (
34+
PartitionAcceptEnum,
3335
_ndjson_elements_file,
3436
_ndjson_elements_file_async,
3537
)
38+
from unstructured_client.models import operations, shared
3639

3740

3841
def _elements(prefix, count):
@@ -547,3 +550,99 @@ def test_no_combined_file_is_created_when_every_chunk_failed(tmp_path):
547550

548551
assert operation_id not in hook.ndjson_output_path
549552
assert _ndjson_files_in(tmp_path) == []
553+
554+
555+
# --- end to end through partition() -----------------------------------------------
556+
#
557+
# The gap these close: every other test here is helper- or hook-level, so nothing
558+
# exercised the response dispatch in `general.py`. That is where the media-type branches
559+
# are chosen, and it is where NDJSON mode silently fell back to `elements`.
560+
561+
562+
def _mock_client(handler):
563+
"""Build a client over a mock transport.
564+
565+
Callers must hold the returned client for the duration of the call: `sdk.py` registers
566+
a `weakref.finalize` that closes the underlying httpx client, so chaining off a
567+
temporary tears the transport down mid-request.
568+
"""
569+
return UnstructuredClient(
570+
api_key_auth="x",
571+
server_url="http://localhost:8000",
572+
client=httpx.Client(transport=httpx.MockTransport(handler)),
573+
)
574+
575+
576+
def _text_request():
577+
"""A non-PDF input, so the split-PDF hook does not engage."""
578+
return operations.PartitionRequest(
579+
partition_parameters=shared.PartitionParameters(
580+
files=shared.Files(content=b"hello", file_name="doc.txt"),
581+
)
582+
)
583+
584+
585+
def test_partition_sets_elements_file_when_server_ignores_the_accept_header():
586+
"""The deployed API only offers application/json, so this is the live unsplit path.
587+
588+
Regression guard: the JSON branch used to be matched first and win, populating
589+
`elements` and leaving `elements_file` None even though NDJSON was requested.
590+
"""
591+
elements = [{"type": "Table", "text": "t0"}, {"type": "NarrativeText", "text": "t1"}]
592+
593+
def handler(_request):
594+
return httpx.Response(
595+
200, headers={"Content-Type": "application/json"}, json=elements
596+
)
597+
598+
client = _mock_client(handler)
599+
res = client.general.partition(
600+
request=_text_request(),
601+
accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON,
602+
)
603+
604+
assert res.elements_file is not None
605+
assert res.elements is None
606+
try:
607+
assert _read_ndjson(res.elements_file) == elements
608+
finally:
609+
os.unlink(res.elements_file)
610+
611+
612+
def test_partition_sets_elements_file_when_server_returns_ndjson():
613+
"""The path that becomes live if the API ever honors the Accept header."""
614+
elements = [{"type": "Table", "text": "t0"}]
615+
body = "".join(json.dumps(e) + "\n" for e in elements).encode()
616+
617+
def handler(_request):
618+
return httpx.Response(
619+
200, headers={"Content-Type": "application/x-ndjson"}, content=body
620+
)
621+
622+
client = _mock_client(handler)
623+
res = client.general.partition(
624+
request=_text_request(),
625+
accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON,
626+
)
627+
628+
assert res.elements is None
629+
try:
630+
assert _read_ndjson(res.elements_file) == elements
631+
finally:
632+
os.unlink(res.elements_file)
633+
634+
635+
def test_partition_without_the_override_still_returns_elements():
636+
"""The default must be untouched: no elements_file, elements populated as before."""
637+
elements = [{"type": "Table", "text": "t0"}]
638+
639+
def handler(_request):
640+
return httpx.Response(
641+
200, headers={"Content-Type": "application/json"}, json=elements
642+
)
643+
644+
client = _mock_client(handler)
645+
res = client.general.partition(request=_text_request())
646+
647+
assert res.elements == elements
648+
assert res.elements_file is None

‎_test_unstructured_client/unit/test_regeneration_guards.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,10 @@ def test_partition_response_keeps_elements_file():
8686
8787
Both the model and the enum value that selects it live in generated files; the
8888
.genignore entries are the only thing keeping them.
89+
90+
Note: SDK generation is currently blocked at the Speakeasy account level, so this
91+
guards a path that cannot execute today. Whether it is worth keeping is a live
92+
question -- see the discussion on PR #347.
8993
"""
9094
from unstructured_client.general import PartitionAcceptEnum
9195
from unstructured_client.models import operations
@@ -102,8 +106,8 @@ def test_partition_response_keeps_elements_file():
102106
):
103107
assert path in genignore, f"{path} carries custom code and must stay in .genignore"
104108

105-
# The docs row is generated from the spec too, so the daily generation workflow would
106-
# drop it without the .genignore entry above.
109+
# The docs row is generated from the spec too, so a regeneration would drop it
110+
# without the .genignore entry above.
107111
response_docs = (REPO_ROOT / "docs/models/operations/partitionresponse.md").read_text()
108112
assert "elements_file" in response_docs
109113

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,11 @@ def combine_chunk_files_to_ndjson(chunk_paths: list[str], out_path: str) -> int:
310310
311311
A chunk file is either a JSON array (server returned `application/json`) or already
312312
NDJSON (server honored `application/x-ndjson`); the first non-whitespace character
313-
says which. NDJSON chunks are copied through without parsing.
313+
says which. A leading `[` is treated as an array, and anything else is assumed to be
314+
one JSON value per line -- an assumption, not a check, so a pretty-printed multi-line
315+
object would be split into invalid lines. No endpoint returns that today.
316+
317+
NDJSON chunks are copied through without parsing.
314318
315319
Args:
316320
chunk_paths: Per-chunk response files, in element order.
@@ -325,6 +329,13 @@ def combine_chunk_files_to_ndjson(chunk_paths: list[str], out_path: str) -> int:
325329
with open(chunk_path, "r", encoding="utf-8") as chunk:
326330
first_char = _first_non_space_char(chunk)
327331
if not first_char:
332+
# A 200 with an empty body. Log it, because otherwise the document is
333+
# silently short and the element count cannot be reconciled against
334+
# the chunk count.
335+
logger.warning(
336+
"split_pdf event=ndjson_empty_chunk file=%s",
337+
os.path.basename(chunk_path),
338+
)
328339
continue
329340
chunk.seek(0)
330341

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

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1509,22 +1509,14 @@ 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-
combined file goes in the cache *parent* directory rather than the operation's
1513-
TemporaryDirectory, because `_clear_operation` cleans that directory up as soon as
1514-
after_success returns, which would delete the file before the caller could read
1515-
it. The combined file therefore outlives the operation and the caller owns
1516-
deleting it (see `PartitionResponse.elements_file`).
1517-
1518-
Recombination writes to a staging file that is renamed into place only once it
1519-
completes. A malformed chunk makes the parse raise partway through, and since the
1520-
combined file is the one thing here nothing else owns, a partial one would survive
1521-
the failed operation as an orphan under the final name.
1522-
1523-
Publishing is also gated on the operation still being live. This runs in a worker
1524-
thread that cancellation cannot interrupt, so `_clear_operation` may already have
1525-
torn the operation down by the time we finish; recording the path then would both
1526-
resurrect a cleared dict entry and orphan the file, since nothing downstream will
1527-
ever read it.
1512+
The combined file goes in the cache *parent* directory rather than the operation's
1513+
TemporaryDirectory, which `_clear_operation` removes as soon as after_success
1514+
returns. It therefore outlives the operation and the caller owns deleting it (see
1515+
`PartitionResponse.elements_file`).
1516+
1517+
Writing to a staging file and renaming keeps a partial file from surviving under
1518+
the final name if a malformed chunk makes the parse raise. Publishing is gated on
1519+
the operation still being live; see `_ndjson_lock`.
15281520
"""
15291521
temp_dir_path = self.cache_tmp_data_dir.get(operation_id) or tempfile.gettempdir()
15301522
out_path = f"{temp_dir_path}/{uuid.uuid4()}.ndjson"

‎src/unstructured_client/general.py‎

Lines changed: 59 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from .basesdk import BaseSDK
44
from enum import Enum
55
import httpx
6+
import json
67
import os
78
import tempfile
89
from typing import Any, Dict, List, Mapping, Optional, Union, cast
@@ -32,6 +33,36 @@ def _new_elements_file():
3233
)
3334

3435

36+
def _ndjson_requested(accept_header_override: Optional[PartitionAcceptEnum]) -> bool:
37+
return accept_header_override == PartitionAcceptEnum.APPLICATION_X_NDJSON
38+
39+
40+
def _json_body_to_elements_file(http_res: httpx.Response) -> str:
41+
"""Write a JSON-array body out as NDJSON, so `elements_file` is set either way.
42+
43+
The deployed API does not offer `application/x-ndjson`: its spec declares only
44+
`application/json` and `text/csv`, so a request that skips the split-PDF hook comes
45+
back as JSON no matter what was asked for. Without this, opting into NDJSON would
46+
silently populate `elements` instead and leave `elements_file` as None, forcing every
47+
caller to handle both shapes for one flag.
48+
49+
This does not bound memory -- the body is already fully read by the time we get here,
50+
and parsing it adds the element list on top. It exists to keep the contract uniform.
51+
The memory win comes from the split-PDF path, where the hook concatenates chunk files
52+
on disk and this function is never reached.
53+
"""
54+
out = _new_elements_file()
55+
try:
56+
with out:
57+
for element in http_res.json():
58+
out.write(json.dumps(element, ensure_ascii=False).encode())
59+
out.write(b"\n")
60+
except BaseException:
61+
_discard_elements_file(out.name)
62+
raise
63+
return out.name
64+
65+
3566
def _discard_elements_file(path: str) -> None:
3667
"""Remove a partially written elements file, ignoring a failure to do so.
3768
@@ -183,7 +214,21 @@ def partition(
183214
)
184215

185216
response_data: Any = None
217+
if utils.match_response(http_res, "200", "application/x-ndjson"):
218+
return operations.PartitionResponse(
219+
elements_file=_ndjson_elements_file(http_res),
220+
status_code=http_res.status_code,
221+
content_type=http_res.headers.get("Content-Type") or "",
222+
raw_response=http_res,
223+
)
186224
if utils.match_response(http_res, "200", "application/json"):
225+
if _ndjson_requested(accept_header_override):
226+
return operations.PartitionResponse(
227+
elements_file=_json_body_to_elements_file(http_res),
228+
status_code=http_res.status_code,
229+
content_type=http_res.headers.get("Content-Type") or "",
230+
raw_response=http_res,
231+
)
187232
return operations.PartitionResponse(
188233
elements=unmarshal_json_response(
189234
Optional[List[Dict[str, Any]]], http_res
@@ -199,13 +244,6 @@ def partition(
199244
content_type=http_res.headers.get("Content-Type") or "",
200245
raw_response=http_res,
201246
)
202-
if utils.match_response(http_res, "200", "application/x-ndjson"):
203-
return operations.PartitionResponse(
204-
elements_file=_ndjson_elements_file(http_res),
205-
status_code=http_res.status_code,
206-
content_type=http_res.headers.get("Content-Type") or "",
207-
raw_response=http_res,
208-
)
209247
if utils.match_response(http_res, "422", "application/json"):
210248
response_data = unmarshal_json_response(
211249
errors.HTTPValidationErrorData, http_res
@@ -315,7 +353,21 @@ async def partition_async(
315353
)
316354

317355
response_data: Any = None
356+
if utils.match_response(http_res, "200", "application/x-ndjson"):
357+
return operations.PartitionResponse(
358+
elements_file=await _ndjson_elements_file_async(http_res),
359+
status_code=http_res.status_code,
360+
content_type=http_res.headers.get("Content-Type") or "",
361+
raw_response=http_res,
362+
)
318363
if utils.match_response(http_res, "200", "application/json"):
364+
if _ndjson_requested(accept_header_override):
365+
return operations.PartitionResponse(
366+
elements_file=_json_body_to_elements_file(http_res),
367+
status_code=http_res.status_code,
368+
content_type=http_res.headers.get("Content-Type") or "",
369+
raw_response=http_res,
370+
)
319371
return operations.PartitionResponse(
320372
elements=unmarshal_json_response(
321373
Optional[List[Dict[str, Any]]], http_res
@@ -331,13 +383,6 @@ async def partition_async(
331383
content_type=http_res.headers.get("Content-Type") or "",
332384
raw_response=http_res,
333385
)
334-
if utils.match_response(http_res, "200", "application/x-ndjson"):
335-
return operations.PartitionResponse(
336-
elements_file=await _ndjson_elements_file_async(http_res),
337-
status_code=http_res.status_code,
338-
content_type=http_res.headers.get("Content-Type") or "",
339-
raw_response=http_res,
340-
)
341386
if utils.match_response(http_res, "422", "application/json"):
342387
response_data = unmarshal_json_response(
343388
errors.HTTPValidationErrorData, http_res

0 commit comments

Comments
 (0)