Skip to content

Commit fce575a

Browse files
badGarnetclaude
andcommitted
feat: NDJSON elements-file mode for partition
On the split-PDF path the SDK rebuilt the whole document in memory to return it: a list per chunk, a flattened list, a json.dumps blob in create_response, and the SDK's re-parse of that blob -- four copies live at once, with the serialization step dominating peak usage on large documents. Passing accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON now returns PartitionResponse.elements_file -- a path to an NDJSON file, one element per line -- instead of PartitionResponse.elements. The per-chunk temp files are concatenated on disk and never parsed, so peak memory is roughly one chunk rather than the whole document. Chunk files are sniffed for their first non-whitespace character, so a server returning application/json still works; NDJSON chunks are copied through untouched. Requesting application/json remains the default and is unchanged. The caller owns the returned file and must delete it. It is deliberately written outside the operation's TemporaryDirectory, which _clear_operation removes as soon as after_success returns. ndjson_mode depends only on the Accept header, never on split_pdf_cache_tmp_data. Those are set by different parties, so gating on both let them disagree: the server would return NDJSON while the hook took the JSON path and res.json() raised on a body this client had itself requested. Both caching modes are handled -- a cached chunk contributes its existing temp-file path, an uncached one spills its body verbatim and then releases it, since every response is retained in api_successful_responses and leaving _content set would keep the document resident regardless. general.py and models/operations/partition.py are both .genignore'd: elements_file is client-side only and can never come from the OpenAPI spec, so a regeneration would silently drop it. test_regeneration_guards.py fails if either entry is lost. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 7ab4de9 commit fce575a

9 files changed

Lines changed: 679 additions & 3 deletions

File tree

‎.genignore‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,10 @@ src/unstructured_client/general.py
2323
# Custom min_attempts / absolute_max_elapsed_time_ms fields on BackoffStrategy.
2424
# Push upstream to Speakeasy templates to remove this entry.
2525
src/unstructured_client/utils/retries.py
26+
27+
# Custom elements_file field on PartitionResponse, for the NDJSON elements-file mode.
28+
# The field is client-side only - the server never returns it - so it cannot come from
29+
# the OpenAPI spec, and regenerating would drop it. If /general/v0/general gains a new
30+
# response field, follow the same procedure as general.py above.
31+
# See test_regeneration_guards.py::test_partition_response_keeps_elements_file.
32+
src/unstructured_client/models/operations/partition.py

‎README.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,33 @@ req = operations.PartitionRequest(
427427
)
428428
```
429429

430+
### Streaming elements to a file instead of memory
431+
432+
For very large documents, the parsed element list can dominate the client's memory: the split-PDF path holds a list per chunk, a flattened list, a serialized blob and the SDK's re-parse of that blob. Request `application/x-ndjson` to skip all of it. The chunk responses are concatenated on disk and you get back a path in `elements_file` instead of a list in `elements`, which keeps peak memory at roughly one chunk.
433+
434+
**You own the returned file and are responsible for deleting it.**
435+
436+
Example:
437+
```python
438+
import json
439+
import os
440+
441+
from unstructured_client.general import PartitionAcceptEnum
442+
443+
res = client.general.partition(
444+
request=req,
445+
accept_header_override=PartitionAcceptEnum.APPLICATION_X_NDJSON,
446+
)
447+
448+
try:
449+
with open(res.elements_file, encoding="utf-8") as f:
450+
for line in f:
451+
element = json.loads(line)
452+
...
453+
finally:
454+
os.unlink(res.elements_file)
455+
```
456+
430457
<!-- Start File uploads [file-upload] -->
431458
## File uploads
432459

Lines changed: 322 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,322 @@
1+
"""Unit tests for NDJSON elements-file mode.
2+
3+
The on-disk recombination replaces the four in-memory copies the split-PDF path used to
4+
make (per-chunk list, flattened list, json.dumps blob, SDK re-parse). It must:
5+
- handle chunk files that are JSON arrays (server returned application/json)
6+
- handle chunk files that are already NDJSON (server honored application/x-ndjson)
7+
- preserve element order across chunks
8+
- round-trip payload strings byte-for-byte
9+
- leave no temp files behind other than the combined file the caller owns
10+
"""
11+
12+
import json
13+
import os
14+
from pathlib import Path
15+
16+
import pytest
17+
18+
import httpx
19+
20+
from unstructured_client._hooks.custom.request_utils import (
21+
ELEMENTS_FILE_HEADER,
22+
combine_chunk_files_to_ndjson,
23+
create_elements_file_response,
24+
write_chunk_body_to_temp,
25+
)
26+
from unstructured_client._hooks.custom.split_pdf_hook import SplitPdfHook
27+
28+
29+
def _elements(prefix, count):
30+
return [
31+
{
32+
"type": "Table" if i % 2 == 0 else "NarrativeText",
33+
"text": f"{prefix}-{i}",
34+
"metadata": {"page_number": i + 1, "image_base64": f"PAYLOAD{prefix}{i}" * 4},
35+
}
36+
for i in range(count)
37+
]
38+
39+
40+
def _write_json_array(path, elements):
41+
path.write_text(json.dumps(elements), encoding="utf-8")
42+
43+
44+
def _write_ndjson(path, elements):
45+
with path.open("w", encoding="utf-8") as f:
46+
for element in elements:
47+
f.write(json.dumps(element))
48+
f.write("\n")
49+
50+
51+
def _read_ndjson(path):
52+
with open(path, encoding="utf-8") as f:
53+
return [json.loads(line) for line in f if line.strip()]
54+
55+
56+
def test_combines_json_array_chunks_in_order(tmp_path):
57+
chunk_a = tmp_path / "a.json"
58+
chunk_b = tmp_path / "b.json"
59+
elements_a = _elements("a", 3)
60+
elements_b = _elements("b", 2)
61+
_write_json_array(chunk_a, elements_a)
62+
_write_json_array(chunk_b, elements_b)
63+
64+
out = tmp_path / "combined.ndjson"
65+
written = combine_chunk_files_to_ndjson([str(chunk_a), str(chunk_b)], str(out))
66+
67+
assert written == 5
68+
assert _read_ndjson(out) == elements_a + elements_b
69+
70+
71+
def test_combines_ndjson_chunks_without_parsing(tmp_path):
72+
"""The zero-parse path: both ends speak NDJSON."""
73+
chunk_a = tmp_path / "a.ndjson"
74+
chunk_b = tmp_path / "b.ndjson"
75+
elements_a = _elements("a", 4)
76+
elements_b = _elements("b", 1)
77+
_write_ndjson(chunk_a, elements_a)
78+
_write_ndjson(chunk_b, elements_b)
79+
80+
out = tmp_path / "combined.ndjson"
81+
written = combine_chunk_files_to_ndjson([str(chunk_a), str(chunk_b)], str(out))
82+
83+
assert written == 5
84+
assert _read_ndjson(out) == elements_a + elements_b
85+
86+
87+
def test_mixed_chunk_formats(tmp_path):
88+
"""A server upgraded mid-flight, or a retry served by an older pod."""
89+
chunk_a = tmp_path / "a.json"
90+
chunk_b = tmp_path / "b.ndjson"
91+
elements_a = _elements("a", 2)
92+
elements_b = _elements("b", 2)
93+
_write_json_array(chunk_a, elements_a)
94+
_write_ndjson(chunk_b, elements_b)
95+
96+
out = tmp_path / "combined.ndjson"
97+
written = combine_chunk_files_to_ndjson([str(chunk_a), str(chunk_b)], str(out))
98+
99+
assert written == 4
100+
assert _read_ndjson(out) == elements_a + elements_b
101+
102+
103+
@pytest.mark.parametrize("body", ["", " ", "\n\n"])
104+
def test_empty_chunk_files_are_skipped(tmp_path, body):
105+
chunk_a = tmp_path / "a.json"
106+
chunk_empty = tmp_path / "empty.json"
107+
elements_a = _elements("a", 2)
108+
_write_json_array(chunk_a, elements_a)
109+
chunk_empty.write_text(body, encoding="utf-8")
110+
111+
out = tmp_path / "combined.ndjson"
112+
written = combine_chunk_files_to_ndjson([str(chunk_a), str(chunk_empty)], str(out))
113+
114+
assert written == 2
115+
assert _read_ndjson(out) == elements_a
116+
117+
118+
def test_empty_array_chunk_contributes_nothing(tmp_path):
119+
"""A chunk that legitimately produced no elements (e.g. blank pages)."""
120+
chunk_a = tmp_path / "a.json"
121+
chunk_b = tmp_path / "b.json"
122+
_write_json_array(chunk_a, [])
123+
elements_b = _elements("b", 3)
124+
_write_json_array(chunk_b, elements_b)
125+
126+
out = tmp_path / "combined.ndjson"
127+
written = combine_chunk_files_to_ndjson([str(chunk_a), str(chunk_b)], str(out))
128+
129+
assert written == 3
130+
assert _read_ndjson(out) == elements_b
131+
132+
133+
def test_payload_round_trips_exactly(tmp_path):
134+
"""Base64 payloads are the reason this path exists; they must survive unchanged."""
135+
payload = "A" * 100_000
136+
element = {"type": "Table", "text": "t", "metadata": {"image_base64": payload}}
137+
chunk = tmp_path / "a.json"
138+
_write_json_array(chunk, [element])
139+
140+
out = tmp_path / "combined.ndjson"
141+
combine_chunk_files_to_ndjson([str(chunk)], str(out))
142+
143+
result = _read_ndjson(out)
144+
assert result[0]["metadata"]["image_base64"] == payload
145+
146+
147+
def test_non_ascii_is_preserved(tmp_path):
148+
element = {"type": "NarrativeText", "text": "日本語 café ✓", "metadata": {}}
149+
chunk = tmp_path / "a.json"
150+
_write_json_array(chunk, [element])
151+
152+
out = tmp_path / "combined.ndjson"
153+
combine_chunk_files_to_ndjson([str(chunk)], str(out))
154+
155+
assert _read_ndjson(out)[0]["text"] == "日本語 café ✓"
156+
157+
158+
def test_write_chunk_body_to_temp_roundtrips(tmp_path):
159+
"""The cache_tmp_data=OFF path: an in-memory NDJSON body must spill verbatim.
160+
161+
Regression guard. `ndjson_mode` used to also require cache_tmp_data, so with caching off
162+
the server returned NDJSON while the hook took the JSON path and `res.json()` raised on a
163+
body this client had itself requested.
164+
"""
165+
elements = _elements("x", 3)
166+
body = "".join(json.dumps(e) + "\n" for e in elements).encode()
167+
response = httpx.Response(status_code=200, content=body)
168+
169+
path = write_chunk_body_to_temp(response, str(tmp_path))
170+
assert _read_ndjson(path) == elements
171+
172+
173+
def test_combine_accepts_bodies_spilled_without_caching(tmp_path):
174+
"""End-to-end of the uncached path: spill two bodies, then combine them."""
175+
a, b = _elements("a", 2), _elements("b", 3)
176+
ra = httpx.Response(200, content="".join(json.dumps(e) + "\n" for e in a).encode())
177+
rb = httpx.Response(200, content="".join(json.dumps(e) + "\n" for e in b).encode())
178+
paths = [write_chunk_body_to_temp(r, str(tmp_path)) for r in (ra, rb)]
179+
180+
out = tmp_path / "combined.ndjson"
181+
written = combine_chunk_files_to_ndjson(paths, str(out))
182+
183+
assert written == 5
184+
assert _read_ndjson(out) == a + b
185+
186+
187+
def test_spilled_body_is_released_from_the_response(tmp_path):
188+
"""After spilling, the response must no longer hold the body.
189+
190+
Regression guard: every chunk response is retained in `api_successful_responses` for
191+
failure bookkeeping, so spilling to disk without releasing `_content` still
192+
accumulates the whole document in memory, defeating the point of spilling.
193+
"""
194+
elements = _elements("a", 3)
195+
body = "".join(json.dumps(e) + "\n" for e in elements).encode()
196+
response = httpx.Response(status_code=200, content=body)
197+
assert len(response.content) == len(body)
198+
199+
path = write_chunk_body_to_temp(response, str(tmp_path))
200+
response._content = path.encode()
201+
202+
# The body is on disk, and the response now costs a path rather than a payload.
203+
assert _read_ndjson(path) == elements
204+
assert response.text == path
205+
assert len(response.content) < 512
206+
207+
208+
def test_elements_file_response_carries_path_in_header_and_body(tmp_path):
209+
path = str(tmp_path / "combined.ndjson")
210+
response = create_elements_file_response(path)
211+
212+
assert response.status_code == 200
213+
assert response.headers[ELEMENTS_FILE_HEADER] == path
214+
assert response.headers["Content-Type"] == "application/x-ndjson"
215+
# Body-as-path mirrors the existing cached-chunk convention in the split hook.
216+
assert response.text == path
217+
218+
219+
# --- hook-level temp-file lifecycle ------------------------------------------------
220+
221+
222+
def _ndjson_response(elements):
223+
body = "".join(json.dumps(e) + "\n" for e in elements).encode()
224+
return httpx.Response(status_code=200, content=body)
225+
226+
227+
def _hook_in_ndjson_mode(operation_id, tmp_path):
228+
"""A hook set up as `before_request` would leave it for an uncached NDJSON run."""
229+
hook = SplitPdfHook()
230+
hook.ndjson_mode[operation_id] = True
231+
hook.cache_tmp_data_feature[operation_id] = False
232+
hook.cache_tmp_data_dir[operation_id] = str(tmp_path)
233+
hook.allow_failed[operation_id] = False
234+
return hook
235+
236+
237+
def _ndjson_files_in(directory):
238+
return sorted(p.name for p in Path(directory).glob("*.ndjson"))
239+
240+
241+
def test_spilled_chunk_files_are_deleted_after_combining(tmp_path):
242+
"""Regression guard: spilled chunks used to be left in the temp dir forever.
243+
244+
`cache_tmp_data` defaults to off, so this is the default path. One file per chunk
245+
accumulating for the lifetime of the host is a disk leak, not a memory one.
246+
"""
247+
operation_id = "op-cleanup"
248+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
249+
responses = [(0, _ndjson_response(_elements("a", 2))), (1, _ndjson_response(_elements("b", 3)))]
250+
251+
hook._elements_from_task_responses(operation_id, responses, started_at=0.0)
252+
253+
combined = hook.ndjson_output_path[operation_id]
254+
# Exactly one file survives: the combined output the caller owns.
255+
assert _ndjson_files_in(tmp_path) == [Path(combined).name]
256+
assert len(_read_ndjson(combined)) == 5
257+
258+
259+
def test_spilled_chunks_land_in_the_operation_tempdir_when_one_exists(tmp_path):
260+
"""Spilling into the operation's tempdir means cleanup happens even if we miss it."""
261+
operation_id = "op-tempdir"
262+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
263+
operation_dir = tmp_path / "unstructured_client_op"
264+
operation_dir.mkdir()
265+
266+
class _FakeTempDir:
267+
name = str(operation_dir)
268+
269+
hook.tempdirs[operation_id] = _FakeTempDir() # type: ignore[assignment]
270+
spill_dir = hook._operation_tempdir_path(operation_id)
271+
272+
assert spill_dir == str(operation_dir)
273+
274+
275+
def test_combined_file_is_returned_on_success(tmp_path):
276+
operation_id = "op-success"
277+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
278+
elements = _elements("a", 4)
279+
280+
hook._elements_from_task_responses(
281+
operation_id, [(0, _ndjson_response(elements))], started_at=0.0
282+
)
283+
response = hook._build_after_success_response(operation_id, httpx.Response(200), [])
284+
285+
combined = response.headers[ELEMENTS_FILE_HEADER]
286+
assert os.path.exists(combined)
287+
assert _read_ndjson(combined) == elements
288+
289+
290+
def test_combined_file_is_discarded_when_a_failure_response_is_returned(tmp_path):
291+
"""Regression guard: on the failure path nothing downstream learns the path.
292+
293+
`_build_after_success_response` returns the failed chunk response instead, so the
294+
combined file would be leaked for the lifetime of the host.
295+
"""
296+
operation_id = "op-strict-failure"
297+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
298+
responses = [
299+
(0, _ndjson_response(_elements("a", 2))),
300+
(1, httpx.Response(status_code=500, content=b"boom")),
301+
]
302+
303+
hook._elements_from_task_responses(operation_id, responses, started_at=0.0)
304+
combined = hook.ndjson_output_path[operation_id]
305+
assert os.path.exists(combined)
306+
307+
response = hook._build_after_success_response(operation_id, httpx.Response(200), [])
308+
309+
assert response.status_code == 500
310+
assert not os.path.exists(combined)
311+
assert _ndjson_files_in(tmp_path) == []
312+
313+
314+
def test_no_combined_file_is_created_when_every_chunk_failed(tmp_path):
315+
operation_id = "op-all-failed"
316+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
317+
responses = [(0, httpx.Response(status_code=500, content=b"boom"))]
318+
319+
hook._elements_from_task_responses(operation_id, responses, started_at=0.0)
320+
321+
assert operation_id not in hook.ndjson_output_path
322+
assert _ndjson_files_in(tmp_path) == []

‎_test_unstructured_client/unit/test_regeneration_guards.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,27 @@ def test_ci_installs_with_locked_uv_sync():
8181
assert "run: make install" in workflow
8282

8383

84+
def test_partition_response_keeps_elements_file():
85+
"""`elements_file` is client-side only, so no spec change can restore it after a regen.
86+
87+
Both the model and the enum value that selects it live in generated files; the
88+
.genignore entries are the only thing keeping them.
89+
"""
90+
from unstructured_client.general import PartitionAcceptEnum
91+
from unstructured_client.models import operations
92+
93+
assert "elements_file" in operations.PartitionResponse.model_fields
94+
assert "elements_file" in operations.PartitionResponseTypedDict.__annotations__
95+
assert PartitionAcceptEnum.APPLICATION_X_NDJSON.value == "application/x-ndjson"
96+
97+
genignore = (REPO_ROOT / ".genignore").read_text()
98+
for path in (
99+
"src/unstructured_client/general.py",
100+
"src/unstructured_client/models/operations/partition.py",
101+
):
102+
assert path in genignore, f"{path} carries custom code and must stay in .genignore"
103+
104+
84105
def test_body_create_job_input_files_are_serialized_as_multipart_files():
85106
request = shared.BodyCreateJob(
86107
request_data="{}",

0 commit comments

Comments
 (0)