Skip to content

Commit 5fc5a14

Browse files
badGarnetclaude
andcommitted
fix: close remaining temp-file and cancellation gaps in NDJSON mode
Addresses review findings on the elements-file path. Orphaned files on failure. Both `_ndjson_elements_file` helpers create their destination with delete=False, so a body that raises or is cancelled partway through left the partial copy behind; they now unlink it and re-raise. `write_chunk_body_to_temp` had the same shape -- the caller only registers the path for cleanup once the function returns, so a failed write orphaned the file, and a full disk is exactly the failure that repeats. Cancellation race. Recombination runs in a worker thread that cancellation cannot interrupt, so `_clear_operation` could tear the operation down while it was still running; publishing the path afterwards resurrected a cleared dict entry and orphaned the file. Publishing is now gated on the operation still being live, under a lock that `_clear_operation` also takes when dropping `pending_operation_ids`. Ownership is explicit either way: the success path claims the path out of `ndjson_output_path`, so anything still recorded at teardown was never delivered and is safe to delete. Docs regeneration. docs/models/operations/partitionresponse.md is generated and tracked in gen.lock, and the generation workflow runs on a daily cron, so the elements_file row would have been dropped within a day of merging. Added to .genignore alongside the model, and the regeneration guard now asserts the row. README. Noted that the memory saving applies to the split-PDF path -- unsplit inputs still buffer the body -- so the caveat is visible where the feature is advertised rather than only in the PR. The example's cleanup used a bare unlink in a finally, which would mask a failure to open the file with FileNotFoundError; it now uses Path.unlink(missing_ok=True). The spilled-body regression guard asserted against `_content` it had assigned itself, so it could not fail if the hook stopped releasing the body. It now drives `_elements_from_task_responses`, and was confirmed to fail with the release removed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent c01a6d1 commit 5fc5a14

7 files changed

Lines changed: 179 additions & 32 deletions

File tree

‎.genignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,7 @@ src/unstructured_client/utils/retries.py
3030
# response field, follow the same procedure as general.py above.
3131
# See test_regeneration_guards.py::test_partition_response_keeps_elements_file.
3232
src/unstructured_client/models/operations/partition.py
33+
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.
36+
docs/models/operations/partitionresponse.md

‎README.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -433,10 +433,13 @@ For very large documents, the parsed element list can dominate the client's memo
433433

434434
**You own the returned file and are responsible for deleting it.**
435435

436+
> [!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.
438+
436439
Example:
437440
```python
438441
import json
439-
import os
442+
from pathlib import Path
440443

441444
from unstructured_client.general import PartitionAcceptEnum
442445

@@ -451,7 +454,8 @@ try:
451454
element = json.loads(line)
452455
...
453456
finally:
454-
os.unlink(res.elements_file)
457+
# missing_ok so a failure to open the file isn't masked by the cleanup.
458+
Path(res.elements_file).unlink(missing_ok=True)
455459
```
456460

457461
<!-- Start File uploads [file-upload] -->

‎_test_unstructured_client/unit/test_ndjson_elements_file.py‎

Lines changed: 76 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -186,24 +186,32 @@ def test_combine_accepts_bodies_spilled_without_caching(tmp_path):
186186

187187

188188
def test_spilled_body_is_released_from_the_response(tmp_path):
189-
"""After spilling, the response must no longer hold the body.
189+
"""After spilling, the chunk response must no longer hold the body.
190190
191-
Regression guard: every chunk response is retained in `api_successful_responses` for
192-
failure bookkeeping, so spilling to disk without releasing `_content` still
193-
accumulates the whole document in memory, defeating the point of spilling.
191+
Regression guard for the release step in `_elements_from_task_responses`: every chunk
192+
response stays in `api_successful_responses` for failure bookkeeping, so spilling to
193+
disk without clearing `_content` still accumulates the whole document in memory,
194+
defeating the point of spilling.
195+
196+
Driven through the hook on purpose. The release happens there, not in
197+
`write_chunk_body_to_temp`, so a test that clears `_content` itself would still pass
198+
if the hook ever stopped doing it.
194199
"""
195-
elements = _elements("a", 3)
196-
body = "".join(json.dumps(e) + "\n" for e in elements).encode()
197-
response = httpx.Response(status_code=200, content=body)
198-
assert len(response.content) == len(body)
200+
operation_id = "op-release"
201+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
202+
elements = [
203+
{"type": "Table", "text": f"t{i}", "metadata": {"image_base64": "A" * 2000}}
204+
for i in range(3)
205+
]
206+
response = _ndjson_response(elements)
207+
assert len(response.content) > 512
199208

200-
path = write_chunk_body_to_temp(response, str(tmp_path))
201-
response._content = path.encode()
209+
hook._elements_from_task_responses(operation_id, [(0, response)], started_at=0.0)
202210

203-
# The body is on disk, and the response now costs a path rather than a payload.
204-
assert _read_ndjson(path) == elements
205-
assert response.text == path
211+
# The response now costs a path rather than a payload...
206212
assert len(response.content) < 512
213+
# ...and the elements still made it into the combined output.
214+
assert _read_ndjson(hook.ndjson_output_path[operation_id]) == elements
207215

208216

209217
def test_elements_file_response_carries_path_in_extension_and_body(tmp_path):
@@ -258,6 +266,8 @@ def _hook_in_ndjson_mode(operation_id, tmp_path):
258266
hook.cache_tmp_data_feature[operation_id] = False
259267
hook.cache_tmp_data_dir[operation_id] = str(tmp_path)
260268
hook.allow_failed[operation_id] = False
269+
# Marks the operation live; `_clear_operation` removing it is what signals teardown.
270+
hook.pending_operation_ids[operation_id] = operation_id
261271
return hook
262272

263273

@@ -338,6 +348,59 @@ def test_combined_file_is_discarded_when_a_failure_response_is_returned(tmp_path
338348
assert _ndjson_files_in(tmp_path) == []
339349

340350

351+
def test_output_is_discarded_when_the_operation_was_cleared_mid_recombination(tmp_path):
352+
"""Recombination runs in a thread that cancellation cannot interrupt.
353+
354+
If `_clear_operation` tears the operation down first, publishing the path would both
355+
resurrect a cleared dict entry and orphan the file, since nothing will ever read it.
356+
"""
357+
operation_id = "op-cancelled"
358+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
359+
# `before_request` registers this; `_clear_operation` removing it is what marks the
360+
# operation dead. Simulate the teardown having already happened.
361+
hook.pending_operation_ids.pop(operation_id, None)
362+
363+
hook._elements_from_task_responses(
364+
operation_id, [(0, _ndjson_response(_elements("a", 2)))], started_at=0.0
365+
)
366+
367+
assert operation_id not in hook.ndjson_output_path
368+
assert _ndjson_files_in(tmp_path) == []
369+
370+
371+
def test_clear_operation_deletes_an_unclaimed_output_file(tmp_path):
372+
"""A path still recorded at teardown was never handed to the caller, so it is ours."""
373+
operation_id = "op-unclaimed"
374+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
375+
376+
hook._elements_from_task_responses(
377+
operation_id, [(0, _ndjson_response(_elements("a", 2)))], started_at=0.0
378+
)
379+
combined = hook.ndjson_output_path[operation_id]
380+
assert os.path.exists(combined)
381+
382+
hook._clear_operation(operation_id)
383+
384+
assert not os.path.exists(combined)
385+
386+
387+
def test_clear_operation_keeps_an_output_file_the_caller_claimed(tmp_path):
388+
"""The success path hands the path over, so teardown must not delete it."""
389+
operation_id = "op-claimed"
390+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
391+
392+
hook._elements_from_task_responses(
393+
operation_id, [(0, _ndjson_response(_elements("a", 2)))], started_at=0.0
394+
)
395+
response = hook._build_after_success_response(operation_id, httpx.Response(200), [])
396+
combined = response.extensions[ELEMENTS_FILE_EXTENSION_KEY]
397+
398+
hook._clear_operation(operation_id)
399+
400+
assert os.path.exists(combined)
401+
assert len(_read_ndjson(combined)) == 2
402+
403+
341404
def test_malformed_chunk_leaves_no_partial_output_behind(tmp_path):
342405
"""Regression guard: recombination that raises must not orphan a partial file.
343406

‎_test_unstructured_client/unit/test_regeneration_guards.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,15 @@ def test_partition_response_keeps_elements_file():
9898
for path in (
9999
"src/unstructured_client/general.py",
100100
"src/unstructured_client/models/operations/partition.py",
101+
"docs/models/operations/partitionresponse.md",
101102
):
102103
assert path in genignore, f"{path} carries custom code and must stay in .genignore"
103104

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

105111
def test_body_create_job_input_files_are_serialized_as_multipart_files():
106112
request = shared.BodyCreateJob(

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,8 +360,18 @@ def write_chunk_body_to_temp(response: httpx.Response, dir_: Optional[str] = Non
360360
The path to the spilled file. The caller owns deleting it.
361361
"""
362362
fd, path = tempfile.mkstemp(suffix=".ndjson", dir=dir_ or tempfile.gettempdir())
363-
with os.fdopen(fd, "wb") as f:
364-
f.write(response.content)
363+
try:
364+
with os.fdopen(fd, "wb") as f:
365+
f.write(response.content)
366+
except BaseException:
367+
# The caller only registers this path for cleanup once we return, so a failed
368+
# write (a full disk, most likely) has to clean up after itself or the file is
369+
# orphaned -- and a full disk is exactly the case that repeats.
370+
try:
371+
os.unlink(path)
372+
except OSError:
373+
pass
374+
raise
365375
return path
366376

367377

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

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -543,9 +543,13 @@ def __init__(self) -> None:
543543
self.cache_tmp_data_dir: dict[str, str] = {}
544544
# NDJSON elements-file mode: when the caller asks for application/x-ndjson the
545545
# per-chunk temp files are concatenated on disk instead of being parsed and
546-
# re-serialized, and the combined path is handed back via the response header.
546+
# re-serialized, and the combined path is handed back on the response.
547547
self.ndjson_mode: dict[str, bool] = {}
548548
self.ndjson_output_path: dict[str, str] = {}
549+
# Guards publishing the combined file against concurrent operation teardown.
550+
# Recombination runs in a worker thread that a cancelled operation cannot stop, so
551+
# it can still be running when `_clear_operation` fires on the event-loop thread.
552+
self._ndjson_lock = threading.Lock()
549553

550554
@staticmethod
551555
def _get_operation_id_from_request(request: Optional[httpx.Request]) -> Optional[str]:
@@ -1515,6 +1519,12 @@ def _combine_chunks_to_ndjson(self, operation_id: str, chunk_paths: list[str]) -
15151519
completes. A malformed chunk makes the parse raise partway through, and since the
15161520
combined file is the one thing here nothing else owns, a partial one would survive
15171521
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.
15181528
"""
15191529
temp_dir_path = self.cache_tmp_data_dir.get(operation_id) or tempfile.gettempdir()
15201530
out_path = f"{temp_dir_path}/{uuid.uuid4()}.ndjson"
@@ -1527,7 +1537,16 @@ def _combine_chunks_to_ndjson(self, operation_id: str, chunk_paths: list[str]) -
15271537
except BaseException:
15281538
_unlink_quietly([staging_path])
15291539
raise
1530-
self.ndjson_output_path[operation_id] = out_path
1540+
1541+
with self._ndjson_lock:
1542+
if operation_id not in self.pending_operation_ids:
1543+
_unlink_quietly([out_path])
1544+
logger.warning(
1545+
"split_pdf event=ndjson_output_discarded operation_id=%s reason=operation_cleared",
1546+
operation_id,
1547+
)
1548+
return
1549+
self.ndjson_output_path[operation_id] = out_path
15311550
logger.info(
15321551
"split_pdf event=ndjson_combined operation_id=%s chunk_count=%d element_count=%d out_file=%s",
15331552
operation_id,
@@ -1549,10 +1568,21 @@ def _discard_ndjson_output(self, operation_id: str) -> None:
15491568
Once we return a failure response instead, nothing downstream learns the path, so
15501569
without this the combined file is leaked for the lifetime of the host.
15511570
"""
1552-
out_path = self.ndjson_output_path.pop(operation_id, None)
1571+
with self._ndjson_lock:
1572+
out_path = self.ndjson_output_path.pop(operation_id, None)
15531573
if out_path is not None:
15541574
_unlink_quietly([out_path])
15551575

1576+
def _claim_ndjson_output(self, operation_id: str) -> Optional[str]:
1577+
"""Take the combined file's path, transferring ownership of it to the caller.
1578+
1579+
Removing it from `ndjson_output_path` is what makes cleanup unambiguous: a path
1580+
still recorded when the operation is torn down is one the caller never received,
1581+
so `_clear_operation` can delete it without risking the file it just handed over.
1582+
"""
1583+
with self._ndjson_lock:
1584+
return self.ndjson_output_path.pop(operation_id, None)
1585+
15561586
def _build_after_success_response(
15571587
self,
15581588
operation_id: str,
@@ -1587,7 +1617,7 @@ def _build_after_success_response(
15871617
# before the `elements is None` guard because `elements` is intentionally empty
15881618
# here -- nothing was parsed.
15891619
if self.ndjson_mode.get(operation_id, False):
1590-
ndjson_path = self.ndjson_output_path.get(operation_id)
1620+
ndjson_path = self._claim_ndjson_output(operation_id)
15911621
if ndjson_path is None:
15921622
logger.warning(
15931623
"split_pdf event=ndjson_missing_output operation_id=%s falling_back=true",
@@ -1718,9 +1748,16 @@ def _clear_operation(self, operation_id: str) -> None:
17181748
self.allow_failed.pop(operation_id, None)
17191749
self.cache_tmp_data_feature.pop(operation_id, None)
17201750
self.cache_tmp_data_dir.pop(operation_id, None)
1721-
self.ndjson_mode.pop(operation_id, None)
1722-
self.ndjson_output_path.pop(operation_id, None)
1723-
self.pending_operation_ids.pop(operation_id, None)
1751+
with self._ndjson_lock:
1752+
self.ndjson_mode.pop(operation_id, None)
1753+
# Anything still recorded here was never claimed by the caller -- the
1754+
# operation was torn down first -- so this is ours to delete. Dropping
1755+
# `pending_operation_ids` under the same lock is what stops a recombination
1756+
# worker still running in a thread from publishing after this point.
1757+
undelivered_ndjson = self.ndjson_output_path.pop(operation_id, None)
1758+
self.pending_operation_ids.pop(operation_id, None)
1759+
if undelivered_ndjson is not None:
1760+
_unlink_quietly([undelivered_ndjson])
17241761
future = self.operation_futures.pop(operation_id, None)
17251762
loop_holder = self.operation_loops.pop(operation_id, None)
17261763
executor = self.executors.pop(operation_id, None)

‎src/unstructured_client/general.py‎

Lines changed: 31 additions & 8 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 os
67
import tempfile
78
from typing import Any, Dict, List, Mapping, Optional, Union, cast
89
from unstructured_client import utils
@@ -31,6 +32,18 @@ def _new_elements_file():
3132
)
3233

3334

35+
def _discard_elements_file(path: str) -> None:
36+
"""Remove a partially written elements file, ignoring a failure to do so.
37+
38+
The copy is created with delete=False so it can outlive this function, which means a
39+
body that fails or is cancelled partway through would otherwise leave the file behind.
40+
"""
41+
try:
42+
os.unlink(path)
43+
except OSError:
44+
pass
45+
46+
3447
def _ndjson_elements_file(http_res: httpx.Response) -> str:
3548
"""Resolve an NDJSON response to a path on disk, without parsing the elements.
3649
@@ -46,10 +59,15 @@ def _ndjson_elements_file(http_res: httpx.Response) -> str:
4659
if existing_path:
4760
return existing_path
4861

49-
with _new_elements_file() as out:
50-
for byte_chunk in http_res.iter_bytes():
51-
out.write(byte_chunk)
52-
return out.name
62+
out = _new_elements_file()
63+
try:
64+
with out:
65+
for byte_chunk in http_res.iter_bytes():
66+
out.write(byte_chunk)
67+
except BaseException:
68+
_discard_elements_file(out.name)
69+
raise
70+
return out.name
5371

5472

5573
async def _ndjson_elements_file_async(http_res: httpx.Response) -> str:
@@ -58,10 +76,15 @@ async def _ndjson_elements_file_async(http_res: httpx.Response) -> str:
5876
if existing_path:
5977
return existing_path
6078

61-
with _new_elements_file() as out:
62-
async for byte_chunk in http_res.aiter_bytes():
63-
out.write(byte_chunk)
64-
return out.name
79+
out = _new_elements_file()
80+
try:
81+
with out:
82+
async for byte_chunk in http_res.aiter_bytes():
83+
out.write(byte_chunk)
84+
except BaseException:
85+
_discard_elements_file(out.name)
86+
raise
87+
return out.name
6588

6689

6790
class General(BaseSDK):

0 commit comments

Comments
 (0)