|
| 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) == [] |
0 commit comments